дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
Порівняти коміти
18
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
71f77cda23 | ||
|
|
c085f52b59 | ||
|
|
0104ed63c1 | ||
|
|
a441b2a906 | ||
|
|
c4f7fec86c | ||
|
|
37a8aae018 | ||
|
|
acc48a4816 | ||
|
|
8301326289 | ||
|
|
4c71299745 | ||
|
|
08249ca5fd | ||
|
|
edd6746439 | ||
|
|
695424beb2 | ||
|
|
9943d71d02 | ||
|
|
e03c5507f7 | ||
|
|
745099feaa | ||
|
|
6894d0a4e3 | ||
|
|
f80be658ea | ||
|
|
1c377b7f66 |
No files matched your search
@@ -0,0 +1,104 @@
|
||||
name: Nightly
|
||||
|
||||
# Builds main every night, when it has moved since the last nightly, into a prerelease
|
||||
# v<next patch>-nightly.<date> (scripts/nightly-prepare.ts: the tag points at a commit on top of
|
||||
# main that only sets the version). Nightly apps update from the rolling `nightly` release, which
|
||||
# holds the newest nightly's latest.json; stable apps read releases/latest, which is never a
|
||||
# prerelease, so they never see a nightly. The newest 14 nightlies are kept.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 18 * * *" # 02:00 Beijing
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force:
|
||||
description: "Build even when main has not changed since the last nightly"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: nightly
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
if: github.repository == 'l0ng-ai/openidea'
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
tag: ${{ steps.tag.outputs.tag }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
with: { ref: main, fetch-depth: 0 }
|
||||
- id: changed
|
||||
env:
|
||||
FORCE: ${{ inputs.force == true }}
|
||||
run: |
|
||||
last="$(git tag --list 'v*-nightly.*' --sort=-creatordate | head -1)"
|
||||
if [ "$FORCE" != true ] && [ -n "$last" ] && [ "$(git rev-parse "$last^")" = "$(git rev-parse HEAD)" ]; then
|
||||
echo "::notice::main has not changed since $last"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
if: steps.changed.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
- name: Version commit and tag
|
||||
id: tag
|
||||
if: steps.changed.outputs.skip != 'true'
|
||||
env:
|
||||
BUILD: ${{ github.run_number }}
|
||||
run: |
|
||||
version="$(node scripts/nightly-prepare.ts --date "$(date -u +%Y%m%d)" --build "$BUILD" | tail -1)"
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add -A
|
||||
git commit -q -m "chore: v$version"
|
||||
git tag "v$version"
|
||||
# Pushed with GITHUB_TOKEN, the tag does not start release.yml: the job below calls it.
|
||||
git push origin "refs/tags/v$version"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
release:
|
||||
needs: prepare
|
||||
if: needs.prepare.outputs.tag != ''
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/release.yml
|
||||
with:
|
||||
tag: ${{ needs.prepare.outputs.tag }}
|
||||
nightly: true
|
||||
secrets: inherit
|
||||
|
||||
# Points the nightly channel at the new nightly and drops the old ones.
|
||||
channel:
|
||||
needs: [prepare, release]
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
TAG: ${{ needs.prepare.outputs.tag }}
|
||||
steps:
|
||||
- name: Nightly manifest
|
||||
run: |
|
||||
if ! gh release download "$TAG" -p latest.json -D "$RUNNER_TEMP/manifest"; then
|
||||
echo "::warning::$TAG has no latest.json (unsigned build): the nightly channel stays where it was"
|
||||
exit 0
|
||||
fi
|
||||
notes="The update channel of the [nightly builds](https://github.com/$GH_REPO/releases?q=nightly&expanded=true): its latest.json is the newest nightly's, [$TAG](https://github.com/$GH_REPO/releases/tag/$TAG)."
|
||||
if gh release view nightly >/dev/null 2>&1; then
|
||||
gh release edit nightly --notes "$notes"
|
||||
else
|
||||
gh release create nightly --prerelease --target main --title "OpenIDEA Nightly" --notes "$notes"
|
||||
fi
|
||||
gh release upload nightly "$RUNNER_TEMP/manifest/latest.json" --clobber
|
||||
- name: Drop old nightlies
|
||||
run: |
|
||||
gh release list --limit 200 --json tagName,createdAt \
|
||||
--jq '[.[] | select(.tagName | test("^v.*-nightly\\."))] | sort_by(.createdAt) | reverse | .[14:][] | .tagName' |
|
||||
while read -r old; do
|
||||
gh release delete "$old" --cleanup-tag --yes
|
||||
done
|
||||
@@ -7,17 +7,23 @@ on:
|
||||
tag:
|
||||
description: "Tag to release (e.g. v0.1.0); must already exist"
|
||||
required: true
|
||||
# nightly.yml: a nightly is a prerelease whose notes start at the previous nightly, without the
|
||||
# official plugins, the CNB mirror or the Homebrew cask.
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag: { type: string, required: true }
|
||||
nightly: { type: boolean, default: false }
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.event.inputs.tag || github.ref_name }}
|
||||
group: release-${{ inputs.tag || github.ref_name }}
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
TAG: ${{ github.event.inputs.tag || github.ref_name }}
|
||||
TAG: ${{ inputs.tag || github.ref_name }}
|
||||
COMMUNITY_PLUGINS_INDEX: https://github.com/l0ng-ai/openidea-plugins/releases/download/index/index.json
|
||||
|
||||
# The jobs that read a signing key or token, here and in the workflows called below, run in
|
||||
@@ -52,6 +58,8 @@ jobs:
|
||||
fi
|
||||
- id: release
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
env:
|
||||
NIGHTLY: ${{ inputs.nightly == true }}
|
||||
with:
|
||||
script: |
|
||||
const tag = process.env.TAG;
|
||||
@@ -63,8 +71,13 @@ jobs:
|
||||
core.setOutput("id", existing.id);
|
||||
return;
|
||||
}
|
||||
// Prereleases are skipped: the notes span stable release to stable release.
|
||||
const previous = releases.find((r) => !r.draft && !r.prerelease);
|
||||
// Prereleases are skipped: the notes span stable release to stable release. A
|
||||
// nightly's span from the newest published release, nightly or stable (not the
|
||||
// rolling `nightly` release, which only holds the channel's manifest).
|
||||
const nightly = process.env.NIGHTLY === "true";
|
||||
const previous = releases.find(
|
||||
(r) => !r.draft && r.tag_name !== "nightly" && (nightly || !r.prerelease),
|
||||
);
|
||||
const { data: notes } = await github.rest.repos.generateReleaseNotes({
|
||||
owner, repo, tag_name: tag, previous_tag_name: previous?.tag_name,
|
||||
});
|
||||
@@ -80,7 +93,7 @@ jobs:
|
||||
needs: create-release
|
||||
uses: ./.github/workflows/release-build.yml
|
||||
with:
|
||||
tag: ${{ github.event.inputs.tag || github.ref_name }}
|
||||
tag: ${{ inputs.tag || github.ref_name }}
|
||||
release_id: ${{ needs.create-release.outputs.release_id }}
|
||||
secrets: inherit
|
||||
|
||||
@@ -102,10 +115,14 @@ jobs:
|
||||
runs-on: ubuntu-22.04
|
||||
env:
|
||||
SIGNING_KEY: ${{ secrets.PLUGIN_SIGNING_KEY }}
|
||||
NIGHTLY: ${{ inputs.nightly == true }}
|
||||
steps:
|
||||
- id: key
|
||||
run: |
|
||||
if [ -z "$SIGNING_KEY" ]; then
|
||||
if [ "$NIGHTLY" = true ]; then
|
||||
echo "a nightly does not publish the official plugins"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$SIGNING_KEY" ]; then
|
||||
echo "::warning::PLUGIN_SIGNING_KEY is not set: the official plugins are not published"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
@@ -178,13 +195,15 @@ jobs:
|
||||
# The China mirror the updater's CNB source reads; a failure here leaves the GitHub release as is.
|
||||
cnb-mirror:
|
||||
needs: publish
|
||||
if: ${{ !inputs.nightly }}
|
||||
uses: ./.github/workflows/cnb-mirror.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
with: { tag: "${{ inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
|
||||
homebrew:
|
||||
needs: publish
|
||||
if: ${{ !inputs.nightly }}
|
||||
uses: ./.github/workflows/homebrew.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
with: { tag: "${{ inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
Створено
+48
-48
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4183,7 +4183,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4195,7 +4195,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4207,7 +4207,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4225,7 +4225,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4239,7 +4239,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4250,7 +4250,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4261,7 +4261,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4283,7 +4283,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4296,7 +4296,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4326,7 +4326,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4365,7 +4365,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4378,7 +4378,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4392,7 +4392,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4412,7 +4412,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4423,7 +4423,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4435,7 +4435,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4447,7 +4447,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4466,7 +4466,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4549,7 +4549,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"http",
|
||||
@@ -4572,7 +4572,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4595,7 +4595,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4607,7 +4607,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4623,7 +4623,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4632,7 +4632,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4643,7 +4643,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4702,7 +4702,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4732,7 +4732,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4751,7 +4751,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4776,7 +4776,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4798,7 +4798,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4812,7 +4812,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4832,7 +4832,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4858,7 +4858,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4874,7 +4874,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4900,7 +4900,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4921,7 +4921,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -4934,7 +4934,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4959,7 +4959,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4972,7 +4972,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4987,7 +4987,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -5001,7 +5001,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -5014,7 +5014,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -5041,7 +5041,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5063,7 +5063,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5090,7 +5090,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5106,7 +5106,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6754,7 +6754,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -370,7 +370,7 @@ pub fn register(dispatcher: &mut Dispatcher, shell: Arc<WebShellState>) {
|
||||
("window_toggle_zoom", Always),
|
||||
("window_start_drag", Always),
|
||||
("window_drag_files", Always),
|
||||
("file_dialog_needs_gtk", Trusted),
|
||||
("file_dialog_needs_gtk", Always),
|
||||
("clipboard_has_files", Always),
|
||||
("clipboard_has_image", Always),
|
||||
] {
|
||||
@@ -387,7 +387,7 @@ pub fn register(dispatcher: &mut Dispatcher, shell: Arc<WebShellState>) {
|
||||
for (empty_list, trust) in [
|
||||
("window_group_current", Always),
|
||||
("system_font_families", Always),
|
||||
("system_probe_hotkeys", Trusted),
|
||||
("system_probe_hotkeys", Always),
|
||||
("wsl_distros", Always),
|
||||
("web_browsers", Always),
|
||||
("plugin_catalog", Always),
|
||||
|
||||
@@ -242,3 +242,50 @@ for (const theme of ["dark", "light"] as const) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test("a long agent form scrolls above the composer instead of being cut off", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1000, height: 520 });
|
||||
const fields = Array.from({ length: 5 }, (_, q) => ({
|
||||
name: `q${q + 1}`,
|
||||
title: `Question ${q + 1}`,
|
||||
kind: "choice" as const,
|
||||
required: true,
|
||||
options: Array.from({ length: 4 }, (_, o) => ({ value: `a${o + 1}`, label: `Answer ${q + 1}.${o + 1}` })),
|
||||
}));
|
||||
await page.evaluate(
|
||||
async ({ task, fields }) => {
|
||||
const store = await import("/src/features/agents/store.ts");
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
tasks: new Map([[task.id, task]]),
|
||||
entries: new Map([
|
||||
[
|
||||
task.id,
|
||||
[{ type: "permission", id: 1, title: "Plan the change", options: [], chosen: null, form: { fields } }],
|
||||
],
|
||||
]),
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
},
|
||||
{ task, fields },
|
||||
);
|
||||
const card = page.getByRole("form", { name: "Plan the change" });
|
||||
await expect(card).toBeVisible();
|
||||
const composer = page.getByRole("textbox", { name: "Message", exact: true });
|
||||
await expect(composer).toBeInViewport();
|
||||
for (let q = 1; q <= 5; q++) {
|
||||
const last = card.getByRole("radio", { name: `Answer ${q}.4` });
|
||||
await last.scrollIntoViewIfNeeded();
|
||||
const box = (await last.boundingBox())!;
|
||||
const hit = await page.evaluate(
|
||||
({ x, y }) => document.elementFromPoint(x, y)?.closest("label")?.textContent ?? null,
|
||||
{ x: box.x + box.width / 2, y: box.y + box.height / 2 },
|
||||
);
|
||||
expect(hit).toContain(`Answer ${q}.4`);
|
||||
await last.check();
|
||||
}
|
||||
const submit = card.getByRole("button", { name: "Submit", exact: true });
|
||||
await submit.scrollIntoViewIfNeeded();
|
||||
await expect(submit).toBeInViewport({ ratio: 1 });
|
||||
await expect(submit).toBeEnabled();
|
||||
});
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.55",
|
||||
"version": "0.1.56",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { NIGHTLY_ENDPOINT, msiVersion, nightlyVersion, setNightlyConfig } from "./nightly-prepare.ts";
|
||||
|
||||
describe("nightlyVersion", () => {
|
||||
it("is the next patch's nightly once the current version is released", () => {
|
||||
expect(nightlyVersion("0.1.55", true, "20261130", new Set(["v0.1.55"]))).toBe("0.1.56-nightly.20261130");
|
||||
});
|
||||
|
||||
it("is the current version's nightly while that is not released", () => {
|
||||
expect(nightlyVersion("0.1.56", false, "20261130", new Set())).toBe("0.1.56-nightly.20261130");
|
||||
});
|
||||
|
||||
it("numbers further nightlies of the same day, which sort after the first", () => {
|
||||
const tags = new Set(["v0.1.56-nightly.20261130", "v0.1.56-nightly.20261130.2"]);
|
||||
expect(nightlyVersion("0.1.55", true, "20261130", tags)).toBe("0.1.56-nightly.20261130.3");
|
||||
});
|
||||
|
||||
it("refuses a malformed date or version", () => {
|
||||
expect(() => nightlyVersion("0.1.55", true, "2026-11-30", new Set())).toThrow();
|
||||
expect(() => nightlyVersion("0.1", true, "20261130", new Set())).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("msiVersion", () => {
|
||||
it("is the last release with the build number", () => {
|
||||
expect(msiVersion("0.1.55", true, 42)).toBe("0.1.55.42");
|
||||
expect(msiVersion("0.1.56", false, 42)).toBe("0.1.55.42");
|
||||
expect(msiVersion("0.2.0", false, 42)).toBe("0.2.0.42");
|
||||
});
|
||||
|
||||
it("refuses a build number MSI cannot hold", () => {
|
||||
expect(() => msiVersion("0.1.55", true, 65536)).toThrow();
|
||||
expect(() => msiVersion("0.1.55", true, Number.NaN)).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("setNightlyConfig", () => {
|
||||
it("sets the version, the nightly manifest and the MSI version, keeping the rest", () => {
|
||||
const json = JSON.stringify(
|
||||
{
|
||||
version: "0.1.55",
|
||||
bundle: { targets: "all", macOS: { minimumSystemVersion: "11.0" } },
|
||||
plugins: { updater: { pubkey: "key", endpoints: ["https://example.com/latest.json"] } },
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
const config = JSON.parse(setNightlyConfig(json, "0.1.56-nightly.20261130", "0.1.55.42"));
|
||||
expect(config.version).toBe("0.1.56-nightly.20261130");
|
||||
expect(config.plugins.updater).toEqual({ pubkey: "key", endpoints: [NIGHTLY_ENDPOINT] });
|
||||
expect(config.bundle).toEqual({
|
||||
targets: "all",
|
||||
macOS: { minimumSystemVersion: "11.0" },
|
||||
windows: { wix: { version: "0.1.55.42" } },
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses a config without the updater", () => {
|
||||
expect(() =>
|
||||
setNightlyConfig(JSON.stringify({ version: "0.1.55" }), "0.1.56-nightly.20261130", "0.1.55.1"),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Prepares a nightly build commit (nightly.yml): `node scripts/nightly-prepare.ts --date 20261130
|
||||
* --build 42` sets the app version to the next patch's nightly, `0.1.56-nightly.20261130` (`.2`,
|
||||
* `.3`… when that tag already exists), in Cargo.toml, package.json and tauri.conf.json, points the
|
||||
* updater at the nightly channel's manifest, gives the MSI installer a numeric version, refreshes
|
||||
* Cargo.lock and the plugin API snapshot, and prints the version (also `version=` in
|
||||
* $GITHUB_OUTPUT). The next patch is the current version's when that is already released (its
|
||||
* `v` tag exists), else the current version itself.
|
||||
*/
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { appendFileSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
cargoVersion,
|
||||
edit,
|
||||
parseVersion,
|
||||
setCargoVersion,
|
||||
setJsonVersion,
|
||||
syncApiSnapshot,
|
||||
} from "./release-prepare.ts";
|
||||
|
||||
/** The nightly channel's updater manifest: the rolling `nightly` release (nightly.yml). */
|
||||
export const NIGHTLY_ENDPOINT = "https://github.com/l0ng-ai/openidea/releases/download/nightly/latest.json";
|
||||
|
||||
function bump(version: string): string {
|
||||
const [major, minor, patch] = version.split(".").map(Number);
|
||||
return `${major}.${minor}.${patch! + 1}`;
|
||||
}
|
||||
|
||||
/** The nightly's version: the first of `<next>-nightly.<date>`, `….2`, `….3` whose tag is not in `tags`. */
|
||||
export function nightlyVersion(current: string, released: boolean, date: string, tags: Set<string>): string {
|
||||
if (!/^\d{8}$/.test(date)) throw new Error(`expected a date like 20261130, got ${date}`);
|
||||
const base = `${released ? bump(parseVersion(current)) : parseVersion(current)}-nightly.${date}`;
|
||||
for (let n = 1; ; n++) {
|
||||
const version = n === 1 ? base : `${base}.${n}`;
|
||||
if (!tags.has(`v${version}`)) return version;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The MSI ProductVersion (`major.minor.patch.build`, numbers only): the last released version
|
||||
* with the build number, so a nightly sorts after that release and before the next.
|
||||
*/
|
||||
export function msiVersion(current: string, released: boolean, build: number): string {
|
||||
if (!Number.isInteger(build) || build < 0 || build > 65535) throw new Error(`build ${build} is not 0–65535`);
|
||||
const [major, minor, patch] = parseVersion(current).split(".").map(Number);
|
||||
const last = released || patch === 0 ? patch : patch! - 1;
|
||||
return `${major}.${minor}.${last}.${build}`;
|
||||
}
|
||||
|
||||
/** tauri.conf.json for a nightly: its version, the nightly updater manifest and the MSI version. */
|
||||
export function setNightlyConfig(json: string, version: string, msi: string): string {
|
||||
const config = JSON.parse(setJsonVersion(json, version)) as {
|
||||
plugins?: { updater?: { endpoints?: string[] } };
|
||||
bundle?: { windows?: { wix?: { version?: string } } };
|
||||
};
|
||||
if (!config.plugins?.updater) throw new Error("tauri.conf.json: no plugins.updater");
|
||||
config.plugins.updater.endpoints = [NIGHTLY_ENDPOINT];
|
||||
config.bundle ??= {};
|
||||
config.bundle.windows ??= {};
|
||||
config.bundle.windows.wix = { ...config.bundle.windows.wix, version: msi };
|
||||
return `${JSON.stringify(config, null, 2)}\n`;
|
||||
}
|
||||
|
||||
function arg(name: string): string {
|
||||
const index = process.argv.indexOf(`--${name}`);
|
||||
const value = index >= 0 ? process.argv[index + 1] : undefined;
|
||||
if (!value) throw new Error(`missing --${name}`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function git(root: string, ...args: string[]): string {
|
||||
const result = spawnSync("git", args, { cwd: root, encoding: "utf8" });
|
||||
if (result.status !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr}`);
|
||||
return result.stdout;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const root = fileURLToPath(new URL("..", import.meta.url));
|
||||
const date = arg("date");
|
||||
const build = Number(arg("build"));
|
||||
const current = cargoVersion(readFileSync(join(root, "Cargo.toml"), "utf8"));
|
||||
const tags = new Set(git(root, "tag", "--list", "v*").split("\n").filter(Boolean));
|
||||
const released = tags.has(`v${current}`);
|
||||
const version = nightlyVersion(current, released, date, tags);
|
||||
const msi = msiVersion(current, released, build);
|
||||
|
||||
edit(join(root, "Cargo.toml"), (text) => setCargoVersion(text, version));
|
||||
edit(join(root, "package.json"), (text) => setJsonVersion(text, version));
|
||||
edit(join(root, "src-tauri/tauri.conf.json"), (text) => setNightlyConfig(text, version, msi));
|
||||
const cargo = spawnSync("cargo", ["update", "--workspace"], { cwd: root, stdio: "inherit" });
|
||||
if (cargo.status !== 0) throw new Error("cargo update --workspace failed");
|
||||
syncApiSnapshot(root);
|
||||
|
||||
if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `version=${version}\n`);
|
||||
console.log(version);
|
||||
}
|
||||
|
||||
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
|
||||
try {
|
||||
main();
|
||||
} catch (error) {
|
||||
console.error(`nightly-prepare: ${error instanceof Error ? error.message : String(error)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Forking recorded native agent sessions into new tasks (API 1.18). Requires
|
||||
/// the `agents` capability. The session must belong to the invoking window's
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// The commit being prepared in the window the current command or event came
|
||||
/// from (the Commit tool window, or the Commit dialog while it is open): the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Optional export (API 1.16, world `plugin-completion-list`): completion that
|
||||
/// can say its list is incomplete. A plugin exporting it is called instead of
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Plugin-owned project data sources. Requires database.sources and project trust.
|
||||
/// Runs on the Database subsystem's host, including on remote project servers.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Editor and project-tree decorations (API 1.4). Requires project.read. An editor set
|
||||
/// follows its file: the file's own project, or the nearest one when it is outside them all.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// What the pane beside the Services tree shows for a plugin's node.
|
||||
interface detail-types {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Optional export (world `plugin-diagnostics`): problems in the current,
|
||||
/// possibly unsaved document, for the languages declared with the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
|
||||
interface endpoints-provider {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Workbench events, delivered in batches to `event-handler.handle`.
|
||||
interface events {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
interface lifecycle {
|
||||
use types.{context, error};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// What other plugins contributed to the extension points this plugin declares
|
||||
/// (`[[extension-points]]` in `plugin.toml`; the contributors list this plugin
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Optional export (world `plugin-file-actions`): quick fixes and
|
||||
/// refactorings that create, rename or delete files, next to the text edits
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Files outside the open projects: the configuration of the program a
|
||||
/// plugin integrates with, a tool installed elsewhere, a licence file.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Writes to the IDE log, tagged with the plugin id.
|
||||
interface log {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Optional export (world `plugin-hover-actions`): clickable actions rendered
|
||||
/// at the left edge of a line and revealed while the pointer is in the leftmost
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Optional export (world `plugin-hover`): Markdown added to the hover of
|
||||
/// documents of the languages declared with the `hover` provider kind,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Cross-file associations a plugin publishes for the files it declares under
|
||||
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Embedded languages. The host routes plugin providers and configured language
|
||||
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
|
||||
/// the languages declared with the `inlay-hints` provider kind, including
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Problems in files, shown in the editor and the Problems view.
|
||||
interface diagnostics {
|
||||
@@ -108,6 +108,32 @@ interface net {
|
||||
/// project binding, so resource methods cannot be redirected to another
|
||||
/// project.
|
||||
websocket-connect: func(project: borrow<project>, req: websocket-request) -> result<websocket, error>;
|
||||
|
||||
record body-chunk {
|
||||
bytes: list<u8>,
|
||||
/// The body has ended: this read and every later one return no more bytes.
|
||||
done: bool,
|
||||
}
|
||||
|
||||
/// A response whose body is read as it arrives: server-sent events, a
|
||||
/// model's streamed reply (API 1.19). At most eight may be open for a
|
||||
/// plugin. Dropping this resource closes the connection, as does stopping
|
||||
/// the plugin.
|
||||
resource response-stream {
|
||||
status: func() -> u16;
|
||||
headers: func() -> list<header>;
|
||||
/// The next bytes of the body, at most `max-bytes` (and 1 MiB). Waits
|
||||
/// up to `timeout-ms` for them within the call's budget and returns
|
||||
/// none, with `done` false, when nothing arrived in time; zero only
|
||||
/// takes what has already arrived.
|
||||
read: func(max-bytes: u32, timeout-ms: u32) -> result<body-chunk, error>;
|
||||
close: func();
|
||||
}
|
||||
|
||||
/// As `fetch`, with the same grants, secrets and redirects, but returns
|
||||
/// once the response headers arrive (API 1.19). `timeout-ms` bounds the
|
||||
/// wait for the headers; the body has no overall limit.
|
||||
fetch-stream: func(req: request) -> result<response-stream, error>;
|
||||
}
|
||||
|
||||
/// Secrets the user stored for the plugin (Settings › Plugins, kept in the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Additional language features, called only for declared API 1.4 provider kinds.
|
||||
/// Editor calls have a 50 ms soft / 500 ms hard budget; formatting has 5 seconds.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Discovery of the IDE's built-in MCP server; never exposes its URL or token.
|
||||
interface mcp {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
/// `fs` and `workspace`, and everything else goes through the imports below,
|
||||
/// gated by the capabilities granted in `plugin.toml` (a missing one returns
|
||||
/// `error::denied`).
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
world plugin {
|
||||
import log;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Editor features a plugin provides for the languages it declares under
|
||||
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Project-scoped targets owned by the registering plugin (API 1.4).
|
||||
interface run-targets {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Launches this plugin's configurations in the invoking window's Run tool window.
|
||||
interface run {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// On-demand results for `[[contributes.searchCategories]]`. Optional, API 1.13.
|
||||
interface search-provider {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Optional export (world `plugin-semantic-tokens`): semantic colouring of
|
||||
/// documents of the languages declared with the `semantic-tokens` provider
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
|
||||
/// as in the editor and LSP.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Declarative views: tool windows declared
|
||||
/// under `[[contributes.views]]` and custom editors under
|
||||
@@ -203,8 +203,20 @@ interface views {
|
||||
/// The plugin's own settings (`[contributes.settings]`), as the user set them
|
||||
/// (project over global) or the schema's default.
|
||||
interface settings {
|
||||
use types.{error};
|
||||
|
||||
/// The value of `key` as JSON (`true`, `3`, `"text"`), none if unknown.
|
||||
get: func(key: string) -> option<string>;
|
||||
/// Opens Settings at one of the plugin's own pages in the window the
|
||||
/// current command or event came from (API 1.19): `page` is the `id` of a
|
||||
/// `[[contributes.settings.pages]]` entry, none for the plugin's settings
|
||||
/// node itself. `invalid` outside a window's command or event, `not-found`
|
||||
/// for a page the plugin does not declare (or without `[contributes.settings]`).
|
||||
open: func(page: option<string>) -> result<_, error>;
|
||||
/// Opens Settings › Plugins at this plugin's permissions, where the user
|
||||
/// grants an optional capability it lacks (API 1.19). `invalid` outside a
|
||||
/// window's command or event.
|
||||
open-permissions: func() -> result<_, error>;
|
||||
}
|
||||
|
||||
/// Optional export (world `plugin-views`): content of declared views and
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
interface workspace {
|
||||
use types.{error, location};
|
||||
@@ -137,6 +137,10 @@ interface editor {
|
||||
/// the plugin's install directory, selecting a range. Only from
|
||||
/// commands/events of a window. Paths follow views.open-location.
|
||||
open: func(path: string, selection: option<range>) -> result<_, error>;
|
||||
/// `open` in the built-in text editor even when a custom editor claims
|
||||
/// the file, as the IDE's own "Open as Text" does: the same document,
|
||||
/// undo history and Save (API 1.19).
|
||||
open-as-text: func(path: string, selection: option<range>) -> result<_, error>;
|
||||
|
||||
/// Current version and text of an open project document. Unlike
|
||||
/// `text-editor.document`, this is available to background events.
|
||||
|
||||
@@ -636,11 +636,18 @@ fn config_endpoints<R: tauri::Runtime>(app: &AppHandle<R>) -> Vec<String> {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Nightly builds (`x.y.z-nightly.…`, nightly.yml) update from the nightly channel's manifest
|
||||
/// only: the CNB mirror carries stable releases.
|
||||
fn is_nightly(version: &str) -> bool {
|
||||
version.contains("-nightly.")
|
||||
}
|
||||
|
||||
/// The endpoints tried in order: `source` first, the other source when it fails or has
|
||||
/// no manifest. Bundles are signed, so either source's manifest and downloads verify.
|
||||
/// No official endpoint (a build without updates) means no mirror either.
|
||||
fn source_endpoints(official: Vec<String>, source: UpdateSource) -> Vec<String> {
|
||||
if official.is_empty() {
|
||||
/// No official endpoint (a build without updates) means no mirror either, and a nightly
|
||||
/// build of `version` has no mirror.
|
||||
fn source_endpoints(official: Vec<String>, source: UpdateSource, version: &str) -> Vec<String> {
|
||||
if official.is_empty() || is_nightly(version) {
|
||||
return official;
|
||||
}
|
||||
let mirror = vec![CNB_ENDPOINT.to_string()];
|
||||
@@ -669,7 +676,7 @@ pub(crate) fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option
|
||||
}
|
||||
let endpoints = match update_endpoint_env() {
|
||||
Some(url) => vec![url],
|
||||
None => source_endpoints(config_endpoints(app), source),
|
||||
None => source_endpoints(config_endpoints(app), source, env!("CARGO_PKG_VERSION")),
|
||||
};
|
||||
let endpoints = endpoints
|
||||
.iter()
|
||||
@@ -867,7 +874,7 @@ pub async fn app_release_notes(
|
||||
) -> IdeResult<Option<BTreeMap<String, String>>> {
|
||||
let endpoints = match update_endpoint_env() {
|
||||
Some(url) => vec![url],
|
||||
None => source_endpoints(config_endpoints(&app), source),
|
||||
None => source_endpoints(config_endpoints(&app), source, env!("CARGO_PKG_VERSION")),
|
||||
};
|
||||
let client = ide_http::client::shared()?;
|
||||
for endpoint in endpoints {
|
||||
@@ -1005,10 +1012,24 @@ mod tests {
|
||||
#[test]
|
||||
fn chosen_source_is_tried_first_and_the_other_after_it() {
|
||||
let github = "https://github.com/l0ng-ai/openidea/releases/latest/download/latest.json".to_string();
|
||||
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Github), [github.clone(), CNB_ENDPOINT.into()]);
|
||||
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Cnb), [CNB_ENDPOINT.into(), github]);
|
||||
assert_eq!(
|
||||
source_endpoints(vec![github.clone()], UpdateSource::Github, "0.1.55"),
|
||||
[github.clone(), CNB_ENDPOINT.into()]
|
||||
);
|
||||
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Cnb, "0.1.55"), [CNB_ENDPOINT.into(), github]);
|
||||
// A build without an update endpoint stays without one.
|
||||
assert!(source_endpoints(Vec::new(), UpdateSource::Cnb).is_empty());
|
||||
assert!(source_endpoints(Vec::new(), UpdateSource::Cnb, "0.1.55").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_builds_update_from_the_nightly_manifest_only() {
|
||||
let nightly = "https://github.com/l0ng-ai/openidea/releases/download/nightly/latest.json".to_string();
|
||||
for source in [UpdateSource::Github, UpdateSource::Cnb] {
|
||||
assert_eq!(
|
||||
source_endpoints(vec![nightly.clone()], source, "0.1.56-nightly.20261130"),
|
||||
std::slice::from_ref(&nightly)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.55",
|
||||
"version": "0.1.56",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
@@ -918,6 +918,11 @@ function outsideProject(path: string): boolean {
|
||||
/** Files outside the project that code navigation opened: library sources, shown read-only. */
|
||||
const navigatedLibraryFiles = new Set<string>();
|
||||
|
||||
/** Marks `path` as a library source again, for a tab restored from a saved session. */
|
||||
export function markLibraryFile(path: string): void {
|
||||
navigatedLibraryFiles.add(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a code location a language server or the index answered (a declaration, an
|
||||
* implementation, a documentation link) and selects `selection`. A file outside the project is a
|
||||
|
||||
@@ -3,8 +3,10 @@ import { EditorSelection, EditorState, Transaction, type Extension } from "@code
|
||||
import { indentService, indentUnit } from "@codemirror/language";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { commands } from "@/platform/ipc";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { EDITOR_EXTRA_DEFAULTS, type LineClipboardOptions } from "@/platform/editorSettings";
|
||||
import { isRemoteWindow } from "@/platform/remote";
|
||||
import { useWebConnection } from "@/platform/webBridge";
|
||||
import {
|
||||
clearClipboardHistory,
|
||||
clipboardHistory,
|
||||
@@ -27,6 +29,7 @@ const views: EditorView[] = [];
|
||||
beforeEach(() => {
|
||||
clearClipboardHistory();
|
||||
vi.stubGlobal("__TAURI_INTERNALS__", {});
|
||||
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
|
||||
Object.defineProperty(document, "execCommand", { configurable: true, value: vi.fn(() => false) });
|
||||
Object.defineProperty(document, "queryCommandSupported", { configurable: true, value: vi.fn(() => false) });
|
||||
});
|
||||
@@ -211,6 +214,73 @@ it.each([
|
||||
expect(create.mock.calls[0]![0]).toMatch(hasFile ? /assets\/image\.png$/ : /assets\/image-\d{8}-\d{6}\.png$/);
|
||||
});
|
||||
|
||||
describe("macOS menu paste into Markdown reads the clipboard natively", () => {
|
||||
// WebKit's execCommand("paste") from a menu makes macOS show a "Paste" callout.
|
||||
function markdownView() {
|
||||
usePlatform.setState({ os: "macos" });
|
||||
const view = new EditorView({
|
||||
extensions: [
|
||||
clipboardDocumentPath.of("/p/a.md"),
|
||||
clipboardFilesExtension,
|
||||
markdownImages({ path: "/p/a.md", folder: "assets", pattern: "image-{timestamp}" }),
|
||||
],
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
vi.mocked(document.queryCommandSupported).mockReturnValue(true);
|
||||
return view;
|
||||
}
|
||||
|
||||
it("saves a copied image without the webview's paste", async () => {
|
||||
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: [] });
|
||||
vi.spyOn(commands, "clipboardImage").mockResolvedValue({ status: "ok", data: "data:image/png;base64,iVBORw==" });
|
||||
const create = vi.spyOn(commands, "fsCreateFileBytes").mockResolvedValue({ status: "ok", data: null });
|
||||
const view = markdownView();
|
||||
await pasteEditorClipboard(view);
|
||||
await vi.waitFor(() => expect(view.state.doc.toString()).toMatch(/^!\[\]\(assets\/image-\d{8}-\d{6}\.png\)$/));
|
||||
expect(create.mock.calls[0]![1]).toBe("iVBORw==");
|
||||
expect(document.execCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the execCommand paste in web mode, where the backend has no clipboard", async () => {
|
||||
useWebConnection.setState({ active: true });
|
||||
try {
|
||||
const list = vi.spyOn(commands, "clipboardFileList");
|
||||
vi.mocked(document.execCommand).mockReturnValue(true);
|
||||
await pasteEditorClipboard(markdownView());
|
||||
expect(document.execCommand).toHaveBeenCalledWith("paste");
|
||||
expect(list).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
useWebConnection.setState({ active: false });
|
||||
}
|
||||
});
|
||||
|
||||
it("pastes the text when the clipboard holds no image", async () => {
|
||||
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: [] });
|
||||
vi.spyOn(commands, "clipboardImage").mockResolvedValue({ status: "ok", data: null });
|
||||
vi.spyOn(commands, "clipboardText").mockResolvedValue({ status: "ok", data: "plain" });
|
||||
const view = markdownView();
|
||||
await pasteEditorClipboard(view);
|
||||
expect(view.state.doc.toString()).toBe("plain");
|
||||
expect(document.execCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("embeds a copied image file like the paste event, not as a path", async () => {
|
||||
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/src/pic.png"] });
|
||||
const image = vi.spyOn(commands, "clipboardImage");
|
||||
vi.stubGlobal("__TAURI_INTERNALS__", {
|
||||
invoke: vi.fn(async () => "data:image/png;base64,iVBORw=="),
|
||||
});
|
||||
const create = vi.spyOn(commands, "fsCreateFileBytes").mockResolvedValue({ status: "ok", data: null });
|
||||
const view = markdownView();
|
||||
await pasteEditorClipboard(view);
|
||||
await vi.waitFor(() => expect(view.state.doc.toString()).toBe(""));
|
||||
expect(create.mock.calls[0]![0]).toMatch(/assets\/pic\.png$/);
|
||||
expect(image).not.toHaveBeenCalled();
|
||||
expect(document.execCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("does not insert into a read-only editor", async () => {
|
||||
const list = vi.spyOn(commands, "clipboardFileList");
|
||||
const view = new EditorView({ extensions: [clipboardFilesExtension, EditorState.readOnly.of(true)] });
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { EditorSelection, Facet, Prec, type EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { pasteClipboardFiles, readClipboardText } from "@/platform/clipboard";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { isWebMode } from "@/platform/webBridge";
|
||||
import type { LinePasteMode } from "@/platform/editorSettings";
|
||||
import { isRemoteWindow } from "@/platform/remote";
|
||||
import { isLinewiseClipboardText } from "../clipboardHistory";
|
||||
import { isMarkdown, relativeImagePath } from "./markdownImages";
|
||||
import { isMarkdown, pasteMarkdownImages, relativeImagePath } from "./markdownImages";
|
||||
|
||||
export const clipboardDocumentPath = Facet.define<string, string>({ combine: (paths) => paths[0] ?? "" });
|
||||
|
||||
@@ -125,9 +128,19 @@ export function pasteEditorText(view: EditorView, text: string) {
|
||||
|
||||
export async function pasteEditorClipboard(view: EditorView) {
|
||||
if (!view.dom.isConnected || view.state.readOnly) return;
|
||||
const markdown = isMarkdown(view.state.facet(clipboardDocumentPath));
|
||||
// macOS WebKit asks the user to confirm execCommand("paste") from the editor context menu with a "Paste" callout
|
||||
// (the app-menu Edit > Paste is a native paste: selector and never gets here); the
|
||||
// backend reads the image (or copied image files) without asking, so text then takes the native path below.
|
||||
const native = markdown && isTauri() && !isWebMode() && usePlatform.getState().os === "macos";
|
||||
try {
|
||||
if (native) {
|
||||
const paths: string[] = await call(commands.clipboardFileList()).catch(() => []);
|
||||
const image = paths.length ? null : await call(commands.clipboardImage()).catch(() => null);
|
||||
if (pasteMarkdownImages(view, image ?? paths)) return;
|
||||
}
|
||||
// Successful native paste preserves image blobs and may complete after execCommand returns.
|
||||
if (isMarkdown(view.state.facet(clipboardDocumentPath)) && document.queryCommandSupported("paste")) {
|
||||
if (markdown && !native && document.queryCommandSupported("paste")) {
|
||||
view.focus();
|
||||
if (document.execCommand("paste")) return;
|
||||
}
|
||||
|
||||
@@ -111,6 +111,29 @@ interface ImageOptions {
|
||||
pattern: string;
|
||||
}
|
||||
|
||||
type ImageSource = () => Promise<{ blob: Blob | string; name: string }>;
|
||||
|
||||
// OS paths belong to this client even in a remote project.
|
||||
const fileSource =
|
||||
(path: string): ImageSource =>
|
||||
async () => ({ blob: await invokeLocal<string>("fs_read_image", { path }), name: path.replace(/^.*[\\/]/, "") });
|
||||
|
||||
const imageInserters = new WeakMap<EditorView, (sources: ImageSource[]) => void>();
|
||||
|
||||
/**
|
||||
* Saves and links images the menu Paste read natively, as a paste event would: image files by path, or a
|
||||
* raw clipboard image as a PNG data URL. False when `view` does not take images (not Markdown, read-only,
|
||||
* or not image files).
|
||||
*/
|
||||
export function pasteMarkdownImages(view: EditorView, images: string[] | string): boolean {
|
||||
const insert = imageInserters.get(view);
|
||||
if (!insert || view.state.readOnly) return false;
|
||||
if (typeof images === "string") insert([async () => ({ blob: images, name: "" })]);
|
||||
else if (images.length && images.every((p) => IMAGE_FILE.test(p))) insert(images.map(fileSource));
|
||||
else return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function markdownImages(options: ImageOptions): Extension {
|
||||
if (!isMarkdown(options.path)) return [];
|
||||
return ViewPlugin.fromClass(
|
||||
@@ -118,7 +141,9 @@ export function markdownImages(options: ImageOptions): Extension {
|
||||
alive = true;
|
||||
pending = new Set<{ from: number; to: number }>();
|
||||
unregister: () => void;
|
||||
readonly insertSources = (sources: ImageSource[]) => this.insert(sources);
|
||||
constructor(readonly view: EditorView) {
|
||||
imageInserters.set(view, this.insertSources);
|
||||
this.unregister = registerFileDropHandler((paths, x, y) => {
|
||||
const rect = view.dom.getBoundingClientRect();
|
||||
if (
|
||||
@@ -130,14 +155,7 @@ export function markdownImages(options: ImageOptions): Extension {
|
||||
view.state.readOnly
|
||||
)
|
||||
return false;
|
||||
this.insert(
|
||||
paths.map((path) => async () => {
|
||||
// OS paths belong to this client even in a remote project.
|
||||
const url = await invokeLocal<string>("fs_read_image", { path });
|
||||
return { blob: url, name: path.replace(/^.*[\\/]/, "") };
|
||||
}),
|
||||
view.posAtCoords({ x, y }) ?? view.state.selection.main.head,
|
||||
);
|
||||
this.insert(paths.map(fileSource), view.posAtCoords({ x, y }) ?? view.state.selection.main.head);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
@@ -150,8 +168,9 @@ export function markdownImages(options: ImageOptions): Extension {
|
||||
destroy() {
|
||||
this.alive = false;
|
||||
this.unregister();
|
||||
if (imageInserters.get(this.view) === this.insertSources) imageInserters.delete(this.view);
|
||||
}
|
||||
insert(sources: Array<() => Promise<{ blob: Blob | string; name: string }>>, position?: number) {
|
||||
insert(sources: ImageSource[], position?: number) {
|
||||
const selection = this.view.state.selection.main;
|
||||
const range = { from: position ?? selection.from, to: position ?? selection.to };
|
||||
this.pending.add(range);
|
||||
|
||||
@@ -21,6 +21,8 @@ import {
|
||||
_provideOpenEditorPaths,
|
||||
_setActiveEditor,
|
||||
focusedCellEditor,
|
||||
isLibraryPath,
|
||||
markLibraryFile,
|
||||
shownLine,
|
||||
type NavigationLocation,
|
||||
} from "@/editor/api";
|
||||
@@ -114,7 +116,14 @@ import {
|
||||
import { EditorSlot, type SlotHost } from "./model/slot";
|
||||
import { NavigationHistory } from "./model/navHistory";
|
||||
import { EditHistory } from "./model/editHistory";
|
||||
import { loadSession, restoreTabsState, serializeSession, storeSession, type FileViewState } from "./model/session";
|
||||
import {
|
||||
loadSession,
|
||||
restoreTabsState,
|
||||
serializeSession,
|
||||
sessionLibraryFiles,
|
||||
storeSession,
|
||||
type FileViewState,
|
||||
} from "./model/session";
|
||||
import { docBackend, type DocBackend } from "./backend";
|
||||
import { isClassFile } from "@/platform/classFiles";
|
||||
import { isVirtualUri, virtualDocument } from "@/platform/virtualDocs";
|
||||
@@ -663,7 +672,7 @@ export class EditorController implements SlotHost {
|
||||
const kinds = useContributions.getState().editorKinds;
|
||||
storeSession(
|
||||
root,
|
||||
serializeSession(useTabs.getState(), files, (input) => !!kinds.get(input.kind)?.restorable),
|
||||
serializeSession(useTabs.getState(), files, (input) => !!kinds.get(input.kind)?.restorable, isLibraryPath),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -700,6 +709,8 @@ export class EditorController implements SlotHost {
|
||||
if (this.forgottenSessions.delete(root)) return;
|
||||
const session = loadSession(root);
|
||||
if (!session) return;
|
||||
// Before the documents open: a library source opens read-only.
|
||||
for (const path of sessionLibraryFiles(session)) markLibraryFile(path);
|
||||
const state = restoreTabsState(session, fileKey);
|
||||
const kinds = useContributions.getState().editorKinds;
|
||||
for (const pane of Object.values(state.panes))
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
parseSession,
|
||||
restoreTabsState,
|
||||
serializeSession,
|
||||
sessionLibraryFiles,
|
||||
slashPath,
|
||||
storeSession,
|
||||
type EditorSession,
|
||||
@@ -59,6 +60,17 @@ describe("editor session", () => {
|
||||
expect(r.layout).toMatchObject({ kind: "split", dir: "column" });
|
||||
});
|
||||
|
||||
it("remembers which file tabs are library sources", () => {
|
||||
let s = initialTabsState();
|
||||
s = open(s, "/p/main.swift");
|
||||
s = open(s, "/tmp/sk/Swift.String.swiftinterface");
|
||||
const library = (path: string) => path.endsWith(".swiftinterface");
|
||||
const session = serializeSession(s, {}, undefined, library)!;
|
||||
const parsed = parseSession(JSON.parse(JSON.stringify(session)))!;
|
||||
expect(sessionLibraryFiles(parsed)).toEqual(["/tmp/sk/Swift.String.swiftinterface"]);
|
||||
expect(sessionLibraryFiles(parseSession(JSON.parse(JSON.stringify(serializeSession(s, {})!)))!)).toEqual([]);
|
||||
});
|
||||
|
||||
it("saves tabs of restorable editor kinds with their input", () => {
|
||||
let s = initialTabsState();
|
||||
s = open(s, "/p/a.ts");
|
||||
|
||||
@@ -18,6 +18,8 @@ export interface SessionTab {
|
||||
input?: EditorInput;
|
||||
pinned?: boolean;
|
||||
preview?: boolean;
|
||||
/** A library source (read-only), e.g. an SDK interface code navigation opened outside the project. */
|
||||
library?: boolean;
|
||||
}
|
||||
|
||||
export type SessionLayout =
|
||||
@@ -43,11 +45,15 @@ const STORAGE_PREFIX = "openidea.editorSession.v1:";
|
||||
|
||||
const isFileTab = (t: Tab) => t.input.kind === "file" && !!t.input.path;
|
||||
|
||||
/** `restorable`: whether a non-file tab is saved (its kind asked for it). */
|
||||
/**
|
||||
* `restorable`: whether a non-file tab is saved (its kind asked for it). `library`: whether a
|
||||
* file tab shows a library source, so it opens read-only again.
|
||||
*/
|
||||
export function serializeSession(
|
||||
s: TabsState,
|
||||
files: Record<string, FileViewState>,
|
||||
restorable: (input: EditorInput) => boolean = () => false,
|
||||
library: (path: string) => boolean = () => false,
|
||||
): EditorSession | null {
|
||||
const saved = (t: Tab) => isFileTab(t) || (t.input.kind !== "file" && restorable(t.input));
|
||||
const walk = (n: LayoutNode): SessionLayout | null => {
|
||||
@@ -66,6 +72,7 @@ export function serializeSession(
|
||||
...(isFileTab(t) ? { path: t.input.path! } : { input: { ...t.input } }),
|
||||
...(t.pinned ? { pinned: true } : {}),
|
||||
...(t.preview ? { preview: true } : {}),
|
||||
...(isFileTab(t) && library(t.input.path!) ? { library: true } : {}),
|
||||
})),
|
||||
active,
|
||||
};
|
||||
@@ -151,6 +158,17 @@ export function parseSession(raw: unknown): EditorSession | null {
|
||||
};
|
||||
}
|
||||
|
||||
/** Paths of the file tabs saved as library sources. */
|
||||
export function sessionLibraryFiles(session: EditorSession): string[] {
|
||||
const out: string[] = [];
|
||||
const walk = (l: SessionLayout) =>
|
||||
l.kind === "pane"
|
||||
? l.tabs.forEach((t) => t.library === true && t.path && out.push(t.path))
|
||||
: l.children.forEach(walk);
|
||||
walk(session.layout);
|
||||
return out;
|
||||
}
|
||||
|
||||
let seq = 0;
|
||||
const id = (p: string) => `${p}r${++seq}`;
|
||||
|
||||
|
||||
@@ -283,6 +283,63 @@ describe("applying completions", () => {
|
||||
expect(view.state.selection.main.head).toBe(14);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ doc: " @Over|\n", prefix: "Over", label: "Override", expected: " @Override|\n" },
|
||||
{ doc: '@Supp|("unused")', prefix: "Supp", label: "SuppressWarnings", expected: '@SuppressWarnings|("unused")' },
|
||||
{ doc: "@java.lang.Over|", prefix: "Over", label: "Override", expected: "@java.lang.Override|" },
|
||||
{
|
||||
doc: "@Over| public void run() {}",
|
||||
prefix: "Over",
|
||||
label: "Override",
|
||||
expected: "@Override| public void run() {}",
|
||||
},
|
||||
{
|
||||
doc: "@Over|public void run() {}",
|
||||
prefix: "Over",
|
||||
label: "Override",
|
||||
expected: "@Override |public void run() {}",
|
||||
},
|
||||
{ doc: "implements Run|\n", prefix: "Run", label: "Runnable", expected: "implements Runnable |\n" },
|
||||
])("applies a Java interface completion in $doc", ({ doc, prefix, label, expected }) => {
|
||||
const { view, req, pos } = setup(doc);
|
||||
const suggestion = item({ label, kind: "interface", insertText: `${label} `, isSnippet: true });
|
||||
apply(view, makeCompletion(suggestion, { ...req, language: "java" }), pos - prefix.length);
|
||||
expect(view.state.doc.toString()).toBe(expected.replace("|", ""));
|
||||
expect(view.state.selection.main.head).toBe(expected.indexOf("|"));
|
||||
});
|
||||
|
||||
it("replaces a Java annotation name before its existing arguments with Tab", () => {
|
||||
const { view, req, pos } = setup('@Sup|pressWarnings("unused")');
|
||||
const suggestion = item({
|
||||
label: "SuppressWarnings",
|
||||
kind: "interface",
|
||||
insertText: "SuppressWarnings ",
|
||||
isSnippet: true,
|
||||
replaceRange: { start: { line: 0, col: 1 }, end: { line: 0, col: pos } },
|
||||
replaceRangeTab: { start: { line: 0, col: 1 }, end: { line: 0, col: 17 } },
|
||||
});
|
||||
applyLspCompletion(view, makeCompletion(suggestion, { ...req, language: "java" }), 1, pos, "replace");
|
||||
expect(view.state.doc.toString()).toBe('@SuppressWarnings("unused")');
|
||||
expect(view.state.selection.main.head).toBe(17);
|
||||
});
|
||||
|
||||
it("keeps spacing in a Java annotation attribute completion", () => {
|
||||
const { view, req } = setup("@Tag(va|)");
|
||||
const suggestion = item({ label: "value", kind: "field", insertText: "value = ", isSnippet: true });
|
||||
apply(view, makeCompletion(suggestion, { ...req, language: "java" }), 5);
|
||||
expect(view.state.doc.toString()).toBe("@Tag(value = )");
|
||||
expect(view.state.selection.main.head).toBe(13);
|
||||
});
|
||||
|
||||
it("accounts for what follows each Java annotation when completing at several carets", () => {
|
||||
const { view, req } = setup("@Ov|\n@Ovpublic void run() {}", "", [EditorState.allowMultipleSelections.of(true)]);
|
||||
view.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(3), EditorSelection.cursor(7)]) });
|
||||
const suggestion = item({ label: "Override", kind: "interface", insertText: "Override ", isSnippet: true });
|
||||
applyLspCompletion(view, makeCompletion(suggestion, { ...req, language: "java" }), 1, 3, "insert");
|
||||
expect(view.state.doc.toString()).toBe("@Override\n@Override public void run() {}");
|
||||
expect(view.state.selection.ranges.map((r) => r.head)).toEqual([9, 20]);
|
||||
});
|
||||
|
||||
it("lets Tab step out of the parentheses a completion inserted", () => {
|
||||
const { view, req } = setup("service.cr|", "", [tabOut]);
|
||||
applyLspCompletion(view, makeCompletion(item(), req), 8, 10, "insert");
|
||||
|
||||
@@ -245,6 +245,23 @@ function applyLsp(view: EditorView, completion: Completion, from: number, to: nu
|
||||
applyLspCompletion(view, completion, from, to, replaceMode ? "replace" : "insert");
|
||||
}
|
||||
|
||||
function completionInsertText(
|
||||
item: CompletionItem,
|
||||
language: string | null,
|
||||
doc: Text,
|
||||
from: number,
|
||||
to: number,
|
||||
): string {
|
||||
const { insertText } = item;
|
||||
// JDT LS can append a space to a bare annotation name. It is useful only as a separator.
|
||||
if (language !== "java" || item.kind !== "interface" || insertText !== `${item.label} `) return insertText;
|
||||
const line = doc.lineAt(from);
|
||||
const before = line.text.slice(0, from - line.from);
|
||||
const after = doc.sliceString(to, to + 2);
|
||||
if (!/@(?:[\p{L}\p{N}\p{M}_$]+\.)*$/u.test(before) || identifierEnd(after, 0) > 0) return insertText;
|
||||
return item.label;
|
||||
}
|
||||
|
||||
/** ↵ (`insert`) or ⇥ (`replace`: also overwrites the rest of the identifier). */
|
||||
export function applyLspCompletion(
|
||||
view: EditorView,
|
||||
@@ -291,6 +308,7 @@ export function applyLspCompletion(
|
||||
return;
|
||||
}
|
||||
|
||||
const insertText = completionInsertText(item, req.language, state.doc, start, end);
|
||||
let insertedParens: ReturnType<typeof callParens> = null;
|
||||
let bareCall: number | null = null;
|
||||
if (item.isSnippet) {
|
||||
@@ -300,7 +318,7 @@ export function applyLspCompletion(
|
||||
start = tr.changes.mapPos(start, 1);
|
||||
end = tr.changes.mapPos(end, 1);
|
||||
}
|
||||
const source = lspSnippetToCm(item.insertText, snippetVariables(req.path));
|
||||
const source = lspSnippetToCm(insertText, snippetVariables(req.path));
|
||||
applySnippet(view, [{ from: start, to: end, snippet: source }], completion);
|
||||
// A call snippet without a stop (`ArrayList<>()`): the caret goes inside until
|
||||
// signature help says there is nothing to pass.
|
||||
@@ -320,7 +338,7 @@ export function applyLspCompletion(
|
||||
? callParens(item, state.doc.lineAt(start), start, end)
|
||||
: null;
|
||||
insertedParens = parens;
|
||||
const changes = state.changes([...extra, { from: start, to: end, insert: item.insertText + (parens ? "()" : "") }]);
|
||||
const changes = state.changes([...extra, { from: start, to: end, insert: insertText + (parens ? "()" : "") }]);
|
||||
const caret = changes.mapPos(end, 1) - (parens === "inside" ? 1 : 0);
|
||||
view.dispatch({
|
||||
changes,
|
||||
@@ -391,11 +409,13 @@ function applyAtCarets(
|
||||
|
||||
// Parentheses depend on what follows each site: `a.cr|` gets them, `b.cr|()` does not.
|
||||
const textAt = (site: { from: number; to: number }): { text: string; caret: number } => {
|
||||
if (item.isSnippet) return lspSnippetToPlainWithCaret(item.insertText, snippetVariables(completion.req.path));
|
||||
const { language, path } = completion.req;
|
||||
const insertText = completionInsertText(item, language, state.doc, site.from, site.to);
|
||||
if (item.isSnippet) return lspSnippetToPlainWithCaret(insertText, snippetVariables(path));
|
||||
const parens = editorPrefs().completion.insertParentheses
|
||||
? callParens(item, state.doc.lineAt(site.from), site.from, site.to)
|
||||
: null;
|
||||
const text = item.insertText + (parens ? "()" : "");
|
||||
const text = insertText + (parens ? "()" : "");
|
||||
return { text, caret: text.length - (parens === "inside" ? 1 : 0) };
|
||||
};
|
||||
const texts = sites.map(textAt);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { EditorState, Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { viewShown, type EditorDocContext } from "@/editor/api";
|
||||
import { setLibraryRoots, viewShown, type EditorDocContext } from "@/editor/api";
|
||||
import { lspDoc } from "./lsp";
|
||||
import type { Diagnostic } from "@/bindings";
|
||||
import {
|
||||
@@ -60,6 +60,20 @@ describe("editor diagnostics store", () => {
|
||||
expect(calls).toBe(3);
|
||||
off();
|
||||
});
|
||||
it("keeps no diagnostics for library sources", () => {
|
||||
const dispose = setLibraryRoots("test", ["/sdk"]);
|
||||
const stop = installDiagnosticsEvents();
|
||||
emitLocalIdeEvent({
|
||||
type: "diagnostics",
|
||||
path: "/sdk/Swift.String.swiftinterface",
|
||||
source: "sk",
|
||||
items: [d(0, 0, 1)],
|
||||
});
|
||||
setFileDiagnostics("/sdk/Swift.String.swiftinterface", "local", [d(1, 0, 1)]);
|
||||
expect(diagnosticsFor("/sdk/Swift.String.swiftinterface")).toEqual([]);
|
||||
stop();
|
||||
dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe("toLintDiagnostics", () => {
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { Diagnostic, Severity } from "@/bindings";
|
||||
import { commands, ideEventsReady, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { publishLocalDiagnostics } from "@/platform/localDiagnostics";
|
||||
import { intentionsChanged, scrollbarMarks, shownAgain, type ScrollbarMark } from "@/editor/api";
|
||||
import { intentionsChanged, isLibraryPath, scrollbarMarks, shownAgain, type ScrollbarMark } from "@/editor/api";
|
||||
import { rangeToOffsets } from "./positions";
|
||||
import { lspDoc } from "./lsp";
|
||||
import { showHint } from "./hint";
|
||||
@@ -54,6 +54,9 @@ export function setFileDiagnostics(path: string, source: string, items: Diagnost
|
||||
}
|
||||
|
||||
function storeDiagnostics(path: string, source: string, items: Diagnostic[], published = false) {
|
||||
// A library source opens read-only: errors a server reports in it (an SDK interface it
|
||||
// generated, a dependency's code) are not the user's to fix.
|
||||
if (isLibraryPath(path)) items = [];
|
||||
let sources = byPath.get(path);
|
||||
if (!items.length) {
|
||||
if (!sources?.delete(source) && !published) return;
|
||||
|
||||
@@ -66,6 +66,8 @@ import {
|
||||
isDeclarationName,
|
||||
isSelfTarget,
|
||||
localHighlights,
|
||||
projectIndexDefinitions,
|
||||
usageRole,
|
||||
type DeclarationTarget,
|
||||
} from "./syntaxFallback";
|
||||
import { showHint, showPendingHint } from "./hint";
|
||||
@@ -112,6 +114,27 @@ export async function navigateTo(loc: Location) {
|
||||
await openCodeLocation(loc.path, { line: loc.range.start.line, col: loc.range.start.col });
|
||||
}
|
||||
|
||||
const CLANGD_LANGUAGES = new Set(["c", "cpp", "objective-c", "objective-cpp"]);
|
||||
const CLANGD_SYNTAX_NOTE = "Based on syntax and the project index";
|
||||
const C_HEADER = /\.(?:h|hh|hpp|hxx|h\+\+)$/i;
|
||||
|
||||
/** `pki_check_bin` for `.../pki_check_bin.h`: the stem a source counterpart shares. */
|
||||
function fileStem(path: string): string {
|
||||
const name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
|
||||
const dot = name.lastIndexOf(".");
|
||||
return (dot > 0 ? name.slice(0, dot) : name).toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* `pki_check_bin.c` for `pki_check_bin.h`, or every source when no stem matches: the same
|
||||
* declaration can be implemented in another component (a kernel tree holds many copies).
|
||||
*/
|
||||
function counterpartSources(header: string, sources: readonly DeclarationTarget[]): readonly DeclarationTarget[] {
|
||||
const stem = fileStem(header);
|
||||
const own = sources.filter((l) => fileStem(l.path) === stem);
|
||||
return own.length ? own : sources;
|
||||
}
|
||||
|
||||
const NOT_FOUND: Record<GotoKind, string> = {
|
||||
definition: "Cannot find declaration to go to",
|
||||
declaration: "Cannot find declaration to go to",
|
||||
@@ -373,6 +396,18 @@ async function onDeclarationName(view: EditorView, offset: number): Promise<bool
|
||||
return isDeclarationName(at);
|
||||
}
|
||||
|
||||
/** Whether the caret is on a function call, not a declaration whose self-target is legitimate. */
|
||||
async function onCallName(doc: EditorDocContext, pos: Pos): Promise<boolean> {
|
||||
const at = await structure.nodeAt(doc.doc, { start: pos, end: pos }).catch(() => null);
|
||||
return usageRole(at) === "call";
|
||||
}
|
||||
|
||||
/** A C-family member must come from its receiver's type, not a project-wide bare-name lookup. */
|
||||
async function onMemberName(doc: EditorDocContext, pos: Pos): Promise<boolean> {
|
||||
const at = await structure.nodeAt(doc.doc, { start: pos, end: pos }).catch(() => null);
|
||||
return at?.node.kind === "field_identifier" || at?.node.kind === "property_identifier";
|
||||
}
|
||||
|
||||
/**
|
||||
* Go to Implementation targets for Python from the IDE's inheritance graph: its servers
|
||||
* declare no type hierarchy and analyse one root, so the graph also knows the attached
|
||||
@@ -400,7 +435,20 @@ async function implementationFallbackTargets(
|
||||
pos: Pos,
|
||||
): Promise<readonly DeclarationTarget[]> {
|
||||
const declaration = await requestNavigation(view, offset, "definition").catch(() => []);
|
||||
return declaration.filter((l) => !isSelfTarget([l], path, pos));
|
||||
const targets = declaration.filter((l) => !isSelfTarget([l], path, pos));
|
||||
if (targets.length) return targets;
|
||||
const doc = docOf(view);
|
||||
if (!doc || !CLANGD_LANGUAGES.has(doc.language)) return targets;
|
||||
// Without a compilation database clangd only sees this header. Look the name up in the
|
||||
// project index for a source definition; never offer another header declaration.
|
||||
const name = nameAt(view, offset) ?? (offset > 0 ? nameAt(view, offset - 1) : null);
|
||||
if (!name) return targets;
|
||||
const indexed = await projectIndexDefinitions(path, name, "call").catch(() => []);
|
||||
const sources = indexed.filter((l) => !isSelfTarget([l], path, pos) && !C_HEADER.test(l.path));
|
||||
if (!sources.length) return targets;
|
||||
// The caret's own header names the source that implements it: its stem picks that source
|
||||
// among same-name definitions elsewhere instead of turning the jump into a chooser.
|
||||
return C_HEADER.test(path) ? counterpartSources(path, sources) : sources;
|
||||
}
|
||||
|
||||
/** Whether `line` (0-based) of `text` is an import statement. */
|
||||
@@ -495,6 +543,7 @@ async function gotoResolved(
|
||||
const pos = offsetToPos(view.state.doc, offset);
|
||||
let locs: DeclarationTarget[];
|
||||
let fromSyntax = false;
|
||||
let syntaxNote = SYNTAX_NOTE;
|
||||
const declaration = kind === "definition" || kind === "declaration";
|
||||
// A segment of an import path names a file — possibly in a dependency project, which
|
||||
// neither the single-root server nor the name index resolves.
|
||||
@@ -580,6 +629,35 @@ async function gotoResolved(
|
||||
const declarationTargets = await implementationFallbackTargets(view, offset, doc.path, pos);
|
||||
if (superseded()) return;
|
||||
locs = dedupeLocations(declarationTargets);
|
||||
if (declarationTargets.some((target) => target.name && target.kind)) {
|
||||
fromSyntax = true;
|
||||
syntaxNote = CLANGD_SYNTAX_NOTE;
|
||||
}
|
||||
}
|
||||
// Without a compilation database clangd may not resolve nested #include files. Its empty
|
||||
// answer is not authoritative for these languages; the project index still has the local
|
||||
// declarations. An implicit C declaration can also point at the call itself: replace that
|
||||
// pseudo target only when syntax and the index provide a real target elsewhere.
|
||||
if (declaration && !fromSyntax && CLANGD_LANGUAGES.has(doc.language)) {
|
||||
const selfTargets = locs.length > 0 && locs.every((l) => isSelfTarget([l], doc.path, pos));
|
||||
if (!locs.length || (selfTargets && (await onCallName(doc, pos)))) {
|
||||
const fallback = await gotoFallback(view, doc, pos, false);
|
||||
if (fallback?.length) {
|
||||
if (!locs.length) {
|
||||
locs = fallback;
|
||||
fromSyntax = true;
|
||||
syntaxNote = CLANGD_SYNTAX_NOTE;
|
||||
} else {
|
||||
const elsewhere = fallback.filter((l) => !isSelfTarget([l], doc.path, pos));
|
||||
if (elsewhere.length) {
|
||||
locs = elsewhere;
|
||||
fromSyntax = true;
|
||||
syntaxNote = CLANGD_SYNTAX_NOTE;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (superseded()) return;
|
||||
}
|
||||
if (!locs.length) {
|
||||
// The server has no definition here: a link (`href`, `#include`, Markdown) or a file path.
|
||||
@@ -600,8 +678,12 @@ async function gotoResolved(
|
||||
}
|
||||
// The server only resolves what it sees: answer from the project index, which also
|
||||
// covers attached dependency projects (an unresolved import into them). Never for a
|
||||
// module path: a segment is not a symbol name.
|
||||
if (declaration && !fromSyntax && !moduleName) {
|
||||
// module path: a segment is not a symbol name. A C-family member needs its receiver's
|
||||
// type, so a bare-name dependency lookup would be a guess here too.
|
||||
const clangMember =
|
||||
declaration && !fromSyntax && CLANGD_LANGUAGES.has(doc.language) && (await onMemberName(doc, pos));
|
||||
if (superseded()) return;
|
||||
if (declaration && !fromSyntax && !moduleName && !clangMember) {
|
||||
const name = nameAt(view, offset);
|
||||
const targets = name ? await indexDefinitions(doc.path, name).catch(() => []) : [];
|
||||
if (targets.length) {
|
||||
@@ -687,7 +769,7 @@ async function gotoResolved(
|
||||
setTimeout(() => {
|
||||
if (superseded()) return;
|
||||
const target = activeEditor()?.view;
|
||||
if (target) showHint(target, SYNTAX_NOTE, { timeout: 2500 });
|
||||
if (target) showHint(target, syntaxNote, { timeout: 2500 });
|
||||
}, 150);
|
||||
return;
|
||||
}
|
||||
@@ -775,11 +857,16 @@ async function followReferenceAt(
|
||||
}
|
||||
|
||||
/** Declaration targets from the structure service; null when it cannot answer for this file. */
|
||||
async function gotoFallback(view: EditorView, doc: EditorDocContext, pos: Pos): Promise<DeclarationTarget[] | null> {
|
||||
async function gotoFallback(
|
||||
view: EditorView,
|
||||
doc: EditorDocContext,
|
||||
pos: Pos,
|
||||
allowMember = true,
|
||||
): Promise<DeclarationTarget[] | null> {
|
||||
try {
|
||||
await whenSynced(view);
|
||||
const text = view.state.doc;
|
||||
const fb = await declarationFallback(doc, text, pos);
|
||||
const fb = await declarationFallback(doc, text, pos, undefined, allowMember);
|
||||
return fb.kind === "unsupported" ? null : fb.targets;
|
||||
} catch (e) {
|
||||
console.debug("[syntax] declaration fallback", e);
|
||||
@@ -936,11 +1023,14 @@ async function probeNavigation(
|
||||
navigable = !!(await gotoFallback(view, doc, pos))?.length;
|
||||
fromSyntax = true;
|
||||
}
|
||||
if (!navigable && !fromSyntax && CLANGD_LANGUAGES.has(doc.language))
|
||||
navigable = !!(await gotoFallback(view, doc, pos, false))?.length;
|
||||
if (!navigable && WEB_LANGUAGES.has(doc.language) && !doc.virtual)
|
||||
navigable = !!(await lspRequest(() => commands.webGoto(doc.doc, pos)).catch(() => null))?.targets.length;
|
||||
// The index answers across dependency roots too (unresolved imports), but a module path
|
||||
// segment is a file rather than a name.
|
||||
if (!navigable && !fromSyntax) {
|
||||
// segment is a file rather than a name. Keep member probing consistent with the click path.
|
||||
const clangMember = !fromSyntax && CLANGD_LANGUAGES.has(doc.language) && (await onMemberName(doc, pos));
|
||||
if (!navigable && !fromSyntax && !clangMember) {
|
||||
const moduleName = importModuleName(view, doc, offset);
|
||||
if (moduleName) navigable = !!(await moduleFile(doc, moduleName).catch(() => null));
|
||||
else {
|
||||
|
||||
@@ -3,9 +3,11 @@ import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { commands, Location } from "@/platform/ipc";
|
||||
|
||||
const { lspGoto, lspGotoImplementation } = vi.hoisted(() => ({
|
||||
const { lspGoto, lspGotoImplementation, findSymbols, navIndexDefinitions } = vi.hoisted(() => ({
|
||||
lspGoto: vi.fn<typeof commands.lspGoto>(),
|
||||
lspGotoImplementation: vi.fn<typeof commands.lspGotoImplementation>(),
|
||||
findSymbols: vi.fn<typeof commands.findSymbols>(),
|
||||
navIndexDefinitions: vi.fn<typeof commands.navIndexDefinitions>(),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const real = await orig<typeof import("@/platform/ipc")>();
|
||||
@@ -17,7 +19,15 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
return {
|
||||
...real,
|
||||
isTauri: () => true,
|
||||
commands: { ...real.commands, lspGoto, lspGotoImplementation, fsReadText, navInheritance },
|
||||
commands: {
|
||||
...real.commands,
|
||||
lspGoto,
|
||||
lspGotoImplementation,
|
||||
findSymbols,
|
||||
navIndexDefinitions,
|
||||
fsReadText,
|
||||
navInheritance,
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@tauri-apps/api/core", async (orig) => ({
|
||||
@@ -60,6 +70,8 @@ beforeEach(() => {
|
||||
invalidateConfigurationNavigation();
|
||||
lspGoto.mockResolvedValue(ok([]));
|
||||
lspGotoImplementation.mockResolvedValue(ok([]));
|
||||
findSymbols.mockResolvedValue({ status: "ok", data: [] });
|
||||
navIndexDefinitions.mockResolvedValue({ status: "ok", data: [] });
|
||||
view = editor(TEXT, "go", "/p/store.go");
|
||||
});
|
||||
afterEach(() => {
|
||||
@@ -154,4 +166,94 @@ describe("Go to Implementation on a symbol nothing implements", () => {
|
||||
await gotoTargets(view, "implementation", text.lastIndexOf("Order") + 2);
|
||||
expect(openFile).toHaveBeenCalledWith("/p/order.py", { selection: { line: 0, col: 6 }, focus: true });
|
||||
});
|
||||
|
||||
it("finds a C source definition from the project index when clangd only returns the header", async () => {
|
||||
const name = "verify_firmware";
|
||||
const text = `int ${name}(const char *signed_fw_path);\n`;
|
||||
const col = text.indexOf(name);
|
||||
const range = { start: { line: 0, col }, end: { line: 0, col: col + name.length } };
|
||||
const symbol = (path: string, line: number) => ({
|
||||
name,
|
||||
kind: "function" as const,
|
||||
container: null,
|
||||
path,
|
||||
relPath: path.slice(1),
|
||||
range: { start: { line, col }, end: { line, col: col + name.length } },
|
||||
score: 1,
|
||||
indices: [],
|
||||
});
|
||||
view.destroy();
|
||||
view = editor(text, "c", "/p/pki_check_bin.h");
|
||||
lspGoto.mockResolvedValue(ok([{ path: "/p/pki_check_bin.h", range }]));
|
||||
findSymbols.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [symbol("/p/pki_check_bin.h", 0), symbol("/p/pki_check_bin.c", 190)],
|
||||
});
|
||||
await gotoTargets(view, "implementation", col + 2);
|
||||
expect(findSymbols).toHaveBeenCalledWith(name, "all", 500);
|
||||
expect(openFile).toHaveBeenCalledWith("/p/pki_check_bin.c", { selection: { line: 190, col }, focus: true });
|
||||
expect(navIndexDefinitions).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not treat another header declaration as a C implementation", async () => {
|
||||
const name = "verify_firmware";
|
||||
const text = `int ${name}(const char *signed_fw_path);\n`;
|
||||
const col = text.indexOf(name);
|
||||
const range = { start: { line: 0, col }, end: { line: 0, col: col + name.length } };
|
||||
view.destroy();
|
||||
view = editor(text, "c", "/p/pki_check_bin.h");
|
||||
lspGoto.mockResolvedValue(ok([{ path: "/p/pki_check_bin.h", range }]));
|
||||
findSymbols.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [
|
||||
{
|
||||
name,
|
||||
kind: "function" as const,
|
||||
container: null,
|
||||
path: "/p/other.h",
|
||||
relPath: "p/other.h",
|
||||
range,
|
||||
score: 1,
|
||||
indices: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
await gotoTargets(view, "implementation", col + 2);
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No implementations found");
|
||||
});
|
||||
|
||||
it("prefers the header's own source among same-name definitions elsewhere", async () => {
|
||||
const name = "verify_firmware";
|
||||
const text = `int ${name}(const char *signed_fw_path);\n`;
|
||||
const col = text.indexOf(name);
|
||||
const range = { start: { line: 0, col }, end: { line: 0, col: col + name.length } };
|
||||
const symbol = (path: string, line: number) => ({
|
||||
name,
|
||||
kind: "function" as const,
|
||||
container: null,
|
||||
path,
|
||||
relPath: path.slice(1),
|
||||
range: { start: { line, col }, end: { line, col: col + name.length } },
|
||||
score: 1,
|
||||
indices: [],
|
||||
});
|
||||
view.destroy();
|
||||
view = editor(text, "c", "/p/pki_check_bin.h");
|
||||
lspGoto.mockResolvedValue(ok([{ path: "/p/pki_check_bin.h", range }]));
|
||||
findSymbols.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [
|
||||
symbol("/p/pki_check_bin.h", 0),
|
||||
symbol("/p/pki_check_bin.c", 190),
|
||||
symbol("/kernel/5.15/gvt/firmware.c", 149),
|
||||
symbol("/kernel/5.4/gvt/firmware.c", 154),
|
||||
],
|
||||
});
|
||||
await gotoTargets(view, "implementation", col + 2);
|
||||
expect(openFile).toHaveBeenCalledExactlyOnceWith("/p/pki_check_bin.c", {
|
||||
selection: { line: 190, col },
|
||||
focus: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -48,6 +48,8 @@ const { gotoTargets, navigationExtension, highlightUsages } = await import("./na
|
||||
const { registerNavigationProvider } = await import("@/editor/navigationProviders");
|
||||
const { startRename, renameNamePart } = await import("./rename");
|
||||
const { lspDoc } = await import("./lsp");
|
||||
const { usePlatform } = await import("@/platform/platformInfo");
|
||||
const { resetNavigationModifier } = await import("@/platform/navigationModifier");
|
||||
const { invalidateConfigurationNavigation } = await import("./configurationNavigation");
|
||||
const { useLspPopup, closePopup } = await import("./popupStore");
|
||||
const { inplaceRenameExtension, inplaceSession } = await import("./inplaceRename");
|
||||
@@ -211,6 +213,36 @@ describe("declarationFallback", () => {
|
||||
expect(res).toMatchObject({ kind: "targets", ambiguous: true });
|
||||
});
|
||||
|
||||
it("can reject a member reported by locals without querying the index", async () => {
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "foo", range: r(1, 6, 9), reason: "member" }));
|
||||
const res = await fb.declarationFallback(doc, text, { line: 1, col: 7 }, undefined, false);
|
||||
expect(res).toEqual({ kind: "targets", targets: [], ambiguous: false });
|
||||
expect(cmd.syntaxNodeAt).not.toHaveBeenCalled();
|
||||
expect(cmd.findSymbols).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("can reject a C field node when locals are unavailable", async () => {
|
||||
cmd.syntaxSupport.mockReturnValueOnce(ok({ tree: true, locals: false }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("field_identifier", r(1, 6, 9)), ancestors: [] }));
|
||||
const res = await fb.declarationFallback(
|
||||
{ ...doc, language: "c-fields" },
|
||||
text,
|
||||
{ line: 1, col: 7 },
|
||||
undefined,
|
||||
false,
|
||||
);
|
||||
expect(res).toEqual({ kind: "targets", targets: [], ambiguous: false });
|
||||
expect(cmd.findSymbols).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a no-identifier answer empty outside macro replacement bodies", async () => {
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "noIdentifier" }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("identifier", r(1, 6, 9)), ancestors: [] }));
|
||||
const res = await fb.declarationFallback(doc, text, { line: 1, col: 7 });
|
||||
expect(res).toEqual({ kind: "targets", targets: [], ambiguous: false });
|
||||
expect(cmd.findSymbols).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the node text for languages without locals, and gives up without a grammar", async () => {
|
||||
cmd.syntaxSupport.mockReturnValueOnce(ok({ tree: true, locals: false }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("identifier", r(1, 6, 9)), ancestors: [] }));
|
||||
@@ -345,6 +377,174 @@ describe("navigation wiring", () => {
|
||||
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("Cannot find declaration to go to");
|
||||
});
|
||||
|
||||
function clangCall(language: string, name = "indirect_call") {
|
||||
const text = `#include "direct.h"\nint main(void) { return ${name}(); }\n`;
|
||||
const path = language === "cpp" || language === "objective-cpp" ? "/p/main.cpp" : "/p/main.c";
|
||||
const col = text.split("\n")[1]!.indexOf(name);
|
||||
const range = r(1, col, col + name.length);
|
||||
const at: NodeAt = {
|
||||
node: node("identifier", range, "function"),
|
||||
ancestors: [node("call_expression", r(1, 0, text.split("\n")[1]!.length))],
|
||||
};
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name, range, reason: "topLevel" }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at));
|
||||
const view = editor(text, language, text.indexOf(name) + 2, path);
|
||||
return { view, path, range, at, name };
|
||||
}
|
||||
|
||||
it.each(["c", "cpp", "objective-c", "objective-cpp"])(
|
||||
"uses the local project index when clangd cannot resolve a nested include in %s",
|
||||
async (language) => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
const { view, name } = clangCall(language);
|
||||
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/include/indirect.h")]));
|
||||
await gotoTargets(view, "definition");
|
||||
expect(openFile).toHaveBeenCalledWith("/p/include/indirect.h", { selection: { line: 3, col: 4 }, focus: true });
|
||||
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("resolves a function name inside a C macro replacement body", async () => {
|
||||
const name = "sys_util_read_content";
|
||||
const text = `#define jy_read_country(buf, len) ${name}(FACTORY_DIR "country_code", buf, len)\n`;
|
||||
const col = text.indexOf(name);
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "noIdentifier" }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(
|
||||
ok({
|
||||
node: node("preproc_arg", r(0, col, text.length - 1), "value"),
|
||||
ancestors: [node("preproc_function_def", r(0, 0, text.length - 1))],
|
||||
}),
|
||||
);
|
||||
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/jtutil/jt_sys_util.h")]));
|
||||
const view = editor(text, "c", col + 2, "/p/jy_lib.h");
|
||||
await gotoTargets(view, "definition");
|
||||
expect(openFile).toHaveBeenCalledWith("/p/jtutil/jt_sys_util.h", {
|
||||
selection: { line: 3, col: 4 },
|
||||
focus: true,
|
||||
});
|
||||
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("underlines a nested-include call when the hover probe uses the same index fallback", async () => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
const { view, name } = clangCall("c");
|
||||
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/include/indirect.h")]));
|
||||
const os = usePlatform.getState().os;
|
||||
usePlatform.setState({ os: "macos" });
|
||||
resetNavigationModifier();
|
||||
const offset = view.state.doc.toString().indexOf(name) + 2;
|
||||
vi.spyOn(view, "posAtCoords").mockReturnValue(offset);
|
||||
try {
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, metaKey: true }));
|
||||
await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")).not.toBeNull());
|
||||
} finally {
|
||||
resetNavigationModifier();
|
||||
usePlatform.setState({ os });
|
||||
}
|
||||
});
|
||||
|
||||
it("replaces clangd's implicit-declaration self target with the indexed declaration", async () => {
|
||||
const { view, path, range, at, name } = clangCall("c");
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([{ path, range }]));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at));
|
||||
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/jtutil/jt_sys_util.h")]));
|
||||
executeAction.mockClear();
|
||||
await gotoTargets(view, "definition");
|
||||
expect(openFile).toHaveBeenCalledWith("/p/jtutil/jt_sys_util.h", {
|
||||
selection: { line: 3, col: 4 },
|
||||
focus: true,
|
||||
});
|
||||
expect(executeAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a legitimate declaration self target instead of replacing it from the index", async () => {
|
||||
const name = "indirect_call";
|
||||
const range = r(0, 4, 4 + name.length);
|
||||
const path = "/p/main.c";
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([{ path, range }]));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(
|
||||
ok({
|
||||
node: node("identifier", range, "declarator"),
|
||||
ancestors: [node("function_declarator", r(0, 0, 4 + name.length + 8))],
|
||||
}),
|
||||
);
|
||||
const view = editor(`int ${name}(void) { return 0; }\n`, "c", 6, path);
|
||||
executeAction.mockClear();
|
||||
await gotoTargets(view, "definition");
|
||||
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
|
||||
expect(cmd.findSymbols).not.toHaveBeenCalled();
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps clangd's original self target when the local index has no better answer", async () => {
|
||||
const { view, path, range, at } = clangCall("c");
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([{ path, range }]));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at));
|
||||
executeAction.mockClear();
|
||||
await gotoTargets(view, "definition");
|
||||
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not guess a C member declaration from unrelated project symbols", async () => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
const range = r(0, 3, 10);
|
||||
const at: NodeAt = { node: node("field_identifier", range, "field"), ancestors: [] };
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "handler", range, reason: "member" }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at)).mockReturnValueOnce(ok(at));
|
||||
cmd.navIndexDefinitions.mockReturnValue(ok([sym("handler", "method", "/p/other.c")]));
|
||||
try {
|
||||
const view = editor("s->handler();\n", "c", 5, "/p/main.c");
|
||||
await gotoTargets(view, "definition");
|
||||
expect(cmd.findSymbols).not.toHaveBeenCalled();
|
||||
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
cmd.navIndexDefinitions.mockReturnValue(ok([]));
|
||||
}
|
||||
});
|
||||
|
||||
it("does not underline a C member from a bare-name dependency candidate", async () => {
|
||||
const range = r(0, 3, 10);
|
||||
const at: NodeAt = { node: node("field_identifier", range, "field"), ancestors: [] };
|
||||
cmd.lspGoto.mockReturnValue(ok([]));
|
||||
cmd.syntaxLocals.mockReturnValue(ok({ status: "notLocal", name: "handler", range, reason: "member" }));
|
||||
cmd.syntaxNodeAt.mockReturnValue(ok(at));
|
||||
cmd.navIndexDefinitions.mockReturnValue(ok([sym("handler", "method", "/p/other.c")]));
|
||||
const view = editor("s->handler();\n", "c", 5, "/p/main.c");
|
||||
const os = usePlatform.getState().os;
|
||||
usePlatform.setState({ os: "macos" });
|
||||
resetNavigationModifier();
|
||||
vi.spyOn(view, "posAtCoords").mockReturnValue(5);
|
||||
try {
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, metaKey: true }));
|
||||
await vi.waitFor(() => expect(cmd.syntaxNodeAt).toHaveBeenCalled());
|
||||
expect(view.dom.querySelector(".cm-lsp-link")).toBeNull();
|
||||
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
resetNavigationModifier();
|
||||
usePlatform.setState({ os });
|
||||
cmd.lspGoto.mockReturnValue(unavailable());
|
||||
cmd.syntaxLocals.mockReturnValue(ok({ status: "noIdentifier" }));
|
||||
cmd.syntaxNodeAt.mockReturnValue(ok(null));
|
||||
cmd.navIndexDefinitions.mockReturnValue(ok([]));
|
||||
}
|
||||
});
|
||||
|
||||
it("shows ambiguous nested-include declarations as syntax-based candidates", async () => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
const { view, name } = clangCall("c");
|
||||
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/a.c"), sym(name, "function", "/p/include/a.h")]));
|
||||
await gotoTargets(view, "definition");
|
||||
const popup = useLspPopup.getState().popup;
|
||||
expect(popup?.kind).toBe("list");
|
||||
if (popup?.kind !== "list") return;
|
||||
expect(popup.title).toBe(`Choose Declaration of ${name} (2 found, based on syntax)`);
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("answers from the index when the server cannot resolve an import into a dependency project", async () => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
cmd.navIndexDefinitions.mockReturnValueOnce(ok([sym("ParallelDims", "class", "/deps/engine/model.py")]));
|
||||
|
||||
@@ -154,6 +154,20 @@ export async function indexDefinitions(path: string, name: string): Promise<Decl
|
||||
);
|
||||
}
|
||||
|
||||
/** Exact-name declarations from the whole project index, filtered by use and language family. */
|
||||
export async function projectIndexDefinitions(
|
||||
path: string,
|
||||
name: string,
|
||||
role: UsageRole,
|
||||
): Promise<DeclarationTarget[]> {
|
||||
const matches = await call(commands.findSymbols(name, "all", SYMBOL_LIMIT));
|
||||
const symbols = filterSymbols(matches, name, role).filter((s) => compatibleFiles(path, s.path));
|
||||
return rankTargets(
|
||||
symbols.map((s) => ({ path: s.path, range: s.range, name: s.name, kind: s.kind, container: s.container })),
|
||||
path,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Go to Declaration without a language server: a certain local definition,
|
||||
* otherwise project index symbols with exactly that name (filtered by the
|
||||
@@ -164,32 +178,43 @@ export async function declarationFallback(
|
||||
text: Text,
|
||||
pos: Pos,
|
||||
signal?: AbortSignal,
|
||||
allowMember = true,
|
||||
): Promise<DeclarationFallback> {
|
||||
const support = await structure.support(doc.language);
|
||||
if (!support.tree) return { kind: "unsupported" };
|
||||
let locals: Locals | null = null;
|
||||
if (support.locals) locals = await structure.locals(doc.doc, pos, { signal });
|
||||
if (locals?.status === "noIdentifier") return { kind: "targets", targets: [], ambiguous: false };
|
||||
if (locals?.status === "local") return { kind: "targets", ...localTargets(doc.path, locals.symbol) };
|
||||
if (!allowMember && locals?.status === "notLocal" && locals.reason === "member")
|
||||
return { kind: "targets", targets: [], ambiguous: false };
|
||||
|
||||
const at = await structure.nodeAt(doc.doc, { start: pos, end: pos }, { signal });
|
||||
const name = locals?.status === "notLocal" ? locals.name : identifierText(text, at);
|
||||
if (locals?.status === "noIdentifier" && at?.node.kind !== "preproc_arg")
|
||||
return { kind: "targets", targets: [], ambiguous: false };
|
||||
if (!allowMember && at?.node.kind === "field_identifier") return { kind: "targets", targets: [], ambiguous: false };
|
||||
const name = locals?.status === "notLocal" ? locals.name : identifierText(text, at, pos);
|
||||
if (!name) return { kind: "targets", targets: [], ambiguous: false };
|
||||
// A member (`obj.name`) can be any member of that name; only a plain name has a syntactic role.
|
||||
const role = locals?.status === "notLocal" && locals.reason === "member" ? "other" : usageRole(at);
|
||||
const matches = await call(commands.findSymbols(name, "all", SYMBOL_LIMIT));
|
||||
const symbols = filterSymbols(matches, name, role).filter((s) => compatibleFiles(doc.path, s.path));
|
||||
const targets = rankTargets(
|
||||
symbols.map((s) => ({ path: s.path, range: s.range, name: s.name, kind: s.kind, container: s.container })),
|
||||
doc.path,
|
||||
);
|
||||
const targets = await projectIndexDefinitions(doc.path, name, role);
|
||||
return { kind: "targets", targets, ambiguous: targets.length > 1 };
|
||||
}
|
||||
|
||||
const IDENT = /^[\p{L}_$][\p{L}\p{N}_$]*$/u;
|
||||
const IDENT_PART = /[\p{L}\p{N}_$]/u;
|
||||
|
||||
/** Name of a leaf identifier node (languages without `locals.scm`). */
|
||||
function identifierText(text: Text, at: NodeAt | null): string | null {
|
||||
/** Name of a leaf identifier node, or the identifier at `pos` in a macro replacement body. */
|
||||
function identifierText(text: Text, at: NodeAt | null, pos: Pos): string | null {
|
||||
if (at?.node.kind === "preproc_arg") {
|
||||
if (pos.line >= text.lines) return null;
|
||||
const line = text.line(pos.line + 1).text;
|
||||
let from = Math.min(pos.col, line.length);
|
||||
let to = from;
|
||||
while (from > 0 && IDENT_PART.test(line[from - 1]!)) from--;
|
||||
while (to < line.length && IDENT_PART.test(line[to]!)) to++;
|
||||
const name = line.slice(from, to);
|
||||
return IDENT.test(name) ? name : null;
|
||||
}
|
||||
if (!at || !/identifier|^name$|^constant$|^word$/.test(at.node.kind)) return null;
|
||||
const { from, to } = rangeToOffsets(text, at.node.range);
|
||||
const name = text.sliceString(from, to);
|
||||
|
||||
@@ -13,7 +13,8 @@
|
||||
* The cache outlives the editor view (switching tabs remounts it) until other
|
||||
* files change, a language server settles or its classpath changes: on some servers (jdtls) every
|
||||
* implementation search walks the whole workspace, so asking again is costly.
|
||||
* Library sources ask no inheritors from the server (`isLibrarySource`).
|
||||
* Library sources ask no inheritors from the server (`isLibrarySource`); explicit
|
||||
* Go to Implementation still answers.
|
||||
*/
|
||||
import { RangeSet, StateEffect, StateField, type EditorState, type Extension, type Text } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
@@ -826,11 +827,13 @@ class MarkersPlugin {
|
||||
}
|
||||
|
||||
/**
|
||||
* In a library every method's overriders would be searched for across the whole project,
|
||||
* one search per visible method: only its classes and interfaces get ↓ markers.
|
||||
* Library symbols are referenced everywhere, so an inheritor search walks the whole
|
||||
* project and its dependencies (jdtls builds a full type hierarchy). A JDK interface
|
||||
* such as `java.util.function.Function` then keeps the status bar at "Creating type
|
||||
* hierarchy" and times out. Keep super-method markers, but ask for no inheritors.
|
||||
*/
|
||||
export function libraryCandidates(candidates: readonly MarkerCandidate[]): MarkerCandidate[] {
|
||||
return candidates.map((c) => (c.method && c.inheritable ? { ...c, inheritable: false } : c));
|
||||
return candidates.map((c) => ({ ...c, inheritable: false, implicit: false }));
|
||||
}
|
||||
|
||||
/** LSP access for one pass: this document's outline as known, others' opened on demand, each asked once. */
|
||||
|
||||
@@ -517,18 +517,22 @@ describe("library sources", () => {
|
||||
[`${SHAPE_PATH}:1`]: [loc("/p/Circle.java", 2, 18), loc("/p/Square.java", 1, 18)],
|
||||
};
|
||||
|
||||
it("ask for the inheritors of types only, not one project-wide search per method", async () => {
|
||||
it("ask for no inheritors: a library type's search walks the whole project and its dependencies", async () => {
|
||||
const { deps, calls } = server(shapeImpls, {});
|
||||
const candidates = libraryCandidates(markerCandidates(SHAPE_OUTLINE, lines(SHAPE)));
|
||||
const cache = emptyCache();
|
||||
await fillMarkers(SHAPE_PATH, candidates, ALL, deps(SHAPE_PATH), cache);
|
||||
expect(calls.implementations).toEqual([[{ line: 0, col: 17 }]]);
|
||||
expect(cachedMarkers(candidates, ALL, cache).map((m) => [m.line, m.kind, m.tooltip])).toEqual([
|
||||
[0, "implemented", "Is implemented by Circle, Square"],
|
||||
]);
|
||||
expect(calls.implementations).toEqual([]);
|
||||
expect(calls.subtypes).toBe(0);
|
||||
expect(cachedMarkers(candidates, ALL, cache)).toEqual([]);
|
||||
});
|
||||
|
||||
it("still ask the server for inheritors and subtypes", async () => {
|
||||
it("also drops Go's implicit interface queries", () => {
|
||||
const candidates = libraryCandidates(markerCandidates(GO_OUTLINE, lines(GO), { implicitInterfaces: true }));
|
||||
expect(candidates.some((c) => c.inheritable || c.implicit)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps super-method queries available without enabling inheritor searches", async () => {
|
||||
const off = setLibraryRoots("test", ["/venv/site-packages"]);
|
||||
try {
|
||||
const library = {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useId, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { AgentForm, AgentFormField, AgentTask } from "@/bindings";
|
||||
import { Button, Checkbox, Input, Radio, T } from "@/ui";
|
||||
import type { PermissionEntry } from "./permission";
|
||||
@@ -48,7 +49,7 @@ export function FormCard({ task, entry, form }: { task: AgentTask; entry: Permis
|
||||
};
|
||||
return (
|
||||
<form
|
||||
className={styles.questionCard}
|
||||
className={clsx(styles.questionCard, styles.questionCardPinned)}
|
||||
aria-label={entry.title}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
|
||||
@@ -1632,9 +1632,11 @@
|
||||
font-size: var(--agent-fs-ui, var(--fs-ui));
|
||||
container: question-card / inline-size;
|
||||
}
|
||||
/* A question that outlived its turn waits above the composer, at the composer's width. */
|
||||
/* A question that outlived its turn waits above the composer, at the composer's width. It scrolls within at most
|
||||
half the window, and less when the session is shorter, so the composer and the card's buttons stay in view. */
|
||||
.questionCardPinned {
|
||||
flex: none;
|
||||
flex: 0 1 auto;
|
||||
min-height: 0;
|
||||
max-height: 50vh;
|
||||
overflow-y: auto;
|
||||
width: 100%;
|
||||
|
||||
@@ -276,6 +276,74 @@ describe("build feature", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps output the channel delivers after the build result (an >8 KiB line is fetched late)", async () => {
|
||||
// Tauri sends a channel message over 8 KiB through an async fetch and holds every later message
|
||||
// back to keep their order, so the command's result can arrive before the rest of the output.
|
||||
const run = startBuild("build");
|
||||
await act(async () => {});
|
||||
const long = `${"w".repeat(8_307)}`;
|
||||
const warning = warn("/p/src/B.java", 2);
|
||||
await act(async () => {
|
||||
fake.emit!({ kind: "output", text: "short\n", stderr: false });
|
||||
fake.resolve(result([warning], true));
|
||||
await run;
|
||||
});
|
||||
expect(useBuildRun.getState().status).toBe("success");
|
||||
await act(async () => {
|
||||
fake.emit!({ kind: "output", text: `${long}\n`, stderr: false });
|
||||
fake.emit!({ kind: "output", text: "stream-done\n", stderr: false });
|
||||
fake.emit!({ kind: "message", message: warning });
|
||||
fake.emit!({ kind: "progress", message: "late", fraction: null });
|
||||
fake.emit!({ kind: "output", text: "\nProcess finished with exit code 0\n", stderr: false });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
});
|
||||
const s = useBuildRun.getState();
|
||||
expect(s.lines.map((l) => l.text)).toEqual(["short", long, "stream-done", "", "Process finished with exit code 0"]);
|
||||
// The result already carries every message; a late one is not added twice.
|
||||
expect(s.messages).toEqual([warning]);
|
||||
expect(s.message).toBeNull();
|
||||
|
||||
// A newer build owns the console: the old channel's stragglers are dropped.
|
||||
const stale = fake.emit!;
|
||||
const second = startBuild("build");
|
||||
await act(async () => {});
|
||||
await act(async () => {
|
||||
stale({ kind: "output", text: "stale\n", stderr: false });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
});
|
||||
expect(useBuildRun.getState().lines.map((l) => l.text)).not.toContain("stale");
|
||||
await act(async () => {
|
||||
fake.resolve(result([], true));
|
||||
await second;
|
||||
});
|
||||
});
|
||||
|
||||
it("drops a finished build's late events once a launch build owns the Build window", async () => {
|
||||
const run = startBuild("build");
|
||||
await act(async () => {});
|
||||
const late = fake.emit!;
|
||||
await act(async () => {
|
||||
fake.resolve(result([], true));
|
||||
await run;
|
||||
});
|
||||
const follower = followLaunchBuild(44 as never, "Build before launch: App");
|
||||
follower.onEvent({ kind: "started", system: "maven", title: "launch" });
|
||||
await act(async () => {
|
||||
late({ kind: "step", command: "stale-step", cwd: "/stale" });
|
||||
late({ kind: "output", text: "stale\n", stderr: false });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
});
|
||||
const s = useBuildRun.getState();
|
||||
expect(s.lines.map((l) => l.text)).not.toContain("stale");
|
||||
expect(s.stepCwd).toBeNull();
|
||||
follower.finish("success");
|
||||
await act(async () => {
|
||||
late({ kind: "output", text: "stale2\n", stderr: false });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
});
|
||||
expect(useBuildRun.getState().lines.map((l) => l.text)).not.toContain("stale2");
|
||||
});
|
||||
|
||||
it("streams a failing build into the tree and console, then notifies and clears next time", async () => {
|
||||
const run = startBuild("build");
|
||||
await act(async () => {});
|
||||
|
||||
@@ -237,6 +237,9 @@ export async function startCompileFile(file: string, activate = true): Promise<B
|
||||
);
|
||||
}
|
||||
|
||||
/** The latest build: its channel may still deliver output after its result (see `executeBuild`). */
|
||||
let currentBuild: RequestId | null = null;
|
||||
|
||||
/** Streams one backend build into the Build tool window until it finishes. */
|
||||
async function executeBuild(
|
||||
request: RequestId,
|
||||
@@ -246,6 +249,13 @@ async function executeBuild(
|
||||
cancel: () => void,
|
||||
): Promise<BuildResult | null> {
|
||||
const ownsBuild = () => useBuildRun.getState().request === request;
|
||||
currentBuild = request;
|
||||
// Tauri delivers a channel message over 8 KiB through an async fetch and holds the later ones back
|
||||
// to keep their order, so output can still arrive after the command's result. It belongs to this
|
||||
// build until another build (or a launch build) takes the window; messages and progress are complete
|
||||
// in the result by then.
|
||||
const accepts = () => currentBuild === request;
|
||||
let finished = false;
|
||||
await maybeEditorService()
|
||||
?.saveAll()
|
||||
.catch(() => undefined);
|
||||
@@ -258,15 +268,17 @@ async function executeBuild(
|
||||
timer = undefined;
|
||||
const events = queue;
|
||||
queue = [];
|
||||
if (!ownsBuild() || !events.length) return;
|
||||
if (!accepts() || !events.length) return;
|
||||
let s = useBuildRun.getState();
|
||||
for (const e of events) s = { ...s, ...applyBuildEvent(s, e) };
|
||||
for (const e of events) {
|
||||
if (!finished || e.kind === "output" || e.kind === "step") s = { ...s, ...applyBuildEvent(s, e) };
|
||||
}
|
||||
useBuildRun.setState(s);
|
||||
if (s.message)
|
||||
if (!finished && s.message)
|
||||
upsertTask({ id: BUILD_TASK_ID, title: taskTitle, message: s.message, fraction: null, done: false, cancel });
|
||||
};
|
||||
const onEvent = (e: BuildEvent) => {
|
||||
if (!ownsBuild()) return;
|
||||
if (!accepts()) return;
|
||||
queue.push(e);
|
||||
timer ??= setTimeout(flush, 16);
|
||||
};
|
||||
@@ -276,6 +288,7 @@ async function executeBuild(
|
||||
result = await invoke(useBuildRun.getState().files, onEvent);
|
||||
if (!ownsBuild()) return null;
|
||||
flush();
|
||||
finished = true;
|
||||
const status: BuildStatus = result.success ? "success" : "failed";
|
||||
useBuildRun.setState({
|
||||
status,
|
||||
@@ -311,6 +324,7 @@ async function executeBuild(
|
||||
} catch (e) {
|
||||
if (!ownsBuild()) return null;
|
||||
flush();
|
||||
finished = true;
|
||||
if (isCancelled(e)) {
|
||||
useBuildRun.setState({ status: "cancelled", files: [], message: null });
|
||||
} else {
|
||||
@@ -385,6 +399,7 @@ export function followLaunchBuild(
|
||||
const take = () => {
|
||||
if (owned || isBuilding()) return;
|
||||
owned = true;
|
||||
currentBuild = null;
|
||||
const previous = useBuildRun.getState().files;
|
||||
useBuildRun.setState({ ...INITIAL, request, kind: "build", title, status: "running", files: previous });
|
||||
setContext(BUILD_LAST_STATUS, null);
|
||||
@@ -458,6 +473,7 @@ export function rerunBuild() {
|
||||
}
|
||||
|
||||
export function resetBuildRun() {
|
||||
currentBuild = null;
|
||||
stopBuild();
|
||||
removeTask(BUILD_TASK_ID);
|
||||
setContext(BUILD_RUNNING, false);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { Diagnostic } from "@/bindings";
|
||||
import { setLibraryRoots } from "@/editor/api";
|
||||
import { useProject } from "@/platform/project";
|
||||
import {
|
||||
applyDiagnosticsEvent,
|
||||
@@ -300,3 +301,15 @@ describe("incremental bookkeeping", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("library sources", () => {
|
||||
beforeEach(() => clearProblems());
|
||||
|
||||
it("are not the project's problems", () => {
|
||||
const dispose = setLibraryRoots("test", ["/sdk"]);
|
||||
applyDiagnosticsEvent("/sdk/Foundation.swiftinterface", "sk", [d(1)]);
|
||||
applyDiagnosticsEvent("/p/main.swift", "sk", [d(2)]);
|
||||
expect([...useProblems.getState().map.keys()]).toEqual(["/p/main.swift"]);
|
||||
dispose();
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
import { create } from "zustand";
|
||||
import type { Diagnostic, Severity } from "@/bindings";
|
||||
import { isLibraryPath } from "@/editor/api";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { onLocalDiagnostics } from "@/platform/localDiagnostics";
|
||||
import {
|
||||
@@ -256,6 +257,8 @@ function applyTo(snapshot: ProblemsSnapshot, path: string, source: string, items
|
||||
}
|
||||
|
||||
export function applyDiagnosticsEvent(path: string, source: string, items: readonly Diagnostic[]) {
|
||||
// Library sources (an SDK interface, a dependency's code) are not the project's problems.
|
||||
if (isLibraryPath(path)) items = [];
|
||||
useProblems.setState((s) => {
|
||||
// The file's sources map is replaced, not changed, so this is the list before the event.
|
||||
const before = mergedSources(s.map.get(path));
|
||||
|
||||
@@ -7,6 +7,7 @@ import { applyKeymapSettings, installKeyboardDispatcher, useKeymap } from "@/pla
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import {
|
||||
provideEditorService,
|
||||
registerExternalFileOpenHandler,
|
||||
registerProjectViewRoot,
|
||||
setFileDecorations,
|
||||
type EditorService,
|
||||
@@ -493,6 +494,28 @@ describe("ProjectView", () => {
|
||||
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: undefined, focus: true });
|
||||
});
|
||||
|
||||
it("selects a file opened externally on single click and opens it on double click", async () => {
|
||||
fs = new MemoryFs({ "/w/acme/notes.docx": "x" }, ROOT);
|
||||
setProjectFsForTests(fs, ROOT);
|
||||
initProjectTree(ROOT, "acme");
|
||||
const disposeExternal = registerExternalFileOpenHandler({
|
||||
id: "test.external",
|
||||
matches: (path) => path.endsWith(".docx"),
|
||||
open: vi.fn(async () => true),
|
||||
});
|
||||
try {
|
||||
const { row, rows } = setup();
|
||||
await waitFor(() => expect(rows()).toContain("notes.docx"));
|
||||
const content = row("notes.docx").querySelector("[data-project-path]")!;
|
||||
fireEvent.click(content, { detail: 1 });
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
fireEvent.doubleClick(row("notes.docx"));
|
||||
expect(openFile).toHaveBeenLastCalledWith("/w/acme/notes.docx", { preview: undefined, focus: true });
|
||||
} finally {
|
||||
disposeExternal();
|
||||
}
|
||||
});
|
||||
|
||||
it("opens a selected file in a read-only Quick Preview with Space without creating an editor tab", async () => {
|
||||
dispatchViaKeymap();
|
||||
ipc.fsReadText.mockResolvedValue(ok("# Preview\n\nRead without opening a tab."));
|
||||
|
||||
@@ -34,6 +34,7 @@ import { macStroke, strokeOf } from "@/platform/keymap";
|
||||
import {
|
||||
OWNS_FILE_DROP,
|
||||
getFileDecoration,
|
||||
opensExternally,
|
||||
prepareMenuGroups,
|
||||
useFileDecoration,
|
||||
useFileDecorations,
|
||||
@@ -718,6 +719,7 @@ export function ProjectView() {
|
||||
if (o.singleClickExpand) toggleExpanded(node);
|
||||
return;
|
||||
}
|
||||
if (opensExternally(node.path)) return;
|
||||
if (!o.singleClickOpen && !previewTabEnabled()) return;
|
||||
const opts = { preview: o.singleClickOpen ? undefined : true, focus: false };
|
||||
if (node.member) void revealRange(node.path, { start: node.member.selection_range.start }, opts);
|
||||
|
||||
@@ -13,32 +13,48 @@ import {
|
||||
type PopupAnchor,
|
||||
} from "@/ui";
|
||||
import { useRowHeight } from "@/ui/density";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { useRunConfigTypes, runConfigTypes, type RunConfigTypeContribution } from "@/workbench/contributions";
|
||||
import styles from "./Run.module.css";
|
||||
|
||||
export type TypeRow =
|
||||
| { kind: "group"; key: string; label: string }
|
||||
| { kind: "type"; key: string; type: RunConfigTypeContribution; indices: number[] | null; nested: boolean };
|
||||
| {
|
||||
kind: "type";
|
||||
key: string;
|
||||
type: RunConfigTypeContribution;
|
||||
/** The type's label in the UI language: what the row shows and the query matches. */
|
||||
label: string;
|
||||
indices: number[] | null;
|
||||
nested: boolean;
|
||||
};
|
||||
|
||||
const ROW = 24;
|
||||
|
||||
/** "Add New Configuration" rows: types by label, grouped ones under their group; filtered by `query`. */
|
||||
export function typeRows(types: readonly RunConfigTypeContribution[], query: string): TypeRow[] {
|
||||
/**
|
||||
* "Add New Configuration" rows: types by label, grouped ones under their group; filtered by `query`. Labels and groups
|
||||
* go through `translate` first, so the list is sorted, shown and searched in the UI language.
|
||||
*/
|
||||
export function typeRows(
|
||||
types: readonly RunConfigTypeContribution[],
|
||||
query: string,
|
||||
translate: (text: string) => string = (text) => text,
|
||||
): TypeRow[] {
|
||||
const q = query.trim();
|
||||
const match = (t: RunConfigTypeContribution) =>
|
||||
q ? (fuzzyMatch(t.label, q) ?? (t.group && fuzzyMatch(t.group, q) ? [] : null)) : null;
|
||||
q ? (fuzzyMatch(translate(t.label), q) ?? (t.group && fuzzyMatch(translate(t.group), q) ? [] : null)) : null;
|
||||
const rows: TypeRow[] = [];
|
||||
const groups = new Map<string, RunConfigTypeContribution[]>();
|
||||
const entries: Array<{ label: string; group?: string; type?: RunConfigTypeContribution }> = [];
|
||||
for (const t of types) {
|
||||
if (!t.group) {
|
||||
entries.push({ label: t.label, type: t });
|
||||
entries.push({ label: translate(t.label), type: t });
|
||||
continue;
|
||||
}
|
||||
let g = groups.get(t.group);
|
||||
if (!g) {
|
||||
groups.set(t.group, (g = []));
|
||||
entries.push({ label: t.group, group: t.group });
|
||||
entries.push({ label: translate(t.group), group: t.group });
|
||||
}
|
||||
g.push(t);
|
||||
}
|
||||
@@ -46,7 +62,8 @@ export function typeRows(types: readonly RunConfigTypeContribution[], query: str
|
||||
for (const e of entries) {
|
||||
if (e.type) {
|
||||
const indices = match(e.type);
|
||||
if (!q || indices) rows.push({ kind: "type", key: e.type.id, type: e.type, indices, nested: false });
|
||||
if (!q || indices)
|
||||
rows.push({ kind: "type", key: e.type.id, type: e.type, label: e.label, indices, nested: false });
|
||||
continue;
|
||||
}
|
||||
const members = groups
|
||||
@@ -54,8 +71,9 @@ export function typeRows(types: readonly RunConfigTypeContribution[], query: str
|
||||
.map((t) => ({ t, indices: match(t) }))
|
||||
.filter((x) => !q || x.indices);
|
||||
if (!members.length) continue;
|
||||
rows.push({ kind: "group", key: `group:${e.group}`, label: e.group! });
|
||||
for (const { t, indices } of members) rows.push({ kind: "type", key: t.id, type: t, indices, nested: true });
|
||||
rows.push({ kind: "group", key: `group:${e.group}`, label: e.label });
|
||||
for (const { t, indices } of members)
|
||||
rows.push({ kind: "type", key: t.id, type: t, label: translate(t.label), indices, nested: true });
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
@@ -73,7 +91,8 @@ export function AddConfigPopup({
|
||||
const types = useRunConfigTypes((s) => s.types);
|
||||
const rowHeight = useRowHeight(ROW);
|
||||
const [query, setQuery] = useState("");
|
||||
const rows = useMemo(() => typeRows(runConfigTypes(types), query), [types, query]);
|
||||
const tx = useTx();
|
||||
const rows = useMemo(() => typeRows(runConfigTypes(types), query, tx), [types, query, tx]);
|
||||
const isSection = (r: TypeRow) => r.kind === "group";
|
||||
const [active, setActive] = useState(-1);
|
||||
const clamped = Math.min(active, rows.length - 1);
|
||||
@@ -149,10 +168,13 @@ export function AddConfigPopup({
|
||||
}
|
||||
renderItem={(r) =>
|
||||
r.kind === "type" ? (
|
||||
<span className={clsx(styles.chooserRow, r.nested && styles.typeNested)} title={r.type.description}>
|
||||
<span
|
||||
className={clsx(styles.chooserRow, r.nested && styles.typeNested)}
|
||||
title={r.type.description && tx(r.type.description)}
|
||||
>
|
||||
<Icon name={r.type.icon} size={16} className={styles.chooserIcon} />
|
||||
<span className={styles.chooserName}>
|
||||
{r.indices?.length ? <HighlightedText text={r.type.label} indices={r.indices} /> : r.type.label}
|
||||
{r.indices?.length ? <HighlightedText text={r.label} indices={r.indices} /> : r.label}
|
||||
</span>
|
||||
</span>
|
||||
) : null
|
||||
|
||||
@@ -647,7 +647,7 @@ function EditConfigsDialog() {
|
||||
onClick={() => setSelection({ type: "template", kind: t.id })}
|
||||
>
|
||||
<Icon name={t.icon} size={13} className={styles.chooserIcon} />
|
||||
<span className={styles.chooserName}>{t.label}</span>
|
||||
<span className={styles.chooserName}>{tx(t.label)}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
runStart: vi.fn(async (_config: RunConfig) => ({ status: "ok", data: 1 })),
|
||||
runStop: vi.fn(async () => ({ status: "ok", data: null })),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
|
||||
});
|
||||
vi.mock("@tauri-apps/api/core", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@tauri-apps/api/core")>()),
|
||||
Channel: class {
|
||||
onmessage: ((m: unknown) => void) | null = null;
|
||||
},
|
||||
}));
|
||||
|
||||
import { provideToolWindowService, type ToolWindowService } from "@/workbench/contributions";
|
||||
import { nodeDuration, nodeOutput, nodeStatus } from "./testing";
|
||||
import { clearConsole, resetRuns, runtime, startRun } from "./store";
|
||||
|
||||
const SEP = "\u0000";
|
||||
const config: RunConfig = {
|
||||
id: "junit:CartTest",
|
||||
name: "CartTest",
|
||||
kind: "shell",
|
||||
command: "true",
|
||||
args: [],
|
||||
cwd: null,
|
||||
env: {},
|
||||
detected: false,
|
||||
isTest: true,
|
||||
debugAdapter: null,
|
||||
};
|
||||
const cls = ["CartTest"];
|
||||
const total = ["CartTest", "total"];
|
||||
|
||||
beforeEach(() => provideToolWindowService({ show: vi.fn(), hide: vi.fn() } as unknown as ToolWindowService));
|
||||
afterEach(() => resetRuns());
|
||||
|
||||
async function testRun() {
|
||||
const session = (await startRun(config, undefined, undefined, { prepared: true }))!;
|
||||
const rt = runtime(session.id)!;
|
||||
rt.console.append({ kind: "stdout", text: "before all\nprinted by total\n" });
|
||||
rt.tests!.apply([
|
||||
{ type: "output", path: cls, line: "before all" },
|
||||
{ type: "output", path: total, line: "printed by total" },
|
||||
{ type: "result", path: total, status: "failed", durationMs: 12 },
|
||||
]);
|
||||
return { id: session.id, rt, tests: rt.tests! };
|
||||
}
|
||||
|
||||
it("Clear All empties the full console and every test node's output, keeping the results (#6975)", async () => {
|
||||
const { id, rt, tests } = await testRun();
|
||||
const leaf = tests.get(total.join(SEP))!;
|
||||
const group = tests.get(cls.join(SEP))!;
|
||||
expect(nodeOutput(group)).toEqual(["before all", "printed by total"]);
|
||||
|
||||
clearConsole(id);
|
||||
|
||||
expect(rt.console.text()).toBe("");
|
||||
expect(nodeOutput(leaf)).toEqual([]);
|
||||
expect(nodeOutput(group)).toEqual([]);
|
||||
expect(nodeStatus(leaf)).toBe("failed");
|
||||
expect(nodeDuration(group)).toBe(12);
|
||||
expect(tests.roots.map((r) => r.children.map((c) => c.name))).toEqual([["total"]]);
|
||||
});
|
||||
|
||||
it("output printed after Clear All shows in the console and on its test", async () => {
|
||||
const { id, rt, tests } = await testRun();
|
||||
clearConsole(id);
|
||||
rt.console.append({ kind: "stdout", text: "after clear\n" });
|
||||
tests.apply([{ type: "output", path: total, line: "after clear" }]);
|
||||
|
||||
expect(rt.console.text()).toBe("after clear");
|
||||
expect(nodeOutput(tests.get(total.join(SEP))!)).toEqual(["after clear"]);
|
||||
expect(nodeOutput(tests.get(cls.join(SEP))!)).toEqual(["after clear"]);
|
||||
});
|
||||
@@ -796,6 +796,20 @@ describe("configuration types", () => {
|
||||
expect(typeRows(types, "grad").map((r) => r.key)).toEqual(["gradle"]);
|
||||
expect(typeRows(types, "dock").map((r) => r.key)).toEqual(["group:Docker", "docker-image"]);
|
||||
});
|
||||
|
||||
it("Add New Configuration shows, sorts and searches types in the UI language", () => {
|
||||
const zh: Record<string, string> = { Compound: "复合", "Docker Image": "Docker 镜像", Docker: "Docker 组" };
|
||||
const translate = (text: string) => zh[text] ?? text;
|
||||
const types = [
|
||||
...runConfigTypes(),
|
||||
{ ...BUILTIN_TYPES[0]!, id: "docker-image", label: "Docker Image", group: "Docker" },
|
||||
];
|
||||
const rows = typeRows(types, "", translate);
|
||||
expect(rows.find((r) => r.kind === "type" && r.type.id === "compound")).toMatchObject({ label: "复合" });
|
||||
expect(rows.find((r) => r.kind === "group")).toMatchObject({ label: "Docker 组" });
|
||||
expect(typeRows(types, "复合", translate).map((r) => r.key)).toEqual(["compound"]);
|
||||
expect(typeRows(types, "镜像", translate).map((r) => r.key)).toEqual(["group:Docker", "docker-image"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("compound configurations", () => {
|
||||
|
||||
@@ -1940,8 +1940,11 @@ export async function closeStdin(sessionId: string): Promise<void> {
|
||||
}
|
||||
|
||||
export function clearConsole(sessionId: string) {
|
||||
runtimes.get(sessionId)?.console.clear();
|
||||
runtimes.get(sessionId)?.terminal?.clear();
|
||||
const rt = runtimes.get(sessionId);
|
||||
rt?.console.clear();
|
||||
rt?.terminal?.clear();
|
||||
// A selected test shows its own captured output, so that goes too (as in IDEA).
|
||||
rt?.tests?.clearOutput();
|
||||
bump(sessionId);
|
||||
}
|
||||
|
||||
|
||||
@@ -101,6 +101,12 @@ export class TestResults {
|
||||
this.version++;
|
||||
}
|
||||
|
||||
/** Console Clear All: drops every node's captured output; statuses, durations and the tree stay. */
|
||||
clearOutput() {
|
||||
for (const n of this.byId.values()) n.output = [];
|
||||
this.version++;
|
||||
}
|
||||
|
||||
/** Finds a test by a suffix of its path (pytest failure headers name `Class.test`). */
|
||||
findBySuffix(suffix: string[]): TestNode | undefined {
|
||||
let best: TestNode | undefined;
|
||||
|
||||
@@ -43,17 +43,26 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("Run Targets detail form", () => {
|
||||
it("does not commit an uncommitted ports edit to the target selected while it is open", () => {
|
||||
it("keeps a ports edit with the target it was made to when another target is selected", () => {
|
||||
mount();
|
||||
// An edit to odoo110's published ports that ListField has not committed yet.
|
||||
// An edit to odoo110's published ports, still focused.
|
||||
fireEvent.change(portsBox(), { target: { value: "8069" } });
|
||||
// Selecting another target switches selection on mousedown, before the blur commits.
|
||||
// Selecting another target switches selection on mousedown, before the field loses focus.
|
||||
fireEvent.mouseDown(screen.getByRole("option", { name: /odoo170/ }));
|
||||
fireEvent.blur(portsBox());
|
||||
// odoo170 keeps its own ports; the uncommitted draft is not written over them.
|
||||
// odoo170 keeps its own ports; the edit is not written over them.
|
||||
expect(portsBox().value).toBe("9000:9000");
|
||||
// And odoo110 still holds what it held before the edit was committed anywhere.
|
||||
// And odoo110 holds the edit.
|
||||
fireEvent.mouseDown(screen.getByRole("option", { name: /odoo110/ }));
|
||||
expect(portsBox().value).toBe("8069:8069");
|
||||
expect(portsBox().value).toBe("8069");
|
||||
});
|
||||
|
||||
it("stages a ports edit before the field loses focus, so OK applies it", () => {
|
||||
mount();
|
||||
fireEvent.change(portsBox(), { target: { value: "8069:8069 8070:8070" } });
|
||||
expect(portsBox().value).toBe("8069:8069 8070:8070");
|
||||
const change = Object.values(useSettingsDialog.getState().staged).find((c) => c.key === "runTargets");
|
||||
const targets = change?.value as Array<{ id: string; ports: string[] }> | undefined;
|
||||
expect(targets?.find((t) => t.id === "odoo110")?.ports).toEqual(["8069:8069", "8070:8070"]);
|
||||
});
|
||||
});
|
||||
@@ -263,7 +263,8 @@ function ListField({
|
||||
hint?: string;
|
||||
}) {
|
||||
const id = useId();
|
||||
// Edited as text; the list is stored once the field loses focus.
|
||||
// Edited as text, which stays as typed while the field has focus; the list is stored on every change, so OK
|
||||
// (Enter included) applies an edit that hasn't left the field.
|
||||
const [draft, setDraft] = useState<string | null>(null);
|
||||
return (
|
||||
<Row label={label} htmlFor={id} className={styles.alignedRow} hint={hint}>
|
||||
@@ -273,11 +274,11 @@ function ListField({
|
||||
className={styles.wide}
|
||||
value={draft ?? value.join(" ")}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onBlur={() => {
|
||||
if (draft !== null) onChange(splitList(draft));
|
||||
setDraft(null);
|
||||
onChange={(e) => {
|
||||
setDraft(e.target.value);
|
||||
onChange(splitList(e.target.value));
|
||||
}}
|
||||
onBlur={() => setDraft(null)}
|
||||
/>
|
||||
</Row>
|
||||
);
|
||||
|
||||
@@ -15,7 +15,14 @@ import {
|
||||
type ReactNode,
|
||||
type Ref,
|
||||
} from "react";
|
||||
import { defaultRangeExtractor, elementScroll, useVirtualizer, type Range } from "@tanstack/react-virtual";
|
||||
import {
|
||||
defaultRangeExtractor,
|
||||
elementScroll,
|
||||
measureElement,
|
||||
observeElementRect,
|
||||
useVirtualizer,
|
||||
type Range,
|
||||
} from "@tanstack/react-virtual";
|
||||
import clsx from "clsx";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { relativeDir, useProject } from "@/platform/project";
|
||||
@@ -278,6 +285,16 @@ export function CombinedDiffView({
|
||||
estimateSize: () => ESTIMATE,
|
||||
overscan: 4,
|
||||
rangeExtractor,
|
||||
// A view with no height (hidden behind a maximized tool window) makes the library render nothing,
|
||||
// skipping `rangeExtractor`: report at least 1 px so the focused and unsaved blocks stay mounted.
|
||||
observeElementRect: (instance, cb) =>
|
||||
observeElementRect(instance, (rect) => cb({ ...rect, height: Math.max(rect.height, 1) })),
|
||||
// While the view is hidden its blocks are 0 px tall: recording that would collapse every block onto
|
||||
// one offset and mount them all. Keep the last known size (or the estimate) instead.
|
||||
measureElement: (node, entry, instance) =>
|
||||
measureElement(node, entry, instance) ||
|
||||
instance.itemSizeCache.get(keys[instance.indexFromElement(node)]!) ||
|
||||
ESTIMATE,
|
||||
// A correction for a block above moves the view by its delta from wherever it is now: a `scrollTo`
|
||||
// (the library's offset plus the delta) can drop wheel scrolling still in flight in WebKit.
|
||||
scrollToFn: (offset, options, instance) => {
|
||||
|
||||
@@ -144,6 +144,82 @@ describe("the all-in-one diff, staged edits", () => {
|
||||
expect(block(paths[0]!)).not.toBeNull();
|
||||
});
|
||||
|
||||
it("with autosave off, keeps them while the view has no height, as when a maximized tool window hides it", async () => {
|
||||
let height = 600;
|
||||
const observers: Array<(entries: unknown[]) => void> = [];
|
||||
vi.stubGlobal(
|
||||
"ResizeObserver",
|
||||
class {
|
||||
constructor(cb: (entries: unknown[]) => void) {
|
||||
observers.push(cb);
|
||||
}
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
},
|
||||
);
|
||||
const heightOf = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "clientHeight")!;
|
||||
Object.defineProperty(HTMLElement.prototype, "clientHeight", { configurable: true, get: () => height });
|
||||
try {
|
||||
await editAndScrollAway(false);
|
||||
height = 0;
|
||||
act(() => observers.forEach((cb) => cb([])));
|
||||
await act(() => new Promise((r) => setTimeout(r, 20)));
|
||||
expect(savedStaged).toEqual([]);
|
||||
expect(block(paths[0]!)).not.toBeNull();
|
||||
} finally {
|
||||
Object.defineProperty(HTMLElement.prototype, "clientHeight", heightOf);
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it("with autosave off, keeps them and mounts only a few blocks while the blocks themselves have no height", async () => {
|
||||
let height = 600;
|
||||
const watched = new Set<Element>();
|
||||
const observers: Array<(entries: unknown[]) => void> = [];
|
||||
vi.stubGlobal(
|
||||
"ResizeObserver",
|
||||
class {
|
||||
constructor(cb: (entries: unknown[]) => void) {
|
||||
observers.push(cb);
|
||||
}
|
||||
observe(el: Element) {
|
||||
watched.add(el);
|
||||
}
|
||||
unobserve(el: Element) {
|
||||
watched.delete(el);
|
||||
}
|
||||
disconnect() {}
|
||||
},
|
||||
);
|
||||
const descriptors = (["clientHeight", "offsetHeight"] as const).map(
|
||||
(name) => [name, Object.getOwnPropertyDescriptor(HTMLElement.prototype, name)!] as const,
|
||||
);
|
||||
for (const [name] of descriptors)
|
||||
Object.defineProperty(HTMLElement.prototype, name, { configurable: true, get: () => height });
|
||||
try {
|
||||
savedStaged.length = 0;
|
||||
useProject.setState({ settings: { files: { autoSave: false } } as never });
|
||||
render(<CombinedDiffTab input={combinedDiffInput({ items: staged })} />);
|
||||
const view = await editableSide(paths[0]!, "b");
|
||||
act(() => view.dispatch({ changes: { from: 0, insert: "EDIT " }, userEvent: "input" }));
|
||||
// `display: none` on the island: the container and every block measure 0 px.
|
||||
height = 0;
|
||||
act(() =>
|
||||
observers.forEach((cb) =>
|
||||
cb([...watched].map((target) => ({ target, borderBoxSize: [{ blockSize: 0, inlineSize: 0 }] }))),
|
||||
),
|
||||
);
|
||||
await act(() => new Promise((r) => setTimeout(r, 20)));
|
||||
expect(savedStaged).toEqual([]);
|
||||
expect(block(paths[0]!)).not.toBeNull();
|
||||
expect(document.querySelectorAll("[data-combined-block]").length).toBeLessThanOrEqual(6);
|
||||
} finally {
|
||||
for (const [name, descriptor] of descriptors) Object.defineProperty(HTMLElement.prototype, name, descriptor);
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it("with autosave on, saves them to the index once scrolled away", async () => {
|
||||
await editAndScrollAway(true);
|
||||
expect(block(paths[0]!)).toBeNull();
|
||||
|
||||
@@ -85,7 +85,7 @@ import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
import { iconNode } from "@/ui/iconNode";
|
||||
import { isMarkdownPath } from "../fileKinds";
|
||||
import { attachPanZoom } from "../panZoom";
|
||||
import { imageUrl } from "../previewImages";
|
||||
import { createPreviewImageLoader } from "../previewImages";
|
||||
|
||||
/**
|
||||
* Line of the heading `anchor` in the Markdown file `path`, from an open editor's text (unsaved
|
||||
@@ -480,7 +480,18 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
let live = true;
|
||||
const size = (img: HTMLImageElement, intrinsic?: { w: number; h: number } | null) =>
|
||||
applyImageZoomWidth(img, intrinsic, img.closest<HTMLElement>(`.${IMAGE_ZOOM}`) ?? img);
|
||||
const resetImageSize = (img: HTMLImageElement) => {
|
||||
const box = img.closest<HTMLElement>(`.${IMAGE_ZOOM}`) ?? img;
|
||||
delete img.dataset.naturalWidth;
|
||||
delete box.dataset.naturalWidth;
|
||||
box.style.removeProperty("--image-width");
|
||||
};
|
||||
const bindImageUrl = (img: HTMLImageElement, url: string, asyncLoad: boolean) => {
|
||||
const changed = img.getAttribute("src") !== url;
|
||||
if (changed && img.hasAttribute("src")) {
|
||||
resetImageSize(img);
|
||||
size(img);
|
||||
}
|
||||
const svgSize = svgDataUrlSize(url);
|
||||
if (svgSize && size(img, svgSize) && asyncLoad) {
|
||||
setDiagramsDrawn((n) => n + 1);
|
||||
@@ -495,11 +506,31 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
setDiagramsDrawn((n) => n + 1);
|
||||
}
|
||||
};
|
||||
if (img.getAttribute("src") !== url) img.src = url;
|
||||
if (!img.hasAttribute("data-natural-width") && img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
|
||||
if (changed) img.src = url;
|
||||
// Only trust synchronous naturalWidth when `src` did not change: right after assigning a new `src`,
|
||||
// browsers still report the previous image's `complete` / `naturalWidth` until the new decode finishes.
|
||||
if (
|
||||
!changed &&
|
||||
!img.hasAttribute("data-natural-width") &&
|
||||
img.complete &&
|
||||
img.naturalWidth > 0 &&
|
||||
img.naturalHeight > 0
|
||||
) {
|
||||
size(img, { w: img.naturalWidth, h: img.naturalHeight });
|
||||
}
|
||||
};
|
||||
const images = createPreviewImageLoader(
|
||||
(img, url) => {
|
||||
img.classList.remove(styles.blocked!);
|
||||
bindImageUrl(img, url, true);
|
||||
},
|
||||
(img) => {
|
||||
resetImageSize(img);
|
||||
img.removeAttribute("src");
|
||||
img.classList.add(styles.blocked!);
|
||||
setDiagramsDrawn((n) => n + 1);
|
||||
},
|
||||
);
|
||||
const imgs = [...root.querySelectorAll<HTMLImageElement>("img[data-src]")];
|
||||
imgs.forEach((img) => {
|
||||
attachImagePanZoom(img);
|
||||
@@ -515,10 +546,7 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
img.title = "Remote images are not loaded";
|
||||
return;
|
||||
}
|
||||
imageUrl(target.path).then(
|
||||
(url) => live && bindImageUrl(img, url, true),
|
||||
() => live && img.classList.add(styles.blocked!),
|
||||
);
|
||||
images.load(img, target.path);
|
||||
});
|
||||
root.querySelectorAll<HTMLElement>("pre > code").forEach((code) => {
|
||||
const pre = code.parentElement!;
|
||||
@@ -531,6 +559,7 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
});
|
||||
return () => {
|
||||
live = false;
|
||||
images.dispose();
|
||||
for (const img of imgs) img.onload = null;
|
||||
};
|
||||
}, [html, path]);
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
|
||||
import { Text } from "@codemirror/state";
|
||||
import * as ipc from "@/platform/ipc";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { useLiveMarkdown } from "./markdown/live";
|
||||
import { MarkdownEditor } from "./markdown/MarkdownEditor";
|
||||
import { useMarkdownModes } from "./markdown/modes";
|
||||
import { imageUrl } from "./previewImages";
|
||||
import { useLiveRst } from "./rst/live";
|
||||
import { RstEditor } from "./rst/RstEditor";
|
||||
import { rstModes } from "./rst/RstLayoutActions";
|
||||
|
||||
const svgUrl = (width: number, height: number) =>
|
||||
`data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}"></svg>`)}`;
|
||||
|
||||
const liveDoc = (lines: string[]) => ({
|
||||
text: Text.of(lines),
|
||||
topLine: 0,
|
||||
sourceAtEnd: false,
|
||||
scrollSeq: 0,
|
||||
fontZoom: 0,
|
||||
previewTop: 0,
|
||||
caretLine: 0,
|
||||
caretSeq: 0,
|
||||
});
|
||||
|
||||
describe("preview image disk refresh", () => {
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
useMarkdownModes.setState({ byTab: {}, fallback: "split" });
|
||||
rstModes.useModes.setState({ byTab: {}, fallback: "split" });
|
||||
useLiveMarkdown.setState({}, true);
|
||||
useLiveRst.setState({}, true);
|
||||
});
|
||||
|
||||
it("evicts cached image URLs on file and parent-directory fsChanged without dropping unrelated paths", async () => {
|
||||
let version = 1;
|
||||
const fsReadImage = vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => ({
|
||||
status: "ok",
|
||||
data: `data:image/png;base64,${path}:v${version}`,
|
||||
}));
|
||||
|
||||
const a1 = await imageUrl("/p/cache/a.png");
|
||||
const b1 = await imageUrl("/p/cache/b.png");
|
||||
const dirImg1 = await imageUrl("/p/cache/assets/diagram.png");
|
||||
expect(await imageUrl("/p/cache/a.png")).toBe(a1);
|
||||
expect(fsReadImage).toHaveBeenCalledTimes(3);
|
||||
|
||||
version = 2;
|
||||
emitLocalIdeEvent({
|
||||
type: "fsChanged",
|
||||
created: [],
|
||||
modified: ["/p/cache/a.png"],
|
||||
removed: [],
|
||||
});
|
||||
|
||||
expect(await imageUrl("/p/cache/a.png")).toBe("data:image/png;base64,/p/cache/a.png:v2");
|
||||
expect(await imageUrl("/p/cache/b.png")).toBe(b1);
|
||||
expect(fsReadImage).toHaveBeenCalledTimes(4);
|
||||
|
||||
version = 3;
|
||||
emitLocalIdeEvent({
|
||||
type: "fsChanged",
|
||||
created: ["/p/cache/assets"],
|
||||
modified: [],
|
||||
removed: [],
|
||||
});
|
||||
|
||||
expect(await imageUrl("/p/cache/assets/diagram.png")).toBe("data:image/png;base64,/p/cache/assets/diagram.png:v3");
|
||||
expect(dirImg1).toBe("data:image/png;base64,/p/cache/assets/diagram.png:v1");
|
||||
expect(await imageUrl("/p/cache/b.png")).toBe(b1);
|
||||
});
|
||||
|
||||
it("keeps a newer reload when an earlier in-flight read rejects or resolves late", async () => {
|
||||
const imgPath = "/p/md-race/shot.png";
|
||||
const mdPath = "/p/md-race/README.md";
|
||||
const resolvers: Array<{ resolve: (v: { status: "ok"; data: string }) => void; reject: (e: Error) => void }> = [];
|
||||
|
||||
vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve, reject) => {
|
||||
resolvers.push({ resolve, reject });
|
||||
}),
|
||||
);
|
||||
|
||||
useMarkdownModes.setState({ byTab: { t: "preview" }, fallback: "split" });
|
||||
useLiveMarkdown.setState({ [mdPath]: liveDoc([""]) });
|
||||
|
||||
render(
|
||||
<MarkdownEditor path={mdPath} tabId="t">
|
||||
<div />
|
||||
</MarkdownEditor>,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(resolvers).toHaveLength(1));
|
||||
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] });
|
||||
});
|
||||
await waitFor(() => expect(resolvers).toHaveLength(2));
|
||||
|
||||
act(() => {
|
||||
resolvers[1]!.resolve({ status: "ok", data: "data:image/png;base64,FRESH" });
|
||||
});
|
||||
|
||||
const preview = screen.getByRole("document", { name: "Markdown preview" });
|
||||
await waitFor(() => {
|
||||
expect(preview.querySelector<HTMLImageElement>('img[alt="Shot"]')?.getAttribute("src")).toBe(
|
||||
"data:image/png;base64,FRESH",
|
||||
);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
resolvers[0]!.reject(new Error("stale read failed"));
|
||||
});
|
||||
await act(async () => {});
|
||||
|
||||
expect(preview.querySelector<HTMLImageElement>('img[alt="Shot"]')?.getAttribute("src")).toBe(
|
||||
"data:image/png;base64,FRESH",
|
||||
);
|
||||
expect(await imageUrl(imgPath)).toBe("data:image/png;base64,FRESH");
|
||||
});
|
||||
|
||||
it("reloads Markdown preview images on fsChanged, updates dimensions, and recovers after removal", async () => {
|
||||
const imgPath = "/p/md-reload/diagram.svg";
|
||||
const mdPath = "/p/md-reload/README.md";
|
||||
let current: string | null = svgUrl(320, 180);
|
||||
|
||||
vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => {
|
||||
if (path === imgPath && current !== null) return { status: "ok", data: current };
|
||||
return { status: "error", error: { kind: "notFound", message: path } } as never;
|
||||
});
|
||||
|
||||
useMarkdownModes.setState({ byTab: { t: "preview" }, fallback: "split" });
|
||||
useLiveMarkdown.setState({ [mdPath]: liveDoc([""]) });
|
||||
|
||||
render(
|
||||
<MarkdownEditor path={mdPath} tabId="t">
|
||||
<div />
|
||||
</MarkdownEditor>,
|
||||
);
|
||||
|
||||
const preview = screen.getByRole("document", { name: "Markdown preview" });
|
||||
await waitFor(() => {
|
||||
const img = preview.querySelector<HTMLImageElement>('img[alt="Diagram"]');
|
||||
expect(img?.getAttribute("src")).toBe(svgUrl(320, 180));
|
||||
});
|
||||
|
||||
const img = preview.querySelector<HTMLImageElement>('img[alt="Diagram"]')!;
|
||||
const box = img.closest<HTMLElement>(".image-zoom") ?? img;
|
||||
expect(box.style.getPropertyValue("--image-width")).toBe("320px");
|
||||
|
||||
current = svgUrl(640, 240);
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] });
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(img.getAttribute("src")).toBe(svgUrl(640, 240));
|
||||
expect(box.style.getPropertyValue("--image-width")).toBe("640px");
|
||||
});
|
||||
|
||||
current = null;
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed: [imgPath] });
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(img.getAttribute("src")).toBeNull();
|
||||
expect(img.hasAttribute("data-natural-width")).toBe(false);
|
||||
expect(box.style.getPropertyValue("--image-width")).toBe("");
|
||||
});
|
||||
|
||||
current = svgUrl(480, 200);
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [imgPath], modified: [], removed: [] });
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(img.getAttribute("src")).toBe(svgUrl(480, 200));
|
||||
expect(box.style.getPropertyValue("--image-width")).toBe("480px");
|
||||
});
|
||||
});
|
||||
|
||||
it("updates raster image width on reload even when old naturalWidth is still reported synchronously", async () => {
|
||||
const imgPath = "/p/md-raster/shot.png";
|
||||
const mdPath = "/p/md-raster/README.md";
|
||||
let current = "data:image/png;base64,V1";
|
||||
|
||||
vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => {
|
||||
if (path === imgPath) return { status: "ok", data: current };
|
||||
return { status: "error", error: { kind: "notFound", message: path } } as never;
|
||||
});
|
||||
|
||||
useMarkdownModes.setState({ byTab: { t: "preview" }, fallback: "split" });
|
||||
useLiveMarkdown.setState({ [mdPath]: liveDoc([""]) });
|
||||
|
||||
render(
|
||||
<MarkdownEditor path={mdPath} tabId="t">
|
||||
<div />
|
||||
</MarkdownEditor>,
|
||||
);
|
||||
|
||||
const preview = screen.getByRole("document", { name: "Markdown preview" });
|
||||
await waitFor(() => {
|
||||
expect(preview.querySelector<HTMLImageElement>('img[alt="Shot"]')?.getAttribute("src")).toBe(
|
||||
"data:image/png;base64,V1",
|
||||
);
|
||||
});
|
||||
|
||||
const img = preview.querySelector<HTMLImageElement>('img[alt="Shot"]')!;
|
||||
const box = img.closest<HTMLElement>(".image-zoom") ?? img;
|
||||
let naturalWidth = 960;
|
||||
let naturalHeight = 600;
|
||||
Object.defineProperty(img, "complete", { get: () => true, configurable: true });
|
||||
Object.defineProperty(img, "naturalWidth", { get: () => naturalWidth, configurable: true });
|
||||
Object.defineProperty(img, "naturalHeight", { get: () => naturalHeight, configurable: true });
|
||||
act(() => {
|
||||
img.dispatchEvent(new Event("load"));
|
||||
});
|
||||
expect(box.style.getPropertyValue("--image-width")).toBe("960px");
|
||||
|
||||
// Simulate HTML spec: right after `img.src = newUrl`, `complete` is still true and `naturalWidth` is still 960
|
||||
// until the new image decodes and fires `load`.
|
||||
current = "data:image/png;base64,V2";
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] });
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(img.getAttribute("src")).toBe("data:image/png;base64,V2");
|
||||
});
|
||||
expect(img.hasAttribute("data-natural-width")).toBe(false);
|
||||
|
||||
naturalWidth = 420;
|
||||
naturalHeight = 280;
|
||||
act(() => {
|
||||
img.dispatchEvent(new Event("load"));
|
||||
});
|
||||
expect(box.style.getPropertyValue("--image-width")).toBe("420px");
|
||||
});
|
||||
|
||||
it("reloads reStructuredText preview images when modified on disk", async () => {
|
||||
const rstPath = "/p/rst-reload/index.rst";
|
||||
const imgPath = "/p/rst-reload/chart.png";
|
||||
let current: string | null = "data:image/png;base64,OLD";
|
||||
|
||||
vi.spyOn(ipc.commands, "rstPreview").mockResolvedValue({
|
||||
status: "ok",
|
||||
data: '<main><img alt="Chart" src="chart.png" /></main>',
|
||||
});
|
||||
vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (path: string) => {
|
||||
if (path === imgPath && current !== null) return { status: "ok", data: current };
|
||||
return { status: "error", error: { kind: "notFound", message: path } } as never;
|
||||
});
|
||||
|
||||
useLiveRst.setState({ [rstPath]: "Title\n=====\n" });
|
||||
render(
|
||||
<RstEditor path={rstPath} tabId="t">
|
||||
<div />
|
||||
</RstEditor>,
|
||||
);
|
||||
|
||||
const preview = document.querySelector<HTMLElement>('[aria-label="reStructuredText preview"]')!;
|
||||
await waitFor(() => {
|
||||
expect(preview.querySelector<HTMLImageElement>('img[alt="Chart"]')?.getAttribute("src")).toBe(
|
||||
"data:image/png;base64,OLD",
|
||||
);
|
||||
});
|
||||
|
||||
current = "data:image/png;base64,NEW";
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [imgPath], removed: [] });
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(preview.querySelector<HTMLImageElement>('img[alt="Chart"]')?.getAttribute("src")).toBe(
|
||||
"data:image/png;base64,NEW",
|
||||
);
|
||||
});
|
||||
|
||||
current = null;
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed: [imgPath] });
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(preview.querySelector<HTMLImageElement>('img[alt="Chart"]')?.getAttribute("src")).toBeNull();
|
||||
});
|
||||
|
||||
current = "data:image/png;base64,RESTORED";
|
||||
act(() => {
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [imgPath], modified: [], removed: [] });
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(preview.querySelector<HTMLImageElement>('img[alt="Chart"]')?.getAttribute("src")).toBe(
|
||||
"data:image/png;base64,RESTORED",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,16 +1,97 @@
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { call, commands, onIdeEvent } from "@/platform/ipc";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
|
||||
/** Loaded local images by absolute path (data URLs), shared by all previews. */
|
||||
const imageCache = new Map<string, Promise<string>>();
|
||||
const IMAGE_CACHE_LIMIT = 64;
|
||||
|
||||
type ImageChangeListener = (changed: readonly string[]) => void;
|
||||
const listeners = new Set<ImageChangeListener>();
|
||||
let offFs: (() => void) | null = null;
|
||||
|
||||
function matchesChanged(path: string, changed: readonly string[]): boolean {
|
||||
return changed.some((entry) => isSameOrInside(path, entry));
|
||||
}
|
||||
|
||||
function ensureWatching(): void {
|
||||
offFs ??= onIdeEvent("fsChanged", (e) => {
|
||||
const changed = [...e.created, ...e.modified, ...e.removed];
|
||||
if (!changed.length) return;
|
||||
for (const cached of [...imageCache.keys()]) {
|
||||
if (matchesChanged(cached, changed)) imageCache.delete(cached);
|
||||
}
|
||||
for (const listener of [...listeners]) listener(changed);
|
||||
});
|
||||
}
|
||||
|
||||
export function imageUrl(path: string): Promise<string> {
|
||||
let p = imageCache.get(path);
|
||||
if (!p) {
|
||||
p = call(commands.fsReadImage(path));
|
||||
p.catch(() => imageCache.delete(path));
|
||||
ensureWatching();
|
||||
let pending = imageCache.get(path);
|
||||
if (!pending) {
|
||||
const request = call(commands.fsReadImage(path));
|
||||
request.catch(() => {
|
||||
if (imageCache.get(path) === request) imageCache.delete(path);
|
||||
});
|
||||
if (imageCache.size >= IMAGE_CACHE_LIMIT) imageCache.delete(imageCache.keys().next().value!);
|
||||
imageCache.set(path, p);
|
||||
imageCache.set(path, request);
|
||||
pending = request;
|
||||
}
|
||||
return p;
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** Loads local preview images and reloads them whenever their disk paths change. */
|
||||
export function createPreviewImageLoader(
|
||||
onLoad: (img: HTMLImageElement, url: string) => void,
|
||||
onError: (img: HTMLImageElement) => void,
|
||||
) {
|
||||
let active = true;
|
||||
const groups = new Map<string, { imgs: HTMLImageElement[]; gen: number }>();
|
||||
let off: (() => void) | null = null;
|
||||
|
||||
const apply = (
|
||||
path: string,
|
||||
group: { imgs: HTMLImageElement[]; gen: number },
|
||||
targets: readonly HTMLImageElement[],
|
||||
) => {
|
||||
const gen = group.gen;
|
||||
imageUrl(path).then(
|
||||
(url) => {
|
||||
if (!active || group.gen !== gen) return;
|
||||
for (const img of targets) onLoad(img, url);
|
||||
},
|
||||
() => {
|
||||
if (!active || group.gen !== gen) return;
|
||||
for (const img of targets) onError(img);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
load(img: HTMLImageElement, path: string) {
|
||||
let group = groups.get(path);
|
||||
if (!group) {
|
||||
group = { imgs: [], gen: 0 };
|
||||
groups.set(path, group);
|
||||
if (!off) {
|
||||
ensureWatching();
|
||||
const onChanged: ImageChangeListener = (changed) => {
|
||||
for (const [watchedPath, watchedGroup] of groups) {
|
||||
if (!matchesChanged(watchedPath, changed)) continue;
|
||||
watchedGroup.gen++;
|
||||
apply(watchedPath, watchedGroup, watchedGroup.imgs);
|
||||
}
|
||||
};
|
||||
listeners.add(onChanged);
|
||||
off = () => listeners.delete(onChanged);
|
||||
}
|
||||
}
|
||||
group.imgs.push(img);
|
||||
apply(path, group, [img]);
|
||||
},
|
||||
dispose() {
|
||||
active = false;
|
||||
off?.();
|
||||
groups.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import { maybeEditorService } from "@/workbench/contributions";
|
||||
import { EmptyState, FloatingToolbar, Spinner, SplitGroup, SplitHandle, SplitPanel, selectableText } from "@/ui";
|
||||
import { modeOf } from "../layoutModes";
|
||||
import { ANCHOR_PREFIX, resolveLink, sanitizePreviewHtml } from "../markdown/render";
|
||||
import { imageUrl } from "../previewImages";
|
||||
import { createPreviewImageLoader } from "../previewImages";
|
||||
import { useLiveRst } from "./live";
|
||||
import { RstLayoutActions, rstModes } from "./RstLayoutActions";
|
||||
import styles from "../markdown/Markdown.module.css";
|
||||
@@ -25,10 +25,20 @@ const DEFAULT_SPLIT_LAYOUT = { editor: 50, preview: 50 };
|
||||
type Rendered = { html: string } | { error: string };
|
||||
|
||||
/** Puts docutils' `html` into `root`: sanitized, local images loaded, code highlighted. */
|
||||
function fill(root: HTMLElement, html: string, path: string, isLive: () => boolean) {
|
||||
function fill(root: HTMLElement, html: string, path: string) {
|
||||
const template = document.createElement("template");
|
||||
template.innerHTML = sanitizePreviewHtml(html);
|
||||
root.replaceChildren(template.content);
|
||||
const images = createPreviewImageLoader(
|
||||
(img, url) => {
|
||||
img.classList.remove(styles.blocked!);
|
||||
if (img.getAttribute("src") !== url) img.src = url;
|
||||
},
|
||||
(img) => {
|
||||
img.removeAttribute("src");
|
||||
img.classList.add(styles.blocked!);
|
||||
},
|
||||
);
|
||||
root.querySelectorAll<HTMLImageElement>("img[data-src]").forEach((img) => {
|
||||
const src = img.dataset.src ?? "";
|
||||
if (/^data:image\//i.test(src)) {
|
||||
@@ -41,19 +51,13 @@ function fill(root: HTMLElement, html: string, path: string, isLive: () => boole
|
||||
img.title = tx("Remote images are not loaded");
|
||||
return;
|
||||
}
|
||||
imageUrl(target.path).then(
|
||||
(url) => {
|
||||
if (isLive()) img.src = url;
|
||||
},
|
||||
() => {
|
||||
if (isLive()) img.classList.add(styles.blocked!);
|
||||
},
|
||||
);
|
||||
images.load(img, target.path);
|
||||
});
|
||||
root.querySelectorAll<HTMLElement>("pre.code > code").forEach((code) => {
|
||||
const lang = [...code.parentElement!.classList].find((c) => c !== "code" && c !== "literal-block") ?? null;
|
||||
void highlightInto(code, code.textContent ?? "", lang);
|
||||
});
|
||||
return () => images.dispose();
|
||||
}
|
||||
|
||||
function RstPreview({ path }: { path: string }) {
|
||||
@@ -84,11 +88,7 @@ function RstPreview({ path }: { path: string }) {
|
||||
useLayoutEffect(() => {
|
||||
const root = ref.current;
|
||||
if (!root || html === null) return;
|
||||
let live = true;
|
||||
fill(root, html, path, () => live);
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
return fill(root, html, path);
|
||||
}, [html, path]);
|
||||
|
||||
const scrollTo = (id: string) =>
|
||||
|
||||
@@ -299,6 +299,7 @@
|
||||
"Base interpreter": "Intérprete base",
|
||||
"Base interpreter:": "Intérprete base:",
|
||||
"Based on syntax (language server not ready)": "Basado en sintaxis (el servidor de lenguaje no está listo)",
|
||||
"Based on syntax and the project index": "Basado en sintaxis y el índice del proyecto",
|
||||
"Behavior": "Comportamiento",
|
||||
"Benchmark function": "Función de benchmark",
|
||||
"Binary response": "Respuesta binaria",
|
||||
|
||||
@@ -255,6 +255,7 @@
|
||||
"Base interpreter": "Interpréteur de base",
|
||||
"Base interpreter:": "Interpréteur de base :",
|
||||
"Based on syntax (language server not ready)": "D'après la syntaxe (serveur de langage pas encore prêt)",
|
||||
"Based on syntax and the project index": "D'après la syntaxe et l'index du projet",
|
||||
"Behavior": "Comportement",
|
||||
"Benchmark function": "Fonction de benchmark",
|
||||
"Binary response": "Réponse binaire",
|
||||
|
||||
@@ -335,6 +335,7 @@
|
||||
"Base interpreter": "기본 인터프리터",
|
||||
"Base interpreter:": "기본 인터프리터:",
|
||||
"Based on syntax (language server not ready)": "구문 기반(언어 서버가 준비되지 않음)",
|
||||
"Based on syntax and the project index": "구문 및 프로젝트 인덱스 기반",
|
||||
"Behavior": "동작",
|
||||
"Benchmark function": "벤치마크 함수",
|
||||
"Binary response": "바이너리 응답",
|
||||
|
||||
@@ -291,6 +291,7 @@
|
||||
"Base interpreter": "Interpreter bazowy",
|
||||
"Base interpreter:": "Interpreter bazowy:",
|
||||
"Based on syntax (language server not ready)": "Na podstawie składni (serwer językowy nie jest gotowy)",
|
||||
"Based on syntax and the project index": "Na podstawie składni i indeksu projektu",
|
||||
"Behavior": "Zachowanie",
|
||||
"Benchmark function": "Funkcja benchmarku",
|
||||
"Binary response": "Odpowiedź binarna",
|
||||
|
||||
@@ -291,6 +291,7 @@
|
||||
"Base interpreter": "Interpretador base",
|
||||
"Base interpreter:": "Interpretador base:",
|
||||
"Based on syntax (language server not ready)": "Baseado na sintaxe (servidor de linguagem não pronto)",
|
||||
"Based on syntax and the project index": "Baseado na sintaxe e no índice do projeto",
|
||||
"Behavior": "Comportamento",
|
||||
"Benchmark function": "Função de benchmark",
|
||||
"Binary response": "Resposta binária",
|
||||
|
||||
@@ -1248,6 +1248,7 @@
|
||||
"Base interpreter": "Базовый интерпретатор",
|
||||
"Base interpreter:": "Базовый интерпретатор:",
|
||||
"Based on syntax (language server not ready)": "На основе синтаксиса (языковой сервер не готов)",
|
||||
"Based on syntax and the project index": "На основе синтаксиса и индекса проекта",
|
||||
"Behavior": "Поведение",
|
||||
"Benchmark function": "Функция бенчмарка",
|
||||
"Binary response": "Двоичный ответ",
|
||||
|
||||
@@ -3092,6 +3092,7 @@
|
||||
"Base interpreter": "Temel yorumlayıcı",
|
||||
"Base interpreter:": "Temel yorumlayıcı:",
|
||||
"Based on syntax (language server not ready)": "Sözdizimine göre (dil sunucusu hazır değil)",
|
||||
"Based on syntax and the project index": "Sözdizimine ve proje dizinine göre",
|
||||
"Behavior": "Davranış",
|
||||
"Benchmark function": "Performans testi fonksiyonu",
|
||||
"Binary response": "İkili yanıt",
|
||||
|
||||
@@ -936,6 +936,7 @@
|
||||
"Base interpreter": "基礎直譯器",
|
||||
"Base interpreter:": "基礎直譯器:",
|
||||
"Based on syntax (language server not ready)": "基於語法(語言伺服器尚未就緒)",
|
||||
"Based on syntax and the project index": "基於語法和專案索引",
|
||||
"Behavior": "行為",
|
||||
"Benchmark function": "基準測試函式",
|
||||
"Binary response": "二進位制回應",
|
||||
|
||||
@@ -1395,6 +1395,7 @@
|
||||
"Base interpreter": "基础解释器",
|
||||
"Base interpreter:": "基础解释器:",
|
||||
"Based on syntax (language server not ready)": "基于语法(语言服务器尚未就绪)",
|
||||
"Based on syntax and the project index": "基于语法和项目索引",
|
||||
"Behavior": "行为",
|
||||
"Benchmark function": "基准测试函数",
|
||||
"Binary response": "二进制响应",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { act, render } from "@testing-library/react";
|
||||
import { useRef } from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { Scrollbar } from "./Scrollbar";
|
||||
|
||||
function Harness({ onScroll }: { onScroll: (top: number) => void }) {
|
||||
@@ -13,7 +13,72 @@ function Harness({ onScroll }: { onScroll: (top: number) => void }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** A ResizeObserver the test fires by hand, for the elements it was told to observe. */
|
||||
function fakeResizeObserver() {
|
||||
const observers = new Set<{ callback: () => void; targets: Set<Element> }>();
|
||||
vi.stubGlobal(
|
||||
"ResizeObserver",
|
||||
class {
|
||||
entry: { callback: () => void; targets: Set<Element> };
|
||||
constructor(callback: () => void) {
|
||||
this.entry = { callback, targets: new Set() };
|
||||
observers.add(this.entry);
|
||||
}
|
||||
observe(target: Element) {
|
||||
this.entry.targets.add(target);
|
||||
}
|
||||
unobserve(target: Element) {
|
||||
this.entry.targets.delete(target);
|
||||
}
|
||||
disconnect() {
|
||||
this.entry.targets.clear();
|
||||
}
|
||||
},
|
||||
);
|
||||
return (target: Element) => {
|
||||
act(() => {
|
||||
for (const o of observers) if (o.targets.has(target)) o.callback();
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
describe("Scrollbar", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("measures again when the scroller's content grows without the scroller resizing", async () => {
|
||||
const resize = fakeResizeObserver();
|
||||
const { getByTestId, container } = render(<Harness onScroll={() => {}} />);
|
||||
const scroller = getByTestId("scroller");
|
||||
const content = document.createElement("div");
|
||||
scroller.append(content);
|
||||
await Promise.resolve();
|
||||
const size = { content: 100 };
|
||||
Object.defineProperties(scroller, {
|
||||
clientHeight: { configurable: true, value: 100 },
|
||||
scrollHeight: { configurable: true, get: () => size.content },
|
||||
scrollTop: { configurable: true, value: 0 },
|
||||
});
|
||||
const track = container.querySelector<HTMLElement>("[aria-hidden]")!;
|
||||
const thumb = track.firstElementChild as HTMLElement;
|
||||
resize(scroller);
|
||||
|
||||
// `contentHeight` stays the same, as in a Markdown preview reflowing at a late block width.
|
||||
size.content = 200;
|
||||
resize(content);
|
||||
expect(thumb.style.height).toBe("50px");
|
||||
|
||||
const replaced = document.createElement("div");
|
||||
act(() => {
|
||||
scroller.replaceChildren(replaced);
|
||||
});
|
||||
await Promise.resolve();
|
||||
size.content = 400;
|
||||
resize(replaced);
|
||||
expect(thumb.style.height).toBe("32px");
|
||||
});
|
||||
|
||||
it("notifies scroll listeners synchronously while the thumb is dragged", () => {
|
||||
const onScroll = vi.fn();
|
||||
const { getByTestId, container } = render(<Harness onScroll={onScroll} />);
|
||||
|
||||
@@ -17,7 +17,8 @@ export const hideNativeHorizontalScrollbar = styles.hideNativeHorizontal;
|
||||
* native one scrolls asynchronously in WebKit and shows blank rows until the
|
||||
* page catches up.
|
||||
*
|
||||
* Pass the scrollable content size to remeasure when content grows. The vertical
|
||||
* Pass the scrollable content size to remeasure when content grows; content that grows without it is
|
||||
* caught by observing the scroller's children. The vertical
|
||||
* scrollbar sets `data-scrollbar-shown` when needed. The horizontal overlay appears
|
||||
* on scroll and fades when idle.
|
||||
*/
|
||||
@@ -83,7 +84,16 @@ export function Scrollbar({
|
||||
lastLeft = el.scrollLeft;
|
||||
sync();
|
||||
});
|
||||
observer.observe(el);
|
||||
// The scroller's size does not change when its content grows (a Markdown preview reflowing),
|
||||
// so observe its children too, and again when they are replaced.
|
||||
const observe = () => {
|
||||
observer.disconnect();
|
||||
observer.observe(el);
|
||||
for (const child of el.children) observer.observe(child);
|
||||
};
|
||||
observe();
|
||||
const replaced = new MutationObserver(observe);
|
||||
replaced.observe(el, { childList: true });
|
||||
window.addEventListener("blur", endDrag);
|
||||
return () => {
|
||||
endDrag();
|
||||
@@ -91,6 +101,7 @@ export function Scrollbar({
|
||||
window.clearTimeout(hideTimer.current);
|
||||
el.removeEventListener("scroll", onScroll);
|
||||
observer.disconnect();
|
||||
replaced.disconnect();
|
||||
};
|
||||
}, [target, endDrag, horizontal, scheduleHide]);
|
||||
|
||||
|
||||
Reference in new issue
Заблокувати користувача