Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai f0486a6826 fix(agents): recover edited draft when sending after rollback fails 2026-10-29 21:26:57 +08:00
l0ng-ai 3c87a8eea7 fix(agents): restore Codex message editing and cancel repaint 2026-10-29 21:09:19 +08:00
l0ng-ai aac924517c fix(agents): preserve Shift selection and add bulk task actions (#283) 2026-10-29 20:53:02 +08:00
l0ng-ai b1347dd331 fix(lsp): keep background usage counts from delaying navigation (#282)
* fix(lsp): keep background usage counts from delaying navigation

* fix(lsp): retry incomplete counts and preserve newer hints
2026-10-29 20:49:01 +08:00
l0ng-ai fc2496c3f0 feat(agents): show unread task indicators 2026-10-29 20:48:02 +08:00
l0ng-ai 0f26b72d07 fix(agents): anchor composer completions below the caret (#278) 2026-10-29 20:37:25 +08:00
ad09a76212 feat(vcs): IntelliJ's diff algorithm and change colouring in the diff viewer (#242)
* feat(vcs): IDEA's diff algorithm and change colouring in the diff viewer

Port IntelliJ's text comparison to TypeScript (src/features/vcs/comparison):
Myers/patience LCS with unique-element discarding, ByLine (smart matching
that skips unimportant lines, chunk optimizer, second-step correction),
ByWord (word chunks, punctuation matching, whitespace policies, line block
splitting) and ComparisonManager's compareLinesInner / processBlocks. The
port runs IntelliJ's own LineComparisonUtilTest, WordComparisonUtilTest and
SplitComparisonUtilTest cases (459 runs), converted to ideaCases.json.

MergeView chunks now come straight from these line fragments, with the
inner word fragments as chunk changes, instead of @codemirror/merge's
presentable diff. Revert and >> / << replace lines as
DiffUtil.applyModification does.

Colour changes as IDEA does: modified (blue), inserted (green) and deleted
(grey) by chunk type, a lighter line background for chunks whose words were
compared, each word fragment in its own type at full line height, a thin
bar for a fragment empty on one side, and the colours carried into the
gutters and the divider bands. New --diff-modified / --diff-inserted /
--diff-deleted theme tokens, imported from .icls DIFF_* attributes.

Add a Playwright suite over a generated git repository of diff cases,
including 10,000-line files, in every viewer mode.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(vcs): preserve unified revert boundaries and bound large diffs

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: l0ng-ai <[email protected]>
2026-10-29 19:59:57 +08:00
Walter WangтаWalt von Neumann 8568a70a05 feat(vcs): add shared and local Git ignore actions (#255)
Co-authored-by: Walt von Neumann <[email protected]>
2026-10-29 19:43:44 +08:00
JawтаClaude Opus 5.5 a20207110e fix(vcs): follow the editor font settings in diff and merge viewers (#253)
The VCS viewers (diff, merge, local history) hard-coded the default mono
font, size and line height, so Settings > Editor > Font had no effect on
them. Read the editor font variables like the main editor does, and apply
fontExtension next to the caret, kept in step with the settings.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-29 19:43:40 +08:00
l0ng-ai 74b2d5f5d7 fix(vcs): prevent Git log refresh flicker and graph seams (#269) 2026-10-29 19:12:31 +08:00
l0ng-ai 297b15a7b1 fix(agents): expose Cursor approval controls (#265) 2026-10-29 19:12:27 +08:00
l0ng-ai 97144421d2 fix(agents): open local file links in Markdown messages (#263) 2026-10-29 19:12:23 +08:00
JawтаClaude Opus 5.5 200ed6a528 fix(project): paste files copied in Finder on macOS (#250)
The OS clipboard's file list was only wired up for Windows (CF_HDROP), so on
macOS the project view never saw files copied in Finder: Paste stayed disabled
and ⌘V did nothing. Read and write the general NSPasteboard's file URLs
instead, so Finder's copies paste into the project view and the project view's
copies paste in Finder.

Closes #246

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-29 18:05:11 +08:00
l0ng-ai 4666c4b9a5 fix(settings): keep macOS settings visible across displays (#254) 2026-10-29 18:05:06 +08:00
JawтаClaude Opus 5.5 ce43a7aa70 chore: add pre-commit hook with simple-git-hooks and lint-staged (#252)
Run oxlint --fix and oxfmt on staged files before each commit, and
rustfmt on staged Rust files. simple-git-hooks installs the hook from
its postinstall, allowed in pnpm-workspace.yaml.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-10-29 17:47:55 +08:00
l0ng-ai f911196f7d ci(release): Write latest.json once after every build (#176)
Each build's tauri-action rewrote the shared latest.json by deleting and re-uploading it, so
parallel macOS builds raced: one failed with 404 on the delete (skipping DMG notarization), or a
platform could silently drop out of the manifest. The builds no longer upload it; a new
updater-manifest job builds it once from the uploaded .sig files and fails if any platform is
missing. publish waits for it.

Claude-Session: https://claude.ai/code/session_01Dq6jQQn8ZhRfkkyj3PRutA
2026-10-29 17:47:47 +08:00
95 змінених файлів з 8974 додано та 521 видалено

No files matched your search

+60 -1
Переглянути файл
@@ -117,6 +117,8 @@ jobs:
releaseId: ${{ needs.create-release.outputs.release_id }}
tagName: ${{ env.TAG }}
args: --target ${{ matrix.target }}
# The parallel builds would race on one latest.json; `updater-manifest` writes it once.
uploadUpdaterJson: false
# tauri-action notarizes the .app but not the DMG around it; notarize and
# staple the DMG too, then replace the uploaded asset.
- name: Notarize DMG
@@ -172,8 +174,65 @@ jobs:
if command -v sha256sum >/dev/null; then sha256sum "$ASSET"; else shasum -a 256 "$ASSET"; fi > "$ASSET.sha256"
gh release upload "$TAG" "$ASSET" "$ASSET.sha256" --clobber
# The updater manifest (latest.json), built once from the signed bundles every build uploaded.
# Fails when a platform is missing, so a release never ships a manifest without it.
updater-manifest:
needs: [create-release, build]
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v7
env:
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
with:
script: |
const { owner, repo } = context.repo;
const release_id = Number(process.env.RELEASE_ID);
const tag = process.env.TAG;
const assets = await github.paginate(github.rest.repos.listReleaseAssets, { owner, repo, release_id });
const sigs = assets.filter((a) => a.name.endsWith(".sig"));
if (sigs.length === 0) {
core.notice("no signed bundles (TAURI_SIGNING_PRIVATE_KEY unset): skipping latest.json");
return;
}
// Bundle suffix → updater platform keys, as tauri-action names them.
const kinds = [
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
[/_x64_en-US\.msi$/, ["windows-x86_64", "windows-x86_64-msi"]],
[/_x64-setup\.exe$/, ["windows-x86_64-nsis"]],
];
const platforms = {};
for (const sig of sigs) {
const bundle = sig.name.slice(0, -".sig".length);
const kind = kinds.find(([re]) => re.test(bundle));
if (!kind) continue;
const { data } = await github.rest.repos.getReleaseAsset({
owner, repo, asset_id: sig.id, headers: { accept: "application/octet-stream" },
});
const signature = Buffer.from(data).toString("utf8").trim();
const url = `https://github.com/${owner}/${repo}/releases/download/${tag}/${encodeURIComponent(bundle)}`;
for (const key of kind[1]) platforms[key] = { signature, url };
}
const missing = kinds.flatMap(([, keys]) => keys).filter((k) => !platforms[k]);
if (missing.length) {
core.setFailed(`latest.json would miss ${missing.join(", ")}`);
return;
}
const manifest = { version: tag.replace(/^v/, ""), notes: "", pub_date: new Date().toISOString(), platforms };
const old = assets.find((a) => a.name === "latest.json");
if (old) await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: old.id });
await github.rest.repos.uploadReleaseAsset({
owner, repo, release_id, name: "latest.json",
data: JSON.stringify(manifest, null, 2),
headers: { "content-type": "application/json" },
});
core.info(`latest.json: ${Object.keys(platforms).sort().join(", ")}`);
publish:
needs: [create-release, build, server]
needs: [create-release, build, server, updater-manifest]
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v7
Створено
+7
Переглянути файл
@@ -4025,6 +4025,11 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.24"
dependencies = [
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
]
[[package]]
name = "ide-core"
@@ -4511,6 +4516,7 @@ dependencies = [
"dunce",
"gix",
"ide-core",
"ignore",
"libc",
"regex-lite",
"serde",
@@ -4528,6 +4534,7 @@ dependencies = [
"chardetng",
"dunce",
"encoding_rs",
"gix",
"globset",
"ide-core",
"ignore",
+13
Переглянути файл
@@ -28,6 +28,19 @@ icon set, copied unmodified (some renamed) from JetBrains' open-source repositor
At render time `src/ui/icons.tsx` may recolour monochrome icons to `currentColor`.
## JetBrains IntelliJ Platform diff algorithm
`src/features/vcs/comparison/**` is a TypeScript port of the text comparison of
[intellij-community](https://github.com/JetBrains/intellij-community) (Apache-2.0):
`platform/util/diff` (`com.intellij.util.diff`: Diff, Reindexer, MyersLCS,
PatienceIntLCS, UniqueLCS; `com.intellij.diff.comparison`: ByLineRt, ByWordRt,
ByCharRt, ChunkOptimizer, ChangeCorrector, LineFragmentSplitter, TrimUtil,
ComparisonUtil, iterables) and `platform/diff-impl` (ComparisonManagerImpl's
`compareLinesInner` and `processBlocks`). `__tests__/ideaCases.json` is converted
from its tests (`LineComparisonUtilTest`, `WordComparisonUtilTest`,
`SplitComparisonUtilTest`). Modified from the originals. Copyright 2000-2026
JetBrains s.r.o. and contributors. Apache License 2.0 (below).
`src/ui/openidea/**` holds OpenIDEA's own file-type icons drawn in the expui style for
languages whose JetBrains icons are not open source (Go, Rust, Ruby, Dart, Lua, Zig,
Svelte, …). Those using the page-with-corner-badge layout (`goMod`, `goWork`,
+34 -1
Переглянути файл
@@ -4,6 +4,39 @@
use crate::model::{AgentCommand, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentUsage};
use serde_json::{Value, json};
/// Cursor exposes execution modes over ACP, but leaves approval policy to its client.
pub(crate) const CURSOR_APPROVAL: &str = "openidea.cursor.approval";
pub(crate) fn add_client_options(provider: &str, config: &mut Vec<AgentConfigOption>) {
if provider != "cursor" || config.iter().any(|o| o.id == CURSOR_APPROVAL) {
return;
}
config.push(AgentConfigOption {
id: CURSOR_APPROVAL.into(),
name: "Approvals".into(),
description: Some("Tool approvals for this Cursor conversation".into()),
category: Some("approval".into()),
current: Some("ask".into()),
via: AgentConfigVia::Option,
values: vec![
AgentConfigValue {
value: "ask".into(),
name: "Ask for approval".into(),
description: Some("Show permission requests from Cursor".into()),
},
AgentConfigValue {
value: "bypass".into(),
name: "Bypass approvals".into(),
description: Some("Automatically approve tool requests in this conversation".into()),
},
],
});
}
pub(crate) fn bypass_approvals(provider: &str, config: &[AgentConfigOption]) -> bool {
provider == "cursor" && config.iter().any(|o| o.id == CURSOR_APPROVAL && o.current.as_deref() == Some("bypass"))
}
/// The settings in a `session/new` or `session/load` result: its select `configOptions`,
/// plus the older `modes` / `models` fields for what those don't cover.
pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
@@ -64,7 +97,7 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
pub(crate) fn merge_update(config: &mut Vec<AgentConfigOption>, options: &Value) {
let fresh = parse_options(options);
let covered = |o: &AgentConfigOption| fresh.iter().any(|f| f.category.is_some() && f.category == o.category);
config.retain(|o| o.via != AgentConfigVia::Option && !covered(o));
config.retain(|o| o.id == CURSOR_APPROVAL || (o.via != AgentConfigVia::Option && !covered(o)));
let legacy = std::mem::take(config);
config.extend(fresh);
config.extend(legacy);
+36 -4
Переглянути файл
@@ -114,7 +114,13 @@ impl Shared {
}
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
self.known.lock().get(provider).map(|k| k.config.clone()).unwrap_or_default()
let mut config = self.known.lock().get(provider).map(|k| k.config.clone()).unwrap_or_default();
config::add_client_options(provider, &mut config);
// Approval bypass belongs to the conversation, never to another new task.
if let Some(o) = config.iter_mut().find(|o| o.id == config::CURSOR_APPROVAL) {
o.current = Some("ask".into());
}
config
}
/// The commands the agent offered last time in this project.
@@ -516,7 +522,7 @@ impl AgentManager {
o.clone()
};
let live = task.live.lock().clone().filter(|l| !l.peer.is_closed());
if let Some(live) = live {
if let Some(live) = live.filter(|_| option != config::CURSOR_APPROVAL) {
let (method, mut params) = config::set_request(&target, &value);
params["sessionId"] = json!(live.session);
let reply: Value =
@@ -534,6 +540,7 @@ impl AgentManager {
}
s.task.model = model_of(&s.task.config).or(s.task.model.take());
}
task.approve_pending();
task.persist();
task.emit_task();
Ok(())
@@ -789,7 +796,8 @@ impl AgentManager {
impl Task {
fn restore(file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
let task = file.task;
let mut task = file.task;
config::add_client_options(&task.provider, &mut task.config);
let conversation = Conversation::restore(file.entries, file.subagents);
Arc::new(Self {
id: task.id.clone(),
@@ -1174,10 +1182,17 @@ impl Task {
let s = self.state.lock();
(if known { reported } else { s.task.config.clone() }, s.wanted.clone())
};
config::add_client_options(&provider_id, &mut options);
self.shared.remember(&provider_id, Some(&options), None);
for choice in &wanted {
// An option the session doesn't offer yet is set once it does (`apply_late_choices`).
let Some(o) = options.iter().find(|o| o.id == choice.id).cloned() else { continue };
if o.id == config::CURSOR_APPROVAL {
if o.values.iter().any(|v| v.value == choice.value) {
options.iter_mut().find(|o| o.id == choice.id).unwrap().current = Some(choice.value.clone());
}
continue;
}
let already = known && o.current.as_deref() == Some(choice.value.as_str());
if already || !o.values.iter().any(|v| v.value == choice.value) {
continue;
@@ -1221,7 +1236,7 @@ impl Task {
s.wanted
.iter()
.filter_map(|c| {
let o = s.task.config.iter().find(|o| o.id == c.id)?;
let o = s.task.config.iter().find(|o| o.id == c.id && o.id != config::CURSOR_APPROVAL)?;
let due = o.current.as_deref() != Some(c.value.as_str())
&& o.values.iter().any(|v| v.value == c.value)
&& sent.insert((c.id.clone(), c.value.clone()));
@@ -1400,6 +1415,7 @@ impl Task {
let entry = self.push_entry(AgentEntry::Permission { id, title, options: options.clone(), chosen: None });
self.permissions.lock().insert(id, tx);
self.set_status(AgentStatus::NeedsInput, None);
self.approve_pending();
let answer = rx.recv().ok().flatten();
let name = answer
@@ -1423,6 +1439,22 @@ impl Task {
}
}
fn approve_pending(&self) {
let s = self.state.lock();
if self.cancel_pending.load(Ordering::Acquire) || !config::bypass_approvals(&s.task.provider, &s.task.config) {
return;
}
let mut pending = self.permissions.lock();
for entry in s.conversation.main.entries.iter().rev() {
if let AgentEntry::Permission { id, options, chosen: None, .. } = entry
&& let Some(option) = options.iter().find(|o| o.kind == "allow_once")
&& let Some(reply) = pending.remove(id)
{
let _ = reply.send(Some(option.id.clone()));
}
}
}
fn cancel_permissions(&self) {
for (_, reply) in self.permissions.lock().drain() {
let _ = reply.send(None);
+45 -2
Переглянути файл
@@ -199,7 +199,12 @@ fn invalid(message: impl Into<String>) -> ResponseError {
fn from_codex(e: RpcError) -> ResponseError {
match e {
RpcError::Server { code, message, data } => {
let code = if message.to_lowercase().contains("auth") { AUTH_REQUIRED } else { code };
// Protocol errors can list method names containing "auth"; they are not sign-in failures.
let protocol = matches!(
code,
codes::PARSE_ERROR | codes::INVALID_REQUEST | codes::METHOD_NOT_FOUND | codes::INVALID_PARAMS
);
let code = if !protocol && message.to_lowercase().contains("auth") { AUTH_REQUIRED } else { code };
ResponseError { code, message, data }
}
RpcError::Closed => error(codes::INTERNAL_ERROR, "Codex exited"),
@@ -426,10 +431,48 @@ impl CodexShim {
async fn rollback(&self, params: &Value) -> Result<Value, ResponseError> {
let session = str_param(params, "sessionId")?;
let turns = params.get("turns").and_then(Value::as_u64).filter(|n| *n > 0).ok_or_else(|| invalid("turns"))?;
self.call("thread/rollback", json!({ "threadId": session, "numTurns": turns })).await?;
match self.call("thread/rollback", json!({ "threadId": session, "numTurns": turns })).await {
Ok(_) => {}
Err(e)
if e.code == codes::METHOD_NOT_FOUND
|| (e.code == codes::INVALID_REQUEST
&& e.message.contains("unknown variant `thread/rollback`")) =>
{
self.revert(session, turns).await?;
}
Err(e) => return Err(e),
}
Ok(json!({}))
}
/// New Codex versions replace rollback counts with an exclusive turn id.
async fn revert(&self, session: &str, mut remaining: u64) -> Result<(), ResponseError> {
let mut cursor = Value::Null;
let mut seen = HashSet::new();
loop {
let page = self
.call(
"thread/turns/list",
json!({ "threadId": session, "sortDirection": "desc", "limit": remaining.min(100), "cursor": cursor }),
)
.await?;
let turns = page.get("data").and_then(Value::as_array).ok_or_else(|| invalid("Codex returned no turns"))?;
if remaining <= turns.len() as u64 {
let before = str_param(&turns[remaining as usize - 1], "id")?;
self.call("thread/revert", json!({ "threadId": session, "beforeTurnId": before })).await?;
return Ok(());
}
remaining -= turns.len() as u64;
let next = page.get("nextCursor").and_then(Value::as_str);
let Some(next) = next.filter(|next| seen.insert((*next).to_owned())) else {
return Err(invalid(
"Codex history has fewer turns than the conversation; reload the task before editing",
));
};
cursor = json!(next);
}
}
/// Stops following the session's thread (codex unloads it once nothing follows it).
async fn close(&self, params: &Value) -> Result<Value, ResponseError> {
let session = str_param(params, "sessionId")?;
+98
Переглянути файл
@@ -593,6 +593,104 @@ async fn resume_replays_history_then_forks_and_rolls_back() {
assert_eq!(sent(&frames, "thread/unsubscribe")[0]["params"], json!({"threadId": thread}));
}
async fn rollback_replies(turns: u32, replies: Vec<(&str, Value)>) -> (Result<Value, RpcError>, Vec<Value>) {
let frames = replies
.into_iter()
.enumerate()
.flat_map(|(i, (method, mut reply))| {
let id = i + 1;
reply["id"] = json!(id);
[(true, json!({ "id": id, "method": method })), (false, reply)]
})
.collect();
let transcript = Transcript { meta: Value::Null, frames };
let (ours, theirs) = tokio::io::duplex(1 << 16);
let acp = attach(Arc::new(Client::default()), |events| {
let (read, write) = tokio::io::split(ours);
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
})
.unwrap();
let (read, write) = tokio::io::split(theirs);
let player = tokio::spawn(async move { play(&transcript, read, write).await });
let result = request(&acp, "_openidea/rollback", json!({ "sessionId": "s", "turns": turns })).await;
let (sent, _read, _write) = player.await.unwrap();
acp.kill();
(result, sent)
}
fn removed_rollback() -> Value {
json!({ "error": { "code": -32600, "message": "Invalid request: unknown variant `thread/rollback`, expected one of `thread/revert`, `account/gatewayOAuth/read`, `getAuthStatus`" } })
}
#[tokio::test(flavor = "multi_thread")]
async fn removed_rollback_reverts_before_the_target_turn_across_pages() {
let (result, frames) = rollback_replies(
3,
vec![
("thread/rollback", removed_rollback()),
(
"thread/turns/list",
json!({ "result": { "data": [{ "id": "last" }, { "id": "middle" }], "nextCursor": "older" } }),
),
(
"thread/turns/list",
json!({ "result": { "data": [{ "id": "edited" }, { "id": "retained" }], "nextCursor": null } }),
),
("thread/revert", json!({ "result": { "thread": { "id": "s", "turns": [] } } })),
],
)
.await;
assert_eq!(result.unwrap(), json!({}));
let pages = sent(&frames, "thread/turns/list");
assert_eq!(pages[0]["params"], json!({ "threadId": "s", "sortDirection": "desc", "limit": 3, "cursor": null }));
assert_eq!(pages[1]["params"]["cursor"], "older");
assert_eq!(pages[1]["params"]["limit"], 1);
assert_eq!(sent(&frames, "thread/revert")[0]["params"], json!({ "threadId": "s", "beforeTurnId": "edited" }));
}
#[tokio::test(flavor = "multi_thread")]
async fn method_not_found_reverts_the_latest_turn() {
let (result, frames) = rollback_replies(
1,
vec![
("thread/rollback", json!({ "error": { "code": -32601, "message": "Method not found" } })),
("thread/turns/list", json!({ "result": { "data": [{ "id": "last" }], "nextCursor": null } })),
("thread/revert", json!({ "result": {} })),
],
)
.await;
assert_eq!(result.unwrap(), json!({}));
assert_eq!(sent(&frames, "thread/revert")[0]["params"]["beforeTurnId"], "last");
}
#[tokio::test(flavor = "multi_thread")]
async fn rollback_refusals_are_not_retried_as_revert() {
let (result, frames) = rollback_replies(
1,
vec![("thread/rollback", json!({ "error": { "code": -32600, "message": "a turn is still running" } }))],
)
.await;
assert!(result.unwrap_err().to_string().contains("a turn is still running"));
assert_eq!(frames.len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn incomplete_or_repeated_history_pages_do_not_revert_the_wrong_turn() {
for next in [Value::Null, json!("older")] {
let (result, frames) = rollback_replies(
3,
vec![
("thread/rollback", removed_rollback()),
("thread/turns/list", json!({ "result": { "data": [{ "id": "last" }], "nextCursor": "older" } })),
("thread/turns/list", json!({ "result": { "data": [], "nextCursor": next } })),
],
)
.await;
assert!(result.unwrap_err().to_string().contains("reload the task"));
assert!(sent(&frames, "thread/revert").is_empty());
}
}
#[tokio::test(flavor = "multi_thread")]
async fn steering_adds_to_the_running_turn() {
let (results, _client, frames, _) = replay(Scenario::Steer).await;
+61
Переглянути файл
@@ -720,3 +720,64 @@ fn retry_updates_become_a_countdown() {
);
assert_eq!(retry_of(&json!({"sessionUpdate": RETRY_UPDATE}), 0.0), None, "no attempt");
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_approval_switch_resolves_pending_and_survives_restart() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let new = || NewAgentTask {
prompt: text("Fix"),
provider: "cursor".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
};
let task = mgr.create(new()).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.set_config(&task.id, config::CURSOR_APPROVAL, "bypass".into()).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(
mgr.entries(&task.id, None)
.unwrap()
.iter()
.any(|e| matches!(e, AgentEntry::Permission { chosen: Some(name), .. } if name == "Allow"))
);
// Agent config updates must not erase the client's approval setting.
mgr.prompt(&task.id, text("late option"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let t = mgr.task(&task.id).unwrap();
assert!(config::bypass_approvals("cursor", &t.state.lock().task.config));
t.kill();
mgr.prompt(&task.id, text("Fix again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(!agent.calls.lock().iter().any(|c| c.contains("bypass")));
assert!(!config::bypass_approvals("cursor", &mgr.shared.known_config("cursor")));
mgr.set_config(&task.id, config::CURSOR_APPROVAL, "ask".into()).await.unwrap();
mgr.prompt(&task.id, text("Fix once more"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
// An unrelated new conversation still asks, even after the cache was updated.
let other = mgr.create(new()).await.unwrap();
wait_for(&mgr, &other.id, AgentStatus::NeedsInput).await;
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_approval_choice_applies_before_first_prompt() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
prompt: text("Fix"),
provider: "cursor".into(),
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.shutdown();
}
+6 -1
Переглянути файл
@@ -1,8 +1,13 @@
[package]
name = "ide-clipboard"
description = "The OS clipboard's file list (Explorer <-> project view): Windows CF_HDROP read/write, no window or message loop"
description = "The OS clipboard's file list (Explorer <-> project view): Windows CF_HDROP or macOS NSPasteboard file URLs, no window or message loop"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = { version = "0.6", default-features = false, features = ["std"] }
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSDictionary", "NSEnumerator", "NSObject", "NSString", "NSURL", "NSValue"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSPasteboard"] }
+78 -4
Переглянути файл
@@ -7,9 +7,12 @@
//! in full rather than rendered on demand, so no window or message loop is
//! needed and the list survives after `CloseClipboard`.
//!
//! Other platforms keep file lists elsewhere (`public.file-url` on macOS,
//! `text/uri-list` on X11) and are not wired up: [`files`] is empty and
//! [`set_files`] fails there.
//! macOS keeps one `public.file-url` item per file on the general
//! `NSPasteboard`; `NSURL` reads and writes them, so Finder's copies paste here
//! and ours paste in Finder.
//!
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
//! empty and [`set_files`] fails there.
use std::path::PathBuf;
@@ -218,7 +221,78 @@ mod imp {
}
}
#[cfg(not(windows))]
#[cfg(target_os = "macos")]
mod imp {
use objc2::ClassType;
use objc2::rc::{Retained, autoreleasepool};
use objc2::runtime::{AnyClass, AnyObject, ProtocolObject};
use objc2_app_kit::{
NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
};
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSURL};
use std::path::PathBuf;
/// `NSURL` as the one class to read, limited to file URLs: a web link the
/// user copied is not a file to paste.
fn read_file_urls<R>(
f: impl FnOnce(&NSPasteboard, &NSArray<AnyClass>, &NSDictionary<NSPasteboardReadingOptionKey, AnyObject>) -> R,
) -> R {
autoreleasepool(|_| {
let board = NSPasteboard::generalPasteboard();
let classes = NSArray::from_slice(&[NSURL::class()]);
let yes = NSNumber::new_bool(true);
// SAFETY: the key is an AppKit constant, valid for the process' lifetime.
let key = unsafe { NSPasteboardURLReadingFileURLsOnlyKey };
let options = NSDictionary::from_slices(&[key], &[yes.as_ref() as &AnyObject]);
f(&board, &classes, &options)
})
}
pub fn has_files() -> bool {
// SAFETY: the class list holds `NSURL`, which reads from pasteboards,
// and the option takes an `NSNumber`.
read_file_urls(|board, classes, options| unsafe {
board.canReadObjectForClasses_options(classes, Some(options))
})
}
pub fn files() -> Vec<PathBuf> {
read_file_urls(|board, classes, options| {
// SAFETY: as in `has_files`; every object read for `NSURL` is one.
let Some(objects) = (unsafe { board.readObjectsForClasses_options(classes, Some(options)) }) else {
return Vec::new();
};
objects
.iter()
.filter_map(|object| object.downcast::<NSURL>().ok())
.filter_map(|url| url.to_file_path())
// Finder ends a folder's URL in `/`; the project view names it without.
.map(|path| path.components().collect())
.collect()
})
}
pub fn set_files(paths: &[PathBuf]) -> bool {
autoreleasepool(|_| {
// Folders get a directory URL (ending in `/`), as Finder writes them.
let urls: Vec<Retained<NSURL>> = paths
.iter()
.filter_map(|p| if p.is_dir() { NSURL::from_directory_path(p) } else { NSURL::from_file_path(p) })
.collect();
if urls.is_empty() {
return false;
}
let writers: Vec<&ProtocolObject<dyn NSPasteboardWriting>> =
urls.iter().map(|url| ProtocolObject::from_ref(&**url)).collect();
let board = NSPasteboard::generalPasteboard();
// Replacing the list also drops the text the user copied before.
board.clearContents();
board.writeObjects(&NSArray::from_slice(&writers))
})
}
}
#[cfg(not(any(windows, target_os = "macos")))]
mod imp {
use std::path::PathBuf;
+30
Переглянути файл
@@ -242,6 +242,33 @@ pub async fn vcs_stage(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeRes
blocking(move || per_repo(&project, &paths, None, |r, paths| r.stage(paths))).await
}
/// Project-host operation (also registered with the remote dispatcher).
pub async fn vcs_add_to_ignore(
host: &Host,
window: &str,
paths: Vec<PathBuf>,
destination: IgnoreDestination,
) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
for path in &paths {
if path == &project.root || !path.starts_with(&project.root) {
return Err(ide_core::IdeError::invalid("Ignore selection is outside the project"));
}
}
apply_git_executable(&project.settings.effective());
let result = ide_vcs::add_to_ignore(&paths, destination);
// Exclude may live outside a worktree's watched directory. Refresh filters and UI explicitly.
project.watcher.reload_ignore_rules();
for (_, watcher) in project.content_watchers.lock().iter() {
watcher.reload_ignore_rules();
}
project.sink.emit(ide_core::IdeEvent::VcsChanged { root: project.root.clone().into() });
result.map(|_| ())
})
.await
}
pub async fn vcs_unstage(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || per_repo(&project, &paths, None, |r, paths| r.unstage(paths))).await
@@ -800,6 +827,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("vcs_branches", |c| async move { vcs_branches(&c.host, &c.window, c.arg("repo")?).await });
d.add("vcs_stashes", |c| async move { vcs_stashes(&c.host, &c.window, c.arg("repo")?).await });
d.add("vcs_stage", |c| async move { vcs_stage(&c.host, &c.window, c.arg("paths")?).await });
d.add("vcs_add_to_ignore", |c| async move {
vcs_add_to_ignore(&c.host, &c.window, c.arg("paths")?, c.arg("destination")?).await
});
d.add("vcs_unstage", |c| async move { vcs_unstage(&c.host, &c.window, c.arg("paths")?).await });
d.add("vcs_stage_patch", |c| async move { vcs_stage_patch(&c.host, &c.window, c.arg("patch")?).await });
d.add("vcs_discard", |c| async move { vcs_discard(&c.host, &c.window, c.arg("paths")?).await });
+20
Переглянути файл
@@ -108,6 +108,26 @@ async fn serves_projects_files_documents_search_and_runs() {
invoke(&peer, "vcs_init", json!({ "dir": project })).await.unwrap();
until("git repository", || project.join(".git").is_dir()).await;
// Real project-host ignore writes travel through the remote command dispatcher.
assert!(Dispatcher::standard().commands().contains(&"vcs_add_to_ignore"));
let ignore_root = dunce::canonicalize(&project).unwrap();
for (name, destination) in [("shared.tmp", "gitignore"), ("private.tmp", "localExclude")] {
let path = ignore_root.join(name);
std::fs::write(&path, "temporary").unwrap();
invoke(&peer, "vcs_add_to_ignore", json!({ "paths": [path], "destination": destination })).await.unwrap();
let entries = invoke(&peer, "fs_read_dir", json!({ "path": ignore_root })).await.unwrap();
let entry = entries.as_array().unwrap().iter().find(|e| e["name"] == name).unwrap();
assert_eq!(entry["ignored"], true);
assert_eq!(entry["excluded"], false);
}
assert!(std::fs::read_to_string(project.join(".gitignore")).unwrap().contains("/shared.tmp"));
assert!(std::fs::read_to_string(project.join(".git/info/exclude")).unwrap().contains("/private.tmp"));
let outside = tmp.path().join("outside.tmp");
std::fs::write(&outside, "keep").unwrap();
assert!(
invoke(&peer, "vcs_add_to_ignore", json!({ "paths": [outside], "destination": "gitignore" })).await.is_err()
);
// Unknown commands and bad arguments come back as IdeErrors.
let e = invoke(&peer, "window_minimize", json!({})).await.unwrap_err();
assert!(e.message.contains("not available remotely"), "{e:?}");
+2
Переглянути файл
@@ -8,11 +8,13 @@ license.workspace = true
[dependencies]
dunce.workspace = true
ide-core.workspace = true
ignore.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
gix = { workspace = true, features = ["sha1", "status", "blob-diff", "revision", "index", "dirwalk", "parallel"] }
tracing.workspace = true
tempfile.workspace = true
which = "8"
regex-lite = "0.1"
+318
Переглянути файл
@@ -0,0 +1,318 @@
//! Literal ignore rules for Project view's Git › Add to .gitignore.
use crate::{Repo, cli};
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::{BTreeMap, HashSet};
use std::fs;
use std::io::{Read, Write};
use std::path::{Component, Path, PathBuf};
#[derive(Clone, Copy, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum IgnoreDestination {
Gitignore,
LocalExclude,
}
struct IgnoreRule {
pattern: String,
relative: PathBuf,
directory: bool,
}
/// Validate the whole selection before writing. Each destination is replaced atomically;
/// a failure in a later repository may leave earlier destinations updated (safe to retry).
/// Never modifies the index or a selected file.
pub fn add_to_ignore(paths: &[PathBuf], destination: IgnoreDestination) -> IdeResult<Vec<PathBuf>> {
let mut edits: BTreeMap<PathBuf, Vec<IgnoreRule>> = BTreeMap::new();
let mut verify = Vec::new();
for path in paths {
// Validate before filesystem access: APFS cannot even stat invalid UTF-8 names.
path.to_str().ok_or_else(|| IdeError::invalid("Path is not UTF-8"))?;
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(IdeError::invalid("Select an absolute path without '..'"));
}
no_symlinks(path)?;
let meta = fs::symlink_metadata(path)?;
if !meta.is_file() && !meta.is_dir() {
return Err(IdeError::invalid("Only regular files and directories can be ignored"));
}
// A selected nested repository directory is an entry of its enclosing repository.
let start = path.parent().ok_or_else(|| IdeError::invalid("Cannot ignore a filesystem root"))?;
let repo = Repo::discover(start)?.ok_or_else(|| IdeError::invalid("Selection is not in a Git repository"))?;
let rel =
path.strip_prefix(repo.root()).map_err(|_| IdeError::invalid("Selection is outside its repository"))?;
let literal = pattern(rel, meta.is_dir())?;
if rel.components().any(|c| c.as_os_str() == ".git") {
return Err(IdeError::invalid("Git administration files cannot be ignored"));
}
let rel_str = rel.to_str().ok_or_else(|| IdeError::invalid("Path is not UTF-8"))?;
let tracked = cli::run(repo.root(), &["--literal-pathspecs", "ls-files", "-z", "--", rel_str], None)?;
if !tracked.stdout.is_empty() {
return Err(IdeError::invalid(format!(
"{} contains tracked files. Ignore rules only affect unversioned files; no files were untracked.",
path.display()
)));
}
// check-ignore rejects --literal-pathspecs; a ./ prefix prevents pathspec
// magic in valid filenames such as :(top)private from being interpreted.
let literal_query = format!("./{rel_str}");
let ignored = cli::run_raw(repo.root(), &["check-ignore", "-q", "--", &literal_query], None)?;
match ignored.code {
Some(0) => continue,
Some(1) => {}
_ => return Err(IdeError::invalid(ignored.stdout_str() + &String::from_utf8_lossy(&ignored.stderr))),
}
verify.push((repo.root().to_path_buf(), rel_str.to_owned()));
let (file, rule, base) = match destination {
IgnoreDestination::LocalExclude => {
let output = cli::run(
repo.root(),
&["rev-parse", "--path-format=absolute", "--git-path", "info/exclude"],
None,
)?;
// Strip only Git's output terminator; spaces are valid in the path.
let raw = output.stdout_str();
let file = crate::repo::absolute(Path::new(
raw.strip_suffix("\r\n").or_else(|| raw.strip_suffix('\n')).unwrap_or(&raw),
))?;
let common = crate::repo::absolute(repo.gix()?.common_dir())?;
if file != common.join("info/exclude") {
return Err(IdeError::invalid("Git returned an unexpected exclude path"));
}
(file, literal, repo.root())
}
IgnoreDestination::Gitignore => {
let base = start
.ancestors()
.take_while(|p| p.starts_with(repo.root()))
.find(|p| p.join(".gitignore").symlink_metadata().is_ok())
.unwrap_or(repo.root());
(base.join(".gitignore"), pattern(path.strip_prefix(base).unwrap(), meta.is_dir())?, base)
}
};
no_symlinks(file.parent().unwrap())?;
validate_file(&file)?;
edits.entry(file).or_default().push(IgnoreRule {
pattern: rule,
relative: path.strip_prefix(base).unwrap().to_path_buf(),
directory: meta.is_dir(),
});
}
let mut changed = Vec::new();
for (file, rules) in edits {
append(&file, &rules).map_err(|e| {
IdeError::new(
e.kind,
format!(
"Could not update {}: {}. Earlier destinations may have succeeded; refresh and retry.",
file.display(),
e.message
),
)
})?;
changed.push(file);
}
for (root, rel) in verify {
if cli::run_raw(&root, &["check-ignore", "-q", "--", &format!("./{rel}")], None)?.code != Some(0) {
return Err(IdeError::invalid(format!(
"Rule saved, but {rel} is still visible to Git. A higher-priority .gitignore rule may override it; edit that file and retry."
)));
}
}
Ok(changed)
}
fn pattern(path: &Path, directory: bool) -> IdeResult<String> {
let mut rule = String::from("/");
for (i, part) in path.components().enumerate() {
let Component::Normal(part) = part else { return Err(IdeError::invalid("Unsafe ignore path")) };
let part = part.to_str().ok_or_else(|| IdeError::invalid("Path is not UTF-8"))?;
if part.contains(['\n', '\r', '\0']) {
return Err(IdeError::invalid(
"Paths containing a newline or NUL cannot be represented safely in an ignore file",
));
}
if i > 0 {
rule.push('/');
}
for ch in part.chars() {
if matches!(ch, '\\' | '*' | '?' | '[' | ']' | '#' | '!' | ' ') {
rule.push('\\');
}
rule.push(ch);
}
}
if rule == "/" {
return Err(IdeError::invalid("Cannot ignore a repository root"));
}
if directory {
rule.push('/');
}
Ok(rule)
}
/// Refuse symlinked ancestors too: writing through them could affect another repository.
fn no_symlinks(path: &Path) -> IdeResult<()> {
for part in path.ancestors() {
match fs::symlink_metadata(part) {
Ok(m) if m.file_type().is_symlink() => {
return Err(IdeError::invalid(format!("Refusing symlink path: {}", part.display())));
}
Ok(_) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
}
Ok(())
}
fn validate_file(file: &Path) -> IdeResult<()> {
match fs::symlink_metadata(file) {
Ok(m) if !m.is_file() || m.file_type().is_symlink() => {
Err(IdeError::invalid("Ignore destination must be a regular file, not a symlink"))
}
Ok(m) if m.permissions().readonly() => {
Err(IdeError::invalid(format!("{} is read-only; make it writable and retry", file.display())))
}
Ok(_) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e.into()),
}
}
#[derive(PartialEq, Eq)]
struct Snapshot {
bytes: Vec<u8>,
modified: Option<std::time::SystemTime>,
permissions: fs::Permissions,
}
fn snapshot(file: &Path) -> IdeResult<Option<Snapshot>> {
validate_file(file)?;
let mut options = fs::OpenOptions::new();
options.read(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.custom_flags(libc::O_NOFOLLOW);
}
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
// Open the reparse point itself rather than following a last-component link.
options.custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT
}
match options.open(file) {
Ok(mut handle) => {
let metadata = handle.metadata()?;
if !metadata.is_file() || metadata.file_type().is_symlink() {
return Err(IdeError::invalid("Ignore destination must be a regular file"));
}
let mut bytes = Vec::new();
handle.read_to_end(&mut bytes)?;
Ok(Some(Snapshot { bytes, modified: metadata.modified().ok(), permissions: metadata.permissions() }))
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
fn append(file: &Path, rules: &[IgnoreRule]) -> IdeResult<()> {
no_symlinks(file.parent().unwrap())?;
fs::create_dir_all(file.parent().unwrap())?;
// Conventional sibling lock: create_new never follows a preexisting symlink.
let lock_path = file.with_file_name(format!("{}.lock", file.file_name().unwrap().to_string_lossy()));
let lock = fs::OpenOptions::new().write(true).create_new(true).open(&lock_path);
// Keep lock cleanup scoped to successfully acquired locks only.
let _lock = Lock {
file: lock.map_err(|_| {
IdeError::invalid(format!("{} is locked or not writable; close other writers and retry", file.display()))
})?,
path: lock_path,
};
let before = snapshot(file)?;
let bytes = before.as_ref().map(|s| s.bytes.as_slice()).unwrap_or_default();
let text =
std::str::from_utf8(bytes).map_err(|_| IdeError::invalid("Ignore file is not UTF-8; edit it manually"))?;
if text.contains('\0') {
return Err(IdeError::invalid("Ignore file contains NUL; edit it manually"));
}
let newline = if text.contains("\r\n") { "\r\n" } else { "\n" };
// Identical text earlier in the file may have been overridden by a later
// negation. Deduplicate only rules that this file still applies to the path.
let mut builder = ignore::gitignore::GitignoreBuilder::new("");
for (index, line) in text.lines().enumerate() {
let line = if index == 0 { line.trim_start_matches('\u{feff}') } else { line };
if let Err(error) = builder.add_line(None, line) {
tracing::debug!("{}: {error}", file.display());
}
}
let existing = builder.build().map_err(|e| IdeError::invalid(format!("Cannot parse ignore rules: {e}")))?;
let mut requested = HashSet::new();
let mut updated = bytes.to_vec();
for rule in rules {
if !requested.insert(rule.pattern.as_str())
|| existing.matched_path_or_any_parents(&rule.relative, rule.directory).is_ignore()
{
continue;
}
if !updated.is_empty() && !updated.ends_with(b"\n") {
updated.extend_from_slice(newline.as_bytes());
}
updated.extend_from_slice(rule.pattern.as_bytes());
updated.extend_from_slice(newline.as_bytes());
}
if updated == bytes {
return Ok(());
}
let mut temp = tempfile::NamedTempFile::new_in(file.parent().unwrap())?;
let permissions = match fs::metadata(file) {
Ok(meta) => meta.permissions(),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => _lock.file.metadata()?.permissions(),
Err(e) => return Err(e.into()),
};
temp.as_file().set_permissions(permissions)?;
temp.write_all(&updated)?;
temp.as_file().sync_all()?;
replace_if_unchanged(file, before, temp)
}
fn replace_if_unchanged(file: &Path, before: Option<Snapshot>, temp: tempfile::NamedTempFile) -> IdeResult<()> {
no_symlinks(file.parent().unwrap())?;
if snapshot(file)? != before {
return Err(IdeError::invalid("Ignore file changed while preparing the update; retry"));
}
temp.persist(file).map_err(|e| IdeError::from(e.error))?;
Ok(())
}
struct Lock {
file: fs::File,
path: PathBuf,
}
impl Drop for Lock {
fn drop(&mut self) {
let _ = &self.file;
let _ = fs::remove_file(&self.path);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn concurrent_writer_is_detected_without_overwriting_it() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let file = root.join(".gitignore");
fs::write(&file, "before\n").unwrap();
let before = snapshot(&file).unwrap();
let mut temp = tempfile::NamedTempFile::new_in(&root).unwrap();
temp.write_all(b"before\n/new\n").unwrap();
fs::write(&file, "external writer\n").unwrap();
assert!(replace_if_unchanged(&file, before, temp).unwrap_err().message.contains("changed"));
assert_eq!(fs::read_to_string(file).unwrap(), "external writer\n");
}
}
+2
Переглянути файл
@@ -441,6 +441,7 @@ pub mod changelists;
mod cli;
mod diff;
mod history;
mod ignore;
mod manage;
mod ops;
mod patch;
@@ -454,6 +455,7 @@ mod write;
pub use cli::{detected_git_executable, git_version, set_askpass_env, set_git_executable};
pub use diff::build_partial_patch;
pub use ignore::{IgnoreDestination, add_to_ignore};
pub use manage::{MergeOptions, RebaseOptions, RemoteEdit, Worktree};
pub use remotes::Remote;
pub use roots::Repos;
+1 -1
Переглянути файл
@@ -50,7 +50,7 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
Ok(Some(Repo { root, git_dir, inner: std::sync::Mutex::new(cache), ignored: Default::default() }))
}
fn absolute(p: &Path) -> IdeResult<PathBuf> {
pub(crate) fn absolute(p: &Path) -> IdeResult<PathBuf> {
let p = if p.is_absolute() { p.to_path_buf() } else { std::env::current_dir()?.join(p) };
// Lexically clean `.`/`..` without resolving symlinks, keeping the caller's spelling.
let mut out = PathBuf::new();
+311
Переглянути файл
@@ -0,0 +1,311 @@
//! Runtime tests against real temporary repositories and the Git executable.
use ide_vcs::{IgnoreDestination::*, add_to_ignore};
use std::path::{Path, PathBuf};
use std::process::Command;
fn git(root: &Path, args: &[&str]) -> String {
let output = Command::new("git")
.current_dir(root)
.args(args)
.env_remove("GIT_DIR")
.env_remove("GIT_WORK_TREE")
.env_remove("GIT_INDEX_FILE")
.env("GIT_CONFIG_NOSYSTEM", "1")
.env("GIT_CONFIG_GLOBAL", if cfg!(windows) { "NUL" } else { "/dev/null" })
.output()
.unwrap();
assert!(output.status.success(), "{args:?}: {}", String::from_utf8_lossy(&output.stderr));
String::from_utf8(output.stdout).unwrap()
}
struct Fixture {
_tmp: tempfile::TempDir,
root: PathBuf,
}
impl Fixture {
fn new() -> Self {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("repo");
std::fs::create_dir(&root).unwrap();
git(&root, &["init", "-q"]);
git(&root, &["config", "core.excludesFile", if cfg!(windows) { "NUL" } else { "/dev/null" }]);
Self { _tmp: tmp, root }
}
fn file(&self, name: &str) -> PathBuf {
let path = self.root.join(name);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, "data\n").unwrap();
path
}
fn ignored(&self, rel: &str) {
assert!(!git(&self.root, &["check-ignore", "--", &format!("./{rel}")]).is_empty());
assert!(
git(&self.root, &["--literal-pathspecs", "status", "--porcelain", "--untracked-files=all", "--", rel])
.is_empty()
);
}
}
#[test]
fn shared_literals_multiselect_and_directory_are_anchored() {
let fx = Fixture::new();
let mut names = vec!["has space", "#hash", "!bang", "[ab].txt", "-dash", "中文.txt"];
// Win32 filenames cannot contain wildcard characters or end in a space.
if cfg!(unix) {
names.extend(["has space ", "[ab]*?.txt", ":(top)literal", ":!literal", ":(glob)*"]);
}
let mut paths: Vec<_> = names.iter().map(|n| fx.file(n)).collect();
fx.file("literal");
fx.file("cache/a.txt");
fx.file("other/cache/a.txt");
paths.push(fx.root.join("cache"));
for name in &names {
fx.file(&format!("other/{name}"));
}
add_to_ignore(&paths, Gitignore).unwrap();
for name in &names {
fx.ignored(name);
}
fx.ignored("cache/a.txt");
let status = git(&fx.root, &["status", "--porcelain", "--untracked-files=all"]);
assert!(status.contains("other/cache/a.txt"));
assert!(status.contains("other/!bang"));
assert!(status.lines().any(|line| line == "?? literal"));
let text = std::fs::read_to_string(fx.root.join(".gitignore")).unwrap();
assert!(text.contains("/cache/\n"));
assert!(text.contains("/\\[ab\\].txt\n"));
if cfg!(unix) {
assert!(text.contains("/\\[ab\\]\\*\\?.txt\n"));
}
}
#[test]
fn local_exclude_is_local_preserves_comments_crlf_and_deduplicates() {
let fx = Fixture::new();
let path = fx.file("private.txt");
let exclude = fx.root.join(".git/info/exclude");
std::fs::write(&exclude, "# keep this\r\n/other\r\n# no final newline").unwrap();
add_to_ignore(&[path.clone(), path.clone()], LocalExclude).unwrap();
let once = std::fs::read(&exclude).unwrap();
assert_eq!(
String::from_utf8(once.clone()).unwrap(),
"# keep this\r\n/other\r\n# no final newline\r\n/private.txt\r\n"
);
add_to_ignore(&[path], LocalExclude).unwrap();
assert_eq!(std::fs::read(&exclude).unwrap(), once);
fx.ignored("private.txt");
assert!(git(&fx.root, &["status", "--porcelain"]).is_empty());
assert!(!fx.root.join(".gitignore").exists());
}
#[test]
fn nearest_existing_ignore_and_nested_repositories_use_correct_bases() {
let fx = Fixture::new();
let a = fx.file("pkg/deep/a.txt");
std::fs::write(fx.root.join("pkg/.gitignore"), "# nested\n").unwrap();
add_to_ignore(&[a], Gitignore).unwrap();
fx.ignored("pkg/deep/a.txt");
assert_eq!(std::fs::read_to_string(fx.root.join("pkg/.gitignore")).unwrap(), "# nested\n/deep/a.txt\n");
assert!(!fx.root.join(".gitignore").exists());
let b = fx.file("nested/b.txt");
git(&fx.root.join("nested"), &["init", "-q"]);
add_to_ignore(&[b], Gitignore).unwrap();
assert_eq!(std::fs::read_to_string(fx.root.join("nested/.gitignore")).unwrap(), "/b.txt\n");
assert!(!fx.root.join(".gitignore").exists());
}
#[test]
fn tracked_files_and_directories_fail_before_any_write() {
let fx = Fixture::new();
let tracked = fx.file("dir/tracked");
let new = fx.file("new");
git(&fx.root, &["add", "dir/tracked"]);
for path in [tracked, fx.root.join("dir")] {
let error = add_to_ignore(&[new.clone(), path], Gitignore).unwrap_err();
assert!(error.message.contains("tracked files"));
assert!(!fx.root.join(".gitignore").exists());
}
assert!(git(&fx.root, &["diff", "--cached", "--name-only"]).contains("dir/tracked"));
}
#[test]
fn worktree_and_submodule_git_files_resolve_common_exclude() {
let fx = Fixture::new();
fx.file("initial");
git(&fx.root, &["add", "initial"]);
git(
&fx.root,
&[
"-c",
"user.name=Test",
"-c",
"[email protected]",
"-c",
"commit.gpgsign=false",
"commit",
"-qm",
"initial",
],
);
let worktree = fx.root.parent().unwrap().join("linked");
git(&fx.root, &["worktree", "add", "-qb", "linked", worktree.to_str().unwrap()]);
let p = worktree.join("private");
std::fs::write(&p, "x").unwrap();
add_to_ignore(&[p], LocalExclude).unwrap();
assert!(std::fs::read_to_string(fx.root.join(".git/info/exclude")).unwrap().contains("/private\n"));
assert_eq!(git(&worktree, &["check-ignore", "private"]), "private\n");
assert!(git(&worktree, &["status", "--porcelain"]).is_empty());
// A real gitfile layout like a submodule, with metadata outside its worktree.
let sub = fx.root.join("sub");
std::fs::create_dir(&sub).unwrap();
let metadata = fx.root.join(".git/modules/sub");
std::fs::create_dir_all(metadata.parent().unwrap()).unwrap();
git(&sub, &["init", "-q", "--separate-git-dir", metadata.to_str().unwrap()]);
std::fs::write(sub.join("tracked"), "x").unwrap();
git(&sub, &["add", "tracked"]);
git(
&sub,
&[
"-c",
"user.name=Test",
"-c",
"[email protected]",
"-c",
"commit.gpgsign=false",
"commit",
"-qm",
"submodule initial",
],
);
let commit = git(&sub, &["rev-parse", "HEAD"]);
std::fs::write(
fx.root.join(".gitmodules"),
"[submodule \"sub\"]\n\tpath = sub\n\turl = https://example.invalid/sub.git\n",
)
.unwrap();
git(&fx.root, &["update-index", "--add", "--cacheinfo", "160000", commit.trim(), "sub"]);
assert!(add_to_ignore(std::slice::from_ref(&sub), LocalExclude).unwrap_err().message.contains("tracked files"));
std::fs::write(sub.join("private"), "x").unwrap();
add_to_ignore(&[sub.join("private")], LocalExclude).unwrap();
assert!(std::fs::read_to_string(metadata.join("info/exclude")).unwrap().contains("/private\n"));
assert_eq!(git(&sub, &["check-ignore", "private"]), "private\n");
}
#[test]
fn lock_failure_invalid_destination_and_traversal_preserve_data() {
let fx = Fixture::new();
let path = fx.file("new");
let file = fx.root.join(".gitignore");
std::fs::write(&file, "# original\n").unwrap();
std::fs::write(fx.root.join(".gitignore.lock"), "another writer").unwrap();
assert!(add_to_ignore(std::slice::from_ref(&path), Gitignore).unwrap_err().message.contains("locked"));
assert_eq!(std::fs::read_to_string(&file).unwrap(), "# original\n");
assert_eq!(std::fs::read_to_string(fx.root.join(".gitignore.lock")).unwrap(), "another writer");
assert!(add_to_ignore(&[fx.root.join("dir/../new")], Gitignore).is_err());
std::fs::remove_file(fx.root.join(".gitignore.lock")).unwrap();
std::fs::write(&file, b"# invalid\xff").unwrap();
assert!(add_to_ignore(&[path], Gitignore).is_err());
assert_eq!(std::fs::read(file).unwrap(), b"# invalid\xff");
assert!(!fx.root.join(".gitignore.lock").exists());
}
#[cfg(unix)]
#[test]
fn backslash_is_literal_newlines_and_symlinks_are_rejected() {
use std::os::unix::fs::symlink;
let fx = Fixture::new();
let backslash = fx.file("back\\slash");
add_to_ignore(&[backslash], Gitignore).unwrap();
fx.ignored("back\\slash");
let original = std::fs::read(fx.root.join(".gitignore")).unwrap();
for name in ["line\nname", "line\rname"] {
let path = fx.file(name);
assert!(add_to_ignore(&[path], Gitignore).is_err());
}
let outside = fx.root.parent().unwrap().join("outside");
std::fs::write(&outside, "safe").unwrap();
std::fs::remove_file(fx.root.join(".gitignore")).unwrap();
symlink(&outside, fx.root.join(".gitignore")).unwrap();
assert!(add_to_ignore(&[fx.file("new")], Gitignore).is_err());
assert_eq!(std::fs::read_to_string(&outside).unwrap(), "safe");
std::fs::remove_file(fx.root.join(".gitignore")).unwrap();
std::fs::write(fx.root.join(".gitignore"), &original).unwrap();
symlink(fx.root.parent().unwrap(), fx.root.join("link")).unwrap();
assert!(add_to_ignore(&[fx.root.join("link/outside")], LocalExclude).is_err());
assert_eq!(std::fs::read(fx.root.join(".gitignore")).unwrap(), original);
}
#[test]
fn overridden_local_rule_is_not_duplicated_and_explains_precedence() {
let fx = Fixture::new();
let path = fx.file("private");
std::fs::write(fx.root.join(".gitignore"), "!/private\n").unwrap();
let error = add_to_ignore(std::slice::from_ref(&path), LocalExclude).unwrap_err();
assert!(error.message.contains("higher-priority"));
let exclude = fx.root.join(".git/info/exclude");
let once = std::fs::read(&exclude).unwrap();
assert!(add_to_ignore(&[path], LocalExclude).is_err());
assert_eq!(std::fs::read(exclude).unwrap(), once);
}
#[test]
fn readonly_and_nonfile_destinations_remain_untouched() {
let fx = Fixture::new();
let path = fx.file("new");
let file = fx.root.join(".gitignore");
std::fs::create_dir(&file).unwrap();
assert!(add_to_ignore(std::slice::from_ref(&path), Gitignore).is_err());
std::fs::remove_dir(&file).unwrap();
std::fs::write(&file, "# original\n").unwrap();
let original = std::fs::metadata(&file).unwrap().permissions();
let mut permissions = original.clone();
permissions.set_readonly(true);
std::fs::set_permissions(&file, permissions).unwrap();
let result = add_to_ignore(&[path], Gitignore);
std::fs::set_permissions(&file, original).unwrap();
assert!(result.unwrap_err().message.contains("read-only"));
assert_eq!(std::fs::read_to_string(file).unwrap(), "# original\n");
}
#[test]
fn existing_bytes_are_preserved_for_newline_and_bom_variants() {
for original in [b"# comment".as_slice(), b"unrelated\\", b"\xef\xbb\xbf# BOM\r\n", b"# LF\n", b""] {
let fx = Fixture::new();
let path = fx.file("new");
let file = fx.root.join(".gitignore");
std::fs::write(&file, original).unwrap();
add_to_ignore(&[path], Gitignore).unwrap();
assert!(std::fs::read(file).unwrap().starts_with(original));
fx.ignored("new");
}
}
#[cfg(unix)]
#[test]
fn non_utf8_paths_are_rejected_without_creating_ignore_files() {
use std::os::unix::ffi::OsStringExt;
let fx = Fixture::new();
let path = fx.root.join(std::ffi::OsString::from_vec(b"invalid\xff".to_vec()));
// APFS rejects creation of this filename; the request must fail clearly before I/O.
assert!(add_to_ignore(&[path], Gitignore).unwrap_err().message.contains("UTF-8"));
assert!(!fx.root.join(".gitignore").exists());
}
#[test]
fn later_negations_allow_reignoring_shared_and_local_paths_without_batch_duplicates() {
for destination in [Gitignore, LocalExclude] {
let fx = Fixture::new();
let path = fx.file("private");
let file = match destination {
Gitignore => fx.root.join(".gitignore"),
LocalExclude => fx.root.join(".git/info/exclude"),
};
std::fs::write(&file, "/private\n!/private\n").unwrap();
assert!(git(&fx.root, &["status", "--porcelain", "--untracked-files=all"]).contains("private"));
add_to_ignore(&[path.clone(), path.clone()], destination).unwrap();
assert_eq!(std::fs::read_to_string(&file).unwrap(), "/private\n!/private\n/private\n");
fx.ignored("private");
let once = std::fs::read(&file).unwrap();
add_to_ignore(&[path], destination).unwrap();
assert_eq!(std::fs::read(file).unwrap(), once);
}
}
+1
Переглянути файл
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
dunce.workspace = true
gix = { workspace = true, features = ["sha1"] }
ide-core.workspace = true
serde.workspace = true
specta.workspace = true
+26 -2
Переглянути файл
@@ -80,20 +80,24 @@ pub(crate) struct GitignoreStack {
/// `.git/info/exclude` and the global excludes file, rooted at the repo root.
repo_level: RwLock<Vec<Gitignore>>,
cache: Mutex<HashMap<PathBuf, Option<Arc<Gitignore>>>>,
nested: Mutex<HashMap<PathBuf, Option<Arc<GitignoreStack>>>>,
}
impl GitignoreStack {
pub fn new(near: &Path) -> Self {
let repo_root = find_repo_root(near);
let repo_level = RwLock::new(Self::load_repo_level(repo_root.as_deref()));
Self { repo_root, repo_level, cache: Mutex::default() }
Self { repo_root, repo_level, cache: Mutex::default(), nested: Mutex::default() }
}
fn load_repo_level(repo_root: Option<&Path>) -> Vec<Gitignore> {
let mut repo_level = Vec::new();
if let Some(root) = repo_root {
let mut builder = GitignoreBuilder::new(root);
let exclude = root.join(".git").join("info").join("exclude");
let exclude = gix::discover(root)
.ok()
.map(|r| r.common_dir().join("info/exclude"))
.unwrap_or_else(|| root.join(".git/info/exclude"));
if exclude.is_file() {
builder.add(exclude);
}
@@ -115,11 +119,13 @@ impl GitignoreStack {
/// Re-reads `.git/info/exclude` and the global excludes file.
pub fn reload_repo_level(&self) {
self.nested.lock().clear();
*self.repo_level.write() = Self::load_repo_level(self.repo_root.as_deref());
}
/// Forgets the cached rules of `dir` and every directory below it.
pub fn invalidate_tree(&self, dir: &Path) {
self.nested.lock().clear();
let mut cache = self.cache.lock();
// Lookups always populate every ancestor, so no key below `dir` exists without `dir`.
if cache.contains_key(dir) {
@@ -133,6 +139,7 @@ impl GitignoreStack {
/// Forgets the cached rules of `dir` (after its `.gitignore` changed).
pub fn invalidate(&self, dir: &Path) {
self.nested.lock().clear();
self.cache.lock().remove(dir);
}
@@ -169,6 +176,23 @@ impl GitignoreStack {
/// Whether `path` (absolute) is ignored. `is_dir` refers to `path` itself.
pub fn is_ignored(&self, path: &Path, is_dir: bool) -> bool {
// A project's watcher can span independent nested repositories. Their local
// excludes and ignore ancestry must stop at their own repository boundary.
if let Some(parent) = path.parent() {
let nested = self
.nested
.lock()
.entry(parent.to_path_buf())
.or_insert_with(|| {
find_repo_root(parent)
.filter(|root| self.repo_root.as_ref() != Some(root))
.map(|_| Arc::new(Self::new(parent)))
})
.clone();
if let Some(nested) = nested {
return nested.is_ignored(path, is_dir);
}
}
if self.repo_root.as_deref() == Some(path) {
return false;
}
+11 -3
Переглянути файл
@@ -50,6 +50,7 @@ type OnChange = Box<dyn Fn(&FsBatch) + Send + Sync>;
pub struct Watcher {
inner: Inner,
excludes: SharedExcludes,
rules: Arc<GitignoreStack>,
}
type SharedExcludes = Arc<RwLock<ExcludeMatcher>>;
@@ -74,6 +75,7 @@ impl Watcher {
let root = dunce::canonicalize(root)?;
let filter = EventFilter::new(root.clone(), &excludes);
let shared = filter.excludes.clone();
let rules = filter.gitignore.clone();
let emit = move |batch: &FsBatch| {
sink.emit(IdeEvent::FsChanged {
created: batch.created.iter().map(Into::into).collect(),
@@ -87,7 +89,7 @@ impl Watcher {
WatchMode::Flat => Self::start_recursive(root, filter, emit, RecursiveMode::NonRecursive),
WatchMode::PerDirectory => Self::start_per_directory(root, filter, emit),
}?;
Ok(Self { inner, excludes: shared })
Ok(Self { inner, excludes: shared, rules })
}
/// Replaces the exclude globs (Settings › Project Structure / File Types
@@ -97,6 +99,12 @@ impl Watcher {
*self.excludes.write() = ExcludeMatcher::new(excludes);
}
/// Explicit refresh for writes to Git common metadata outside the watched root.
pub fn reload_ignore_rules(&self) {
self.rules.reload_repo_level();
self.rules.invalidate_tree(self.rules.repo_root().unwrap_or(Path::new("/")));
}
/// Number of OS-level watches (1 in recursive and flat mode).
pub fn watch_count(&self) -> usize {
match &self.inner {
@@ -374,13 +382,13 @@ fn merge(prev: Option<Change>, next: Change) -> Change {
pub(crate) struct EventFilter {
root: PathBuf,
excludes: SharedExcludes,
gitignore: GitignoreStack,
gitignore: Arc<GitignoreStack>,
}
impl EventFilter {
pub fn new(root: PathBuf, excludes: &[String]) -> Self {
Self {
gitignore: GitignoreStack::new(&root),
gitignore: Arc::new(GitignoreStack::new(&root)),
excludes: Arc::new(RwLock::new(ExcludeMatcher::new(excludes))),
root,
}
+44
Переглянути файл
@@ -321,3 +321,47 @@ fn watcher_reports_changes() {
std::thread::sleep(Duration::from_millis(500));
assert_eq!(batches.lock().len(), n, "no events after drop");
}
#[test]
fn worktree_and_nested_repository_local_excludes_are_reflected_in_listings() {
fn git(root: &std::path::Path, args: &[&str]) {
let out = std::process::Command::new("git").current_dir(root).args(args).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
}
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("repo");
std::fs::create_dir(&root).unwrap();
git(&root, &["init", "-q"]);
std::fs::write(root.join("initial"), "x").unwrap();
git(&root, &["add", "initial"]);
git(
&root,
&[
"-c",
"user.name=Test",
"-c",
"[email protected]",
"-c",
"commit.gpgsign=false",
"commit",
"-qm",
"initial",
],
);
let linked = root.parent().unwrap().join("linked");
git(&root, &["worktree", "add", "-qb", "linked", linked.to_str().unwrap()]);
std::fs::write(linked.join("private"), "x").unwrap();
std::fs::write(root.join(".git/info/exclude"), "/private\n").unwrap();
let entries = ide_vfs::read_dir(&linked, &[]).unwrap();
assert!(entries.iter().find(|e| e.name == "private").unwrap().ignored);
assert!(!entries.iter().find(|e| e.name == "private").unwrap().excluded);
let nested = linked.join("nested");
std::fs::create_dir(&nested).unwrap();
git(&nested, &["init", "-q"]);
std::fs::write(nested.join("private"), "x").unwrap();
let entries = ide_vfs::read_dir(&nested, &[]).unwrap();
assert!(!entries.iter().find(|e| e.name == "private").unwrap().ignored);
std::fs::write(nested.join(".git/info/exclude"), "/private\n").unwrap();
let entries = ide_vfs::read_dir(&nested, &[]).unwrap();
assert!(entries.iter().find(|e| e.name == "private").unwrap().ignored);
}
+4 -1
Переглянути файл
@@ -295,7 +295,7 @@ a token.
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
219 themeable tokens: 113 in the UI theme file, 106 in the editor colour scheme file.
222 themeable tokens: 116 in the UI theme file, 106 in the editor colour scheme file.
### Surfaces (UI theme)
@@ -374,6 +374,9 @@ a token.
| `--gutter-modified` | `#375fad` | `#88adf7` |
| `--gutter-added` | `#549159` | `#7fc784` |
| `--gutter-deleted` | `#868a91` | `#767a8a` |
| `--diff-modified` | `#385570` | `#c2d8f2` |
| `--diff-inserted` | `#294436` | `#bee6be` |
| `--diff-deleted` | `#484a4a` | `#d6d6d6` |
### Syntax (editor scheme)
+336
Переглянути файл
@@ -0,0 +1,336 @@
/**
* The diff viewer over a real git repository (`diffRepo.ts`): each case opens
* HEAD against the working copy and checks the IDEA-style change types of
* lines and words, the difference count against `git diff`, and that the
* 10,000-line files open, scroll and navigate in every viewer mode.
*/
import { rmSync } from "node:fs";
import { dirname } from "node:path";
import type { Page } from "@playwright/test";
import { gitHunks, readSides, tempDiffRepo } from "./diffRepo";
import { expect, test } from "./fixtures";
type Kind = "modified" | "inserted" | "deleted";
interface Opts {
mode?: "split" | "unified";
/** Padded panes (true), or panes joined by a curved divider (false, the default). */
alignChanges?: boolean;
syncScroll?: boolean;
collapse?: boolean;
ignore?: "none" | "trim" | "whitespace" | "whitespaceAndLines";
}
let repo = "";
test.beforeAll(() => {
repo = tempDiffRepo();
});
test.afterAll(() => rmSync(dirname(repo), { recursive: true, force: true }));
const toolbar = (page: Page) => page.getByRole("toolbar", { name: "Diff" });
const counter = (page: Page) =>
toolbar(page)
.locator("span")
.filter({ hasText: /differen|identical/ });
/** Opens HEAD ↔ working tree of `path` and waits until the difference count shows; returns the time it took. */
async function openCase(page: Page, path: string, opts: Opts = {}): Promise<number> {
const { left, right } = readSides(repo, path);
const options = {
mode: "split",
ignore: "none",
highlight: "words",
collapse: false,
alignChanges: true,
syncScroll: true,
...opts,
};
const started = Date.now();
await page.evaluate(
async ({ path, left, right, options }) => {
localStorage.setItem("openidea.vcs.diffOptions", JSON.stringify(options));
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("diff.compareTexts", {
path,
title: path,
left: { text: left, label: "HEAD" },
right: { text: right, label: "Working tree" },
});
},
{ path, left, right, options },
);
await expect(counter(page)).toBeVisible({ timeout: 20_000 });
const elapsed = Date.now() - started;
// Word highlights land a microtask after both panes exist.
await page.evaluate(() => new Promise(requestAnimationFrame));
return elapsed;
}
interface Side {
lines: Kind[];
words: [string, Kind][];
}
/** Change types of the rendered lines and words of each pane (`a` / `b`; unified: `b` only). */
async function rendered(page: Page): Promise<{ a: Side; b: Side; deletedChunks: number }> {
return page
.locator(".cm-mergeView, .cm-editor.cm-merge-b")
.first()
.evaluate((el) => {
const root = el.closest("[role=region]") ?? el;
const kind = (e: Element, prefix: string) =>
(e.className.match(new RegExp(`${prefix}-(modified|inserted|deleted)`))?.[1] ?? null) as Kind | null;
const side = (cls: string) => {
const ed = root.querySelector(`.cm-editor.cm-merge-${cls}`);
const lines = [...(ed?.querySelectorAll(".cm-content > .cm-line") ?? [])]
.map((l) => kind(l, "cm-diffLine"))
.filter((k): k is Kind => !!k);
const words = [...(ed?.querySelectorAll(".cm-diffWord") ?? [])].map(
(w) => [w.textContent ?? "", kind(w, "cm-diffWord")!] as [string, Kind],
);
return { lines, words };
};
return { a: side("a"), b: side("b"), deletedChunks: root.querySelectorAll(".cm-deletedChunk").length };
});
}
const differences = (n: number) => (n === 1 ? "1 difference" : `${n} differences`);
async function expectCount(page: Page, path: string, n = gitHunks(repo, path)) {
await expect(counter(page)).toHaveText(new RegExp(`^(${differences(n)}|\\d+ of ${n} differences)$`));
}
const all = (n: number, k: Kind) => Array<Kind>(n).fill(k);
async function shot(page: Page, name: string) {
const path = test.info().outputPath(`${name}.png`);
await page.getByRole("region").last().screenshot({ path, animations: "disabled" });
await test.info().attach(name, { path, contentType: "image/png" });
}
test.describe("small cases (side-by-side, Highlight words)", () => {
const cases: {
path: string;
a: Kind[];
b: Kind[];
wordsA?: [string, Kind][];
wordsB?: [string, Kind][];
}[] = [
{
path: "src/words.ts",
a: all(2, "modified"),
b: all(2, "modified"),
wordsA: [["true", "modified"]],
wordsB: [
["false", "modified"],
[" x,", "inserted"],
],
},
{ path: "src/insert.ts", a: [], b: all(5, "inserted"), wordsA: [], wordsB: [] },
{ path: "src/delete.ts", a: all(4, "deleted"), b: [], wordsA: [], wordsB: [] },
{
path: "docs/readme-zh.md",
a: ["modified"],
b: ["modified"],
wordsA: [["测试", "modified"]],
wordsB: [["示例", "modified"]],
},
{
path: "docs/emoji.md",
a: ["modified"],
b: ["modified"],
wordsA: [["👋", "modified"]],
wordsB: [["🌍", "modified"]],
},
{
path: "data/no-eol.txt",
a: ["modified"],
b: ["modified"],
wordsA: [["beta", "modified"]],
wordsB: [["gamma", "modified"]],
},
{ path: "src/indent.py", a: all(3, "modified"), b: all(3, "modified") },
{ path: "src/moved.ts", a: all(5, "deleted"), b: all(5, "inserted"), wordsA: [], wordsB: [] },
{ path: "src/new-file.ts", a: [], b: all(6, "inserted"), wordsA: [], wordsB: [] },
{ path: "src/deleted-file.ts", a: all(6, "deleted"), b: [], wordsA: [], wordsB: [] },
];
for (const c of cases)
test(c.path, async ({ workbench: page }) => {
await openCase(page, c.path);
await expectCount(page, c.path);
const { a, b } = await rendered(page);
expect(a.lines, "left lines").toEqual(c.a);
expect(b.lines, "right lines").toEqual(c.b);
if (c.wordsA) expect(a.words, "left words").toEqual(c.wordsA);
if (c.wordsB) expect(b.words, "right words").toEqual(c.wordsB);
});
test("a renamed field with a comment added reads as one modified block", async ({ workbench: page }) => {
await openCase(page, "src/options.ts");
await expectCount(page, "src/options.ts", 1);
const { a, b } = await rendered(page);
expect(a.lines).toEqual(["modified"]);
expect(b.lines).toEqual(all(6, "modified"));
expect(a.words).toEqual([["syncScroll", "modified"]]);
expect(b.words.every(([, k]) => k === "modified")).toBe(true);
const text = b.words.map(([t]) => t).join("\n");
expect(text).toMatch(/^\/\*\*\n/);
expect(text).toMatch(/syncScrolling$/);
await shot(page, "options");
});
test("an edit in the middle of a 44,000-character minified line", async ({ workbench: page }) => {
const path = "dist/app.min.js";
await openCase(page, path);
await expectCount(page, path);
// Long lines render only around the horizontal viewport: scroll to the edit.
const { left } = readSides(repo, path);
const at = left.indexOf("f(1000,") / left.length;
for (const side of ["a", "b"])
await page
.locator(`.cm-editor.cm-merge-${side} .cm-scroller`)
.evaluate((s, at) => (s.scrollLeft = at * s.scrollWidth - s.clientWidth / 2), at);
await expect.poll(async () => (await rendered(page)).a.words).toEqual([["f", "modified"]]);
const { a, b } = await rendered(page);
expect(a.lines).toEqual(["modified"]);
expect(b.lines).toEqual(["modified"]);
expect(b.words).toEqual([["g", "modified"]]);
await shot(page, "minified");
});
test("a final newline added", async ({ workbench: page }) => {
await openCase(page, "data/add-eol.txt");
await expectCount(page, "data/add-eol.txt");
const { a, b } = await rendered(page);
// IDEA compares lines without their breaks: an empty line inserted, "beta" unchanged.
expect(a.lines).toEqual([]);
expect(b.lines).toEqual(["inserted"]);
await shot(page, "add-eol");
});
test("ignoring whitespace hides an indentation-only change", async ({ workbench: page }) => {
await openCase(page, "src/indent.py", { ignore: "whitespace" });
await expect(counter(page)).toHaveText("No differences");
expect((await rendered(page)).b.lines).toEqual([]);
});
test("unified viewer shows old lines deleted and new lines inserted", async ({ workbench: page }) => {
await openCase(page, "src/options.ts", { mode: "unified" });
await expectCount(page, "src/options.ts", 1);
const { b, deletedChunks } = await rendered(page);
expect(deletedChunks).toBe(1);
expect(b.lines).toEqual(all(6, "inserted"));
await shot(page, "options-unified");
});
});
test.describe("10,000-line files", () => {
test.describe.configure({ timeout: 60_000 });
const modes: [string, Opts][] = [
["padded", {}],
["sync scrolling", { alignChanges: false }],
["unified", { mode: "unified" }],
["collapsed", { collapse: true }],
];
/** Scrolls the diff to the end: the padded panes scroll together, the others from the right (or unified) pane. */
async function scrollToEnd(page: Page) {
await page
.locator(".cm-editor.cm-merge-b")
.first()
.evaluate((ed) => {
const merge = ed.closest<HTMLElement>(".cm-mergeView");
const s =
merge && merge.scrollHeight > merge.clientHeight ? merge : ed.querySelector<HTMLElement>(".cm-scroller")!;
s.scrollTop = s.scrollHeight;
});
await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
}
/** Text of the first line fully shown in each pane. */
async function topLines(page: Page) {
return page
.locator(".cm-mergeView")
.first()
.evaluate((mv) => {
const top = (side: string) => {
const ed = mv.querySelector(`.cm-editor.cm-merge-${side}`)!;
const r = mv.getBoundingClientRect();
const s = ed.querySelector(".cm-scroller")!.getBoundingClientRect();
const y = Math.max(r.top, s.top);
return [...ed.querySelectorAll(".cm-content > .cm-line")].find((l) => l.getBoundingClientRect().top >= y)
?.textContent;
};
return [top("a"), top("b")];
});
}
for (const [mode, opts] of modes) {
test(`scattered edits, inserts and deletes (${mode})`, async ({ workbench: page }) => {
const path = "big/scattered.ts";
const ms = await openCase(page, path, opts);
test.info().annotations.push({ type: "open", description: `${ms} ms` });
expect(ms, "time to open").toBeLessThan(8_000);
await expectCount(page, path, 42);
// The first change is a single edited identifier.
await page.locator(".cm-editor.cm-merge-b .cm-content").first().click();
await page.keyboard.press("Meta+ArrowUp");
await page.keyboard.press("F7");
await expect(counter(page)).toHaveText("1 of 42 differences");
const first = await rendered(page);
if (opts.mode !== "unified") {
expect(first.a.words).toContainEqual(["compute", "modified"]);
expect(first.b.words).toContainEqual(["computeFast", "modified"]);
}
// The last difference is reachable and still highlighted.
await page.keyboard.press("Meta+ArrowDown");
await page.keyboard.press("Shift+F7");
await expect(counter(page)).toHaveText("42 of 42 differences");
const last = await rendered(page);
if (opts.mode === "unified") expect(last.b.lines).toContain("inserted");
else expect(last.b.words).toContainEqual(["computeFast", "modified"]);
await scrollToEnd(page);
if (opts.mode !== "unified") {
const [a, b] = await topLines(page);
expect(a, "panes line up at the end").toBe(b);
// Collapsed, the unchanged tail folds away.
if (!opts.collapse) expect(b).toMatch(/value99\d\d/);
}
await shot(page, `scattered-${mode.replace(" ", "-")}`);
});
}
test("every tenth line edited: 1,000 differences", async ({ workbench: page }) => {
const path = "big/every-tenth.ts";
const ms = await openCase(page, path, { alignChanges: false });
test.info().annotations.push({ type: "open", description: `${ms} ms` });
expect(ms, "time to open").toBeLessThan(8_000);
await expectCount(page, path, 1_000);
await scrollToEnd(page);
const { a, b } = await rendered(page);
expect(b.words.length).toBeGreaterThan(0);
expect(b.words.every(([t, k]) => t === "entry" && k === "modified")).toBe(true);
expect(a.words.every(([t, k]) => t === "item" && k === "modified")).toBe(true);
await shot(page, "every-tenth");
});
for (const [mode, opts] of modes.slice(0, 3))
test(`every line edited: one 10,000-line block (${mode})`, async ({ workbench: page }) => {
const path = "big/rewrite.ts";
const ms = await openCase(page, path, opts);
test.info().annotations.push({ type: "open", description: `${ms} ms` });
expect(ms, "time to open").toBeLessThan(8_000);
await expectCount(page, path, 1);
await scrollToEnd(page);
const { b } = await rendered(page);
if (opts.mode === "unified") expect(b.lines.every((k) => k === "inserted")).toBe(true);
else {
expect(b.lines.length).toBeGreaterThan(10);
expect(b.lines.every((k) => k === "modified")).toBe(true);
expect(b.words).toContainEqual(["let", "modified"]);
}
await shot(page, `rewrite-${mode.replace(" ", "-")}`);
});
});
+189
Переглянути файл
@@ -0,0 +1,189 @@
/**
* A git repository of diff viewer cases: each file is committed, then changed
* in the working tree (or added / deleted), covering word edits, pure inserts
* and deletes, whitespace, CJK, missing final newlines, moves, a minified line
* and 10,000-line files. The e2e specs open HEAD against the working copy; run
* `node e2e/diffRepo.ts <dir>` to build it for manual QA in the app.
*/
import { execFileSync } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
export interface DiffCase {
path: string;
/** Committed content; null for a file added in the working tree. */
before: string | null;
/** Working-tree content; null for a deleted file. */
after: string | null;
}
const lines = (n: number, line: (i: number) => string) => Array.from({ length: n }, (_, i) => line(i) + "\n").join("");
/** A 10,000-line source file; `edit(i)` may replace line `i` (or return null to drop it). */
function bigFile(edit: (i: number, line: string) => string | string[] | null = (_, l) => l) {
const out: string[] = [];
for (let i = 0; i < 10_000; i++) {
const line = i % 50 === 0 ? `// section ${i / 50}` : `export const value${i} = compute(${i}, "item-${i}");`;
const e = edit(i, line);
if (e !== null) out.push(...(Array.isArray(e) ? e : [e]));
}
return out.map((l) => l + "\n").join("");
}
const OPTIONS_BEFORE = `export interface DiffViewOptions {
mode: DiffMode;
ignore: IgnorePolicy;
highlight: HighlightPolicy;
collapse: boolean;
syncScroll: boolean;
}
`;
const OPTIONS_AFTER = `export interface DiffViewOptions {
mode: DiffMode;
ignore: IgnorePolicy;
highlight: HighlightPolicy;
collapse: boolean;
/**
* IDEA's synchronized scrolling of the side-by-side panes: unpadded panes
* that carry each other along, with a curved divider. Off, the panes are
* padded so unchanged lines line up and scroll together.
*/
syncScrolling: boolean;
}
`;
const FUNCS = ["parse", "format", "validate", "render", "save"].map(
(name) => `function ${name}(input) {\n const result = ${name}Impl(input);\n return result;\n}\n`,
);
const MINIFIED = Array.from({ length: 2_000 }, (_, i) => `var a${i}=f(${i},"k${i}");`).join("");
export const CASES: readonly DiffCase[] = [
// A word edited and a comment added: one modified block (the reported case).
{ path: "src/options.ts", before: OPTIONS_BEFORE, after: OPTIONS_AFTER },
{
path: "src/words.ts",
before: "const flag = true;\ncall(a, b);\nconst keep = 1;\n",
after: "const flag = false;\ncall(a, x, b);\nconst keep = 1;\n",
},
{
path: "src/insert.ts",
before: lines(10, (i) => `line ${i}`),
after: lines(10, (i) => `line ${i}`).replace("line 5\n", "line 5\n" + lines(5, (i) => `added ${i}`)),
},
{
path: "src/delete.ts",
before: lines(12, (i) => `line ${i}`),
after: lines(12, (i) => `line ${i}`).replace(
lines(4, (i) => `line ${i + 4}`),
"",
),
},
{
path: "src/indent.py",
before: "def f():\n if x:\n return 1\n return 0\n",
after: "def f():\n if x:\n return 1\n return 0\n",
},
{ path: "docs/readme-zh.md", before: "# 说明\n\n这是一个测试文件。\n", after: "# 说明\n\n这是一个示例文件。\n" },
{ path: "docs/emoji.md", before: "Hello 👋 world\n", after: "Hello 🌍 world\n" },
{ path: "data/no-eol.txt", before: "alpha\nkeep\nbeta", after: "alpha\nkeep\ngamma" },
{ path: "data/add-eol.txt", before: "alpha\nbeta", after: "alpha\nbeta\n" },
{ path: "src/moved.ts", before: FUNCS.join("\n"), after: [...FUNCS.slice(1), FUNCS[0]!].join("\n") },
{ path: "src/new-file.ts", before: null, after: lines(6, (i) => `export const n${i} = ${i};`) },
{ path: "src/deleted-file.ts", before: lines(6, (i) => `export const d${i} = ${i};`), after: null },
{
path: "dist/app.min.js",
before: MINIFIED + "\n",
after: MINIFIED.replace('f(1000,"k1000")', 'g(1000,"k1000")') + "\n",
},
// 10,000 lines: 40 scattered word edits, a 200-line insert and a 100-line delete.
{
path: "big/scattered.ts",
before: bigFile(),
after: bigFile((i, l) =>
i === 5_000
? [l, ...Array.from({ length: 200 }, (_, k) => `export const inserted${k} = ${k};`)]
: i >= 8_000 && i < 8_100
? null
: i % 250 === 125
? l.replace("compute(", "computeFast(")
: l,
),
},
// 10,000 lines, every tenth one edited: 1,000 differences.
{
path: "big/every-tenth.ts",
before: bigFile(),
after: bigFile((i, l) => (i % 10 === 5 ? l.replace('"item-', '"entry-') : l)),
},
// 10,000 lines, every line edited: one 10,000-line modified block.
{
path: "big/rewrite.ts",
before: bigFile(),
after: bigFile((_, l) => l.replace("export const", "export let").replace("// section", "// part")),
},
];
const git = (cwd: string, ...args: string[]) =>
execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 << 20, stdio: ["ignore", "pipe", "pipe"] });
/** Builds the repository in `dir` (created, or emptied first). */
export function buildDiffRepo(dir: string): string {
rmSync(dir, { recursive: true, force: true });
mkdirSync(dir, { recursive: true });
const write = (path: string, text: string) => {
mkdirSync(dirname(join(dir, path)), { recursive: true });
writeFileSync(join(dir, path), text);
};
git(dir, "init", "-q", "-b", "main");
git(dir, "config", "user.email", "[email protected]");
git(dir, "config", "user.name", "e2e");
git(dir, "config", "core.autocrlf", "false");
for (const c of CASES) if (c.before !== null) write(c.path, c.before);
git(dir, "add", "-A");
git(dir, "commit", "-qm", "initial");
for (const c of CASES) {
if (c.after === null) rmSync(join(dir, c.path));
else write(c.path, c.after);
}
// Intent-to-add, so `git diff HEAD` lists the new files too.
const added = CASES.filter((c) => c.before === null).map((c) => c.path);
if (added.length) git(dir, "add", "-N", "--", ...added);
return dir;
}
export function tempDiffRepo(): string {
return buildDiffRepo(join(mkdtempSync(join(tmpdir(), "openidea-diff-")), "repo"));
}
/** HEAD and working-tree texts of `path` ("" when missing on that side). */
export function readSides(dir: string, path: string): { left: string; right: string } {
let left = "";
try {
left = git(dir, "show", `HEAD:${path}`);
} catch {
// added in the working tree
}
let right = "";
try {
right = readFileSync(join(dir, path), "utf8");
} catch {
// deleted in the working tree
}
return { left, right };
}
/** Hunks of `git diff -U0` for `path`, the reference count of line differences. */
export function gitHunks(dir: string, path: string): number {
const out = git(dir, "diff", "-U0", "--no-color", "--diff-algorithm=patience", "HEAD", "--", path);
return out.split("\n").filter((l) => l.startsWith("@@")).length;
}
if (import.meta.url === `file://${process.argv[1]}`) {
const dir = resolve(process.argv[2] ?? "diff-repo");
buildDiffRepo(dir);
console.log(`Built ${CASES.length} diff cases in ${dir}`);
console.log(git(dir, "status", "--short"));
}
+113
Переглянути файл
@@ -0,0 +1,113 @@
/** Linux browser acceptance: synthetic MemoryFs + mocked native IPC, real menu/action/refresh UI. */
import { expect, test } from "./fixtures";
for (const destination of ["gitignore", "localExclude"] as const) {
test(`ignore ${destination}: menu dispatch and immediate tree/status refresh`, async ({ workbench: page }) => {
await page.evaluate(async (destination) => {
const fsModule = "/src/features/project-tree/fs.ts";
const storeModule = "/src/features/project-tree/store.ts";
const ipcModule = "/src/platform/ipc.ts";
const { projectFs } = await import(fsModule);
const { reloadAll } = await import(storeModule);
const { commands } = await import(ipcModule);
const root = "/dev/acme-api";
const path = `${root}/scratch.log`;
const fs = projectFs(root);
await fs.createFile(path);
let written = false;
commands.vcsAddToIgnore = async (paths: string[], actual: string) => {
if (actual !== destination || paths.length !== 1 || paths[0] !== path)
throw new Error("Wrong ignore destination or paths");
written = true;
fs.ignored.add(path);
return { status: "ok", data: null };
};
commands.vcsStatus = async () => {
document.body.dataset.ignoreStatusRefresh = written ? "after-write" : "before-write";
return {
status: "ok",
data: written
? []
: [{ path, relPath: "scratch.log", staged: null, unstaged: "untracked", renamedFrom: null }],
};
};
commands.vcsRoots = async () => ({
status: "ok",
data: [{ root, operation: null, head: "main", headCommit: null }],
});
commands.vcsBranchInfo = async () => ({
status: "ok",
data: { head: "main", headCommit: null, upstream: null, ahead: 0, behind: 0, operation: null },
});
const vcsModule = "/src/features/vcs/store.ts";
const { useVcs } = await import(vcsModule);
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
await reloadAll();
const banner = document.createElement("div");
banner.textContent = "LINUX BROWSER E2E · SYNTHETIC FIXTURE · NATIVE IPC MOCKED";
Object.assign(banner.style, {
position: "fixed",
bottom: "28px",
right: "18px",
zIndex: "999999",
padding: "10px 14px",
background: "#fff4ce",
color: "#362a00",
font: "bold 12px sans-serif",
border: "1px solid #9e8500",
borderRadius: "5px",
});
document.body.append(banner);
}, destination);
await page.getByRole("treeitem", { name: "scratch.log", exact: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Git", exact: true }).hover();
await page.getByRole("menuitem", { name: "Add to .gitignore", exact: true }).hover();
await expect(page.getByRole("menuitem", { name: ".gitignore", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: ".git/info/exclude", exact: true })).toBeVisible();
const captureDir = process.env.OPENIDEA_ACCEPTANCE_DIR;
if (captureDir && destination === "gitignore")
await page.screenshot({ path: `${captureDir}/01-ignore-destinations.png` });
await page
.getByRole("menuitem", { name: destination === "gitignore" ? ".gitignore" : ".git/info/exclude", exact: true })
.click();
await expect
.poll(async () =>
page.evaluate(async () => {
const module = "/src/features/project-tree/store.ts";
const { useProjectTree } = await import(module);
return useProjectTree
.getState()
.listings.get("/dev/acme-api")
?.find((entry: { name: string }) => entry.name === "scratch.log")?.ignored;
}),
)
.toBe(true);
await expect
.poll(async () =>
page.evaluate(async () => {
const module = "/src/features/vcs/store.ts";
const { useVcs } = await import(module);
return useVcs.getState().status.length;
}),
)
.toBe(0);
await expect(page.locator("body")).toHaveAttribute("data-ignore-status-refresh", "after-write");
// Display fixture rule text in the actual editor. This is browser memory, not a native disk read.
await page.evaluate(async (destination) => {
const module = "/src/workbench/contributions.ts";
const { editorService } = await import(module);
await editorService().openFile(
`/dev/acme-api/${destination === "gitignore" ? ".gitignore" : ".git/info/exclude"}`,
{ focus: true },
);
}, destination);
const content = page.locator(".cm-editor .cm-content").first();
await content.fill(
`# Synthetic acceptance fixture: ${destination === "gitignore" ? "shared repository rules" : ".git/info/exclude: local rules (common to linked worktrees)"}\n/scratch.log\n`,
);
if (captureDir)
await page.screenshot({
path: `${captureDir}/${destination === "gitignore" ? "02-shared-ignore-effect" : "03-local-exclude-effect"}.png`,
});
});
}
+13
Переглянути файл
@@ -35,3 +35,16 @@ test("type-ahead jumps to a matching node", async ({ workbench: page }) => {
await page.keyboard.type("READ");
await expect(tree.locator('[role="treeitem"][aria-selected="true"]')).toHaveText("README.md");
});
test("Git ignore submenu offers shared and local destinations for files and folders", async ({ workbench: page }) => {
for (const name of ["README.md", "src"]) {
await page.getByRole("treeitem", { name, exact: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Git", exact: true }).hover();
await page.getByRole("menuitem", { name: "Add to .gitignore", exact: true }).hover();
await expect(page.getByRole("menuitem", { name: ".gitignore", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: ".git/info/exclude", exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
}
});
+10
Переглянути файл
@@ -24,6 +24,14 @@
"perf": "node perf/run.ts",
"perf:rust": "node perf/rust.ts"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged"
},
"lint-staged": {
"*.{js,jsx,mjs,cjs,ts,tsx,mts,cts}": "oxlint --fix --no-error-on-unmatched-pattern",
"*": "oxfmt --no-error-on-unmatched-pattern",
"*.rs": "rustfmt --edition 2024"
},
"dependencies": {
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
@@ -71,8 +79,10 @@
"@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^6.0.2",
"jsdom": "^30.1.3",
"lint-staged": "^17.6.0",
"oxfmt": "^0.74.0",
"oxlint": "^1.89.0",
"simple-git-hooks": "^2.14.0",
"tsrs": "^0.20.0-ts7.1.0-beta",
"typescript": "~6.0.3",
"vite": "^8.0.16",
Створено
+54 -14
Переглянути файл
@@ -116,7 +116,7 @@ importers:
version: 2.12.3
'@testing-library/jest-dom':
specifier: ^7.0.1
version: 7.0.1(@testing-library/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])))
version: 7.0.1(@testing-library/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])))
'@testing-library/react':
specifier: ^16.3.3
version: 16.3.3(@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
@@ -137,16 +137,22 @@ importers:
version: 19.3.0(@types/[email protected])
'@vitejs/plugin-react':
specifier: ^6.0.2
version: 6.1.2([email protected](@types/[email protected]))
version: 6.1.2([email protected](@types/[email protected])([email protected]))
jsdom:
specifier: ^30.1.3
version: 30.1.3
lint-staged:
specifier: ^17.6.0
version: 17.6.0
oxfmt:
specifier: ^0.74.0
version: 0.74.0
oxlint:
specifier: ^1.89.0
version: 1.89.0
simple-git-hooks:
specifier: ^2.14.0
version: 2.14.0
tsrs:
specifier: ^0.20.0-ts7.1.0-beta
version: 0.20.0-ts7.1.0-beta
@@ -155,10 +161,10 @@ importers:
version: 6.0.3
vite:
specifier: ^8.0.16
version: 8.3.4(@types/[email protected])
version: 8.3.4(@types/[email protected])([email protected])
vitest:
specifier: ^5.0.5
version: 5.0.5(@types/[email protected])([email protected])([email protected](@types/[email protected]))
version: 5.0.5(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))
packages:
@@ -1581,6 +1587,11 @@ packages:
resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==}
engines: {node: '>= 12.0.0'}
[email protected]:
resolution: {integrity: sha512-nOhBfYkZEwkFtNzD5pK9s9LkcWoxJ+whLzEnhqi9nl7zTB5n7tg8+9iYgMGx2Wm3VlLu8cbNj0RACzY+nWi5iQ==}
engines: {node: '>=22.22.1'}
hasBin: true
[email protected]:
resolution: {integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==}
@@ -1748,6 +1759,10 @@ packages:
[email protected]:
resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==}
[email protected]:
resolution: {integrity: sha512-kkTORPAuxQz2g1QUuN0J8yGWT28tjGBfPOdJ4xT7Vbeu30veKUZQIoID2qGgCDAakaQn59UeZJJ4cFGB8PVP2A==}
hasBin: true
[email protected]:
resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
engines: {node: '>=0.10.0'}
@@ -1755,6 +1770,10 @@ packages:
[email protected]:
resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==}
[email protected]:
resolution: {integrity: sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==}
engines: {node: '>=0.6.19'}
[email protected]:
resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==}
engines: {node: '>=8'}
@@ -1936,6 +1955,11 @@ packages:
[email protected]:
resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==}
[email protected]:
resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==}
engines: {node: '>= 14.6'}
hasBin: true
[email protected]:
resolution: {integrity: sha512-MpSEjRiBkA9crSYeOUH32rJC7SVqAbm0Fqcqge/bUi2PPoLcBWKOsG+C8mevmpr8TwXHBVkChbbJiyvkE+i/3A==}
engines: {node: '>=12.20.0'}
@@ -2698,7 +2722,7 @@ snapshots:
picocolors: 1.1.1
pretty-format: 27.5.1
'@testing-library/[email protected](@testing-library/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])))':
'@testing-library/[email protected](@testing-library/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])))':
dependencies:
'@adobe/css-tools': 4.5.0
'@testing-library/dom': 10.4.2
@@ -2708,7 +2732,7 @@ snapshots:
picocolors: 1.1.1
redent: 3.0.0
optionalDependencies:
vitest: 5.0.5(@types/[email protected])([email protected])([email protected](@types/[email protected]))
vitest: 5.0.5(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))
'@testing-library/[email protected](@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':
dependencies:
@@ -2899,19 +2923,19 @@ snapshots:
d3-selection: 3.0.0
d3-transition: 3.0.1([email protected])
'@vitejs/[email protected]([email protected](@types/[email protected]))':
'@vitejs/[email protected]([email protected](@types/[email protected])([email protected]))':
dependencies:
'@rolldown/pluginutils': 1.0.1
vite: 8.3.4(@types/[email protected])
vite: 8.3.4(@types/[email protected])([email protected])
'@vitest/[email protected]([email protected](@types/[email protected]))':
'@vitest/[email protected]([email protected](@types/[email protected])([email protected]))':
dependencies:
'@jridgewell/trace-mapping': 0.3.31
'@vitest/spy': 5.0.5
estree-walker: 3.0.3
magic-string: 1.4.3
optionalDependencies:
vite: 8.3.4(@types/[email protected])
vite: 8.3.4(@types/[email protected])([email protected])
'@vitest/[email protected]': {}
@@ -3331,6 +3355,14 @@ snapshots:
lightningcss-win32-arm64-msvc: 1.33.0
lightningcss-win32-x64-msvc: 1.33.0
[email protected]:
dependencies:
picomatch: 4.0.7
string-argv: 0.3.2
tinyexec: 1.3.1
optionalDependencies:
yaml: 2.9.1
[email protected]: {}
[email protected]: {}
@@ -3525,10 +3557,14 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]:
dependencies:
min-indent: 1.0.1
@@ -3582,7 +3618,7 @@ snapshots:
[email protected]: {}
[email protected](@types/[email protected]):
[email protected](@types/[email protected])([email protected]):
dependencies:
lightningcss: 1.33.0
picomatch: 4.0.7
@@ -3592,11 +3628,12 @@ snapshots:
optionalDependencies:
'@types/node': 26.6.5
fsevents: 2.3.3
yaml: 2.9.1
[email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])):
[email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])):
dependencies:
'@types/chai': 5.2.3
'@vitest/mocker': 5.0.5([email protected](@types/[email protected]))
'@vitest/mocker': 5.0.5([email protected](@types/[email protected])([email protected]))
chai: 6.3.0
es-module-lexer: 2.3.2
expect-type: 1.4.0
@@ -3607,7 +3644,7 @@ snapshots:
tinybench: 6.2.2
tinyexec: 1.3.1
tinyglobby: 0.2.17
vite: 8.3.4(@types/[email protected])
vite: 8.3.4(@types/[email protected])([email protected])
why-is-node-running: 3.2.1
optionalDependencies:
'@types/node': 26.6.5
@@ -3639,6 +3676,9 @@ snapshots:
[email protected]: {}
[email protected]:
optional: true
[email protected](@types/[email protected])([email protected])([email protected]):
optionalDependencies:
'@types/react': 19.3.0
+2
Переглянути файл
@@ -0,0 +1,2 @@
allowBuilds:
simple-git-hooks: true
+3
Переглянути файл
@@ -111,6 +111,9 @@ export const ICLS_ATTRIBUTES: Record<string, Array<[Part, string]>> = {
["FOREGROUND", "--fg-editor"],
["BACKGROUND", "--bg-editor"],
],
DIFF_MODIFIED: [["BACKGROUND", "--diff-modified"]],
DIFF_INSERTED: [["BACKGROUND", "--diff-inserted"]],
DIFF_DELETED: [["BACKGROUND", "--diff-deleted"]],
DEFAULT_KEYWORD: [["FOREGROUND", "--syn-keyword"]],
DEFAULT_STRING: [["FOREGROUND", "--syn-string"]],
DEFAULT_NUMBER: [["FOREGROUND", "--syn-number"]],
+1
Переглянути файл
@@ -201,6 +201,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_branches,
vcs::vcs_stashes,
vcs::vcs_stage,
vcs::vcs_add_to_ignore,
vcs::vcs_unstage,
vcs::vcs_stage_patch,
vcs::vcs_discard,
+11
Переглянути файл
@@ -108,6 +108,17 @@ pub async fn vcs_stage(window: Window, state: State<'_, AppState>, paths: Vec<Pa
ide_host::ops::vcs::vcs_stage(&state.host, window.label(), paths).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_add_to_ignore(
window: Window,
state: State<'_, AppState>,
paths: Vec<PathBuf>,
destination: IgnoreDestination,
) -> IdeResult<()> {
ide_host::ops::vcs::vcs_add_to_ignore(&state.host, window.label(), paths, destination).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_unstage(window: Window, state: State<'_, AppState>, paths: Vec<PathBuf>) -> IdeResult<()> {
+9 -5
Переглянути файл
@@ -6,7 +6,7 @@
//! (`window_take_launch`), and re-taken whenever [`LAUNCH_EVENT`] fires (a
//! second app instance asking an already-loaded window to open a path).
//!
//! Settings open in a native child window `settings-<parent>` (one per project
//! Settings open in a separate window `settings-<parent>` (one per project
//! window) that shares its parent's project (see [`AppState::project`]); its
//! [`Launch::settings_page`] tells it which page to show.
@@ -666,7 +666,7 @@ pub fn cycle(app: &AppHandle, current: &str, forward: bool) {
}
/// Opens (or focuses) the settings window of `parent` showing `page`: a
/// native child window centred over its parent, sized like IDEA's Settings.
/// separate window centred over its parent, sized like IDEA's Settings.
pub fn open_settings_window(
app: &AppHandle,
parent: &WebviewWindow,
@@ -699,13 +699,17 @@ pub fn open_settings_window(
config.maximized = false;
config.fullscreen = false;
config.drag_drop_enabled = false;
// macOS shows a child window as soon as it is attached, before the page loads: paint the theme's frame colour.
// Paint the theme's frame colour before the page loads.
if let Some(color) = background.as_deref().and_then(hex_color) {
config.background_color = Some(color);
}
windows.set_launch(&label, Launch { settings_page: page, new_projects, ..Default::default() });
let window = WebviewWindowBuilder::from_config(app, &config)
.and_then(|b| b.parent(&parent))
let builder = WebviewWindowBuilder::from_config(app, &config);
// AppKit child windows can disappear when dragged to another display's Space.
// The settings label already tracks ownership and parent-close cleanup.
#[cfg(not(target_os = "macos"))]
let builder = builder.and_then(|b| b.parent(&parent));
let window = builder
.and_then(|b| b.build())
.map_err(|e| IdeError::internal(format!("cannot create settings window: {e}")))?;
apply_zoom(app, &window);
+3
Переглянути файл
@@ -404,6 +404,7 @@ export const commands = {
vcsBranches: (repo: string | null) => typedError<Branch[], IdeError>(__TAURI_INVOKE("vcs_branches", { repo })),
vcsStashes: (repo: string | null) => typedError<Stash[], IdeError>(__TAURI_INVOKE("vcs_stashes", { repo })),
vcsStage: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stage", { paths })),
vcsAddToIgnore: (paths: string[], destination: IgnoreDestination) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_add_to_ignore", { paths, destination })),
vcsUnstage: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_unstage", { paths })),
vcsStagePatch: (patch: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stage_patch", { patch })),
vcsDiscard: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_discard", { paths })),
@@ -3338,6 +3339,8 @@ export type IdentifierOccurrence = {
qualified: boolean,
};
export type IgnoreDestination = "gitignore" | "localExclude";
export type IndentConfig = IndentConfig_Serialize | IndentConfig_Deserialize;
export type IndentConfig_Deserialize = {
+189 -3
Переглянути файл
@@ -1,6 +1,72 @@
import { describe, expect, it } from "vitest";
import type { OutlineItem } from "@/platform/ipc";
import { lensTargets } from "./codeLens";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { OutlineItem, References } from "@/platform/ipc";
import { _addEditor, _removeEditor, codeLenses, documentSynced } from "@/editor/api";
const ipc = vi.hoisted(() => ({
docOutline: vi.fn(),
lspReferences: vi.fn(),
cancelRequest: vi.fn<(id: number) => Promise<void>>(async () => {}),
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
});
const executeAction = vi.hoisted(() => vi.fn(async () => true));
vi.mock("@/platform/actions", () => ({ executeAction }));
const { lensTargets, usagesLensExtension } = await import("./codeLens");
const { lspDoc } = await import("./lsp");
const { useProject } = await import("@/platform/project");
const { emitLocalIdeEvent } = await import("@/platform/ipc");
const ctx = { doc: 7, path: "/p/a.rs", language: "rust", uiMode: "Rust", readOnly: false };
const views: EditorView[] = [];
const ok = <T>(data: T) => ({ status: "ok" as const, data });
const refs = (n: number, incomplete: References["incomplete"] = null) =>
ok({
locations: Array.from({ length: n }, () => ({ path: "/p/b.rs", range: item("x", "function", 0).range })),
incomplete,
});
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((r) => (resolve = r));
return { promise, resolve };
}
function editor(count = 1, sync?: () => Promise<void>) {
const view = new EditorView({
state: EditorState.create({
doc: Array.from({ length: count }, (_, i) => `fn f${i}() {}`).join("\n"),
extensions: [lspDoc.of(ctx), usagesLensExtension(), ...(sync ? [documentSynced.of(sync)] : [])],
}),
parent: document.body,
});
views.push(view);
return view;
}
const titles = (view: EditorView) => view.state.facet(codeLenses).map((l) => l.title);
const settle = () => vi.advanceTimersByTimeAsync(1000);
beforeEach(() => {
vi.useFakeTimers();
ipc.docOutline.mockReset().mockResolvedValue(ok([item("f0", "function", 0)]));
ipc.lspReferences.mockReset().mockResolvedValue(refs(2));
ipc.cancelRequest.mockClear();
executeAction.mockClear();
useProject.setState({
settings: { editor: { inlay: { codeVisionUsages: true, codeVisionAuthor: false } } } as never,
});
});
afterEach(() => {
views.splice(0).forEach((v) => v.destroy());
useProject.setState({ settings: null });
vi.useRealTimers();
});
const item = (name: string, kind: OutlineItem["kind"], line: number, children: OutlineItem[] = []): OutlineItem => {
const r = { start: { line, col: 0 }, end: { line, col: 1 } };
@@ -18,3 +84,123 @@ describe("usages lens targets", () => {
expect(lensTargets(items).map((t) => t.name)).toEqual(["Cart", "count"]);
});
});
describe("background usage counts", () => {
it("uses the server's existing scope and leaves full searches to the explicit action", async () => {
const view = editor();
await settle();
expect(ipc.lspReferences).toHaveBeenCalledWith(expect.any(Number), 7, { line: 0, col: 0 }, false, false);
expect(titles(view)).toEqual(["2 usages"]);
view.state.facet(codeLenses)[0]!.run!(view, new MouseEvent("click"));
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
});
it("allows a full search even when the server's current scope has no usages", async () => {
ipc.lspReferences.mockResolvedValue(refs(0));
const view = editor();
await settle();
expect(titles(view)).toEqual(["no usages"]);
view.state.facet(codeLenses)[0]!.run!(view, new MouseEvent("click"));
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
});
it("does not cache an incomplete count while indexing, and retries on server refresh", async () => {
ipc.lspReferences.mockResolvedValueOnce(refs(0, "indexing"));
const view = editor();
await settle();
expect(titles(view)).toEqual([]);
emitLocalIdeEvent({ type: "lspRefresh", kind: "codeLens", server: 1 });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
expect(titles(view)).toEqual(["2 usages"]);
});
it("cancels obsolete requests immediately on edits and ignores their late replies", async () => {
const old = deferred<ReturnType<typeof refs>>();
ipc.lspReferences.mockReturnValueOnce(old.promise);
const view = editor();
await settle();
const request = ipc.lspReferences.mock.calls[0]![0];
view.dispatch({ changes: { from: view.state.doc.length, insert: " " } });
expect(ipc.cancelRequest).toHaveBeenCalledWith(request);
await settle();
expect(titles(view)).toEqual(["2 usages"]);
old.resolve(refs(99));
await settle();
expect(titles(view)).toEqual(["2 usages"]);
});
it("retries incomplete counts when indexing ends without a code-lens refresh", async () => {
ipc.lspReferences.mockResolvedValueOnce(refs(0, "indexing"));
const view = editor();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "busy", message: null });
await settle();
expect(titles(view)).toEqual([]);
await settle();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "ready", message: null });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
expect(titles(view)).toEqual(["2 usages"]);
});
it("does not repeat complete counts when the server finishes other work", async () => {
const view = editor();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "busy", message: null });
await settle();
await settle();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "ready", message: null });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
expect(titles(view)).toEqual(["2 usages"]);
});
it("cancels all in-flight requests on destroy without starting the next batch", async () => {
const pending = deferred<ReturnType<typeof refs>>();
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 8 }, (_, i) => item(`f${i}`, "function", i))));
ipc.lspReferences.mockReturnValue(pending.promise);
const view = editor(8);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(4);
const requests = ipc.lspReferences.mock.calls.map(([id]) => id);
view.destroy();
views.splice(views.indexOf(view), 1);
expect(ipc.cancelRequest.mock.calls.map(([id]) => id)).toEqual(requests);
pending.resolve(refs(1));
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(4);
});
it("cancels pending counts when the feature is disabled", async () => {
const pending = deferred<ReturnType<typeof refs>>();
ipc.lspReferences.mockReturnValue(pending.promise);
const view = editor();
await settle();
useProject.setState({
settings: { editor: { inlay: { codeVisionUsages: false, codeVisionAuthor: false } } } as never,
});
expect(ipc.cancelRequest).toHaveBeenCalledWith(ipc.lspReferences.mock.calls[0]![0]);
pending.resolve(refs(2));
await settle();
expect(titles(view)).toEqual([]);
});
it("does not send obsolete requests after waiting for document synchronization", async () => {
const synced = deferred<void>();
const view = editor(1, () => synced.promise);
const handle = { view, ctx };
_addEditor(handle);
try {
await settle();
expect(ipc.docOutline).not.toHaveBeenCalled();
view.destroy();
views.splice(views.indexOf(view), 1);
synced.resolve();
await settle();
expect(ipc.docOutline).not.toHaveBeenCalled();
expect(ipc.lspReferences).not.toHaveBeenCalled();
expect(ipc.cancelRequest).not.toHaveBeenCalled();
} finally {
_removeEditor(handle);
}
});
});
+47 -18
Переглянути файл
@@ -9,11 +9,11 @@ import { EditorSelection, MapMode, StateEffect, StateField, type Extension, type
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { codeLenses, type CodeLens } from "@/editor/api";
import { executeAction } from "@/platform/actions";
import { commands, nextRequestId, type OutlineItem, type SymbolKind } from "@/platform/ipc";
import { commands, nextRequestId, type OutlineItem, type RequestId, type SymbolKind } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { debounce, docOf, isUnavailable, lspRequest } from "./lsp";
import { posToOffset } from "./positions";
import { featureBackoff, onLspRefresh } from "./availability";
import { featureBackoff, onLspRefresh, onServerSettled } from "./availability";
import { editorPrefs } from "@/platform/editorSettings";
import { authorLabel, authorSummary, authorTooltip, blameFor, onBlameInvalidated } from "./authorLens";
import { tx } from "@/platform/i18n";
@@ -106,14 +106,17 @@ function openUsages(view: EditorView, offset: number) {
}
class UsagesLensPlugin {
private refresh = debounce(() => void this.run(), 900);
private schedule = debounce(() => void this.run(), 900);
/** `${line}:${col}:${name}` → count, valid for `cacheDoc`. */
private cache = new Map<string, number>();
private cacheDoc: Text | null = null;
private outline: { doc: Text; targets: LensTarget[] } | null = null;
private generation = 0;
private pending = new Set<RequestId>();
private incomplete = false;
private unsubscribe: () => void;
private offReady: () => void;
private offSettled: () => void;
private offBlame: () => void;
constructor(private view: EditorView) {
@@ -126,6 +129,9 @@ class UsagesLensPlugin {
this.cache.clear();
this.refresh();
});
this.offSettled = onServerSettled(() => {
if (this.incomplete) this.refresh();
});
this.offBlame = onBlameInvalidated(() => this.refresh());
}
@@ -133,12 +139,23 @@ class UsagesLensPlugin {
if (u.docChanged || u.viewportChanged) this.refresh();
}
private cancel() {
this.generation++;
for (const id of this.pending) void commands.cancelRequest(id).catch(() => {});
this.pending.clear();
}
private refresh() {
this.cancel();
this.schedule();
}
private async run() {
const view = this.view;
if (!view.dom.isConnected) return;
const doc = docOf(view);
if (!doc) return;
const gen = ++this.generation;
const gen = this.generation;
const usages = usagesEnabled() && !usagesBackoff.active(doc.doc);
const authors = authorEnabled() && !doc.virtual;
if (!usages && !authors) {
@@ -146,6 +163,8 @@ class UsagesLensPlugin {
return;
}
const text = view.state.doc;
const wanted = () => gen === this.generation && view.state.doc === text;
this.incomplete = false;
// Blame runs beside the reference requests; it never holds up the counts.
const blame = authors ? blameFor(doc.path, text) : Promise.resolve(null);
if (this.cacheDoc !== text) {
@@ -154,8 +173,8 @@ class UsagesLensPlugin {
}
try {
if (this.outline?.doc !== text) {
const items = await lspRequest(() => commands.docOutline(doc.doc));
if (gen !== this.generation || view.state.doc !== text) return;
const items = await lspRequest(() => commands.docOutline(doc.doc), wanted);
if (!wanted()) return;
this.outline = { doc: text, targets: lensTargets(items) };
}
const { from, to } = view.viewport;
@@ -170,21 +189,30 @@ class UsagesLensPlugin {
for (let i = 0; i < todo.length && !unavailable; i += CONCURRENCY) {
await Promise.all(
todo.slice(i, i + CONCURRENCY).map(async (t) => {
const request = nextRequestId();
try {
const { locations: refs } = await lspRequest(() =>
commands.lspReferences(nextRequestId(), doc.doc, { line: t.line, col: t.col }, false, true),
);
this.cache.set(key(t), refs.length);
const { locations: refs, incomplete } = await lspRequest(() => {
this.pending.add(request);
// Opening candidate files for each count triggers expensive server analysis.
// Only an explicit Find Usages should widen the server's scope.
return commands.lspReferences(request, doc.doc, { line: t.line, col: t.col }, false, false);
}, wanted);
if (wanted()) {
if (incomplete) this.incomplete = true;
else this.cache.set(key(t), refs.length);
}
} catch (e) {
if (isUnavailable(e)) unavailable = true;
if (wanted() && isUnavailable(e)) unavailable = true;
} finally {
this.pending.delete(request);
}
}),
);
if (gen !== this.generation || view.state.doc !== text) return;
if (!wanted()) return;
}
if (unavailable) usagesBackoff.mark(doc.doc);
const lines = await blame;
if (gen !== this.generation || view.state.doc !== text) return;
if (!wanted()) return;
const lenses: CodeLens[] = [];
for (const t of visible) {
const offset = posToOffset(text, { line: t.line, col: t.col });
@@ -196,23 +224,24 @@ class UsagesLensPlugin {
lenses.push({
pos: offset,
title: usagesLabel(n),
tooltip: n ? tx`Show usages of ${t.name}` : undefined,
tooltip: tx`Show usages of ${t.name}`,
order: 10,
run: n ? (v) => openUsages(v, Math.min(offset, v.state.doc.length)) : undefined,
run: (v) => openUsages(v, Math.min(offset, v.state.doc.length)),
});
}
if (!sameLenses(view.state.field(lensField), lenses)) view.dispatch({ effects: setLenses.of(lenses) });
} catch (e) {
if (isUnavailable(e)) usagesBackoff.mark(doc.doc);
if (wanted() && isUnavailable(e)) usagesBackoff.mark(doc.doc);
}
}
destroy() {
this.refresh.cancel();
this.schedule.cancel();
this.unsubscribe();
this.offReady();
this.offSettled();
this.offBlame();
this.generation++;
this.cancel();
}
}
+62
Переглянути файл
@@ -0,0 +1,62 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { showHint, showPendingHint } from "./hint";
let view: EditorView;
const hint = () => document.querySelector(".cm-lsp-hint")?.textContent ?? null;
beforeEach(() => {
vi.useFakeTimers();
view = new EditorView({ state: EditorState.create({ doc: "foo()" }), parent: document.body });
});
afterEach(() => {
view.destroy();
vi.useRealTimers();
});
describe("pending hints", () => {
it("does not flash for fast requests", () => {
const done = showPendingHint(view, "Waiting…");
vi.advanceTimersByTime(100);
done();
vi.advanceTimersByTime(1000);
expect(hint()).toBeNull();
});
it("shows a slow request and removes its hint on completion", () => {
const done = showPendingHint(view, "Waiting…");
vi.advanceTimersByTime(250);
expect(hint()).toBe("Waiting…");
done();
expect(hint()).toBeNull();
});
it("does not dismiss a newer hint when an old request finishes", () => {
const done = showPendingHint(view, "Waiting…");
vi.advanceTimersByTime(250);
showHint(view, "New error", { tone: "error" });
done();
expect(hint()).toBe("New error");
});
it("does not overwrite a newer hint while waiting to show progress", () => {
const done = showPendingHint(view, "Waiting…");
vi.advanceTimersByTime(100);
showHint(view, "New error", { tone: "error" });
vi.advanceTimersByTime(150);
expect(hint()).toBe("New error");
done();
expect(hint()).toBe("New error");
});
it.each(["edit", "move", "destroy"])("does not show stale progress after %s", (change) => {
const done = showPendingHint(view, "Waiting…");
if (change === "edit") view.dispatch({ changes: { from: 0, insert: "x" } });
if (change === "move") view.dispatch({ selection: { anchor: 3 } });
if (change === "destroy") view.destroy();
vi.advanceTimersByTime(250);
done();
expect(hint()).toBeNull();
});
});
+26 -1
Переглянути файл
@@ -67,11 +67,36 @@ export function showHint(
timers.set(
view,
setTimeout(() => {
if (view.state.field(hintField, false)) view.dispatch({ effects: setHint.of(null) });
if (view.dom.isConnected && view.state.field(hintField, false)) view.dispatch({ effects: setHint.of(null) });
}, opts.timeout ?? 4000),
);
}
/** Show progress only for slow requests; the disposer removes only its own hint. */
export function showPendingHint(view: EditorView, content: string): () => void {
const { doc, selection } = view.state;
const previous = view.state.field(hintField, false);
let shown: Hint | null = null;
const timer = setTimeout(() => {
if (
!view.dom.isConnected ||
view.state.doc !== doc ||
!view.state.selection.eq(selection) ||
view.state.field(hintField, false) !== previous
)
return;
showHint(view, content, { timeout: 30_000 });
shown = view.state.field(hintField);
}, 250);
return () => {
clearTimeout(timer);
if (shown && view.state.field(hintField, false) === shown) {
clearTimeout(timers.get(view));
if (view.dom.isConnected) hideHint(view);
}
};
}
export function hideHint(view: EditorView): boolean {
if (!view.state.field(hintField, false)) return false;
view.dispatch({ effects: setHint.of(null) });
+7 -2
Переглянути файл
@@ -46,7 +46,7 @@ import {
localHighlights,
type DeclarationTarget,
} from "./syntaxFallback";
import { showHint } from "./hint";
import { showHint, showPendingHint } from "./hint";
import { caretAnchor, openPopup, type ListPopupItem } from "./popupStore";
import { identifierAt, readManyFileLines } from "./files";
import { documentLinks, followReference, knownLinks, linkReference, referenceAt, textReference } from "./links";
@@ -166,7 +166,12 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number)
const declaration = kind === "definition" || kind === "declaration";
let serverDown = false;
try {
locs = dedupeLocations(await gotoAfterEdits(view, () => lspRequest(() => commands.lspGoto(doc.doc, pos, kind))));
const done = showPendingHint(view, tx`Finding navigation target…`);
try {
locs = dedupeLocations(await gotoAfterEdits(view, () => lspRequest(() => commands.lspGoto(doc.doc, pos, kind))));
} finally {
done();
}
} catch (e) {
if (isCancelled(e) || !declaration) {
reportLspError(view, e, true);
+62
Переглянути файл
@@ -0,0 +1,62 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { commands } from "@/platform/ipc";
const lspGoto = vi.hoisted(() => vi.fn<typeof commands.lspGoto>());
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, lspGoto } };
});
const { gotoTargets } = await import("./navigation");
const { lspDoc } = await import("./lsp");
const { provideEditorService } = await import("@/workbench/contributions");
const openFile = vi.fn(async () => {});
provideEditorService({ openFile } as never);
let view: EditorView;
beforeEach(() => {
vi.useFakeTimers();
openFile.mockClear();
view = new EditorView({
state: EditorState.create({
doc: "run()",
extensions: [lspDoc.of({ doc: 1, path: "/p/main.rs", language: "rust", uiMode: "Rust", readOnly: false })],
}),
parent: document.body,
});
});
afterEach(() => {
view.destroy();
vi.useRealTimers();
});
describe("slow navigation feedback", () => {
it("shows progress while finding a definition, then opens the target and clears the hint", async () => {
let resolve!: (result: Awaited<ReturnType<typeof commands.lspGoto>>) => void;
lspGoto.mockImplementationOnce(() => new Promise((r) => (resolve = r)));
const pending = gotoTargets(view, "definition");
await vi.advanceTimersByTimeAsync(250);
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("Finding navigation target…");
expect(openFile).not.toHaveBeenCalled();
resolve({
status: "ok",
data: [{ path: "/p/lib.rs", range: { start: { line: 3, col: 4 }, end: { line: 3, col: 7 } }, uri: null }],
});
await pending;
expect(openFile).toHaveBeenCalledWith("/p/lib.rs", { selection: { line: 3, col: 4 }, focus: true });
expect(document.querySelector(".cm-lsp-hint")).toBeNull();
});
it("replaces progress with the server error", async () => {
let resolve!: (result: Awaited<ReturnType<typeof commands.lspGoto>>) => void;
lspGoto.mockImplementationOnce(() => new Promise((r) => (resolve = r)));
const pending = gotoTargets(view, "implementation");
await vi.advanceTimersByTimeAsync(250);
resolve({ status: "error", error: { kind: "protocol", message: "Server timed out" } });
await pending;
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("Server timed out");
expect(openFile).not.toHaveBeenCalled();
});
});
+11
Переглянути файл
@@ -39,6 +39,17 @@
text-overflow: ellipsis;
white-space: nowrap;
}
.title[data-unread] {
color: var(--fg-strong);
font-weight: 600;
}
.unreadDot {
flex: none;
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--accent);
}
.detail {
flex: 1 1 0;
min-width: 0;
+10 -2
Переглянути файл
@@ -5,11 +5,13 @@ import styles from "./Agents.module.css";
export function AgentsStatus() {
const tasks = useAgents((s) => s.tasks);
const unread = useAgents((s) => s.unread);
const list = [...tasks.values()];
const unseen = list.filter((t) => unread.has(t.id)).sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
const input = list.filter((t) => t.status === "needsInput");
const running = list.filter((t) => t.status === "running" || t.status === "starting").length;
if (!input.length && !running) return null;
const target = input[0] ?? list.find((t) => t.status === "running");
if (!input.length && !running && !unseen.length) return null;
const target = input[0] ?? unseen[0] ?? list.find((t) => t.status === "running" || t.status === "starting");
return (
<button type="button" className={styles.statusItem} onClick={() => target && openTask(target.id)}>
{input.length > 0 && (
@@ -24,6 +26,12 @@ export function AgentsStatus() {
{running} <T>running</T>
</span>
)}
{unseen.length > 0 && (
<span className={styles.statusPart}>
<span className={styles.unreadDot} aria-hidden="true" />
{unseen.length} <T>unread</T>
</span>
)}
</button>
);
}
+209
Переглянути файл
@@ -0,0 +1,209 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { AgentTask } from "@/bindings";
import { registerActions } from "@/platform/actions";
import type { EditorInput } from "@/workbench/contributions";
import { confirmChecked, showError } from "@/workbench/messages";
import { ContextMenuHost, hideContextMenu } from "@/ui";
import { AgentsView } from "./AgentsView";
import { SESSION_KIND } from "./model";
import { archiveTask, deleteTask, openTask, useAgents } from "./store";
import { taskActions } from "./taskActions";
const editor = vi.hoisted(() => ({
active: undefined as EditorInput | undefined,
listener: undefined as ((input: EditorInput) => void) | undefined,
}));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
maybeEditorService: () => ({
activeInput: () => editor.active,
onActiveInputChange: (listener: typeof editor.listener) => {
editor.listener = listener;
return () => {
editor.listener = undefined;
};
},
}),
}));
vi.mock("./store", async (original) => ({
...(await original<typeof import("./store")>()),
openTask: vi.fn((id: string) => editor.listener?.({ kind: "agent-session", key: id, data: { task: id } })),
archiveTask: vi.fn(async () => {}),
deleteTask: vi.fn(async () => {}),
}));
vi.mock("@/workbench/messages", () => ({
confirmChecked: vi.fn(async () => ({ checked: false })),
showError: vi.fn(async () => {}),
}));
function task(
id: string,
status: AgentTask["status"] = "ready",
isolation: AgentTask["isolation"] = "local",
): AgentTask {
return {
id,
title: id,
status,
isolation,
provider: "codex",
model: null,
cwd: "/project",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
}
const row = (id: string) => screen.getByText(id).closest('[role="treeitem"]')!;
const select = (id: string, modifiers: MouseEventInit = {}) =>
fireEvent.mouseDown(row(id), { button: 0, ...modifiers });
const selectedTasks = () =>
screen
.queryAllByRole("treeitem", { selected: true })
.filter((item) => item.getAttribute("aria-level") === "2")
.map((item) => item.querySelector("[title]")?.getAttribute("title"));
const context = (id: string) => {
fireEvent.mouseDown(row(id), { button: 2 });
fireEvent.contextMenu(row(id));
};
let dispose: () => void;
beforeEach(() => {
vi.clearAllMocks();
editor.active = undefined;
vi.mocked(confirmChecked).mockResolvedValue({ checked: false });
useAgents.setState({
loaded: true,
error: null,
tasks: new Map([task("one"), task("two"), task("three"), task("four")].map((t) => [t.id, t])),
});
dispose = registerActions(taskActions);
});
afterEach(() => {
dispose();
hideContextMenu();
});
function setup() {
render(
<>
<AgentsView />
<ContextMenuHost />
</>,
);
}
describe("Agents selection", () => {
it("extends and shrinks a range without opening its lead or losing selection to an editor echo", () => {
setup();
select("one");
select("three", { shiftKey: true });
expect(selectedTasks()).toEqual(["one", "two", "three"]);
expect(openTask).toHaveBeenCalledTimes(1);
act(() => editor.listener?.({ kind: SESSION_KIND, key: "one", data: { task: "one" } }));
expect(selectedTasks()).toEqual(["one", "two", "three"]);
select("two", { shiftKey: true });
expect(selectedTasks()).toEqual(["one", "two"]);
select("four");
expect(selectedTasks()).toEqual(["four"]);
});
it("keeps the initial active task as the anchor for repeated keyboard extension", () => {
editor.active = { kind: SESSION_KIND, key: "one", data: { task: "one" } };
setup();
const tree = screen.getByRole("tree");
fireEvent.keyDown(tree, { key: "ArrowDown", shiftKey: true });
fireEvent.keyDown(tree, { key: "ArrowDown", shiftKey: true });
expect(selectedTasks()).toEqual(["one", "two", "three"]);
expect(openTask).not.toHaveBeenCalled();
});
it.each(["metaKey", "ctrlKey"])("toggles individual tasks with %s", (modifier) => {
setup();
select("one");
select("three", { [modifier]: true });
expect(selectedTasks()).toEqual(["one", "three"]);
select("three", { [modifier]: true });
expect(selectedTasks()).toEqual(["one"]);
expect(openTask).toHaveBeenCalledTimes(1);
});
});
describe("Agents bulk actions", () => {
it("deletes the right-clicked selection after one confirmation, excluding group headers", async () => {
const tasks = [task("one", "running"), task("two"), task("three")];
useAgents.setState({ tasks: new Map(tasks.map((t) => [t.id, t])) });
setup();
select("one");
select("three", { shiftKey: true });
context("two");
fireEvent.click(screen.getByRole("menuitem", { name: "Delete (3)…" }));
await waitFor(() => expect(deleteTask).toHaveBeenCalledTimes(3));
expect(confirmChecked).toHaveBeenCalledTimes(1);
expect(confirmChecked).toHaveBeenCalledWith(
expect.objectContaining({ message: expect.stringContaining("3 agent tasks") }),
);
expect(vi.mocked(deleteTask).mock.calls).toEqual([
["one", false],
["two", false],
["three", false],
]);
});
it("right-clicking outside the selection targets only that task", async () => {
setup();
select("one");
select("two", { shiftKey: true });
context("four");
fireEvent.click(screen.getByRole("menuitem", { name: "Delete…" }));
await waitFor(() => expect(deleteTask).toHaveBeenCalledExactlyOnceWith("four", false));
});
it("archives only eligible tasks in a mixed selection", async () => {
const tasks = [task("one", "running"), task("two"), task("three", "archived")];
useAgents.setState({ tasks: new Map(tasks.map((t) => [t.id, t])) });
setup();
fireEvent.doubleClick(screen.getByText("Archived"));
select("one");
select("three", { shiftKey: true });
context("two");
fireEvent.click(screen.getByRole("menuitem", { name: "Archive (1)" }));
await waitFor(() => expect(archiveTask).toHaveBeenCalledExactlyOnceWith("two"));
});
it("cancels the whole batch", async () => {
vi.mocked(confirmChecked).mockResolvedValue(null);
await taskActions.find((action) => action.id === "agents.deleteTasks")!.run({ ctx: {}, arg: ["one", "two"] });
expect(deleteTask).not.toHaveBeenCalled();
});
it.each([false, true])("applies worktree cleanup (%s) only to worktree tasks", async (checked) => {
const tasks = [task("one"), task("two", "ready", "worktree")];
useAgents.setState({ tasks: new Map(tasks.map((t) => [t.id, t])) });
vi.mocked(confirmChecked).mockResolvedValue({ checked });
await taskActions.find((action) => action.id === "agents.deleteTasks")!.run({ ctx: {}, arg: ["one", "two"] });
expect(vi.mocked(deleteTask).mock.calls).toEqual([
["one", false],
["two", checked],
]);
});
it("continues after an error and reports the failed task", async () => {
vi.mocked(deleteTask).mockRejectedValueOnce(new Error("Cannot remove worktree"));
await taskActions.find((action) => action.id === "agents.deleteTasks")!.run({ ctx: {}, arg: ["one", "two"] });
expect(deleteTask).toHaveBeenCalledTimes(2);
expect(showError).toHaveBeenCalledWith("Cannot delete agent tasks", "one: Cannot remove worktree");
});
});
+23 -36
Переглянути файл
@@ -1,14 +1,13 @@
/** Agents tool window: tasks grouped by what they need from the user. */
import { useEffect, useMemo, useState } from "react";
import type { AgentStatus as Status, AgentTask } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { maybeEditorService, type EditorInput } from "@/workbench/contributions";
import { confirmChecked } from "@/workbench/messages";
import { EmptyState, Icon, IconButton, Spinner, T, Tree, showContextMenu, type MenuItem } from "@/ui";
import { SESSION_KIND, age, branchLabel, groupTasks, isBusy, type TaskGroup } from "./model";
import { archiveTask, deleteTask, openHome, openTask, useAgents } from "./store";
import { EmptyState, Icon, IconButton, Spinner, T, Tree, showContextMenu } from "@/ui";
import { SESSION_KIND, age, branchLabel, groupTasks, type TaskGroup } from "./model";
import { openHome, openTask, useAgents } from "./store";
import { taskMenu } from "./taskActions";
import styles from "./Agents.module.css";
import { tx } from "@/platform/i18n";
import { useTx } from "@/platform/i18n";
export function AgentsHeaderActions() {
return (
@@ -44,9 +43,11 @@ export function TaskStatusIcon({ status }: { status: Status }) {
}
export function AgentsView() {
const tx = useTx();
const loaded = useAgents((s) => s.loaded);
const error = useAgents((s) => s.error);
const tasks = useAgents((s) => s.tasks);
const unread = useAgents((s) => s.unread);
const providers = useAgents((s) => s.providers);
const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set(["g:archived"]));
const [selected, setSelected] = useState<Set<string>>(() => {
@@ -59,7 +60,7 @@ export function AgentsView() {
maybeEditorService()?.onActiveInputChange?.((input) => {
const task = sessionTask(input);
if (!task) return;
setSelected(new Set([task]));
setSelected((current) => (current.has(task) ? current : new Set([task])));
const group = groupTasks(useAgents.getState().tasks.values()).find((g) => g.tasks.some((t) => t.id === task));
const key = group && `g:${group.status}`;
if (key) setCollapsed((c) => (c.has(key) ? new Set([...c].filter((k) => k !== key)) : c));
@@ -100,10 +101,17 @@ export function AgentsView() {
selected={selected}
onSelectionChange={(sel, lead) => {
setSelected(sel);
if (lead?.kind === "task") openTask(lead.task.id);
if (sel.size === 1 && lead?.kind === "task" && sel.has(lead.task.id)) openTask(lead.task.id);
}}
onActivate={(n) => n.kind === "task" && openTask(n.task.id)}
onContextMenu={(n, _sel, e) => n?.kind === "task" && showContextMenu(e, taskMenu(n.task))}
onContextMenu={(n, sel, e) => {
if (n?.kind !== "task") return;
const selection = [...sel].flatMap((id) => {
const task = tasks.get(id);
return task ? [task] : [];
});
showContextMenu(e, taskMenu(selection));
}}
renderNode={(n) =>
n.kind === "group" ? (
<span className={styles.row}>
@@ -115,7 +123,12 @@ export function AgentsView() {
) : (
<span className={styles.row} title={n.task.error ?? n.task.title}>
<TaskStatusIcon status={n.task.status} />
<span className={styles.title}>{n.task.title}</span>
<span className={styles.title} data-unread={unread.has(n.task.id) || undefined}>
{n.task.title}
</span>
{unread.has(n.task.id) && (
<span className={styles.unreadDot} role="img" aria-label={tx("Unread")} title={tx("Unread")} />
)}
<span className={styles.detail}>
{providerName(n.task.provider)}
{n.task.isolation === "worktree" ? ` · ${branchLabel(n.task.branch)}` : ""}
@@ -136,29 +149,3 @@ export function AgentsView() {
</div>
);
}
function taskMenu(task: AgentTask): MenuItem[] {
const busy = isBusy(task.status);
return [
{ label: "Open", run: () => openTask(task.id) },
{ label: "Open in Terminal", icon: "terminal", run: () => void executeAction("terminal.openAt", task.cwd) },
{ kind: "separator" },
{ label: "Archive", disabled: busy || task.status === "archived", run: () => void archiveTask(task.id) },
{ label: "Delete…", run: () => void confirmDelete(task) },
];
}
async function confirmDelete(task: AgentTask) {
const worktree = task.isolation === "worktree";
const r = await confirmChecked({
title: "Delete Agent Task",
message: worktree
? tx`Delete “${task.title}”? Its branch ${task.branch ?? ""} is kept.`
: tx`Delete “${task.title}”? Files it changed are kept.`,
ok: "Delete",
icon: "warning",
checkbox: worktree ? "Also remove its worktree folder" : undefined,
checked: worktree,
});
if (r) await deleteTask(task.id, worktree && r.checked);
}
+16 -11
Переглянути файл
@@ -98,21 +98,26 @@
opacity: 1;
}
/* `@` / `/` completion, above the box like a code-completion popup. */
.popup {
position: absolute;
/* `@` / `/` completion; Popup keeps the list within the viewport. */
.caretMirror {
position: fixed;
top: 0;
left: 0;
bottom: calc(100% + 4px);
z-index: 10;
width: min(560px, 100%);
box-sizing: border-box;
visibility: hidden;
pointer-events: none;
white-space: pre-wrap;
overflow-wrap: break-word;
}
.popup {
width: min(560px, calc(100vw - 12px));
border-radius: var(--radius-popup);
cursor: default;
}
.items {
max-height: 300px;
overflow: auto;
padding: 4px 0;
border: 1px solid var(--border-popup);
border-radius: var(--radius-popup);
background: var(--bg-popup);
box-shadow: var(--shadow-popup);
cursor: default;
}
.item {
display: flex;
+49 -34
Переглянути файл
@@ -10,7 +10,7 @@ import { call, commands, isTauri } from "@/platform/ipc";
import { useTx } from "@/platform/i18n";
import { basename } from "@/platform/project";
import { notifications, OWNS_FILE_DROP } from "@/workbench/contributions";
import { Icon, IconButton, fileIconName } from "@/ui";
import { Icon, IconButton, Popup, fileIconName } from "@/ui";
import {
IMAGE_EXTENSIONS,
MAX_IMAGE_BYTES,
@@ -27,6 +27,7 @@ import {
type FileRef,
} from "./composerModel";
import { composerDraft, updateComposer, useAgents } from "./store";
import { useCompletionAnchor } from "./useCompletionAnchor";
import styles from "./Composer.module.css";
import { isImeKey } from "@/platform/ime";
@@ -127,13 +128,14 @@ export function Composer(props: ComposerProps) {
.map((command) => ({ kind: "command", command }));
}, [completion, files, props.commands]);
const open = !!completion && items.length > 0;
const completionAnchor = useCompletionAnchor(ref, open ? completion.to : null, text);
const setText = (value: string, caret?: number) => {
const setText = (value: string, caret?: number, restoreSelection = true) => {
updateComposer(id, { text: value });
const c = caret ?? value.length;
setCompletion(completionAt(value, c));
setActive(0);
if (caret !== undefined) {
if (caret !== undefined && restoreSelection) {
requestAnimationFrame(() => {
ref.current?.focus();
ref.current?.setSelectionRange(caret, caret);
@@ -281,36 +283,49 @@ export function Composer(props: ComposerProps) {
{...OWNS_FILE_DROP}
onClick={() => ref.current?.focus()}
>
{open && (
<div className={styles.popup} role="listbox" aria-label={tx(completion.kind === "file" ? "Files" : "Commands")}>
{items.map((item, i) => (
<div
key={item.kind === "file" ? item.path : item.command.name}
role="option"
aria-selected={i === active}
className={clsx(styles.item, i === active && styles.active)}
onMouseEnter={() => setActive(i)}
onMouseDown={(e) => {
e.preventDefault();
accept(item);
}}
>
{item.kind === "file" ? (
<>
<Icon name={fileIconName(basename(item.rel))} size={16} />
<span className={styles.itemName}>{basename(item.rel)}</span>
<span className={styles.itemDetail}>{item.rel}</span>
</>
) : (
<>
<span className={styles.itemName}>/{item.command.name}</span>
{item.command.hint && <span className={styles.itemHint}>{item.command.hint}</span>}
<span className={styles.itemDetail}>{item.command.description}</span>
</>
)}
</div>
))}
</div>
{open && completionAnchor && (
<Popup
open
anchor={completionAnchor}
placement="bottom-start"
autoFocus={false}
restoreFocus={false}
closeOnOutsideClick={false}
onClose={() => setCompletion(null)}
className={styles.popup}
role="listbox"
aria-label={tx(completion.kind === "file" ? "Files" : "Commands")}
>
<div className={styles.items}>
{items.map((item, i) => (
<div
key={item.kind === "file" ? item.path : item.command.name}
role="option"
aria-selected={i === active}
className={clsx(styles.item, i === active && styles.active)}
onMouseEnter={() => setActive(i)}
onMouseDown={(e) => {
e.preventDefault();
accept(item);
}}
>
{item.kind === "file" ? (
<>
<Icon name={fileIconName(basename(item.rel))} size={16} />
<span className={styles.itemName}>{basename(item.rel)}</span>
<span className={styles.itemDetail}>{item.rel}</span>
</>
) : (
<>
<span className={styles.itemName}>/{item.command.name}</span>
{item.command.hint && <span className={styles.itemHint}>{item.command.hint}</span>}
<span className={styles.itemDetail}>{item.command.description}</span>
</>
)}
</div>
))}
</div>
</Popup>
)}
{images.length > 0 && (
<div className={styles.images} onClick={(e) => e.stopPropagation()}>
@@ -339,7 +354,7 @@ export function Composer(props: ComposerProps) {
value={text}
aria-label={tx("Message")}
placeholder={tx(props.placeholder)}
onChange={(e) => setText(e.target.value, undefined)}
onChange={(e) => setText(e.target.value, e.target.selectionStart, false)}
onSelect={(e) => setCompletion(completionAt(e.currentTarget.value, e.currentTarget.selectionStart))}
onBlur={() => setCompletion(null)}
onKeyDown={onKeyDown}
+34
Переглянути файл
@@ -0,0 +1,34 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import type { AgentConfigOption } from "@/bindings";
import { ConfigPickers } from "./ConfigPickers";
it("shows Cursor approvals separately from its execution mode and sends the choice", () => {
const option = (id: string, category: string, values: string[]): AgentConfigOption => ({
id,
category,
name: category === "approval" ? "Approvals" : "Mode",
description: null,
via: "option",
current: values[0]!,
values: values.map((value) => ({
value,
name: value === "bypass" ? "Bypass approvals" : value,
description: null,
})),
});
const onChange = vi.fn();
render(
<ConfigPickers
config={[
option("mode", "mode", ["Agent", "Plan", "Ask"]),
option("openidea.cursor.approval", "approval", ["ask", "bypass"]),
]}
onChange={onChange}
/>,
);
expect(screen.getByText("Agent")).toBeVisible();
fireEvent.click(screen.getByLabelText("Approvals"));
fireEvent.click(screen.getByRole("option", { name: "Bypass approvals" }));
expect(onChange).toHaveBeenCalledWith("openidea.cursor.approval", "bypass");
});
+10 -3
Переглянути файл
@@ -1,6 +1,6 @@
/**
* Model / mode / thinking-effort dropdowns for a composer's bottom row. Like other agent
* UIs, only the mode gets icons (one per mode, by what it allows); levels are plain text.
* Model, mode, approvals and thinking-effort dropdowns for a composer's bottom row.
* Modes and approvals use icons; levels are plain text.
*/
import type { AgentConfigOption } from "@/bindings";
import { useTx } from "@/platform/i18n";
@@ -34,7 +34,14 @@ export function ConfigPickers({
options={o.values.map((v) => ({
value: v.value,
label: v.name,
icon: isMode ? modeIcon(v.value) : undefined,
icon:
o.category === "approval"
? v.value === "bypass"
? "unlock"
: "lock"
: isMode
? modeIcon(v.value)
: undefined,
detail: v.description ?? undefined,
}))}
onChange={(v) => onChange(o.id, v)}
+42
Переглянути файл
@@ -0,0 +1,42 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, expect, it, vi } from "vitest";
import { Markdown } from "./Markdown";
const { openFile, openExternalUrl } = vi.hoisted(() => ({
openFile: vi.fn().mockResolvedValue(undefined),
openExternalUrl: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/workbench/contributions", () => ({ editorService: () => ({ openFile }) }));
vi.mock("@/platform/openUrl", () => ({ openExternalUrl }));
beforeEach(() => vi.clearAllMocks());
it.each([
["/Users/thomas/vmos-shots/tiktok-home.jpg", "/Users/thomas/vmos-shots/tiktok-home.jpg", undefined],
["images/home.jpg", "/repo/images/home.jpg", undefined],
["/tmp/截图%20one.jpg", "/tmp/截图 one.jpg", undefined],
["/repo/main.rs:12:5", "/repo/main.rs", { line: 11, col: 4 }],
["/repo/main.rs#L7", "/repo/main.rs", { line: 6, col: 0 }],
])("opens a Markdown file link: %s", (href, path, selection) => {
render(<Markdown text={`[查看文件](${href})`} cwd="/repo" />);
fireEvent.click(screen.getByRole("link", { name: "查看文件" }));
expect(openFile).toHaveBeenCalledWith(path, { focus: true, selection });
expect(openExternalUrl).not.toHaveBeenCalled();
});
it("keeps web links external", () => {
render(<Markdown text="[Website](https://example.com/image.jpg)" cwd="/repo" />);
fireEvent.click(screen.getByRole("link"));
expect(openExternalUrl).toHaveBeenCalledWith("https://example.com/image.jpg");
expect(openFile).not.toHaveBeenCalled();
});
it.each(["#section", "//example.com/image.jpg", "javascript:alert(1)", "/tmp/%ZZ.jpg"])(
"does not open unsupported links as files: %s",
(href) => {
const { container } = render(<Markdown text={`[Link](${href})`} cwd="/repo" />);
fireEvent.click(container.querySelector("a")!);
expect(openFile).not.toHaveBeenCalled();
expect(openExternalUrl).not.toHaveBeenCalled();
},
);
+7 -2
Переглянути файл
@@ -12,7 +12,7 @@ import { tx } from "@/platform/i18n";
import { openExternalUrl } from "@/platform/openUrl";
import { copyText } from "@/ui";
import { editorService } from "@/workbench/contributions";
import { pathLink, type PathLink } from "./conversation";
import { fileHref, pathLink, type PathLink } from "./conversation";
import styles from "./Session.module.css";
const marked = new Marked({ gfm: true, breaks: true });
@@ -131,7 +131,12 @@ export function Markdown({ text, cwd }: { text: string; cwd: string }) {
const a = target.closest("a");
if (!a) return;
e.preventDefault();
if (/^https?:/i.test(a.href)) void openExternalUrl(a.href);
const href = a.getAttribute("href") ?? "";
if (/^https?:/i.test(href)) void openExternalUrl(href);
else {
const link = fileHref(href, cwd);
if (link) openPathLink(link);
}
}}
dangerouslySetInnerHTML={{ __html: html }}
/>
+2 -2
Переглянути файл
@@ -117,8 +117,8 @@
.stream:focus {
outline: none;
}
/* Off-screen entries skip layout, so resizing the pane doesn't reflow a long conversation. */
.stream > * {
/* Skip off-screen output layout; editable messages must repaint immediately when focus/content changes. */
.stream > :not(.message) {
content-visibility: auto;
contain-intrinsic-block-size: auto 80px;
}
+38 -10
Переглянути файл
@@ -23,6 +23,7 @@ import {
showContextMenu,
} from "@/ui";
import { useTx, tx } from "@/platform/i18n";
import { isImeKey } from "@/platform/ime";
import { TaskStatusIcon } from "./AgentsView";
import { Composer } from "./Composer";
import { canSend, emptyDraft, retryParts, usageLabel, workTime } from "./composerModel";
@@ -697,9 +698,9 @@ function UserMessage({
initial={entry.text}
later={turn < turnCount - 1}
onCancel={() => setEditing(false)}
onSend={(text) => {
onSend={async (text) => {
await rerunFrom(task.id, turn, text);
setEditing(false);
void rerunFrom(task.id, turn, text).catch(fail);
}}
/>
);
@@ -770,12 +771,27 @@ function MessageEditor({
/** Turns follow it (they are dropped on send). */
later: boolean;
onCancel: () => void;
onSend: (text: string) => void;
onSend: (text: string) => Promise<void>;
}) {
const tx = useTx();
const [text, setText] = useState(initial);
const send = () => {
if (text.trim()) onSend(text.trim());
const [sending, setSending] = useState(false);
const [error, setError] = useState<string | null>(null);
const pending = useRef(false);
const send = async () => {
if (!text.trim() || pending.current) return;
pending.current = true;
setSending(true);
setError(null);
try {
await onSend(text.trim());
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
notifications().notify({ level: "error", title: "Couldn't send the message", body: String(e) });
} finally {
pending.current = false;
setSending(false);
}
};
return (
<div className={styles.message}>
@@ -784,19 +800,30 @@ function MessageEditor({
value={text}
rows={Math.min(Math.max(text.split("\n").length, 2), 12)}
autoFocus
readOnly={sending}
aria-label={tx("Message")}
onChange={(e) => setText(e.target.value)}
onFocus={(e) => e.currentTarget.setSelectionRange(text.length, text.length)}
onKeyDown={(e) => {
if (isImeKey(e.nativeEvent)) return;
if (e.key === "Escape") {
e.preventDefault();
onCancel();
e.stopPropagation();
if (!pending.current) onCancel();
} else if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
send();
void send();
}
}}
/>
{error && (
<div className={styles.error} role="alert">
<Icon name="error" size={14} />
<span>
<T>Couldn't send the message</T>: {error}
</span>
</div>
)}
<div className={styles.editBar}>
{later && (
<span className={styles.muted}>
@@ -804,11 +831,12 @@ function MessageEditor({
</span>
)}
<span className={styles.editButtons}>
<Button size="small" onClick={onCancel}>
<Button size="small" disabled={sending} onClick={onCancel}>
Cancel
</Button>
<Button size="small" variant="primary" disabled={!text.trim()} onClick={send}>
Send
<Button size="small" variant="primary" disabled={!text.trim() || sending} onClick={() => void send()}>
{sending && <Spinner size={12} />}
<T>Send</T>
</Button>
</span>
</div>
+2
Переглянути файл
@@ -126,6 +126,8 @@ describe("agent composer", () => {
const config = [option("fast", ["on"], null), option("mode", ["ask", "code"], "code"), option("model", ["m"], "m")];
expect(mainOptions(config).map((o) => o.id)).toEqual(["model", "mode"]);
expect(nextValue(config[1]!)).toBe("ask");
const approvals = { ...option("openidea.cursor.approval", ["ask", "bypass"], "ask"), category: "approval" };
expect(mainOptions([...config, approvals]).map((o) => o.id)).toEqual(["model", "mode", approvals.id]);
expect(
["default", "acceptEdits", "plan", "auto", "bypassPermissions", "auto_edit", "read-only", "x"].map(modeIcon),
).toEqual(["lock", "edit", "todo", "run", "unlock", "edit", "eye", "lock"]);
+18
Переглянути файл
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { AgentCommand, AgentProvider } from "@/bindings";
const agentCommands = vi.fn();
@@ -86,4 +87,21 @@ describe("New Task composer commands", () => {
fireEvent.change(box, { target: { value: "/com" } });
expect(await screen.findByRole("option")).toHaveTextContent("/compact");
});
it("completes at the caret without replacing the rest of the message", async () => {
const user = userEvent.setup();
agentCommands.mockResolvedValue({ status: "ok", data: [command("compact", "Free up context")] });
render(<HomeEditor />);
await waitFor(() => expect(agentCommands).toHaveBeenCalled());
const box = screen.getByRole("textbox");
box.focus();
fireEvent.change(box, { target: { value: "/com keep this context", selectionStart: 4, selectionEnd: 4 } });
expect(await screen.findByRole("option")).toHaveTextContent("/compact");
expect(box).toHaveFocus();
await user.keyboard("{Tab}");
expect(box).toHaveValue("/compact keep this context");
await waitFor(() => expect(screen.queryByRole("listbox", { name: "Commands" })).toBeNull());
expect(agentCreate).not.toHaveBeenCalled();
});
});
+2 -2
Переглянути файл
@@ -109,9 +109,9 @@ export function atEdgeLine(text: string, caret: number, dir: -1 | 1): boolean {
return dir < 0 ? !text.slice(0, caret).includes("\n") : !text.slice(caret).includes("\n");
}
/** The settings shown as dropdowns: model, mode, thinking effort, in that order. */
/** The settings shown as dropdowns: model, mode, approvals, thinking effort, in that order. */
export function mainOptions(config: readonly AgentConfigOption[]): AgentConfigOption[] {
const order = ["model", "mode", "thought_level"];
const order = ["model", "mode", "approval", "thought_level"];
return order.flatMap((c) => config.filter((o) => o.category === c).slice(0, 1));
}
+19
Переглянути файл
@@ -22,6 +22,25 @@ export interface PathLink {
const PATH = /^(?:\.\/)?([\w.@-]+(?:\/[\w.@-]+)*\.[A-Za-z][A-Za-z0-9]*)(?::(\d+)(?::(\d+))?|#L(\d+))?$/;
/** Explicit Markdown links can also name files with spaces or non-ASCII names. */
export function fileHref(href: string, cwd: string): PathLink | null {
if (!href || href.startsWith("#") || href.startsWith("//") || /^[a-z][a-z\d+.-]*:/i.test(href)) return null;
let decoded: string;
try {
decoded = decodeURIComponent(href);
} catch {
return null;
}
const match = /^(.*?)(?::(\d+)(?::(\d+))?|#L(\d+))?$/.exec(decoded);
if (!match?.[1] || [...decoded].some((char) => char.charCodeAt(0) < 32)) return null;
const path = match[1].startsWith("/") ? match[1] : `${cwd.replace(/\/$/, "")}/${match[1]}`;
const link: PathLink = { path };
const line = match[2] ?? match[4];
if (line) link.line = Math.max(0, Number(line) - 1);
if (match[3]) link.col = Math.max(0, Number(match[3]) - 1);
return link;
}
/**
* The file an inline code span names (`src/lib.rs`, `src/main.rs:12`, `a/b.ts:3:5`,
* `/abs/x.py#L7`), resolved against `cwd`; null for text that isn't a file path
+5 -1
Переглянути файл
@@ -21,6 +21,7 @@ import { HOME_KIND, REGISTRY_PAGE, SESSION_KIND, TOOL_WINDOW } from "./model";
import { sendPaths, sendSelection } from "./references";
import { focusedSession } from "./sessionFocus";
import { connect, disconnect, openHome, useAgents } from "./store";
import { taskActions } from "./taskActions";
/** Settings › Tools › Agents (also used by the Settings window). */
export function activateSettingsPages(): () => void {
@@ -54,7 +55,9 @@ export function activate(): () => void {
component: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsView)),
headerActions: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsHeaderActions)),
useBadge: () => {
const n = useAgents((s) => [...s.tasks.values()].filter((t) => t.status === "needsInput").length);
const n = useAgents(
(s) => [...s.tasks.values()].filter((t) => t.status === "needsInput" || s.unread.has(t.id)).length,
);
return n || null;
},
}),
@@ -87,6 +90,7 @@ export function activate(): () => void {
: [],
}),
registerActions([
...taskActions,
{
id: "agents.findInConversation",
title: "Find in Conversation",
+171
Переглянути файл
@@ -0,0 +1,171 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { AgentEntry, AgentTask } from "@/bindings";
const ipc = vi.hoisted(() => ({ rollback: vi.fn(), prompt: vi.fn(), cancel: vi.fn() }));
const entries: AgentEntry[] = [
{ type: "user", text: "Original message", attachments: [], sentMs: 1, doneMs: 2, steered: false },
{ type: "agent", text: "Original answer" },
];
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
commands: {
agentEntries: async () => ({ status: "ok", data: entries }),
agentChanges: async () => ({ status: "ok", data: [] }),
vcsBranchInfo: async () => ({ status: "ok", data: { head: "main" } }),
agentRollback: ipc.rollback,
agentPrompt: ipc.prompt,
agentCancel: ipc.cancel,
},
}));
vi.mock("@tauri-apps/api/webview", () => ({
getCurrentWebview: () => ({ onDragDropEvent: () => Promise.resolve(() => {}) }),
}));
import { SessionEditor } from "./SessionEditor";
import { updateComposer, useAgents } from "./store";
const task: AgentTask = {
id: "editing",
title: "Test task",
provider: "codex",
status: "ready",
isolation: "local",
model: null,
cwd: "/project",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
capabilities: { fork: true, rollback: true, steer: true, images: true },
};
beforeEach(() => {
ipc.rollback.mockReset().mockResolvedValue({ status: "ok", data: null });
ipc.prompt.mockReset().mockResolvedValue({ status: "ok", data: null });
ipc.cancel.mockReset().mockResolvedValue({ status: "ok", data: null });
useAgents.setState({ tasks: new Map([[task.id, task]]), entries: new Map(), composers: new Map(), focus: null });
});
async function edit() {
render(<SessionEditor input={{ kind: "agent-session", key: task.id, data: { task: task.id } }} />);
const user = userEvent.setup();
await user.click(await screen.findByRole("button", { name: "Edit" }));
const box = screen.getAllByRole("textbox", { name: "Message" })[0]!;
fireEvent.change(box, { target: { value: "Edited message" } });
return { user, box, send: screen.getAllByRole("button", { name: "Send" })[0]! };
}
describe("editing a sent agent message", () => {
it("keeps Enter, Shift+Enter and IME confirmation for editing", async () => {
const { box } = await edit();
fireEvent.keyDown(box, { key: "Enter" });
fireEvent.keyDown(box, { key: "Enter", shiftKey: true });
fireEvent.keyDown(box, { key: "Enter", metaKey: true, isComposing: true });
fireEvent.keyDown(box, { key: "Enter", metaKey: true, keyCode: 229 });
expect(ipc.rollback).not.toHaveBeenCalled();
expect(box).toHaveValue("Edited message");
});
it("keeps the draft and shows a rollback failure beside it", async () => {
ipc.rollback.mockResolvedValue({ status: "error", error: { kind: "internal", message: "Rollback failed" } });
const { user, box, send } = await edit();
await user.click(send);
expect(await screen.findByRole("alert")).toHaveTextContent("Rollback failed");
expect(box).toHaveValue("Edited message");
expect(box).toBeInTheDocument();
expect(send).toBeEnabled();
expect(ipc.prompt).not.toHaveBeenCalled();
ipc.rollback.mockResolvedValue({ status: "ok", data: null });
await user.click(send);
await waitFor(() => expect(ipc.prompt).toHaveBeenCalledTimes(1));
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("rolls back before sending the edited text when Send is clicked", async () => {
let finish!: (value: unknown) => void;
ipc.rollback.mockReturnValue(
new Promise((resolve) => {
finish = resolve;
}),
);
const { user, box, send } = await edit();
await user.click(send);
expect(ipc.rollback).toHaveBeenCalledWith(task.id, 0);
expect(ipc.prompt).not.toHaveBeenCalled();
expect(send).toBeDisabled();
fireEvent.keyDown(box, { key: "Enter", metaKey: true });
expect(ipc.rollback).toHaveBeenCalledTimes(1);
await act(async () => finish({ status: "ok", data: null }));
await waitFor(() =>
expect(ipc.prompt).toHaveBeenCalledWith(task.id, { text: "Edited message", files: [], images: [] }, false),
);
});
it.each(["", "Another draft"])("recovers the edit after rollback if sending fails (draft: %j)", async (draft) => {
ipc.rollback.mockImplementation(async () => {
// The backend emits Truncated before replying, removing the inline editor.
useAgents.setState({ entries: new Map([[task.id, []]]) });
return { status: "ok", data: null };
});
let finish!: (value: unknown) => void;
ipc.prompt.mockReturnValue(
new Promise((resolve) => {
finish = resolve;
}),
);
const { user, box, send } = await edit();
act(() => updateComposer(task.id, { text: draft }));
await user.click(send);
expect(box).not.toBeInTheDocument();
await act(async () => finish({ status: "error", error: { kind: "internal", message: "Send failed" } }));
expect(screen.getByRole("textbox", { name: "Message" })).toHaveValue(
draft ? `Edited message\n${draft}` : "Edited message",
);
expect(screen.getByRole("textbox", { name: "Message" })).toHaveFocus();
ipc.prompt.mockResolvedValue({ status: "ok", data: null });
await user.click(screen.getByRole("button", { name: "Send" }));
expect(ipc.prompt).toHaveBeenCalledTimes(2);
expect(ipc.rollback).toHaveBeenCalledTimes(1);
});
it.each([{ metaKey: true }, { ctrlKey: true }])("still sends with modified Enter (%j)", async (modifier) => {
const { box } = await edit();
fireEvent.keyDown(box, { key: "Enter", ...modifier });
await waitFor(() => expect(ipc.prompt).toHaveBeenCalledTimes(1));
});
it("waits for a running turn to stop before rolling it back", async () => {
useAgents.setState({ tasks: new Map([[task.id, { ...task, status: "running" }]]) });
const { user, send } = await edit();
await user.click(send);
expect(ipc.cancel).toHaveBeenCalledWith(task.id, null);
expect(ipc.rollback).not.toHaveBeenCalled();
act(() => useAgents.setState({ tasks: new Map([[task.id, task]]) }));
await waitFor(() => expect(ipc.prompt).toHaveBeenCalledTimes(1));
});
it.each(["Cancel", "Escape"])(
"%s restores the message and discards edits without touching the conversation",
async (method) => {
const { user, box } = await edit();
if (method === "Cancel") await user.click(screen.getByRole("button", { name: "Cancel" }));
else fireEvent.keyDown(box, { key: "Escape" });
expect(box).not.toBeInTheDocument();
expect(screen.getByText("Original message")).toBeInTheDocument();
expect(screen.getByText("Original answer")).toBeInTheDocument();
expect(ipc.rollback).not.toHaveBeenCalled();
expect(ipc.prompt).not.toHaveBeenCalled();
await user.click(screen.getByRole("button", { name: "Edit" }));
expect(screen.getAllByRole("textbox", { name: "Message" })[0]).toHaveValue("Original message");
},
);
});
+67 -8
Переглянути файл
@@ -44,6 +44,8 @@ interface AgentsState {
/** Why the tasks could not be loaded. */
error: string | null;
tasks: Map<string, AgentTask>;
/** Tasks with unseen replies or status changes in this project. */
unread: Set<string>;
/** Entries of the tasks (and subagents) opened in this window, by `entriesKey`. */
entries: Map<string, AgentEntry[]>;
changes: Map<string, AgentChange[]>;
@@ -85,6 +87,7 @@ export const useAgents = create<AgentsState>(() => ({
loaded: false,
error: null,
tasks: new Map(),
unread: new Set(),
entries: new Map(),
changes: new Map(),
providers: [],
@@ -110,11 +113,40 @@ export function updateComposer(key: string, patch: Partial<ComposerDraft>) {
}));
}
/** Session tabs on screen; their tasks do not notify. */
const visible = new Set<string>();
/** Session tabs on screen; a task can be shown in more than one split. */
const visible = new Map<string, number>();
const windowFocused = () => document.visibilityState !== "hidden" && document.hasFocus();
const viewing = (task: string) => visible.has(task) && windowFocused();
function setUnread(task: string, value: boolean) {
const s = useAgents.getState();
if (s.unread.has(task) === value) return;
const unread = new Set(s.unread);
if (value) unread.add(task);
else unread.delete(task);
useAgents.setState({ unread });
}
function markUnread(task: string) {
const current = useAgents.getState().tasks.get(task);
if (current && current.status !== "archived" && !viewing(task)) setUnread(task, true);
}
export function markVisible(task: string): () => void {
visible.add(task);
return () => visible.delete(task);
visible.set(task, (visible.get(task) ?? 0) + 1);
const read = () => {
if (viewing(task)) setUnread(task, false);
};
read();
window.addEventListener("focus", read);
document.addEventListener("visibilitychange", read);
return () => {
const count = (visible.get(task) ?? 1) - 1;
if (count) visible.set(task, count);
else visible.delete(task);
window.removeEventListener("focus", read);
document.removeEventListener("visibilitychange", read);
};
}
let generation = 0;
@@ -154,7 +186,14 @@ export async function connect(): Promise<void> {
export function disconnect() {
generation++;
useAgents.setState({ loaded: false, error: null, tasks: new Map(), entries: new Map(), changes: new Map() });
useAgents.setState({
loaded: false,
error: null,
tasks: new Map(),
unread: new Set(),
entries: new Map(),
changes: new Map(),
});
}
function onEvent(e: AgentEvent) {
@@ -163,6 +202,8 @@ function onEvent(e: AgentEvent) {
case "task": {
const prev = s.tasks.get(e.task.id);
useAgents.setState({ tasks: new Map(s.tasks).set(e.task.id, e.task) });
if (e.task.status === "archived") setUnread(e.task.id, false);
else if (attentionChange(prev?.status, e.task.status)) markUnread(e.task.id);
notifyChange(prev, e.task);
if (prev?.status !== e.task.status && !isBusy(e.task.status)) {
void refreshChanges(e.task.id);
@@ -175,7 +216,9 @@ function onEvent(e: AgentEvent) {
tasks.delete(e.id);
const composers = new Map(s.composers);
composers.delete(e.id);
useAgents.setState({ tasks, composers });
const unread = new Set(s.unread);
unread.delete(e.id);
useAgents.setState({ tasks, composers, unread });
editorService().closeInput?.(sessionKey(e.id));
break;
}
@@ -186,6 +229,14 @@ function onEvent(e: AgentEvent) {
break;
}
case "entry": {
if (
!e.subagent &&
((e.entry.type === "agent" && e.entry.text.trim()) ||
e.entry.type === "error" ||
(e.entry.type === "permission" && e.entry.chosen === null))
) {
markUnread(e.task);
}
const key = entriesKey(e.task, e.subagent);
const current = s.entries.get(key);
if (!current) return;
@@ -203,7 +254,7 @@ function onEvent(e: AgentEvent) {
function notifyChange(prev: AgentTask | undefined, task: AgentTask) {
const change = attentionChange(prev?.status, task.status);
if (!change) return;
if (visible.has(task.id) && document.hasFocus()) return;
if (viewing(task.id)) return;
const body =
change === "input"
? "Waiting for your answer"
@@ -364,7 +415,15 @@ export async function rerunFrom(task: string, turn: number, text: string): Promi
await settled(task);
}
await call(commands.agentRollback(task, turn));
await call(commands.agentPrompt(task, { text, files: [], images: [] }, false));
try {
await call(commands.agentPrompt(task, { text, files: [], images: [] }, false));
} catch (e) {
// Rollback removes the inline editor; recover its text in the session composer.
const current = composerDraft(task);
updateComposer(task, { text: current.text ? `${text}\n${current.text}` : text });
focusComposer(task);
throw e;
}
}
/** Resolves once the task's turn has ended (or after a while). */
+115
Переглянути файл
@@ -0,0 +1,115 @@
import type { AgentTask } from "@/bindings";
import type { Action } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import type { MenuItem } from "@/ui";
import { showError, confirmChecked } from "@/workbench/messages";
import { isBusy } from "./model";
import { archiveTask, deleteTask, openTask, useAgents } from "./store";
const canArchive = (task: AgentTask) => !isBusy(task.status) && task.status !== "archived";
function resolveTasks(arg: unknown): AgentTask[] {
if (!Array.isArray(arg)) return [];
return [...new Set(arg)].flatMap((id: unknown) => {
const task = typeof id === "string" ? useAgents.getState().tasks.get(id) : undefined;
return task ? [task] : [];
});
}
async function runTasks(tasks: AgentTask[], run: (task: AgentTask) => Promise<unknown>, title: string) {
const errors: string[] = [];
for (const task of tasks) {
try {
await run(task);
} catch (error) {
errors.push(`${task.title}: ${error instanceof Error ? error.message : String(error)}`);
}
}
if (errors.length) await showError(title, errors.join("\n"));
}
async function confirmDelete(tasks: AgentTask[]) {
if (!tasks.length) return;
const task = tasks[0]!;
const multiple = tasks.length > 1;
const worktree = tasks.some((t) => t.isolation === "worktree");
const r = await confirmChecked({
title: multiple ? "Delete Agent Tasks" : "Delete Agent Task",
message: multiple
? tx`Delete ${tasks.length} agent tasks? Their branches and files outside worktrees are kept.`
: worktree
? tx`Delete “${task.title}”? Its branch ${task.branch ?? ""} is kept.`
: tx`Delete “${task.title}”? Files it changed are kept.`,
ok: "Delete",
icon: "warning",
checkbox: worktree
? multiple
? "Also remove their worktree folders"
: "Also remove its worktree folder"
: undefined,
checked: worktree,
});
if (r)
await runTasks(
tasks,
(t) => deleteTask(t.id, t.isolation === "worktree" && r.checked),
tx("Cannot delete agent tasks"),
);
}
export const taskActions: Action[] = [
{
id: "agents.openTask",
title: "Open Agent Task",
category: "Agents",
hidden: true,
run: ({ arg }) => {
if (typeof arg === "string") openTask(arg);
},
},
{
id: "agents.archiveTasks",
title: "Archive Agent Tasks",
category: "Agents",
hidden: true,
run: ({ arg }) =>
runTasks(resolveTasks(arg).filter(canArchive), (task) => archiveTask(task.id), tx("Cannot archive agent tasks")),
},
{
id: "agents.deleteTasks",
title: "Delete Agent Tasks",
category: "Agents",
hidden: true,
run: ({ arg }) => confirmDelete(resolveTasks(arg)),
},
];
export function taskMenu(tasks: AgentTask[]): MenuItem[] {
if (!tasks.length) return [];
const ids = tasks.map((task) => task.id);
const task = tasks[0]!;
const multiple = tasks.length > 1;
const archivable = tasks.filter(canArchive).length;
return [
...(!multiple
? ([
{ kind: "action", action: "agents.openTask", label: "Open", arg: task.id },
{ kind: "action", action: "terminal.openAt", label: "Open in Terminal", icon: "terminal", arg: task.cwd },
{ kind: "separator" },
] satisfies MenuItem[])
: []),
{
kind: "action",
action: "agents.archiveTasks",
label: multiple ? tx`Archive (${archivable})` : "Archive",
arg: ids,
disabled: !archivable,
},
{
kind: "action",
action: "agents.deleteTasks",
label: multiple ? tx`Delete (${tasks.length})…` : "Delete…",
arg: ids,
},
];
}
+224
Переглянути файл
@@ -0,0 +1,224 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import type { AgentEntry, AgentEvent, AgentTask } from "@/bindings";
import { useContributions } from "@/workbench/contributions";
import { AgentsView } from "./AgentsView";
import { AgentsStatus } from "./AgentsStatus";
import { activate } from "./index";
import { connect, disconnect, markVisible, useAgents } from "./store";
const backend = vi.hoisted(() => ({
channel: null as { onmessage: (event: AgentEvent) => void } | null,
tasks: [] as AgentTask[],
notify: vi.fn(),
openInput: vi.fn(),
closeInput: vi.fn(),
}));
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage = () => {};
},
}));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: {
agentSubscribe: async (channel: typeof backend.channel) => {
backend.channel = channel;
return { status: "ok", data: backend.tasks };
},
agentProviders: async () => ({ status: "ok", data: [] }),
agentChanges: async () => ({ status: "ok", data: [] }),
},
}));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
editorService: () => ({ openInput: backend.openInput, closeInput: backend.closeInput }),
notifications: () => ({ notify: backend.notify }),
}));
const task = (id: string, status: AgentTask["status"] = "running"): AgentTask => ({
id,
title: id,
status,
provider: "codex",
isolation: "local",
model: null,
cwd: "/project",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
});
const emit = (event: AgentEvent) => act(() => backend.channel!.onmessage(event));
const reply = (id = "one", text = "New reply") =>
emit({ type: "entry", task: id, subagent: null, index: 0, entry: { type: "agent", text } });
const visible: Array<() => void> = [];
const show = (id = "one") => {
let hide!: () => void;
act(() => {
hide = markVisible(id);
});
visible.push(hide);
return () => visible.splice(visible.indexOf(hide), 1)[0]!();
};
beforeEach(async () => {
vi.clearAllMocks();
vi.spyOn(document, "hasFocus").mockReturnValue(true);
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
disconnect();
backend.tasks = [task("one"), task("two", "ready")];
await connect();
});
afterEach(() => {
visible.splice(0).forEach((hide) => hide());
disconnect();
vi.restoreAllMocks();
});
describe("agent unread activity", () => {
it("does not mark historical tasks unread, but tracks replies even without loaded entries", () => {
expect(useAgents.getState().unread.size).toBe(0);
reply();
reply("one", "New reply, streamed further");
reply("two");
expect([...useAgents.getState().unread]).toEqual(["one", "two"]);
expect(useAgents.getState().entries.size).toBe(0);
expect(backend.notify).not.toHaveBeenCalled();
});
it.each(["ready", "needsInput", "failed", "limited"] as const)("marks background %s transitions unread", (status) => {
emit({ type: "task", task: task("one", status) });
expect(useAgents.getState().unread.has("one")).toBe(true);
expect(backend.notify).toHaveBeenCalledTimes(1);
show();
emit({ type: "task", task: task("one", status) });
expect(useAgents.getState().unread.size).toBe(0);
expect(backend.notify).toHaveBeenCalledTimes(1);
});
it("ignores user messages, thoughts, empty replies and subagent streaming", () => {
const entries: AgentEntry[] = [
{ type: "user", text: "Do this", attachments: [] },
{ type: "thought", text: "Thinking" },
{ type: "agent", text: " " },
];
for (const entry of entries) emit({ type: "entry", task: "one", subagent: null, index: 0, entry });
emit({ type: "entry", task: "one", subagent: "child", index: 0, entry: { type: "agent", text: "Working" } });
emit({ type: "task", task: { ...task("one"), title: "Renamed" } });
expect(useAgents.getState().unread.size).toBe(0);
});
it("clears only the viewed task and keeps reading while either split shows it", () => {
reply();
reply("two");
const hide = show();
show();
hide();
reply();
emit({ type: "task", task: task("one", "ready") });
expect([...useAgents.getState().unread]).toEqual(["two"]);
expect(backend.notify).not.toHaveBeenCalled();
});
it("keeps a visible session unread while the window is unfocused, then clears on focus", () => {
vi.mocked(document.hasFocus).mockReturnValue(false);
reply();
show();
expect(useAgents.getState().unread.has("one")).toBe(true);
vi.mocked(document.hasFocus).mockReturnValue(true);
fireEvent(window, new Event("focus"));
expect(useAgents.getState().unread.size).toBe(0);
reply();
expect(useAgents.getState().unread.size).toBe(0);
});
it("does not read hidden windows and removes focus listeners when the session closes", () => {
vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");
const hide = show();
reply();
fireEvent(window, new Event("focus"));
expect(useAgents.getState().unread.has("one")).toBe(true);
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
fireEvent(document, new Event("visibilitychange"));
expect(useAgents.getState().unread.size).toBe(0);
hide();
reply();
fireEvent(window, new Event("focus"));
expect(useAgents.getState().unread.has("one")).toBe(true);
});
it("cleans up archived and deleted tasks, ignores late replies, and resets on project switch", async () => {
reply();
reply("two");
emit({ type: "task", task: task("one", "archived") });
reply();
expect([...useAgents.getState().unread]).toEqual(["two"]);
emit({ type: "removed", id: "two" });
reply("two");
expect(useAgents.getState().unread.size).toBe(0);
emit({ type: "task", task: task("one") });
reply();
const oldChannel = backend.channel!;
disconnect();
backend.tasks = [task("other")];
await connect();
oldChannel.onmessage({ type: "task", task: task("one", "ready") });
expect(useAgents.getState().unread.size).toBe(0);
expect([...useAgents.getState().tasks.keys()]).toEqual(["other"]);
});
});
describe("agent unread indicators", () => {
it("shows a dot on the task and a clickable status count even when all tasks are idle", () => {
emit({ type: "task", task: task("one", "ready") });
render(
<>
<AgentsView />
<AgentsStatus />
</>,
);
expect(screen.getByRole("img", { name: "Unread" })).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "1 unread" }));
expect(backend.openInput).toHaveBeenCalledWith(expect.objectContaining({ data: { task: "one", title: "one" } }), {
focus: true,
});
show();
expect(screen.queryByRole("img", { name: "Unread" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /unread/ })).not.toBeInTheDocument();
});
it("counts unread and needs-input tasks once each in the sidebar badge", () => {
const dispose = activate();
try {
const useBadge = useContributions.getState().toolWindows.get("agents")!.useBadge!;
function Badge() {
return <span data-testid="badge">{useBadge()}</span>;
}
act(() =>
useAgents.setState({
tasks: new Map([task("one", "needsInput"), task("two", "ready")].map((t) => [t.id, t])),
unread: new Set(["one", "two"]),
}),
);
render(<Badge />);
expect(screen.getByTestId("badge")).toHaveTextContent("2");
show("two");
expect(screen.getByTestId("badge")).toHaveTextContent("1");
show("one");
expect(screen.getByTestId("badge")).toHaveTextContent("1");
} finally {
act(dispose);
}
});
});
+69
Переглянути файл
@@ -0,0 +1,69 @@
import { useLayoutEffect, useState, type RefObject } from "react";
import type { VirtualElement } from "@floating-ui/react-dom";
import styles from "./Composer.module.css";
const TEXT_STYLES = [
"fontFamily",
"fontSize",
"fontWeight",
"fontStyle",
"fontVariant",
"lineHeight",
"letterSpacing",
"wordSpacing",
"textIndent",
"textAlign",
"textTransform",
"tabSize",
"paddingTop",
"paddingRight",
"paddingBottom",
"paddingLeft",
] as const;
/** A textarea has no text DOM to measure; mirror its wrapping and scroll offset. */
function caretRect(textarea: HTMLTextAreaElement, caret: number): DOMRect {
const computed = getComputedStyle(textarea);
const mirror = document.createElement("div");
mirror.className = styles.caretMirror ?? "";
for (const property of TEXT_STYLES) mirror.style[property] = computed[property];
mirror.style.width = `${textarea.clientWidth}px`;
mirror.textContent = textarea.value.slice(0, caret);
const marker = document.createElement("span");
marker.textContent = textarea.value.slice(caret) || "\u200b";
mirror.append(marker);
document.body.append(mirror);
try {
const box = textarea.getBoundingClientRect();
const lineHeight = parseFloat(computed.lineHeight) || parseFloat(computed.fontSize) * 1.5;
return new DOMRect(
box.left + textarea.clientLeft + marker.offsetLeft - textarea.scrollLeft,
box.top + textarea.clientTop + marker.offsetTop - textarea.scrollTop,
0,
lineHeight,
);
} finally {
mirror.remove();
}
}
export function useCompletionAnchor(
ref: RefObject<HTMLTextAreaElement | null>,
caret: number | null,
text: string,
): VirtualElement | null {
const [anchor, setAnchor] = useState<VirtualElement | null>(null);
useLayoutEffect(() => {
const textarea = ref.current;
if (!textarea || caret === null) {
setAnchor(null);
return;
}
const update = () =>
setAnchor({ contextElement: textarea, getBoundingClientRect: () => caretRect(textarea, caret) });
update();
textarea.addEventListener("scroll", update);
return () => textarea.removeEventListener("scroll", update);
}, [ref, caret, text]);
return anchor;
}
+18
Переглянути файл
@@ -111,6 +111,24 @@ describe("project view context menu", () => {
expect(sub(items, "Git")?.slice(0, 4)).toEqual(["Commit File…", "Add", "-", "Annotate with Git Blame"]);
});
it("offers both ignore destinations for files, directories and multi-selection, separately from IDE exclusion", () => {
const dispose = registerActions(
["vcs.ignoreShared", "vcs.ignoreLocal"].map((id) => ({ id, title: id, run: () => undefined })),
);
try {
for (const nodes of [[node("/p/a")], [node("/p/dir", true)], [node("/p/a"), node("/p/dir", true)]]) {
const git = resolveMenuItems(contextMenuItems(nodes)).find((item) => item.label === "Git")!;
expect(sub(git.submenu!, "Add to .gitignore")).toEqual([".gitignore", ".git/info/exclude"]);
}
const root = resolveMenuItems(contextMenuItems([node("/p", true, true)])).find((item) => item.label === "Git")!;
expect(labels(root.submenu!)).not.toContain("Add to .gitignore");
const folder = contextMenuItems([node("/p/dir", true)]);
expect(sub(folder, "Mark Directory as")).toContain("Excluded");
} finally {
dispose();
}
});
it("shows Mark Directory as for folders, without file-only items", () => {
const l = labels(contextMenuItems([node(`${ROOT}/src`, true)]));
expect(l).toContain("Mark Directory as");
+7
Переглянути файл
@@ -321,6 +321,13 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
[
act("vcs.commit", undefined, dirs || nodes.length > 1 ? "Commit…" : "Commit File…"),
act("vcs.addToVcs", arg, "Add"),
nonRoot.length === nodes.length &&
nodes.length > 0 &&
nodes.every((n) => !n.placeholder) &&
submenu("gitIgnore", "Add to .gitignore", [
act("vcs.ignoreShared", arg, ".gitignore"),
act("vcs.ignoreLocal", arg, ".git/info/exclude"),
]),
{ kind: "separator" },
singleFile && act("vcs.annotate", singleFile.path, "Annotate with Git Blame"),
act("vcs.showDiff", arg, "Show Diff"),
+12 -16
Переглянути файл
@@ -179,7 +179,9 @@
}
.noHighlight :global(.cm-changedLine),
.noHighlight :global(.cm-insertedLine),
.noHighlight :global(.cm-changedText) {
.noHighlight :global(.cm-changedText),
.noHighlight :global(.cm-diffLine),
.noHighlight :global(.cm-diffChangedGutter) {
background: none !important;
}
/* Side-by-side without alignment (IDEA's default): each pane scrolls itself. */
@@ -216,17 +218,17 @@
position: absolute;
inset: 0;
}
/* Opaque mixes of the line backgrounds (cm.ts), so bands and their midlines read as one shape. */
/* The full colours of the change types (cm.ts), so bands and their midlines read as one shape. */
.host :global(.cm-diffBand-inserted) {
--band: color-mix(in srgb, var(--success) 26%, var(--bg-app));
--band: var(--diff-inserted);
}
.host :global(.cm-diffBand-deleted) {
--band: color-mix(in srgb, var(--danger) 26%, var(--bg-app));
--band: var(--diff-deleted);
}
.host :global(.cm-diffBand-modified) {
--band: color-mix(in srgb, var(--gutter-added) 20%, var(--bg-app));
--band: var(--diff-modified);
}
.host :global(.cm-diffBand:not(.cm-diffBand-modified)) {
.host :global(.cm-diffBand) {
fill: var(--band);
}
.host :global(.cm-diffBandLine) {
@@ -234,12 +236,6 @@
stroke: var(--band);
stroke-width: 1px;
}
.host :global(.cm-diffBandStopA) {
stop-color: color-mix(in srgb, var(--gutter-deleted) 20%, var(--bg-app));
}
.host :global(.cm-diffBandStopB) {
stop-color: color-mix(in srgb, var(--gutter-added) 20%, var(--bg-app));
}
.host :global(.cm-diffDivider button.cm-diffArrow) {
position: absolute;
display: flex;
@@ -266,16 +262,16 @@
}
/* Where the other pane has lines this one lacks. */
.host :global(.cm-diffGap-inserted) {
box-shadow: inset 0 1px 0 var(--success);
box-shadow: inset 0 1px 0 var(--gutter-added);
}
.host :global(.cm-diffGap-deleted) {
box-shadow: inset 0 1px 0 var(--danger);
box-shadow: inset 0 1px 0 var(--gutter-deleted);
}
.host :global(.cm-diffGap-inserted.cm-diffGapEnd) {
box-shadow: inset 0 -1px 0 var(--success);
box-shadow: inset 0 -1px 0 var(--gutter-added);
}
.host :global(.cm-diffGap-deleted.cm-diffGapEnd) {
box-shadow: inset 0 -1px 0 var(--danger);
box-shadow: inset 0 -1px 0 var(--gutter-deleted);
}
/* Review comments under diff lines (pull requests). */
+19 -20
Переглянути файл
@@ -5,15 +5,7 @@ import clsx from "clsx";
import { EditorView, keymap } from "@codemirror/view";
import { Prec, Text, type Extension } from "@codemirror/state";
import { history, historyKeymap } from "@codemirror/commands";
import {
MergeView,
getChunks,
goToNextChunk,
goToPreviousChunk,
rejectChunk,
unifiedMergeView,
Chunk,
} from "@codemirror/merge";
import { MergeView, getChunks, goToNextChunk, goToPreviousChunk, unifiedMergeView, Chunk } from "@codemirror/merge";
import { attachDocument, embeddedEditorExtensions, type DocumentAttachment } from "@/editor/api";
import { setFindOpen } from "@/editor/core/cm/find";
import { FindPanel, searchAgain, seedFind, type FindTarget } from "@/editor/core/view/FindBar";
@@ -23,14 +15,14 @@ import { bindingsFor, normalizeBinding, shortcutLabel, strokeOf } from "@/platfo
import { tx } from "@/platform/i18n";
import { IconButton, Select, Spinner, T, showContextMenu } from "@/ui";
import { editorService, type EditorInput } from "@/workbench/contributions";
import { languageFor, viewerBase } from "./cm";
import { applyChunk, arrowControls, chunkAt, hoverRevert } from "./diffControls";
import { changedLineGutters, diffWords, languageFor, viewerBase } from "./cm";
import { applyChunk, arrowControls, chunkAt, hoverRevert, revertUnifiedChunk } from "./diffControls";
import {
HIGHLIGHT_OPTIONS,
IGNORE_OPTIONS,
ideaDiffConfig,
loadDiffOptions,
saveDiffOptions,
whitespaceDiff,
type DiffViewOptions,
type HighlightPolicy,
type IgnorePolicy,
@@ -259,8 +251,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
},
});
const collapseUnchanged = opts.collapse ? { margin: 3, minSize: 6 } : undefined;
const override = whitespaceDiff(opts.ignore);
const diffConfig = { override };
const diffConfig = ideaDiffConfig(opts.ignore, opts.highlight);
const highlightChanges = opts.highlight === "words";
const inclusion = includable ? inclusionGutter(path, textA) : [];
const side = (att: DocumentAttachment | null, editable: boolean, notes?: "left" | "right"): Extension[] => [
@@ -289,11 +280,14 @@ export function DiffEditor({ input }: { input: EditorInput }) {
? { toA: editableA, toB: editableB, apply: (i, source) => merge && applyChunk(merge, i, source) }
: undefined,
});
// IDEA's colouring: lines by chunk type, carried into the gutters, and typed word highlights.
const colours = [changedLineGutters, highlightChanges ? diffWords : []];
const mv = new MergeView({
a: {
doc: textA,
extensions: [
side(attached.a, editableA, "left"),
colours,
panes?.extension ?? [],
focusTracker("a"),
findWatch("a"),
@@ -304,6 +298,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
doc: textB,
extensions: [
side(attached.b, editableB, "right"),
colours,
panes?.extension ?? [],
listener,
focusTracker("b"),
@@ -319,9 +314,9 @@ export function DiffEditor({ input }: { input: EditorInput }) {
!panes && (editableA || editableB)
? arrowControls(() => merge, { toA: editableA, toB: editableB })
: undefined,
highlightChanges,
// Unpadded panes tint the gutters of changed lines instead of a change bar.
gutter: !panes,
// Words are highlighted by type (`diffWords`), and gutters tinted instead of a change bar.
highlightChanges: false,
gutter: false,
collapseUnchanged,
diffConfig,
});
@@ -353,13 +348,14 @@ export function DiffEditor({ input }: { input: EditorInput }) {
focusTracker("b"),
findWatch("b"),
inclusion,
highlightChanges ? diffWords : [],
unifiedMergeView({
original: textA,
highlightChanges,
gutter: true,
syntaxHighlightDeletions: true,
mergeControls: editableB
? (type, action) => {
? (type) => {
const btn = document.createElement("button");
if (type === "accept") {
btn.hidden = true;
@@ -367,7 +363,10 @@ export function DiffEditor({ input }: { input: EditorInput }) {
}
btn.textContent = "Revert";
btn.title = "Revert this change";
btn.onmousedown = action;
btn.onmousedown = (event) => {
event.preventDefault();
revertUnifiedChunk(view, view.posAtDOM(btn));
};
return btn;
}
: false,
@@ -536,7 +535,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
const cur = currentChunk();
if (!views || !cur) return;
if (views.merge) applyChunk(views.merge, cur.index, "a");
else rejectChunk(views.b, cur.chunk.fromB);
else revertUnifiedChunk(views.b, cur.chunk.fromB);
};
const stageChunk = async () => {
+2 -1
Переглянути файл
@@ -173,7 +173,8 @@
display: flex;
align-items: center;
gap: 6px;
overflow: hidden;
/* Let graph endpoints overlap adjacent rows; text is clipped by .subject. */
overflow: visible;
}
.colAuthor {
flex: none;
+8 -5
Переглянути файл
@@ -178,7 +178,7 @@ function LogView() {
.then((all) => {
if (!live) return;
const signature = JSON.stringify(all);
if (allRefs.current !== null && allRefs.current !== signature) void reloadLog();
if (allRefs.current !== null && allRefs.current !== signature) void reloadLog({ preserve: true });
allRefs.current = signature;
})
.catch(() => undefined);
@@ -215,7 +215,8 @@ function LogView() {
const refs = refsSignature(branch, branches) + JSON.stringify(useVcs.getState().heads);
const previous = lastRefs.current;
lastRefs.current = refs;
if (previous !== null && previous !== refs && useGitLog.getState().commits.length) void reloadLog();
if (previous !== null && previous !== refs && useGitLog.getState().commits.length)
void reloadLog({ preserve: true });
}, [version]);
return (
@@ -742,7 +743,7 @@ function FilterBar() {
onClear={() => setLogFilters({ path: null })}
/>
<span className={styles.grow} />
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void reloadLog()} />
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void reloadLog({ preserve: true })} />
<IconButton
icon="sort"
title="Graph Options"
@@ -1003,7 +1004,7 @@ function CommitList() {
const c = commits[v.index];
if (!c)
return (
<div key="loading" className={styles.row} style={{ transform: `translateY(${v.start}px)` }}>
<div key="loading" className={styles.row} style={{ top: v.start }}>
<Spinner size={12} />{" "}
<span className={styles.muted}>
<T>Loading…</T>
@@ -1075,7 +1076,7 @@ const CommitRow = memo(function CommitRow({
role="option"
aria-selected={selected}
className={clsx(styles.row, onBranch && styles.currentBranch, selected && styles.selected)}
style={{ transform: `translateY(${top}px)` }}
style={{ top }}
onMouseDown={(e) => {
if (e.shiftKey) e.preventDefault(); // no text selection on range clicks
onPick(commitKey(c), e);
@@ -1132,6 +1133,7 @@ export function GraphCell({ row, head }: { row: GraphRow; head?: boolean }) {
key={`u${i}`}
d={seg(x(s.from), 0, x(s.to), cy) + (s.arrow ? arrowHead(x(s.from), 0, -1) : "")}
stroke={laneColor(s.color)}
strokeLinecap={s.dashed ? "butt" : "square"}
strokeDasharray={s.dashed ? "2 2" : undefined}
/>
))}
@@ -1140,6 +1142,7 @@ export function GraphCell({ row, head }: { row: GraphRow; head?: boolean }) {
key={`d${i}`}
d={seg(x(s.from), cy, x(s.to), ROW) + (s.arrow ? arrowHead(x(s.to), ROW, 1) : "")}
stroke={laneColor(s.color)}
strokeLinecap={s.dashed ? "butt" : "square"}
strokeDasharray={s.dashed ? "2 2" : undefined}
/>
))}
+181 -49
Переглянути файл
@@ -1,23 +1,24 @@
import { describe, expect, it } from "vitest";
import { Chunk, MergeView } from "@codemirror/merge";
import { Text } from "@codemirror/state";
import { ChangeSet, Text } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { applyChunk, arrowControls } from "../diffControls";
import {
DEFAULT_DIFF_OPTIONS,
parseDiffOptions,
ideaChunks,
ideaDiffConfig,
transferChunk,
whitespaceDiff,
type IgnorePolicy,
} from "../diffOptions";
import { clipboardDiffData, compareFilesData, parseTextsArg } from "../compare";
import { diffInput, diffTitle, sideFile, sideKey } from "../diffInput";
import { changedLineGutters, viewerBase } from "../cm";
import { changedLineGutters, chunkKind, diffWords, viewerBase } from "../cm";
const doc = (s: string) => Text.of(s.split("\n"));
function chunks(a: string, b: string, ignore: IgnorePolicy) {
const override = whitespaceDiff(ignore);
return Chunk.build(doc(a), doc(b), { override });
return ideaChunks(doc(a), doc(b), ignore, "words");
}
describe("diff options", () => {
@@ -124,47 +125,121 @@ describe("diff options", () => {
}
});
it("decorates consecutive inserted and deleted lines as whole lines", () => {
it("colours lines by their chunk's type, as IDEA does", () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const extensions = [viewerBase({ readOnly: true }), diffWords];
const mv = new MergeView({
a: { doc: "before\nremoved one\nremoved two\nafter\n", extensions: viewerBase({ readOnly: true }) },
b: { doc: "before\nafter\n", extensions: viewerBase({ readOnly: true }) },
a: { doc: "keep\nremoved one\nremoved two\nmid\nvalue = old\nend\n", extensions },
b: { doc: "keep\nmid\nvalue = new\nadded\nend\n", extensions },
parent,
diffConfig: { override: whitespaceDiff("none") },
highlightChanges: false,
diffConfig: ideaDiffConfig("none", "words"),
});
expect(mv.a.dom.querySelectorAll(".cm-diffWholeLine")).toHaveLength(2);
expect(mv.b.dom.querySelectorAll(".cm-diffWholeLine")).toHaveLength(0);
const lines = (v: EditorView, kind: string) =>
[...v.dom.querySelectorAll(`.cm-diffLine-${kind}`)].map((e) => e.textContent);
expect(lines(mv.a, "deleted")).toEqual(["removed one", "removed two"]);
// A block with lines on both sides is modified as a whole, on both sides.
expect(lines(mv.a, "modified")).toEqual(["value = old"]);
expect(lines(mv.b, "modified")).toEqual(["value = new", "added"]);
expect(lines(mv.b, "inserted")).toEqual([]);
expect(chunkKind(mv.chunks[1]!)).toBe("modified");
mv.destroy();
parent.remove();
});
it("keeps word highlighting on paired lines of a multi-line replacement", () => {
it("highlights the words of a modified block by their own type", async () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const extensions = [viewerBase({ readOnly: true }), diffWords];
const mv = new MergeView({
a: {
doc: "before\nfrom old.first import X\nfrom old.second import Y\nafter\n",
extensions: viewerBase({ readOnly: true }),
},
b: {
doc: "before\nfrom new.first import A\nfrom new.second import B\nadded line\nafter\n",
extensions: viewerBase({ readOnly: true }),
},
a: { doc: "x\n syncScroll: boolean;\ny\n", extensions },
b: { doc: "x\n /** Docs. */\n syncScrolling: boolean;\ny\n", extensions },
parent,
diffConfig: { override: whitespaceDiff("none") },
highlightChanges: false,
diffConfig: ideaDiffConfig("none", "words"),
});
expect(mv.a.dom.querySelectorAll(".cm-changedLine")).toHaveLength(2);
expect(mv.a.dom.querySelector(".cm-diffWholeLine")).toBeNull();
expect([...mv.a.dom.querySelectorAll(".cm-changedText")].map((e) => e.textContent)).toEqual([
"old",
"X",
"old",
"Y",
// The left pane highlights its words once the right one exists.
await Promise.resolve();
const words = (v: EditorView, kind: string) =>
[...v.dom.querySelectorAll(`.cm-diffWord.cm-diffWord-${kind}`)].map((e) => e.textContent);
// The edited identifier is highlighted whole, joined by the comment added before it.
expect(words(mv.a, "modified")).toEqual(["syncScroll"]);
expect(words(mv.b, "modified").join("")).toBe("/** Docs. */ syncScrolling");
expect(mv.a.dom.classList.contains("cm-diffWords")).toBe(true);
mv.destroy();
parent.remove();
});
it("marks inserted and deleted words inside a modified line", async () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const extensions = [viewerBase({ readOnly: true }), diffWords];
const mv = new MergeView({
a: { doc: "call(first, extra, last)\n", extensions },
b: { doc: "call(first, last, more)\n", extensions },
parent,
highlightChanges: false,
diffConfig: ideaDiffConfig("none", "words"),
});
// The left pane highlights its words once the right one exists.
await Promise.resolve();
const words = (v: EditorView, kind: string) =>
[...v.dom.querySelectorAll(`.cm-diffWord.cm-diffWord-${kind}`)].map((e) => e.textContent);
expect(words(mv.a, "deleted").join("")).toContain("extra");
expect(words(mv.b, "inserted").join("")).toContain("more");
expect(words(mv.a, "inserted")).toEqual([]);
expect(words(mv.b, "deleted")).toEqual([]);
mv.destroy();
parent.remove();
});
it("diffs changed blocks by words (ByWord)", () => {
const pairs = (a: string, b: string) =>
chunks(a, b, "none").flatMap((ch) =>
ch.changes.map((c) => [
a.slice(ch.fromA + c.fromA, ch.fromA + c.toA),
b.slice(ch.fromB + c.fromB, ch.fromB + c.toB),
]),
);
// An edited identifier is changed whole.
expect(pairs(" syncScroll: boolean;", " syncScrolling: boolean;")).toEqual([["syncScroll", "syncScrolling"]]);
// Punctuation is matched between matched words only: two changed words around ":" are one fragment.
expect(pairs(" syncScroll: true,", " syncScrolling: false,")).toEqual([
["syncScroll: true", "syncScrolling: false"],
]);
expect(mv.b.dom.querySelectorAll(".cm-changedLine")).toHaveLength(3);
expect([...mv.b.dom.querySelectorAll(".cm-diffWholeLine")].map((e) => e.textContent)).toEqual(["added line"]);
expect(mv.b.dom.querySelectorAll(".cm-changedLine:not(.cm-diffWholeLine) .cm-changedText")).toHaveLength(4);
expect(pairs("f(a, b)", "f(a, x, b)")).toEqual([["", " x,"]]);
// Each character of a script written without spaces is a word.
expect(pairs("你好世界", "你们世界")).toEqual([["好", "们"]]);
expect(pairs("a b", "a b")).toEqual([[" ", ""]]);
// A 10,000-line block edited on every line still pairs up its words.
const big = (kw: string) =>
Array.from({ length: 10_000 }, (_, i) => `export ${kw} value${i} = compute(${i});\n`).join("");
const changes = pairs(big("const"), big("let"));
expect(changes).toHaveLength(10_000);
expect(changes.every(([a, b]) => a === "const" && b === "let")).toBe(true);
});
it("keeps a line with only words added modified on both sides", async () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const extensions = [viewerBase({ readOnly: true }), diffWords];
const mv = new MergeView({
a: { doc: "f() {\n return a;\n}\n", extensions },
b: { doc: "f() {\n return a + b;\n}\n", extensions },
parent,
highlightChanges: false,
diffConfig: ideaDiffConfig("none", "words"),
});
await Promise.resolve();
expect([...mv.a.dom.querySelectorAll(".cm-diffLine-modified")].map((e) => e.textContent)).toEqual([" return a;"]);
expect([...mv.b.dom.querySelectorAll(".cm-diffLine-modified")].map((e) => e.textContent)).toEqual([
" return a + b;",
]);
// IDEA keeps the space before an inserted word in the fragment.
expect([...mv.b.dom.querySelectorAll(".cm-diffWord-inserted")].map((e) => e.textContent).join("")).toBe(" + b");
// and marks where it would be on the other side
expect(mv.a.dom.querySelectorAll(".cm-diffWordEmpty.cm-diffWord-inserted")).toHaveLength(1);
mv.destroy();
parent.remove();
});
@@ -175,47 +250,76 @@ describe("diff options", () => {
const extensions = [viewerBase({ readOnly: true }), changedLineGutters];
const mv = new MergeView({
a: { doc: "keep\nlet x = 1;\nend\n", extensions },
b: { doc: "keep\nlet x = 2;\nadded\nend\n", extensions },
b: { doc: "keep\nlet x = 2;\nadded\nend\nnew\n", extensions },
parent,
gutter: false,
diffConfig: { override: whitespaceDiff("none") },
diffConfig: ideaDiffConfig("none", "words"),
});
const numbers = (v: typeof mv.a, cls: string) =>
[...v.dom.querySelectorAll(`.cm-lineNumbers .${cls}`)].map((e) => e.textContent);
expect(numbers(mv.a, "cm-diffChangedGutter")).toEqual(["2"]);
expect(numbers(mv.b, "cm-diffChangedGutter")).toEqual(["2", "3"]);
expect(numbers(mv.b, "cm-diffWholeGutter")).toEqual(["3"]);
expect(numbers(mv.a, "cm-diffGutter-modified")).toEqual(["2"]);
expect(numbers(mv.b, "cm-diffGutter-modified")).toEqual(["2", "3"]);
expect(numbers(mv.b, "cm-diffGutter-inserted")).toEqual(["5"]);
mv.destroy();
parent.remove();
});
it("marks a deleted last line as a whole line", () => {
it("shows a final line break added as an inserted empty line, gutter included", () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const extensions = [viewerBase({ readOnly: true }), changedLineGutters];
const mv = new MergeView({
a: { doc: "keep\ngone", extensions: viewerBase({ readOnly: true }) },
b: { doc: "keep", extensions: viewerBase({ readOnly: true }) },
a: { doc: "alpha\nbeta", extensions },
b: { doc: "alpha\nbeta\n", extensions },
parent,
diffConfig: { override: whitespaceDiff("none") },
gutter: false,
diffConfig: ideaDiffConfig("none", "words"),
});
expect([...mv.a.dom.querySelectorAll(".cm-diffWholeLine")].map((e) => e.textContent)).toEqual(["gone"]);
const lines = [...mv.b.contentDOM.querySelectorAll(".cm-line")].map((l) => l.classList.contains("cm-diffLine"));
const gutters = [...mv.b.dom.querySelectorAll(".cm-lineNumbers .cm-gutterElement:not([style*='hidden'])")]
.filter((e) => e.textContent)
.map((e) => e.classList.contains("cm-diffChangedGutter"));
// IDEA compares lines without their breaks: "beta" is unchanged, the empty last line inserted.
expect(lines).toEqual([false, false, true]);
expect(gutters).toEqual(lines);
expect(mv.b.contentDOM.querySelectorAll(".cm-diffLine-inserted")).toHaveLength(1);
mv.destroy();
parent.remove();
});
it("keeps word highlighting for a single-line replacement", () => {
it("shows a last line removed as a deleted line only", async () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const extensions = [viewerBase({ readOnly: true }), diffWords];
const mv = new MergeView({
a: { doc: "keep\ngone", extensions },
b: { doc: "keep", extensions },
parent,
highlightChanges: false,
diffConfig: ideaDiffConfig("none", "words"),
});
await Promise.resolve();
// "keep" loses its line break, which IDEA does not count as a change.
expect([...mv.a.dom.querySelectorAll(".cm-diffLine")].map((e) => e.textContent)).toEqual(["gone"]);
expect(mv.a.dom.querySelectorAll(".cm-diffLine-deleted")).toHaveLength(1);
mv.destroy();
parent.remove();
});
it("keeps word highlighting for a single-line replacement", async () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const mv = new MergeView({
a: { doc: "before\nvalue = old\nafter\n", extensions: viewerBase({ readOnly: true }) },
b: { doc: "before\nvalue = new\nafter\n", extensions: viewerBase({ readOnly: true }) },
a: { doc: "before\nvalue = old\nafter\n", extensions: [viewerBase({ readOnly: true }), diffWords] },
b: { doc: "before\nvalue = new\nafter\n", extensions: [viewerBase({ readOnly: true }), diffWords] },
parent,
diffConfig: { override: whitespaceDiff("none") },
highlightChanges: false,
diffConfig: ideaDiffConfig("none", "words"),
});
expect(mv.a.dom.querySelector(".cm-diffWholeLine")).toBeNull();
expect(mv.b.dom.querySelector(".cm-diffWholeLine")).toBeNull();
expect(mv.a.dom.querySelector(".cm-changedText")).not.toBeNull();
expect(mv.b.dom.querySelector(".cm-changedText")).not.toBeNull();
// The left pane highlights its words once the right one exists.
await Promise.resolve();
expect([...mv.a.dom.querySelectorAll(".cm-diffWord-modified")].map((e) => e.textContent)).toEqual(["old"]);
expect([...mv.b.dom.querySelectorAll(".cm-diffWord-modified")].map((e) => e.textContent)).toEqual(["new"]);
mv.destroy();
parent.remove();
});
@@ -305,3 +409,31 @@ describe("compare entry points", () => {
expect(diffInput(compareFilesData("/p/a", "/p/b")).key).toContain("file:/p/a");
});
});
describe("oversized line comparison", () => {
it("falls back to transferable chunks on initial comparison and either-side edits", () => {
const a = doc("alpha\n".repeat(12000) + "beta\n".repeat(12000));
const b = doc("beta\n".repeat(12000) + "alpha\n".repeat(12000));
const config = ideaDiffConfig("none", "words");
const built = Chunk.build(a, b, config);
const editB = ChangeSet.of({ from: 0, insert: "header\n" }, b.length);
const nextB = editB.apply(b);
const updatedB = Chunk.updateB(built, a, nextB, editB, config);
const editA = ChangeSet.of({ from: 0, insert: "other\n" }, a.length);
const nextA = editA.apply(a);
const updatedA = Chunk.updateA(built, nextA, b, editA, config);
for (const [chunks, source, target] of [
[built, a, b],
[updatedB, a, nextB],
[updatedA, nextA, b],
] as const) {
expect(chunks.length).toBeGreaterThan(0);
let restored = target;
for (const chunk of [...chunks].reverse()) {
const edit = transferChunk(chunk, "a", source, restored);
restored = restored.replace(edit.from, edit.to, doc(edit.insert));
}
expect(restored.toString()).toBe(source.toString());
}
}, 20000);
});
+62 -4
Переглянути файл
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { render, screen, waitFor, within } from "@testing-library/react";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type { EditorInput } from "@/workbench/contributions";
import { Chunk } from "@codemirror/merge";
import { Text } from "@codemirror/state";
@@ -29,6 +29,19 @@ vi.mock("@/workbench/contributions", async (importOriginal) => ({
editorService: () => ({ openFile }),
}));
vi.mock("@/editor/api", async (importOriginal) => ({
...(await importOriginal<typeof import("@/editor/api")>()),
attachDocument: (path: string) =>
Promise.resolve({
path,
text: () => working,
readOnly: false,
extension: [],
save: () => Promise.resolve(),
release: () => {},
}),
}));
import { DiffEditor, mapLine } from "../DiffEditor";
/** Git Log opens a commit's file: both sides are revisions. */
@@ -94,7 +107,7 @@ describe("Diff toolbar", () => {
// Unpadded panes joined by the divider.
await waitFor(() => expect(document.querySelector(".cm-diffDivider")).not.toBeNull());
expect(document.querySelector(".cm-changeGutter")).toBeNull();
expect(document.querySelector(".cm-merge-b .cm-lineNumbers .cm-diffWholeGutter")?.textContent).toBe("2");
expect(document.querySelector(".cm-merge-b .cm-lineNumbers .cm-diffGutter-inserted")?.textContent).toBe("2");
// The lock turns scrolling together off without rebuilding the panes.
const divider = document.querySelector(".cm-diffDivider");
(await screen.findByRole("button", { name: "Synchronize Scrolling" })).click();
@@ -104,9 +117,9 @@ describe("Diff toolbar", () => {
const item = await screen.findByRole("menuitemcheckbox", { name: "Align Changes" });
expect(item.getAttribute("aria-checked")).toBe("false");
item.click();
// Padded panes with a change bar.
// Padded panes, the changed lines' gutters still tinted as in IDEA.
await waitFor(() => expect(document.querySelector(".cm-diffDivider")).toBeNull());
expect(document.querySelector(".cm-changeGutter")).not.toBeNull();
expect(document.querySelector(".cm-merge-b .cm-lineNumbers .cm-diffGutter-inserted")?.textContent).toBe("2");
expect(JSON.parse(localStorage.getItem("openidea.vcs.diffOptions")!)).toMatchObject({
alignChanges: true,
syncScroll: false,
@@ -178,3 +191,48 @@ describe("Jump to Source of a revision diff", () => {
expect(await jumpFrom(0, 2)).toEqual(["/p/a.ts", { selection: { line: 5, col: 1 }, focus: true }]);
});
});
describe("Unified Revert", () => {
for (const control of ["toolbar", "chunk"] as const) {
it.each([
["a\nb", "a"],
["same", "same\n"],
["same\n", "same"],
["", "added"],
["deleted", ""],
])(`${control} restores %j from %j`, async (original, changed) => {
localStorage.setItem("openidea.vcs.diffOptions", JSON.stringify({ mode: "unified", collapse: false }));
texts.HEAD = original;
working = changed;
const mounted = render(
<DiffEditor
input={
{
...input,
data: {
path: "/p/a.ts",
left: { type: "rev", rev: "HEAD" },
right: { type: "worktree" },
},
} as EditorInput
}
/>,
);
try {
await waitFor(() => expect(document.querySelectorAll(".cm-editor")).toHaveLength(1));
const view = EditorView.findFromDOM(document.querySelector<HTMLElement>(".cm-editor")!)!;
if (control === "toolbar") {
const button = await screen.findByRole("button", { name: "Revert Change" });
await waitFor(() => expect(button).not.toBeDisabled());
fireEvent.click(button);
} else {
fireEvent.mouseDown(await screen.findByRole("button", { name: /^Revert$/ }));
}
await waitFor(() => expect(view.state.doc.toString()).toBe(original));
} finally {
mounted.unmount();
localStorage.clear();
}
});
}
});
+51
Переглянути файл
@@ -0,0 +1,51 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
write: vi.fn(),
reload: vi.fn(),
refresh: vi.fn(),
failure: vi.fn(),
}));
vi.mock("@/platform/ipc", () => ({
commands: { vcsAddToIgnore: mocks.write },
call: async (result: Promise<unknown>) => result,
}));
vi.mock("@/features/project-tree/store", () => ({ reloadAll: mocks.reload }));
vi.mock("../store", () => ({ refreshNow: mocks.refresh }));
vi.mock("../ops", () => ({
runOp: async (_title: string, run: () => Promise<unknown>) => {
try {
return await run();
} catch (error) {
mocks.failure(error);
return undefined;
}
},
}));
import { addToIgnore } from "../ignore";
describe("ignore action", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.write.mockResolvedValue(null);
});
it.each(["gitignore", "localExclude"] as const)(
"routes all paths to %s then refreshes status and tree",
async (destination) => {
await addToIgnore(["/p/file", "/p/directory"], destination);
expect(mocks.write).toHaveBeenCalledWith(["/p/file", "/p/directory"], destination);
expect(mocks.refresh).toHaveBeenCalledOnce();
expect(mocks.reload).toHaveBeenCalledOnce();
},
);
it("refreshes after a failed or partially completed multi-repository write", async () => {
mocks.write.mockRejectedValue(new Error("locked; retry"));
await addToIgnore(["/p/file"], "gitignore");
expect(mocks.failure).toHaveBeenCalledOnce();
expect(mocks.refresh).toHaveBeenCalledOnce();
expect(mocks.reload).toHaveBeenCalledOnce();
});
it("ignores an empty selection", async () => {
await addToIgnore([], "gitignore");
expect(mocks.write).not.toHaveBeenCalled();
});
});
+75
Переглянути файл
@@ -149,3 +149,78 @@ describe("multi-root Git log", () => {
}
});
});
describe("Git log background refresh", () => {
it("keeps history and selection visible until the replacement is ready", async () => {
useVcs.setState({ roots: ["/project/front"] });
log.mockResolvedValue({ status: "ok", data: [commit("old")] });
await reloadLog();
const before = useGitLog.getState();
selectCommit(commitKey(before.commits[0]!));
let finish!: (value: unknown) => void;
log.mockImplementation(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
const refresh = reloadLog({ preserve: true });
await vi.waitFor(() => expect(finish).toBeDefined());
expect(useGitLog.getState().commits).toBe(before.commits);
expect(useGitLog.getState().rows).toBe(before.rows);
expect(useGitLog.getState().loading).toBe(true);
finish({ status: "ok", data: [commit("new"), commit("old")] });
await refresh;
expect(useGitLog.getState().commits.map((c) => c.id)).toEqual(["new", "old"]);
expect(useGitLog.getState().rows).toHaveLength(2);
expect(useGitLog.getState().selected).toBe(commitKey(before.commits[0]!));
expect(useGitLog.getState().loading).toBe(false);
});
it("refreshes the loaded range and resumes paging at the replacement's end", async () => {
useVcs.setState({ roots: ["/project/front"] });
const history = Array.from({ length: PAGE * 3 }, (_, i) => commit(String(i)));
log.mockImplementation(async (_repo, q) => ({ status: "ok", data: history.slice(q.skip, q.skip + q.limit) }));
await reloadLog();
await loadMore();
history.unshift(commit("new"));
await reloadLog({ preserve: true });
expect(useGitLog.getState().commits).toHaveLength(PAGE * 2);
expect(log.mock.lastCall?.[1]).toMatchObject({ skip: 0, limit: PAGE * 2 });
await loadMore();
expect(log.mock.lastCall?.[1]).toMatchObject({ skip: PAGE * 2, limit: PAGE });
expect(useGitLog.getState().commits.map((c) => c.id)).toEqual(history.slice(0, PAGE * 3).map((c) => c.id));
});
it("retains the current history if refreshing fails", async () => {
useVcs.setState({ roots: ["/project/front"] });
log.mockResolvedValue({ status: "ok", data: [commit("old")] });
await reloadLog();
const before = useGitLog.getState();
log.mockRejectedValue(new Error("unavailable"));
await reloadLog({ preserve: true });
expect(useGitLog.getState().commits).toBe(before.commits);
expect(useGitLog.getState().rows).toBe(before.rows);
expect(useGitLog.getState().error).toContain("unavailable");
expect(useGitLog.getState().loading).toBe(false);
});
it("ignores a refresh that finishes after the filters have changed", async () => {
useVcs.setState({ roots: ["/project/front"] });
let finish!: (value: unknown) => void;
log.mockImplementationOnce(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
const refresh = reloadLog({ preserve: true });
await vi.waitFor(() => expect(finish).toBeDefined());
useGitLog.setState({ filters: { ...emptyFilters(), text: "filtered" } });
log.mockResolvedValue({ status: "ok", data: [commit("filtered")] });
await reloadLog();
finish({ status: "ok", data: [commit("stale")] });
await refresh;
expect(useGitLog.getState().commits.map((c) => c.id)).toEqual(["filtered"]);
});
});
+36
Переглянути файл
@@ -0,0 +1,36 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { useProject } from "@/platform/project";
import type { Settings } from "@/platform/ipc";
import { viewerBase } from "../cm";
const previous = useProject.getState().settings;
const views: EditorView[] = [];
afterEach(() => {
views.splice(0).forEach((v) => v.destroy());
useProject.setState({ settings: previous });
});
const setEditor = (editor: object) => useProject.setState({ settings: { editor } as unknown as Settings });
describe("viewer font", () => {
it("follows the editor's font settings, also when they change", () => {
setEditor({ fontFamily: "Fira Code", fontSize: 16, lineHeight: 22 });
const view = new EditorView({
state: EditorState.create({ doc: "a", extensions: viewerBase({ readOnly: true }) }),
});
views.push(view);
const style = () => view.dom.style;
expect(style().getPropertyValue("--openidea-editor-font")).toContain("Fira Code");
expect(style().getPropertyValue("--openidea-editor-font-size")).toBe("16px");
expect(style().getPropertyValue("--openidea-editor-line-height")).toBe("22px");
expect(view.dom.classList.contains("cm-openidea-ligatures")).toBe(false);
setEditor({ fontSize: 11, ligatures: true });
expect(style().getPropertyValue("--openidea-editor-font")).toBe("");
expect(style().getPropertyValue("--openidea-editor-font-size")).toBe("11px");
expect(view.dom.classList.contains("cm-openidea-ligatures")).toBe(true);
});
});
+10
Переглянути файл
@@ -41,6 +41,8 @@ import {
import { refreshNow, repoName } from "./store";
import { tx } from "@/platform/i18n";
import { addToIgnore } from "./ignore";
const VCS = "vcsAvailable";
const IN_COMMIT_WINDOW = "vcsAvailable && activeToolWindow == commit";
@@ -456,6 +458,14 @@ export function registerVcsActions(): () => void {
void revealCommit(id, commit ? commitRepo(commit) : undefined);
},
},
...(["gitignore", "localExclude"] as const).map((destination): Action => ({
id: destination === "gitignore" ? "vcs.ignoreShared" : "vcs.ignoreLocal",
title: destination === "gitignore" ? "Add to .gitignore" : "Add to .git/info/exclude",
category: "Git",
when: VCS,
keywords: ["ignore", "unversioned", "exclude"],
run: ({ arg }) => addToIgnore(contextPaths(arg), destination),
})),
{
id: "vcs.addToVcs",
title: "Add to VCS",
+189 -84
Переглянути файл
@@ -8,6 +8,7 @@ import {
EditorState,
RangeSet,
RangeSetBuilder,
StateEffect,
StateField,
type Extension,
type Line,
@@ -21,28 +22,72 @@ import {
highlightActiveLine,
keymap,
lineNumbers,
WidgetType,
type DecorationSet,
type ViewUpdate,
} from "@codemirror/view";
import { getChunks } from "@codemirror/merge";
import { getChunks, mergeViewSiblings, type Chunk } from "@codemirror/merge";
import { defaultKeymap } from "@codemirror/commands";
import { search, searchKeymap } from "@codemirror/search";
import { tags as t } from "@lezer/highlight";
import { findExtension } from "@/editor/core/cm/find";
import { caretExtension } from "@/editor/core/cm/prefs";
import { fontExtension } from "@/editor/core/cm/setup";
import { caretStyles, findLocals, findStyles } from "@/editor/core/cm/theme";
import { editorPrefs } from "@/platform/editorSettings";
import { useProject } from "@/platform/project";
import { hasInnerFragments } from "./diffOptions";
const wholeLine = Decoration.line({ class: "cm-diffWholeLine" });
/** IDEA's change types (TextDiffType): both sides have text, only the new side, only the old side. */
export type DiffKind = "modified" | "inserted" | "deleted";
const kindOf = (hasA: boolean, hasB: boolean): DiffKind => (hasA && hasB ? "modified" : hasA ? "deleted" : "inserted");
/** A chunk's type (DiffUtil.getLineDiffType), by the sides it has lines on. */
export const chunkKind = (chunk: Chunk): DiffKind => kindOf(chunk.fromA !== chunk.toA, chunk.fromB !== chunk.toB);
const KINDS: readonly DiffKind[] = ["modified", "inserted", "deleted"];
const byKind = <T>(make: (kind: DiffKind) => T) =>
Object.fromEntries(KINDS.map((k) => [k, make(k)])) as Record<DiffKind, T>;
/** Line backgrounds by type; `fine` ones (words compared) are lighter. */
const lineDecos = byKind((kind) => ({
coarse: Decoration.line({ class: `cm-diffLine cm-diffLine-${kind}` }),
fine: Decoration.line({ class: `cm-diffLine cm-diffLine-${kind} cm-diffLine-fine` }),
}));
const wordDecos = byKind((kind) => Decoration.mark({ class: `cm-diffWord cm-diffWord-${kind}` }));
/** A word on the other side only: a thin bar where it would be (DiffEmptyHighlighterRenderer). */
class EmptyWordMarker extends WidgetType {
constructor(readonly kind: DiffKind) {
super();
}
eq(other: EmptyWordMarker) {
return other.kind === this.kind;
}
toDOM() {
const span = document.createElement("span");
span.className = `cm-diffWordEmpty cm-diffWord-${this.kind}`;
span.setAttribute("aria-hidden", "true");
return span;
}
}
const emptyWordDecos = byKind((kind) => Decoration.widget({ widget: new EmptyWordMarker(kind), side: 1 }));
/**
* Calls `f` for the changed lines of a side-by-side pane between `vpFrom` and
* `vpTo`, with whether the line has no counterpart on the other side (inserted
* or deleted as a whole). Lines paired with a line on the other side keep the
* line tint plus word-level highlights.
* `vpTo`, with the type of their chunk (DiffUtil.getLineDiffType): a chunk
* with lines on both sides is modified as a whole, however its words changed.
*/
function forChangedLines(state: EditorState, vpFrom: number, vpTo: number, f: (line: Line, whole: boolean) => void) {
function forChangedLines(
state: EditorState,
vpFrom: number,
vpTo: number,
f: (line: Line, kind: DiffKind, fine: boolean) => void,
) {
const info = getChunks(state);
if (!info || !info.side) return;
const isA = info.side === "a";
@@ -50,38 +95,70 @@ function forChangedLines(state: EditorState, vpFrom: number, vpTo: number, f: (l
for (const chunk of info.chunks) {
const from = isA ? chunk.fromA : chunk.fromB;
const to = isA ? chunk.toA : chunk.toB;
if (from >= vpTo) break;
if (from > vpTo) break;
if (from === to || to < vpFrom) continue;
const otherEmpty = isA ? chunk.fromB === chunk.toB : chunk.fromA === chunk.toA;
const ranges = chunk.changes.map((c) => (isA ? [c.fromA, c.toA] : [c.fromB, c.toB]).map((p) => p + from));
// Covered including the line break after it, or the one before it (a deleted last line).
const covered = (line: Line) =>
ranges.some(([f = 0, t = 0]) => (f <= line.from && t > line.to) || (f < line.from && t >= line.to));
for (let line = doc.lineAt(Math.max(from, vpFrom)); line.from < Math.min(to, vpTo);) {
f(line, otherEmpty || covered(line));
const kind = chunkKind(chunk);
const fine = hasInnerFragments(chunk);
// A line starting at `vpTo` is still in view (the empty last line).
for (let line = doc.lineAt(Math.max(from, vpFrom)); line.from < to && line.from <= vpTo;) {
f(line, kind, fine);
if (line.number === doc.lines) break;
line = doc.line(line.number + 1);
}
}
}
/** Solid background for the lines changed as a whole. */
function wholeLineDeco(view: EditorView): DecorationSet {
/**
* Line backgrounds in the colour of their chunk's type
* (DiffDrawUtil.LineHighlighterBuilder). The unified view shows every new
* line as inserted, below the old ones as deleted (createUnifiedChunkHighlighters).
*/
function lineDeco(view: EditorView): DecorationSet {
const unified = !mergeViewSiblings(view);
const builder = new RangeSetBuilder<Decoration>();
forChangedLines(view.state, view.viewport.from, view.viewport.to, (line, whole) => {
if (whole) builder.add(line.from, line.from, wholeLine);
forChangedLines(view.state, view.viewport.from, view.viewport.to, (line, kind, fine) => {
const decos = lineDecos[unified ? "inserted" : kind];
builder.add(line.from, line.from, fine ? decos.fine : decos.coarse);
});
return builder.finish();
}
/**
* The inner fragments of chunks whose words were compared, each in the colour
* of its own type (SimpleDiffChangeUi.createInlineHighlighter); a fragment
* empty on this side is a thin bar.
*/
function wordDeco(view: EditorView): DecorationSet {
const info = getChunks(view.state);
// The unified view highlights words itself (`highlightChanges`).
if (!info || !info.side || !mergeViewSiblings(view)) return Decoration.none;
const isA = info.side === "a";
const { from: vpFrom, to: vpTo } = view.viewport;
const builder = new RangeSetBuilder<Decoration>();
for (const chunk of info.chunks) {
const base = isA ? chunk.fromA : chunk.fromB;
if (base > vpTo) break;
if ((isA ? chunk.toA : chunk.toB) < vpFrom || !hasInnerFragments(chunk)) continue;
for (const c of chunk.changes) {
const [from, to] = isA ? [c.fromA, c.toA] : [c.fromB, c.toB];
const kind = kindOf(c.fromA !== c.toA, c.fromB !== c.toB);
if (from < to) builder.add(base + from, base + to, wordDecos[kind]);
else builder.add(base + from, base + from, emptyWordDecos[kind]);
}
}
return builder.finish();
}
class LineClassMarker extends GutterMarker {
constructor(readonly elementClass: string) {
super();
}
}
const changedGutter = new LineClassMarker("cm-diffChangedGutter");
const wholeGutter = new LineClassMarker("cm-diffChangedGutter cm-diffWholeGutter");
const gutterMarkers = byKind((kind) => ({
coarse: new LineClassMarker(`cm-diffChangedGutter cm-diffGutter-${kind}`),
fine: new LineClassMarker(`cm-diffChangedGutter cm-diffGutter-${kind} cm-diffGutter-fine`),
}));
/** The line background of changed lines carried into the gutters (line numbers, inclusion boxes), as in IDEA. */
export const changedLineGutters = StateField.define<RangeSet<GutterMarker>>({
@@ -95,29 +172,42 @@ export const changedLineGutters = StateField.define<RangeSet<GutterMarker>>({
function changedGutterMarkers(state: EditorState): RangeSet<GutterMarker> {
const builder = new RangeSetBuilder<GutterMarker>();
forChangedLines(state, 0, state.doc.length + 1, (line, whole) =>
builder.add(line.from, line.from, whole ? wholeGutter : changedGutter),
forChangedLines(state, 0, state.doc.length, (line, kind, fine) =>
builder.add(line.from, line.from, fine ? gutterMarkers[kind].fine : gutterMarkers[kind].coarse),
);
return builder.finish();
}
const wholeChangedLines = ViewPlugin.fromClass(
class {
decorations: DecorationSet;
constructor(view: EditorView) {
this.decorations = wholeLineDeco(view);
}
update(update: ViewUpdate) {
if (
update.docChanged ||
update.viewportChanged ||
getChunks(update.startState)?.chunks !== getChunks(update.state)?.chunks
)
this.decorations = wholeLineDeco(update.view);
}
},
{ decorations: (value) => value.decorations },
);
/** Recomputes `build` when the document, viewport or chunks change. */
const chunkDecorations = (build: (view: EditorView) => DecorationSet) =>
ViewPlugin.fromClass(
class {
decorations: DecorationSet;
constructor(view: EditorView) {
this.decorations = build(view);
}
update(update: ViewUpdate) {
if (
update.docChanged ||
update.viewportChanged ||
getChunks(update.startState)?.chunks !== getChunks(update.state)?.chunks
)
this.decorations = build(update.view);
}
},
{ decorations: (value) => value.decorations },
);
const changedLines = chunkDecorations(lineDeco);
/**
* IDEA's "Highlight words" for a side-by-side pane: the inner fragments of
* chunks whose words were compared, over their lighter line background.
*/
export const diffWords: Extension = [
chunkDecorations(wordDeco),
EditorView.editorAttributes.of({ class: "cm-diffWords" }),
];
export const viewerHighlight = HighlightStyle.define([
{
@@ -145,10 +235,16 @@ export const viewerTheme = EditorView.theme(
height: "100%",
backgroundColor: "var(--bg-app)",
color: "var(--fg)",
fontSize: "var(--fs-code)",
fontSize: "var(--openidea-editor-font-size, var(--fs-code))",
...findLocals,
},
".cm-scroller": { fontFamily: "var(--font-mono)", fontWeight: "var(--fw-code, 400)", lineHeight: "var(--lh-code)" },
".cm-scroller": {
fontFamily: "var(--openidea-editor-font, var(--font-mono))",
fontWeight: "var(--fw-code, 400)",
lineHeight: "var(--openidea-editor-line-height, var(--lh-code))",
fontVariantLigatures: "none",
},
"&.cm-openidea-ligatures .cm-scroller": { fontVariantLigatures: "normal" },
".cm-content": { caretColor: "var(--caret, var(--fg-strong))", WebkitUserSelect: "text", userSelect: "text" },
...caretStyles,
"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, ::selection": {
@@ -162,44 +258,38 @@ export const viewerTheme = EditorView.theme(
},
".cm-lineNumbers .cm-gutterElement": { padding: "0 8px 0 12px", minWidth: "32px" },
".cm-activeLineGutter": { backgroundColor: "transparent", color: "var(--fg-secondary)" },
// @codemirror/merge
"&.cm-merge-a .cm-changedLine, .cm-deletedChunk": {
backgroundColor: "color-mix(in srgb, var(--gutter-deleted) 12%, transparent)",
// Side-by-side panes colour lines by their chunk's type (changedLines) instead of the library's tint.
"&.cm-merge-a .cm-changedLine, &.cm-merge-b .cm-changedLine": { backgroundColor: "transparent" },
".cm-line.cm-diffLine-modified, .cm-diffGutter-modified": { backgroundColor: "var(--diff-modified)" },
".cm-line.cm-diffLine-inserted, .cm-diffGutter-inserted": { backgroundColor: "var(--diff-inserted)" },
".cm-line.cm-diffLine-deleted, .cm-diffGutter-deleted": { backgroundColor: "var(--diff-deleted)" },
// Chunks whose words were compared take the lighter colour (TextDiffType.getIgnoredColor), their fragments the full one.
...Object.fromEntries(
KINDS.map((k) => [
`.cm-line.cm-diffLine-fine.cm-diffLine-${k}, .cm-diffGutter-fine.cm-diffGutter-${k}`,
{ backgroundColor: `color-mix(in srgb, var(--diff-${k}) 40%, var(--bg-app))` },
]),
),
// Full line height, as IDEA paints them: an inline background only covers the font's height,
// leaving stripes between the lines of a multi-line fragment.
".cm-diffWord": { display: "inline-block" },
".cm-diffWord-modified": { backgroundColor: "var(--diff-modified)" },
".cm-diffWord-inserted": { backgroundColor: "var(--diff-inserted)" },
".cm-diffWord-deleted": { backgroundColor: "var(--diff-deleted)" },
".cm-diffWordEmpty": {
display: "inline-block",
width: "2px",
height: "1lh",
margin: "0 -1px",
verticalAlign: "top",
},
"&.cm-merge-b .cm-changedLine, .cm-inlineChangedLine": {
backgroundColor: "color-mix(in srgb, var(--gutter-added) 12%, transparent)",
},
"&.cm-merge-a .cm-changedLine.cm-diffWholeLine": {
backgroundColor: "color-mix(in srgb, var(--danger) 26%, transparent)",
},
"&.cm-merge-b .cm-changedLine.cm-diffWholeLine": {
backgroundColor: "color-mix(in srgb, var(--success) 26%, transparent)",
},
"&.cm-merge-a .cm-diffWholeLine .cm-changedText, &.cm-merge-b .cm-diffWholeLine .cm-changedText": {
background: "transparent",
},
"&.cm-merge-a .cm-changedText, .cm-deletedChunk .cm-deletedText": {
background: "color-mix(in srgb, var(--danger) 26%, transparent)",
},
"&.cm-merge-b .cm-changedText": {
background: "color-mix(in srgb, var(--success) 26%, transparent)",
},
"&.cm-merge-b .cm-changedText, .cm-insertedLine .cm-changedText": {
background: "color-mix(in srgb, var(--success) 26%, transparent)",
},
// Gutters of changed lines take the line background (changedLineGutters).
"&.cm-merge-a .cm-diffChangedGutter": {
backgroundColor: "color-mix(in srgb, var(--gutter-deleted) 12%, transparent)",
},
"&.cm-merge-b .cm-diffChangedGutter": {
backgroundColor: "color-mix(in srgb, var(--gutter-added) 12%, transparent)",
},
"&.cm-merge-a .cm-diffWholeGutter": {
backgroundColor: "color-mix(in srgb, var(--danger) 26%, transparent)",
},
"&.cm-merge-b .cm-diffWholeGutter": {
backgroundColor: "color-mix(in srgb, var(--success) 26%, transparent)",
// The unified view: old lines deleted, new lines inserted.
".cm-deletedChunk": { backgroundColor: "var(--diff-deleted)" },
"&.cm-diffWords .cm-deletedChunk": {
backgroundColor: "color-mix(in srgb, var(--diff-deleted) 40%, var(--bg-app))",
},
".cm-deletedChunk .cm-deletedText": { background: "var(--diff-deleted)" },
"&.cm-merge-b .cm-changedText": { background: "var(--diff-inserted)" },
".cm-changeGutter": { width: "3px", paddingLeft: "0" },
"&.cm-merge-a .cm-changedLineGutter, .cm-deletedLineGutter": { background: "var(--gutter-deleted)" },
"&.cm-merge-b .cm-changedLineGutter": { background: "var(--gutter-modified)" },
@@ -231,18 +321,33 @@ export const viewerTheme = EditorView.theme(
);
const caretSlot = new Compartment();
const fontSlot = new Compartment();
/** The editor's caret (Settings › Editor › General › Appearance), kept in step with the settings. */
function viewerCaret(): Extension {
const editorSettings = () => useProject.getState().settings?.editor;
/**
* The editor's caret (Settings › Editor › General › Appearance) and font
* (Settings › Editor › Font), kept in step with the settings.
*/
function viewerEditorLook(): Extension {
return [
caretSlot.of(caretExtension(editorPrefs())),
fontSlot.of(fontExtension(editorSettings())),
ViewPlugin.define((view) => {
let appearance = editorPrefs().appearance;
let editor = editorSettings();
const unsubscribe = useProject.subscribe(() => {
const effects: StateEffect<unknown>[] = [];
const next = editorPrefs();
if (JSON.stringify(next.appearance) === JSON.stringify(appearance)) return;
appearance = next.appearance;
view.dispatch({ effects: caretSlot.reconfigure(caretExtension(next)) });
if (JSON.stringify(next.appearance) !== JSON.stringify(appearance)) {
appearance = next.appearance;
effects.push(caretSlot.reconfigure(caretExtension(next)));
}
if (editorSettings() !== editor) {
editor = editorSettings();
effects.push(fontSlot.reconfigure(fontExtension(editor)));
}
if (effects.length) view.dispatch({ effects });
});
return { destroy: unsubscribe };
}),
@@ -256,14 +361,14 @@ function viewerCaret(): Extension {
export function viewerBase(opts: { readOnly: boolean; lineNumbers?: boolean; findBar?: boolean }): Extension[] {
return [
opts.lineNumbers === false ? [] : lineNumbers(),
viewerCaret(),
viewerEditorLook(),
highlightActiveLine(),
opts.findBar
? [findExtension(), keymap.of(defaultKeymap)]
: [search({ top: true }), keymap.of([...searchKeymap, ...defaultKeymap])],
syntaxHighlighting(viewerHighlight),
viewerTheme,
wholeChangedLines,
changedLines,
EditorState.readOnly.of(opts.readOnly),
EditorView.editable.of(!opts.readOnly),
// Non-editable revision panes still need keyboard selection and copy.
+133
Переглянути файл
@@ -0,0 +1,133 @@
/**
* IntelliJ's own comparison tests (LineComparisonUtilTest,
* WordComparisonUtilTest, SplitComparisonUtilTest; Apache-2.0, Copyright
* JetBrains s.r.o. and contributors), converted from their Kotlin DSL into
* `ideaCases.json`, run against the port.
*/
import { describe, expect, it } from "vitest";
import {
compareLineFragments,
compareLinesInner,
compareWords,
processBlocks,
type ComparisonPolicy,
type LineFragment,
type Range,
} from "..";
import cases from "./ideaCases.json";
type Policy = "default" | "trim" | "ignore";
type Change = [number, number, number, number];
interface Case {
source: string;
test: string;
type: "lines" | "lines_inner" | "words" | "splitter";
squash: boolean;
trim: boolean;
before: string;
after: string;
changes: Partial<Record<Policy, Change[]>>;
matchings: Partial<Record<Policy, [string, string]>>;
policies: Policy[];
}
/** PolicyData.get: "ignore" falls back to "trim", then "default". */
const forPolicy = <T>(data: Partial<Record<Policy, T>>, policy: Policy): T | undefined =>
policy === "ignore"
? (data.ignore ?? data.trim ?? data.default)
: policy === "trim"
? (data.trim ?? data.default)
: data.default;
const POLICY: Record<Policy, ComparisonPolicy> = { default: "default", trim: "trim", ignore: "ignore" };
/** Changed character offsets marked by non-space characters, '.' skipped (DiffTestCase.parseMatching). */
function parseMatching(matching: string): number[] {
return [...matching.replace(/\./g, "")].flatMap((c, i) => (c !== " " ? [i] : []));
}
/** Changed lines: lines (split at '_' / '*') with a character other than ' ' and '_' (parseLineMatching). */
function parseLineMatching(matching: string): number[] {
const out: number[] = [];
let line = 0;
let index = 0;
while (index < matching.length) {
let end = matching.slice(index).search(/[_*]/) + 1;
end = end === 0 ? matching.length : index + end;
if (/[^ _]/.test(matching.slice(index, end))) out.push(line);
line++;
index = end;
}
return out;
}
const charSets = (fragments: readonly Range[]) => {
const s1 = new Set<number>();
const s2 = new Set<number>();
for (const f of fragments) {
for (let i = f.start1; i < f.end1; i++) s1.add(i);
for (let i = f.start2; i < f.end2; i++) s2.add(i);
}
return [[...s1].sort((a, b) => a - b), [...s2].sort((a, b) => a - b)];
};
const lineSets = (fragments: readonly LineFragment[]) =>
charSets(fragments.map((f) => ({ start1: f.startLine1, end1: f.endLine1, start2: f.startLine2, end2: f.endLine2 })));
const lineChanges = (fragments: readonly LineFragment[]): Change[] =>
fragments.map((f) => [f.startLine1, f.endLine1, f.startLine2, f.endLine2]);
const rangeChanges = (fragments: readonly Range[]): Change[] =>
fragments.map((f) => [f.start1, f.end1, f.start2, f.end2]);
function checkWords(fragments: readonly Range[], changes?: Change[], matching?: [string, string]) {
if (changes) expect(rangeChanges(fragments)).toEqual(changes);
if (matching) expect(charSets(fragments)).toEqual([parseMatching(matching[0]), parseMatching(matching[1])]);
}
function run(c: Case, policy: Policy) {
const p = POLICY[policy];
const changes = forPolicy(c.changes, policy);
const matching = forPolicy(c.matchings, policy);
expect(changes ?? matching, "the case has expectations").toBeDefined();
switch (c.type) {
case "lines": {
const fragments = compareLineFragments(c.before, c.after, p);
if (changes) expect(lineChanges(fragments)).toEqual(changes);
if (matching)
expect(lineSets(fragments)).toEqual([parseLineMatching(matching[0]), parseLineMatching(matching[1])]);
break;
}
case "lines_inner": {
const fragments = processBlocks(compareLinesInner(c.before, c.after, p), c.before, c.after, p, true, false);
expect(fragments).toHaveLength(1);
const [f] = fragments;
expect([f!.startOffset1, f!.endOffset1, f!.startOffset2, f!.endOffset2]).toEqual([
0,
c.before.length,
0,
c.after.length,
]);
checkWords(f!.inner!, changes, matching);
checkWords(compareWords(c.before, c.after, p), changes, matching);
break;
}
case "words":
checkWords(compareWords(c.before, c.after, p), changes, matching);
break;
case "splitter": {
const inner = compareLinesInner(c.before, c.after, p);
expect(lineChanges(processBlocks(inner, c.before, c.after, p, c.squash, c.trim))).toEqual(changes);
break;
}
}
}
describe("IntelliJ comparison tests", () => {
(cases as Case[]).forEach((c, i) => {
for (const policy of new Set(c.policies))
it(`${c.source}.${c.test} #${i} ${c.type} ${JSON.stringify(c.before)} - ${JSON.stringify(c.after)} (${policy})`, () =>
run(c, policy));
});
});
File diff suppressed because it is too large. Load diff
+30
Переглянути файл
@@ -0,0 +1,30 @@
/**
* Character-level comparison of punctuation (IntelliJ's ByCharRt
* .comparePunctuation, ported; Apache-2.0, Copyright JetBrains s.r.o. and
* contributors): only punctuation is matched, everything else stays changed.
*/
import { ChangeBuilder, type DiffIterable, unchanged, diffSequences } from "./iterables";
import { isPunctuation } from "./text";
export function comparePunctuation(text1: string, text2: string): DiffIterable {
const chars = (text: string) => {
const codes: number[] = [];
const offsets: number[] = [];
for (let i = 0; i < text.length; i++) {
const c = text.charCodeAt(i);
if (isPunctuation(c)) {
codes.push(c);
offsets.push(i);
}
}
return { codes, offsets };
};
const chars1 = chars(text1);
const chars2 = chars(text2);
const changes = diffSequences(chars1.codes, chars2.codes);
const builder = new ChangeBuilder(text1.length, text2.length);
for (const r of unchanged(changes))
for (let i = 0; i < r.end1 - r.start1; i++)
builder.markEqual(chars1.offsets[r.start1 + i]!, chars2.offsets[r.start2 + i]!);
return builder.finish();
}
+205
Переглянути файл
@@ -0,0 +1,205 @@
/**
* Line-level comparison (IntelliJ's ByLineRt with SmartLineChangeCorrector,
* ported; Apache-2.0, Copyright JetBrains s.r.o. and contributors): lines are
* first matched ignoring whitespace and "unimportant" lines (blank, `}`), the
* gaps are filled, boundaries optimized, then whitespace-only matches that
* the policy doesn't allow are corrected.
*/
import { optimizeLineChunks, UNIMPORTANT_LINE_CHAR_COUNT, type LineInfo } from "./chunkOptimizer";
import {
ChangeBuilder,
create,
type DiffIterable,
diffSequences,
expandEqual,
ExpandChangeBuilder,
unchanged,
} from "./iterables";
import { isEmptyRange, type Range } from "./lcs";
import { type ComparisonPolicy, isSpace, lineKey } from "./text";
interface Line extends LineInfo {
readonly content: string;
/** The key ignoring whitespace. */
readonly iwKey: string;
}
function toLine(content: string, policy: ComparisonPolicy): Line {
let nonSpaceChars = 0;
for (let i = 0; i < content.length; i++) if (!isSpace(content[i])) nonSpaceChars++;
const iwKey = lineKey(content, "ignore");
return { content, key: policy === "ignore" ? iwKey : lineKey(content, policy), iwKey, nonSpaceChars };
}
/** Line changes between two lists of line texts (without line breaks). */
export function compareLines(
lines1: readonly string[],
lines2: readonly string[],
policy: ComparisonPolicy,
): DiffIterable {
const l1 = lines1.map((l) => toLine(l, policy));
const l2 = lines2.map((l) => toLine(l, policy));
const iw1 = l1.map((l) => l.iwKey);
const iw2 = l2.map((l) => l.iwKey);
if (policy === "ignore") {
const changes = optimizeLineChunks(l1, l2, compareSmart(l1, l2, iw1, iw2));
const keys1 = l1.map((l) => l.key);
const keys2 = l2.map((l) => l.key);
const expanded: Range[] = [];
for (const c of changes.changes) {
const r = expandEqual(keys1, keys2, c.start1, c.start2, c.end1, c.end2);
if (!isEmptyRange(r)) expanded.push(r);
}
return create(expanded, l1.length, l2.length);
}
const iwChanges = optimizeLineChunks(l1, l2, compareSmart(l1, l2, iw1, iw2));
return correctChangesSecondStep(l1, l2, iwChanges);
}
/**
* Matches lines ignoring the unimportant ones, then compares the gaps between
* the matches with all lines (compareSmart + SmartLineChangeCorrector).
*/
function compareSmart(
lines1: readonly Line[],
lines2: readonly Line[],
keys1: string[],
keys2: string[],
): DiffIterable {
const big = (lines: readonly Line[]) => {
const indexes: number[] = [];
lines.forEach((l, i) => l.nonSpaceChars > UNIMPORTANT_LINE_CHAR_COUNT && indexes.push(i));
return indexes;
};
const indexes1 = big(lines1);
const indexes2 = big(lines2);
const changes = diffSequences(
indexes1.map((i) => keys1[i]!),
indexes2.map((i) => keys2[i]!),
);
const builder = new ChangeBuilder(lines1.length, lines2.length);
const matchGap = (start1: number, end1: number, start2: number, end2: number) => {
const expand = expandEqual(keys1, keys2, start1, start2, end1, end2);
const inner = diffSequences(keys1.slice(expand.start1, expand.end1), keys2.slice(expand.start2, expand.end2));
builder.markEqual(start1, start2, expand.start1, expand.start2);
for (const r of unchanged(inner))
builder.markEqualCount(expand.start1 + r.start1, expand.start2 + r.start2, r.end1 - r.start1);
builder.markEqual(expand.end1, expand.end2, end1, end2);
};
let last1 = 0;
let last2 = 0;
for (const r of unchanged(changes)) {
for (let i = 0; i < r.end1 - r.start1; i++) {
const start1 = indexes1[r.start1 + i]!;
const start2 = indexes2[r.start2 + i]!;
matchGap(last1, start1, last2, start2);
builder.markEqual(start1, start2, start1 + 1, start2 + 1);
last1 = start1 + 1;
last2 = start2 + 1;
}
}
matchGap(last1, lines1.length, last2, lines2.length);
return builder.finish();
}
/**
* Fixes lines matched ignoring whitespace but not equal under the policy
* (ByLineRt.correctChangesSecondStep). Equal lines stay matched, unmatched
* stay unmatched; for whitespace-equal runs the alignment with the most equal
* pairs wins, so ".{ ..{ ...{" vs "..{ ...{" matches the last two.
*/
function correctChangesSecondStep(
lines1: readonly Line[],
lines2: readonly Line[],
changes: DiffIterable,
): DiffIterable {
const builder = new ExpandChangeBuilder(
lines1.map((l) => l.key),
lines2.map((l) => l.key),
);
const equal = (i1: number, i2: number) => lines1[i1]!.key === lines2[i2]!.key;
let sample: string | null = null;
let last1 = 0;
let last2 = 0;
const alignExactMatching = (sub1: number[], sub2: number[]) => {
const n = Math.max(sub1.length, sub2.length);
// brute force over the combinations: limit the search space
if (n > 10 || sub1.length === sub2.length) {
for (let i = 0; i < Math.min(sub1.length, sub2.length); i++)
if (equal(sub1[i]!, sub2[i]!)) builder.markEqual(sub1[i]!, sub2[i]!);
return;
}
if (sub1.length < sub2.length) {
const matching = bestMatchingAlignment(sub1, sub2, equal);
for (let i = 0; i < sub1.length; i++) {
const index2 = sub2[matching[i]!]!;
if (equal(sub1[i]!, index2)) builder.markEqual(sub1[i]!, index2);
}
} else {
const matching = bestMatchingAlignment(sub2, sub1, (i2, i1) => equal(i1, i2));
for (let i = 0; i < sub2.length; i++) {
const index1 = sub1[matching[i]!]!;
if (equal(index1, sub2[i]!)) builder.markEqual(index1, sub2[i]!);
}
}
};
const flush = (line1: number, line2: number) => {
if (sample === null) return;
const start1 = Math.max(last1, builder.index1);
const start2 = Math.max(last2, builder.index2);
const sub1: number[] = [];
const sub2: number[] = [];
for (let i = start1; i < line1; i++)
if (lines1[i]!.iwKey === sample) {
sub1.push(i);
last1 = i + 1;
}
for (let i = start2; i < line2; i++)
if (lines2[i]!.iwKey === sample) {
sub2.push(i);
last2 = i + 1;
}
alignExactMatching(sub1, sub2);
sample = null;
};
for (const r of unchanged(changes)) {
for (let i = 0; i < r.end1 - r.start1; i++) {
const index1 = r.start1 + i;
const index2 = r.start2 + i;
if (sample === lines1[index1]!.iwKey) continue;
flush(index1, index2);
if (equal(index1, index2)) builder.markEqual(index1, index2);
else sample = lines1[index1]!.iwKey;
}
}
flush(changes.length1, changes.length2);
return builder.finish();
}
/** The combination of `sub2` positions for `sub1` with the most equal pairs (getBestMatchingAlignment). */
function bestMatchingAlignment(sub1: number[], sub2: number[], equal: (i1: number, i2: number) => boolean): number[] {
const size = sub1.length;
const comb = new Array<number>(size).fill(0);
let best = Array.from({ length: size }, (_, i) => i);
let bestWeight = 0;
const combinations = (start: number, n: number, k: number) => {
if (k === size) {
let weight = 0;
for (let i = 0; i < size; i++) if (equal(sub1[i]!, sub2[comb[i]!]!)) weight++;
if (weight > bestWeight) {
bestWeight = weight;
best = [...comb];
}
return;
}
for (let i = start; i <= n; i++) {
comb[k] = i;
combinations(i + 1, n, k + 1);
}
};
combinations(0, sub2.length - 1, 0);
return best;
}
+428
Переглянути файл
@@ -0,0 +1,428 @@
/**
* Word-level comparison of a changed block (IntelliJ's ByWordRt
* .compareAndSplit with LineFragmentSplitter, ported; Apache-2.0, Copyright
* JetBrains s.r.o. and contributors): words and line breaks are diffed, the
* block is split into "logically different" line blocks, punctuation between
* matched words is matched by character, and whitespace by the policy.
*/
import { comparePunctuation } from "./byChar";
import { optimizeWordChunks, type WordChunk } from "./chunkOptimizer";
import { ChangeBuilder, create, type DiffIterable, diffSequences, subIterable, unchanged } from "./iterables";
import { isEmptyRange, range, type Range } from "./lcs";
import {
type ComparisonPolicy,
charCount,
expandWhitespaces,
expandWhitespacesBackward,
expandWhitespacesForward,
isAlpha,
isContinuousScript,
isEqualsIgnoreWhitespacesRange,
isEqualsRange,
isSpace,
trimEnd,
trimRange,
trimStart,
} from "./text";
export interface InlineChunk extends WordChunk {
/** Equal keys are equal chunks: the word itself, or "\n". */
readonly key: string;
}
/**
* The words of a text (ByWordRt.getInlineChunks): runs of letters and digits
* (anything but ASCII whitespace and punctuation), single characters of
* scripts written without spaces, and line breaks. Punctuation is matched
* separately.
*/
export function getInlineChunks(text: string): InlineChunk[] {
const chunks: InlineChunk[] = [];
const word = (from: number, to: number): InlineChunk => ({
offset1: from,
offset2: to,
newline: false,
key: text.slice(from, to),
});
let wordStart = -1;
for (let offset = 0; offset < text.length;) {
const ch = text.codePointAt(offset)!;
const n = charCount(ch);
const alpha = isAlpha(ch);
if (alpha && !isContinuousScript(ch)) {
if (wordStart === -1) wordStart = offset;
} else {
if (wordStart !== -1) {
chunks.push(word(wordStart, offset));
wordStart = -1;
}
if (alpha) chunks.push(word(offset, offset + n));
else if (ch === 10) chunks.push({ offset1: offset, offset2: offset + 1, newline: true, key: "\n" });
}
offset += n;
}
if (wordStart !== -1) chunks.push(word(wordStart, text.length));
return chunks;
}
/** Word changes of two texts (ByWordRt.compare). */
export function compareWords(text1: string, text2: string, policy: ComparisonPolicy): readonly Range[] {
const words1 = getInlineChunks(text1);
const words2 = getInlineChunks(text2);
const keys1 = words1.map((w) => w.key);
const keys2 = words2.map((w) => w.key);
let wordChanges = diffSequences(keys1, keys2);
wordChanges = optimizeWordChunks(keys1, keys2, words1, words2, text1, text2, wordChanges);
const delimiters = matchPunctuation(text1, text2, words1, words2, 0, 0, wordChanges);
return matchWhitespaces(text1, text2, delimiters, policy).changes;
}
export interface LineBlock {
/** Changed ranges of the block's texts, relative to `offsets`. */
readonly fragments: readonly Range[];
readonly offsets: Range;
readonly newlines1: number;
readonly newlines2: number;
}
/** Word changes of a changed line block, split into line blocks (ByWordRt.compareAndSplit). */
export function compareAndSplit(text1: string, text2: string, policy: ComparisonPolicy): LineBlock[] {
const words1 = getInlineChunks(text1);
const words2 = getInlineChunks(text2);
const keys1 = words1.map((w) => w.key);
const keys2 = words2.map((w) => w.key);
let wordChanges = diffSequences(keys1, keys2);
wordChanges = optimizeWordChunks(keys1, keys2, words1, words2, text1, text2, wordChanges);
const wordBlocks = splitLineFragments(text1, text2, words1, words2, wordChanges);
const changed = wordChanges.changes;
let index = 0;
return wordBlocks.map((block) => {
const { offsets, words } = block;
while (index < changed.length) {
const r = changed[index]!;
if (r.end1 < words.start1 || r.end2 < words.start2) index++;
else break;
}
const sub = subIterable(changed, words.start1, words.end1, words.start2, words.end2, index);
const subtext1 = text1.slice(offsets.start1, offsets.end1);
const subtext2 = text2.slice(offsets.start2, offsets.end2);
const subwords1 = words1.slice(words.start1, words.end1);
const subwords2 = words2.slice(words.start2, words.end2);
const delimiters = matchPunctuation(subtext1, subtext2, subwords1, subwords2, offsets.start1, offsets.start2, sub);
const iterable = matchWhitespaces(subtext1, subtext2, delimiters, policy);
return {
fragments: iterable.changes,
offsets,
newlines1: subwords1.filter((w) => w.newline).length,
newlines2: subwords2.filter((w) => w.newline).length,
};
});
}
interface WordBlock {
readonly words: Range;
readonly offsets: Range;
}
interface PendingChunk {
readonly block: WordBlock;
readonly hasEqualWords: boolean;
readonly hasWordsInside: boolean;
readonly isEqualIgnoreWhitespaces: boolean;
}
/**
* Splits a changed block at matched line breaks and at matched first words of
* lines (LineFragmentSplitter). Word indexes: -1 is the start of the text,
* `words.length` its end.
*/
function splitLineFragments(
text1: string,
text2: string,
words1: readonly InlineChunk[],
words2: readonly InlineChunk[],
iterable: DiffIterable,
): WordBlock[] {
const result: WordBlock[] = [];
let last1 = -1;
let last2 = -1;
let pending: PendingChunk | null = null;
const offset = (words: readonly InlineChunk[], text: string, index: number) =>
index === -1 ? 0 : index === words.length ? text.length : words[index]!.offset2;
const createChunk = (start1: number, start2: number, end1: number, end2: number, hasEqualWords: boolean) => {
const offsets = range(
offset(words1, text1, start1),
offset(words1, text1, end1),
offset(words2, text2, start2),
offset(words2, text2, end2),
);
const words = range(
Math.max(0, start1 + 1),
Math.min(end1 + 1, words1.length),
Math.max(0, start2 + 1),
Math.min(end2 + 1, words2.length),
);
const block = { words, offsets };
let hasWordsInside = false;
for (let i = words.start1; i < words.end1 && !hasWordsInside; i++) hasWordsInside = !words1[i]!.newline;
for (let i = words.start2; i < words.end2 && !hasWordsInside; i++) hasWordsInside = !words2[i]!.newline;
return {
block,
hasEqualWords,
hasWordsInside,
isEqualIgnoreWhitespaces: isEqualsIgnoreWhitespacesRange(text1, text2, offsets),
};
};
const shouldMerge = (c1: PendingChunk, c2: PendingChunk) =>
// lines matched only by '\n'
(!c1.hasEqualWords && !c2.hasEqualWords) ||
// whitespace-only changed lines
(c1.isEqualIgnoreWhitespaces && c2.isEqualIgnoreWhitespaces) ||
// a block without words in it
!c1.hasWordsInside ||
!c2.hasWordsInside;
const merge = (c1: PendingChunk, c2: PendingChunk): PendingChunk => ({
block: {
words: range(c1.block.words.start1, c2.block.words.end1, c1.block.words.start2, c2.block.words.end2),
offsets: range(c1.block.offsets.start1, c2.block.offsets.end1, c1.block.offsets.start2, c2.block.offsets.end2),
},
hasEqualWords: c1.hasEqualWords || c2.hasEqualWords,
hasWordsInside: c1.hasWordsInside || c2.hasWordsInside,
isEqualIgnoreWhitespaces: c1.isEqualIgnoreWhitespaces && c2.isEqualIgnoreWhitespaces,
});
const addLineChunk = (end1: number, end2: number, hasEqualWords: boolean) => {
if (last1 > end1 || last2 > end2) return;
const chunk = createChunk(last1, last2, end1, end2, hasEqualWords);
if (isEmptyRange(chunk.block.offsets)) return;
if (pending && shouldMerge(pending, chunk)) pending = merge(pending, chunk);
else {
if (pending) result.push(pending.block);
pending = chunk;
}
last1 = end1;
last2 = end2;
};
const firstInLine = (words: readonly InlineChunk[], index: number) => index === 0 || words[index - 1]!.newline;
let hasEqualWords = false;
for (const r of unchanged(iterable)) {
for (let i = 0; i < r.end1 - r.start1; i++) {
const index1 = r.start1 + i;
const index2 = r.start2 + i;
if (words1[index1]!.newline && words2[index2]!.newline) {
// split by matched newlines
addLineChunk(index1, index2, hasEqualWords);
hasEqualWords = false;
} else {
if (firstInLine(words1, index1) && firstInLine(words2, index2)) {
// split by matched first word in line
addLineChunk(index1 - 1, index2 - 1, hasEqualWords);
hasEqualWords = false;
}
hasEqualWords = true;
}
}
}
addLineChunk(words1.length, words2.length, hasEqualWords);
if (pending) result.push((pending as PendingChunk).block);
return result;
}
/**
* Matches punctuation between words (AdjustmentPunctuationMatcher): the
* separators around each pair of matched words are compared by character, so
* "[ X { A ! B } Y ]" vs "( X ... Y )" compares "[" with "(", "{" + "}" with
* "..." and "]" with ")".
*/
function matchPunctuation(
text1: string,
text2: string,
words1: readonly InlineChunk[],
words2: readonly InlineChunk[],
startShift1: number,
startShift2: number,
changes: DiffIterable,
): DiffIterable {
const len1 = text1.length;
const len2 = text2.length;
const builder = new ChangeBuilder(len1, len2);
const startOffset1 = (i: number) => words1[i]!.offset1 - startShift1;
const startOffset2 = (i: number) => words2[i]!.offset1 - startShift2;
const endOffset1 = (i: number) => words1[i]!.offset2 - startShift1;
const endOffset2 = (i: number) => words2[i]!.offset2 - startShift2;
let lastStart1 = -1;
let lastStart2 = -1;
let lastEnd1 = -1;
let lastEnd2 = -1;
const matchRange = (start1: number, start2: number, end1: number, end2: number) => {
if (start1 === end1 && start2 === end2) return;
const inner = comparePunctuation(text1.slice(start1, end1), text2.slice(start2, end2));
for (const r of unchanged(inner))
builder.markEqual(start1 + r.start1, start2 + r.start2, start1 + r.end1, start2 + r.end2);
};
// One sequence compared with two others as if they were one (comparePunctuation2Side).
const compare2Side = (text: string, text21: string, text22: string): [Range[], Range[]] => {
const changes = comparePunctuation(text, text21 + text22);
const ranges1: Range[] = [];
const ranges2: Range[] = [];
const split = text21.length;
for (const r of unchanged(changes)) {
if (r.end2 <= split) ranges1.push(r);
else if (r.start2 >= split) ranges2.push(range(r.start1, r.end1, r.start2 - split, r.end2 - split));
else {
const len = split - r.start2;
ranges1.push(range(r.start1, r.start1 + len, r.start2, split));
ranges2.push(range(r.start1 + len, r.end1, 0, r.end2 - split));
}
}
return [ranges1, ranges2];
};
const matchComplexRange = (
start11: number,
start12: number,
end11: number,
end12: number,
start21: number,
start22: number,
end21: number,
end22: number,
) => {
if (start11 === start21 && end11 === end21) {
const [first, second] = compare2Side(
text1.slice(start11, end11),
text2.slice(start12, end12),
text2.slice(start22, end22),
);
for (const r of first)
builder.markEqual(start11 + r.start1, start12 + r.start2, start11 + r.end1, start12 + r.end2);
for (const r of second)
builder.markEqual(start11 + r.start1, start22 + r.start2, start11 + r.end1, start22 + r.end2);
} else if (start12 === start22 && end12 === end22) {
// mirrored: two left sides against one right side
const [first, second] = compare2Side(
text2.slice(start12, end12),
text1.slice(start11, end11),
text1.slice(start21, end21),
);
for (const r of first)
builder.markEqual(start11 + r.start2, start12 + r.start1, start11 + r.end2, start12 + r.end1);
for (const r of second)
builder.markEqual(start21 + r.start2, start12 + r.start1, start21 + r.end2, start12 + r.end1);
} else {
throw new Error("unexpected punctuation ranges");
}
};
const matchForward = (index1: number, index2: number) => {
lastStart1 = index1 === -1 ? 0 : endOffset1(index1);
lastStart2 = index2 === -1 ? 0 : endOffset2(index2);
lastEnd1 = index1 + 1 === words1.length ? len1 : startOffset1(index1 + 1);
lastEnd2 = index2 + 1 === words2.length ? len2 : startOffset2(index2 + 1);
};
const matchBackward = (index1: number, index2: number) => {
const start1 = index1 === 0 ? 0 : endOffset1(index1 - 1);
const start2 = index2 === 0 ? 0 : endOffset2(index2 - 1);
const end1 = index1 === words1.length ? len1 : startOffset1(index1);
const end2 = index2 === words2.length ? len2 : startOffset2(index2);
if (lastStart1 === start1 && lastStart2 === start2) {
// adjacent matched words, match the gap between ("A B" - "A B")
matchRange(start1, start2, end1, end2);
} else if (lastStart1 < start1 && lastStart2 < start2) {
// matched words with unmatched ones between ("A X B" - "A Y B")
matchRange(lastStart1, lastStart2, lastEnd1, lastEnd2);
matchRange(start1, start2, end1, end2);
} else {
// one side adjacent, the other with unmatched words between ("A B" - "A Y B")
matchComplexRange(lastStart1, lastStart2, lastEnd1, lastEnd2, start1, start2, end1, end2);
}
lastStart1 = lastStart2 = lastEnd1 = lastEnd2 = -1;
};
matchForward(-1, -1);
for (const r of unchanged(changes)) {
for (let i = 0; i < r.end1 - r.start1; i++) {
const index1 = r.start1 + i;
const index2 = r.start2 + i;
matchBackward(index1, index2);
builder.markEqual(startOffset1(index1), startOffset2(index2), endOffset1(index1), endOffset2(index2));
matchForward(index1, index2);
}
}
matchBackward(words1.length, words2.length);
return builder.finish();
}
/** Whitespace handling of the changes by policy (ByWordRt.matchAdjustmentWhitespaces). */
export function matchWhitespaces(text1: string, text2: string, iterable: DiffIterable, policy: ComparisonPolicy) {
if (policy === "ignore") return ignoreSpaces(iterable, text1, text2);
const corrected = defaultSpaces(iterable, text1, text2);
return policy === "trim" ? trimSpaces(corrected, text1, text2) : corrected;
}
/** Equal whitespace at the edges of a change is unchanged (DefaultCorrector). */
function defaultSpaces(iterable: DiffIterable, text1: string, text2: string): DiffIterable {
const changes: Range[] = [];
for (const r of iterable.changes) {
const endCut = expandWhitespacesBackward(text1, text2, r.start1, r.start2, r.end1, r.end2);
const startCut = expandWhitespacesForward(text1, text2, r.start1, r.start2, r.end1 - endCut, r.end2 - endCut);
const expanded = range(r.start1 + startCut, r.end1 - endCut, r.start2 + startCut, r.end2 - endCut);
if (!isEmptyRange(expanded)) changes.push(expanded);
}
return create(changes, text1.length, text2.length);
}
/** Whitespace is matched where possible and ignored where not (IgnoreSpacesCorrector). */
function ignoreSpaces(iterable: DiffIterable, text1: string, text2: string): DiffIterable {
const changes: Range[] = [];
for (const r of iterable.changes) {
const trimmed = trimRange(text1, text2, expandWhitespaces(text1, text2, r));
if (!isEmptyRange(trimmed) && !isEqualsIgnoreWhitespacesRange(text1, text2, trimmed)) changes.push(trimmed);
}
return create(changes, text1.length, text2.length);
}
function isLeadingSpace(text: string, start: number): boolean {
if (start < 0 || start === text.length || !isSpace(text[start])) return false;
for (let i = start - 1; i >= 0; i--) {
if (text[i] === "\n") return true;
if (!isSpace(text[i])) return false;
}
return true;
}
function isTrailingSpace(text: string, end: number): boolean {
if (end < 0 || end === text.length || !isSpace(text[end])) return false;
for (let i = end; i < text.length; i++) {
if (text[i] === "\n") return true;
if (!isSpace(text[i])) return false;
}
return true;
}
const isLeadingTrailingSpace = (text: string, i: number) => isLeadingSpace(text, i) || isTrailingSpace(text, i);
/** Leading and trailing whitespace of lines is not a change (TrimSpacesCorrector). */
function trimSpaces(iterable: DiffIterable, text1: string, text2: string): DiffIterable {
const changes: Range[] = [];
for (const r of iterable.changes) {
let { start1, start2, end1, end2 } = r;
if (isLeadingTrailingSpace(text1, start1)) start1 = trimStart(text1, start1, end1);
if (isLeadingTrailingSpace(text1, end1 - 1)) end1 = trimEnd(text1, start1, end1);
if (isLeadingTrailingSpace(text2, start2)) start2 = trimStart(text2, start2, end2);
if (isLeadingTrailingSpace(text2, end2 - 1)) end2 = trimEnd(text2, start2, end2);
const trimmed = range(start1, end1, start2, end2);
if (!isEmptyRange(trimmed) && !isEqualsRange(text1, text2, trimmed)) changes.push(trimmed);
}
return create(changes, text1.length, text2.length);
}
+183
Переглянути файл
@@ -0,0 +1,183 @@
/**
* Shifts ambiguous changes to where people expect them (IntelliJ's
* ChunkOptimizer, ported; Apache-2.0, Copyright JetBrains s.r.o. and
* contributors): touching changes are merged, and an insertion or deletion
* that could sit at several places moves to a word boundary (words) or next to
* an empty line (lines).
*/
import { createUnchanged, expandBackward, expandForward, type DiffIterable, unchanged } from "./iterables";
import { range, type Range } from "./lcs";
import { isSpace } from "./text";
/** `touchLeft`: the changes touch on the left side; returns the shift (> 0 forward, < 0 backward). */
type GetShift = (
touchLeft: boolean,
equalForward: number,
equalBackward: number,
range1: Range,
range2: Range,
) => number;
function optimize<T>(data1: readonly T[], data2: readonly T[], iterable: DiffIterable, getShift: GetShift) {
const ranges: Range[] = [];
const processLastRanges = (): void => {
if (ranges.length < 2) return;
const range1 = ranges[ranges.length - 2]!;
const range2 = ranges[ranges.length - 1]!;
// Changes that don't touch can't be optimized (the input would not be an LCS).
if (range1.end1 !== range2.start1 && range1.end2 !== range2.start2) return;
const count1 = range1.end1 - range1.start1;
const count2 = range2.end1 - range2.start1;
const equalForward = expandForward(
data1,
data2,
range1.end1,
range1.end2,
Math.min(range1.end1 + count2, data1.length),
Math.min(range1.end2 + count2, data2.length),
);
const equalBackward = expandBackward(
data1,
data2,
Math.max(range2.start1 - count1, 0),
Math.max(range2.start2 - count1, 0),
range2.start1,
range2.start2,
);
if (equalForward === 0 && equalBackward === 0) return;
// merge chunks left [A]B[B] -> [AB]B
if (equalForward === count2) {
ranges.splice(-2, 2, range(range1.start1, range1.end1 + count2, range1.start2, range1.end2 + count2));
return processLastRanges();
}
// merge chunks right [A]A[B] -> A[AB]
if (equalBackward === count1) {
ranges.splice(-2, 2, range(range2.start1 - count1, range2.end1, range2.start2 - count1, range2.end2));
return processLastRanges();
}
const shift = getShift(range1.end1 === range2.start1, equalForward, equalBackward, range1, range2);
if (shift !== 0)
ranges.splice(
-2,
2,
range(range1.start1, range1.end1 + shift, range1.start2, range1.end2 + shift),
range(range2.start1 + shift, range2.end1, range2.start2 + shift, range2.end2),
);
};
for (const r of unchanged(iterable)) {
ranges.push(r);
processLastRanges();
}
return createUnchanged(ranges, data1.length, data2.length);
}
export interface WordChunk {
readonly offset1: number;
readonly offset2: number;
readonly newline: boolean;
}
/**
* Words: fewer chunks, and fewer changed "sentences" (runs of words not
* separated by whitespace): "[AX] [AZ]" - "[AX] AY [AZ]", not "[AX A][Z]".
*/
export function optimizeWordChunks(
keys1: readonly string[],
keys2: readonly string[],
words1: readonly WordChunk[],
words2: readonly WordChunk[],
text1: string,
text2: string,
iterable: DiffIterable,
): DiffIterable {
const separated = (text: string, word1: WordChunk, word2: WordChunk) => {
if (word1.newline || word2.newline) return true;
for (let i = word1.offset2; i < word2.offset1; i++) if (isSpace(text[i])) return true;
return false;
};
const edgeShift = (text: string, words: readonly WordChunk[], offset: number, count: number, ltr: boolean) => {
for (let i = 0; i < count; i++) {
const [w1, w2] = ltr
? [words[offset + i]!, words[offset + i + 1]!]
: [words[offset - i - 1]!, words[offset - i]!];
if (separated(text, w1, w2)) return i + 1;
}
return -1;
};
return optimize(keys1, keys2, iterable, (touchLeft, equalForward, equalBackward, _range1, range2) => {
const words = touchLeft ? words1 : words2;
const text = touchLeft ? text1 : text2;
const touchStart = touchLeft ? range2.start1 : range2.start2;
// already separated by whitespace
if (separated(text, words[touchStart - 1]!, words[touchStart]!)) return 0;
// shift chunks left [X]A Y[A ZA] -> [XA] YA [ZA]
const left = edgeShift(text, words, touchStart, equalForward, true);
if (left > 0) return left;
// shift chunks right [AX A]Y A[Z] -> [AX] AY [AZ]
const right = edgeShift(text, words, touchStart - 1, equalBackward, false);
if (right > 0) return -right;
return 0;
});
}
/** Lines with at most this many non-space characters are "unimportant" (`}`, blank). */
export const UNIMPORTANT_LINE_CHAR_COUNT = 3;
export interface LineInfo {
readonly key: string;
readonly nonSpaceChars: number;
}
/**
* Lines: fewer chunks, and insertions / deletions bounded by an empty (or
* unimportant) line: "ABooYZ [ABuuYZ ]ABzzYZ", not "ABooYZ AB[uuYZ AB]zzYZ".
*/
export function optimizeLineChunks(
lines1: readonly LineInfo[],
lines2: readonly LineInfo[],
iterable: DiffIterable,
): DiffIterable {
const nextUnimportant = (lines: readonly LineInfo[], offset: number, count: number, threshold: number) => {
for (let i = 0; i < count; i++) if (lines[offset + i]!.nonSpaceChars <= threshold) return i;
return -1;
};
const prevUnimportant = (lines: readonly LineInfo[], offset: number, count: number, threshold: number) => {
for (let i = 0; i < count; i++) if (lines[offset - i]!.nonSpaceChars <= threshold) return i;
return -1;
};
const toShift = (forward: number, backward: number): number | null => {
if (forward === -1 && backward === -1) return null;
if (forward === 0 || backward === 0) return 0;
return forward !== -1 ? forward : -backward;
};
const keys1 = lines1.map((l) => l.key);
const keys2 = lines2.map((l) => l.key);
return optimize(keys1, keys2, iterable, (touchLeft, equalForward, equalBackward, range1, range2) => {
// an empty line boundary in unchanged lines: the insertion / deletion goes right before / after it
const unchangedBoundary = (threshold: number) => {
const lines = touchLeft ? lines1 : lines2;
const touchStart = touchLeft ? range2.start1 : range2.start2;
return toShift(
nextUnimportant(lines, touchStart, equalForward + 1, threshold),
prevUnimportant(lines, touchStart - 1, equalBackward + 1, threshold),
);
};
// an empty line boundary in changed lines: the insertion / deletion starts / ends with it
const changedBoundary = (threshold: number) => {
const lines = touchLeft ? lines2 : lines1;
const changeStart = touchLeft ? range1.end2 : range1.end1;
const changeEnd = touchLeft ? range2.start2 : range2.start1;
return toShift(
nextUnimportant(lines, changeStart, equalForward + 1, threshold),
prevUnimportant(lines, changeEnd - 1, equalBackward + 1, threshold),
);
};
return (
unchangedBoundary(0) ??
changedBoundary(0) ??
unchangedBoundary(UNIMPORTANT_LINE_CHAR_COUNT) ??
changedBoundary(UNIMPORTANT_LINE_CHAR_COUNT) ??
0
);
});
}
+255
Переглянути файл
@@ -0,0 +1,255 @@
/**
* IntelliJ's text comparison (ComparisonManagerImpl.compareLinesInner and
* processBlocks, ported; Apache-2.0, Copyright JetBrains s.r.o. and
* contributors): lines are compared, each changed block is compared by words
* and split into line blocks, then adjoining blocks are squashed back and,
* when ignoring whitespace and empty lines, whitespace-only blocks trimmed.
*/
import { compareLines } from "./byLine";
import { compareAndSplit } from "./byWord";
import { DiffTooBigError, type Range } from "./lcs";
import { type ComparisonPolicy, isEqualTexts, stripSpaces } from "./text";
export type { ComparisonPolicy } from "./text";
export type { Range } from "./lcs";
export { compareWords } from "./byWord";
export interface LineFragment {
readonly startLine1: number;
readonly endLine1: number;
readonly startLine2: number;
readonly endLine2: number;
/** Text offsets; the end includes the last line's line break, when it has one. */
readonly startOffset1: number;
readonly endOffset1: number;
readonly startOffset2: number;
readonly endOffset2: number;
/**
* Changed ranges inside the fragment, relative to its start offsets; null
* when not computed (by-line highlighting, or a block too big to compare).
*/
readonly inner: readonly Range[] | null;
}
export interface CompareOptions {
policy: ComparisonPolicy;
/** Compare changed blocks by words ("Highlight words"). */
words: boolean;
/** Drop leading / trailing whitespace-only blocks ("Ignore whitespaces and empty lines"). */
trimChunks?: boolean;
/** Keep the line blocks words split a change into ("Highlight split changes"). */
split?: boolean;
}
/** Do not compare by words after that many blocks were too big (DiffConfig.MAX_BAD_LINES). */
const MAX_BAD_LINES = 3;
class LineOffsets {
private readonly starts: number[] = [0];
constructor(readonly text: string) {
for (let i = text.indexOf("\n"); i >= 0; i = text.indexOf("\n", i + 1)) this.starts.push(i + 1);
}
get lineCount() {
return this.starts.length;
}
lineStart(line: number) {
return this.starts[line]!;
}
lineEnd(line: number, includeNewline = false) {
if (line === this.starts.length - 1) return this.text.length;
return this.starts[line + 1]! - (includeNewline ? 0 : 1);
}
lines(): string[] {
return this.starts.map((_, i) => this.text.slice(this.lineStart(i), this.lineEnd(i)));
}
/** Offsets of lines `[start, end)` (ComparisonManagerImpl.getOffsets). */
offsets(start: number, end: number): [number, number] {
if (start === end) {
const offset = start < this.lineCount ? this.lineStart(start) : this.lineEnd(this.lineCount - 1, true);
return [offset, offset];
}
return [this.lineStart(start), this.lineEnd(end - 1, true)];
}
}
/** Line fragments of two texts with their inner word changes, as IDEA's diff viewer computes them. */
export function compareTexts(text1: string, text2: string, options: CompareOptions): LineFragment[] {
const { policy } = options;
const fragments = options.words
? compareLinesInner(text1, text2, policy)
: compareLineFragments(text1, text2, policy);
return processBlocks(fragments, text1, text2, policy, !options.split, !!options.trimChunks);
}
/** Changed lines (ComparisonManagerImpl.compareLines). */
export function compareLineFragments(text1: string, text2: string, policy: ComparisonPolicy): LineFragment[] {
const offsets1 = new LineOffsets(text1);
const offsets2 = new LineOffsets(text2);
return compareLines(offsets1.lines(), offsets2.lines(), policy).changes.map((r) => {
const [startOffset1, endOffset1] = offsets1.offsets(r.start1, r.end1);
const [startOffset2, endOffset2] = offsets2.offsets(r.start2, r.end2);
return {
startLine1: r.start1,
endLine1: r.end1,
startLine2: r.start2,
endLine2: r.end2,
startOffset1,
endOffset1,
startOffset2,
endOffset2,
inner: null,
};
});
}
/** Changed lines split into line blocks with their word changes (ComparisonManagerImpl.compareLinesInner). */
export function compareLinesInner(text1: string, text2: string, policy: ComparisonPolicy): LineFragment[] {
return innerFragments(compareLineFragments(text1, text2, policy), text1, text2, policy);
}
function innerFragments(
fragments: readonly LineFragment[],
text1: string,
text2: string,
policy: ComparisonPolicy,
): LineFragment[] {
const out: LineFragment[] = [];
let tooBig = 0;
for (const f of fragments) {
const sub1 = text1.slice(f.startOffset1, f.endOffset1);
const sub2 = text2.slice(f.startOffset2, f.endOffset2);
if (f.startLine1 === f.endLine1 || f.startLine2 === f.endLine2) {
// insertion / deletion
out.push(isEqualTexts(sub1, sub2, policy) ? { ...f, inner: [] } : f);
continue;
}
if (tooBig >= MAX_BAD_LINES) {
out.push(f);
continue;
}
try {
const blocks = compareAndSplit(sub1, sub2, policy);
let line1 = f.startLine1;
let line2 = f.startLine2;
blocks.forEach((block, i) => {
// the last block ends with the fragment, whatever its last line
const last = i === blocks.length - 1;
const endLine1 = last ? f.endLine1 : line1 + block.newlines1;
const endLine2 = last ? f.endLine2 : line2 + block.newlines2;
out.push({
startLine1: line1,
endLine1,
startLine2: line2,
endLine2,
startOffset1: f.startOffset1 + block.offsets.start1,
endOffset1: f.startOffset1 + block.offsets.end1,
startOffset2: f.startOffset2 + block.offsets.start2,
endOffset2: f.startOffset2 + block.offsets.end2,
inner: block.fragments,
});
line1 = endLine1;
line2 = endLine2;
});
} catch (e) {
if (!(e instanceof DiffTooBigError)) throw e;
out.push(f);
tooBig++;
}
}
return out;
}
const adjoining = (before: LineFragment, after: LineFragment) =>
before.endLine1 === after.startLine1 &&
before.endLine2 === after.startLine2 &&
before.endOffset1 === after.startOffset1 &&
before.endOffset2 === after.startOffset2;
/** Squashes adjoining fragments and trims whitespace-only ones at their edges (processBlocks). */
export function processBlocks(
fragments: LineFragment[],
text1: string,
text2: string,
policy: ComparisonPolicy,
squash: boolean,
trim: boolean,
): LineFragment[] {
if ((!squash && !trim) || !fragments.length) return fragments;
const out: LineFragment[] = [];
let start = 0;
for (let i = 1; i <= fragments.length; i++) {
if (i < fragments.length && adjoining(fragments[i - 1]!, fragments[i]!)) continue;
out.push(...processAdjoining(fragments.slice(start, i), text1, text2, policy, squash, trim));
start = i;
}
return out;
}
function processAdjoining(
fragments: LineFragment[],
text1: string,
text2: string,
policy: ComparisonPolicy,
squash: boolean,
trim: boolean,
): LineFragment[] {
let start = 0;
let end = fragments.length;
if (trim && policy === "ignore") {
const ignorable = (f: LineFragment) =>
(f.inner !== null && f.inner.length === 0) ||
stripSpaces(text1.slice(f.startOffset1, f.endOffset1)) === stripSpaces(text2.slice(f.startOffset2, f.endOffset2));
while (start < end && ignorable(fragments[start]!)) start++;
while (start < end && ignorable(fragments[end - 1]!)) end--;
}
if (start === end) return [];
return squash ? [doSquash(fragments.slice(start, end))] : fragments.slice(start, end);
}
function doSquash(fragments: LineFragment[]): LineFragment {
if (fragments.length === 1) return fragments[0]!;
const first = fragments[0]!;
const last = fragments[fragments.length - 1]!;
const inner: Range[] = [];
for (const f of fragments) {
const shift1 = f.startOffset1 - first.startOffset1;
const shift2 = f.startOffset2 - first.startOffset2;
const own = f.inner ?? [
{ start1: 0, end1: f.endOffset1 - f.startOffset1, start2: 0, end2: f.endOffset2 - f.startOffset2 },
];
for (const r of own) {
const prev = inner[inner.length - 1];
if (prev && prev.end1 === r.start1 + shift1 && prev.end2 === r.start2 + shift2)
inner[inner.length - 1] = {
start1: prev.start1,
end1: r.end1 + shift1,
start2: prev.start2,
end2: r.end2 + shift2,
};
else
inner.push({
start1: r.start1 + shift1,
end1: r.end1 + shift1,
start2: r.start2 + shift2,
end2: r.end2 + shift2,
});
}
}
return {
startLine1: first.startLine1,
endLine1: last.endLine1,
startLine2: first.startLine2,
endLine2: last.endLine2,
startOffset1: first.startOffset1,
endOffset1: last.endOffset1,
startOffset2: first.startOffset2,
endOffset2: last.endOffset2,
inner,
};
}
+191
Переглянути файл
@@ -0,0 +1,191 @@
/**
* Changed / unchanged ranges between two sequences (IntelliJ's DiffIterable
* and DiffIterableUtil, ported; Apache-2.0, Copyright JetBrains s.r.o. and
* contributors). Changes are kept as a sorted list; "fair" iterables, whose
* unchanged ranges have equal lengths on both sides, use the same shape.
*/
import { diffKeys, isEmptyRange, range, type Range } from "./lcs";
export interface DiffIterable {
readonly length1: number;
readonly length2: number;
readonly changes: readonly Range[];
}
export const create = (changes: readonly Range[], length1: number, length2: number): DiffIterable => ({
length1,
length2,
changes,
});
/** The ranges between the changes (ChangeDiffIterableBase.UnchangedIterator). */
export function unchanged(it: DiffIterable): Range[] {
const out: Range[] = [];
let last1 = 0;
let last2 = 0;
let i = 0;
const { changes } = it;
if (changes.length && changes[0]!.start1 === 0 && changes[0]!.start2 === 0) {
last1 = changes[0]!.end1;
last2 = changes[0]!.end2;
i = 1;
}
for (; i < changes.length; i++) {
const c = changes[i]!;
out.push(range(last1, c.start1, last2, c.start2));
last1 = c.end1;
last2 = c.end2;
}
if (last1 !== it.length1 || last2 !== it.length2) out.push(range(last1, it.length1, last2, it.length2));
return out;
}
export const invert = (it: DiffIterable): DiffIterable => create(unchanged(it), it.length1, it.length2);
export const createUnchanged = (ranges: readonly Range[], length1: number, length2: number) =>
invert(create(ranges, length1, length2));
/** Both changed and unchanged ranges in order, without empty ones (DiffIterableUtil.iterateAll). */
export function iterateAll(it: DiffIterable): [Range, boolean][] {
const out: [Range, boolean][] = [];
let last1 = 0;
let last2 = 0;
for (const c of it.changes) {
const gap = range(last1, c.start1, last2, c.start2);
if (!isEmptyRange(gap)) out.push([gap, true]);
out.push([c, false]);
last1 = c.end1;
last2 = c.end2;
}
const tail = range(last1, it.length1, last2, it.length2);
if (!isEmptyRange(tail)) out.push([tail, true]);
return out;
}
/** Changes of sequences of keys compared by equality (DiffIterableUtil.diff). */
export const diffSequences = <T>(a: readonly T[], b: readonly T[]): DiffIterable =>
create(diffKeys(a, b), a.length, b.length);
/** The part of `changed` inside the given ranges, relative to their starts (SubiterableDiffIterable). */
export function subIterable(
changed: readonly Range[],
start1: number,
end1: number,
start2: number,
end2: number,
firstIndex: number,
): DiffIterable {
const out: Range[] = [];
for (let i = firstIndex; i < changed.length; i++) {
const r = changed[i]!;
if (r.end1 < start1 || r.end2 < start2) continue;
if (r.start1 > end1 || r.start2 > end2) break;
const sub = range(
Math.max(start1, r.start1) - start1,
Math.min(end1, r.end1) - start1,
Math.max(start2, r.start2) - start2,
Math.min(end2, r.end2) - start2,
);
if (!isEmptyRange(sub)) out.push(sub);
}
return create(out, end1 - start1, end2 - start2);
}
/** Collects changes from the equal ranges marked in order (DiffIterableUtil.ChangeBuilder). */
export class ChangeBuilder {
index1 = 0;
index2 = 0;
protected readonly changes: Range[] = [];
constructor(
readonly length1: number,
readonly length2: number,
) {}
markEqual(index1: number, index2: number, end1 = index1 + 1, end2 = index2 + 1) {
if (index1 === end1 && index2 === end2) return;
if (this.index1 !== index1 || this.index2 !== index2) this.addChange(this.index1, this.index2, index1, index2);
this.index1 = end1;
this.index2 = end2;
}
markEqualCount(index1: number, index2: number, count: number) {
this.markEqual(index1, index2, index1 + count, index2 + count);
}
finish(): DiffIterable {
if (this.length1 !== this.index1 || this.length2 !== this.index2) {
this.addChange(this.index1, this.index2, this.length1, this.length2);
this.index1 = this.length1;
this.index2 = this.length2;
}
return create(this.changes, this.length1, this.length2);
}
protected addChange(start1: number, start2: number, end1: number, end2: number) {
this.changes.push(range(start1, end1, start2, end2));
}
}
/** A ChangeBuilder that shrinks each change by its equal ends (ExpandChangeBuilder). */
export class ExpandChangeBuilder<T> extends ChangeBuilder {
constructor(
private readonly objects1: readonly T[],
private readonly objects2: readonly T[],
) {
super(objects1.length, objects2.length);
}
protected override addChange(start1: number, start2: number, end1: number, end2: number) {
const r = expandEqual(this.objects1, this.objects2, start1, start2, end1, end2);
if (!isEmptyRange(r)) super.addChange(r.start1, r.start2, r.end1, r.end2);
}
}
/** Shrinks `[start, end)` by the equal elements at both ends (TrimUtil.expand). */
export function expandEqual<T>(
a: ArrayLike<T>,
b: ArrayLike<T>,
start1: number,
start2: number,
end1: number,
end2: number,
): Range {
const forward = expandForward(a, b, start1, start2, end1, end2);
start1 += forward;
start2 += forward;
const backward = expandBackward(a, b, start1, start2, end1, end2);
return range(start1, end1 - backward, start2, end2 - backward);
}
export function expandForward<T>(
a: ArrayLike<T>,
b: ArrayLike<T>,
start1: number,
start2: number,
end1: number,
end2: number,
): number {
const old = start1;
while (start1 < end1 && start2 < end2 && a[start1] === b[start2]) {
start1++;
start2++;
}
return start1 - old;
}
export function expandBackward<T>(
a: ArrayLike<T>,
b: ArrayLike<T>,
start1: number,
start2: number,
end1: number,
end2: number,
): number {
const old = end1;
while (start1 < end1 && start2 < end2 && a[end1 - 1] === b[end2 - 1]) {
end1--;
end2--;
}
return old - end1;
}
+512
Переглянути файл
@@ -0,0 +1,512 @@
/**
* Longest common subsequence of two sequences, ported from the IntelliJ
* Platform (`com.intellij.util.diff`: Diff, Reindexer, MyersLCS,
* PatienceIntLCS, UniqueLCS; Apache-2.0, Copyright JetBrains s.r.o. and
* contributors): common prefix / suffix trimmed, elements unique to one side
* discarded, then Myers' O(ND) diff bounded by a threshold, falling back to
* patience diff when the sequences differ too much.
*/
/** Half-open index ranges `[start1, end1)` and `[start2, end2)`. */
export interface Range {
readonly start1: number;
readonly end1: number;
readonly start2: number;
readonly end2: number;
}
export const range = (start1: number, end1: number, start2: number, end2: number): Range => ({
start1,
end1,
start2,
end2,
});
export const isEmptyRange = (r: Range) => r.start1 === r.end1 && r.start2 === r.end2;
/** The sequences differ too much to be compared (DiffTooBigException). */
export class DiffTooBigError extends Error {
constructor() {
super("Diff is too big");
}
}
/** Thrown inside the LCS when a bounded search gives up (FilesTooBigForDiffException). */
class FilesTooBig extends Error {}
/** Changed ranges between two int sequences (Diff.buildChanges). */
export function diffInts(a: ArrayLike<number>, b: ArrayLike<number>): Range[] {
const n1 = a.length;
const n2 = b.length;
let startShift = 0;
while (startShift < Math.min(n1, n2) && a[startShift] === b[startShift]) startShift++;
let endCut = 0;
while (endCut < Math.min(n1, n2) - startShift && a[n1 - endCut - 1] === b[n2 - endCut - 1]) endCut++;
const len1 = n1 - startShift - endCut;
const len2 = n2 - startShift - endCut;
if (len1 === 0 || len2 === 0)
return len1 || len2 ? [range(startShift, startShift + len1, startShift, startShift + len2)] : [];
const ints1 = Int32Array.from({ length: len1 }, (_, i) => a[startShift + i]!);
const ints2 = Int32Array.from({ length: len2 }, (_, i) => b[startShift + i]!);
try {
return buildChanges(ints1, ints2, startShift);
} catch (e) {
if (e instanceof FilesTooBig) throw new DiffTooBigError();
throw e;
}
}
/** Changed ranges between two sequences of keys, equal keys being equal elements. */
export function diffKeys<T>(a: readonly T[], b: readonly T[]): Range[] {
const numbers = new Map<T, number>();
const enumerate = (xs: readonly T[]) =>
Int32Array.from(xs, (x) => {
let n = numbers.get(x);
if (n === undefined) numbers.set(x, (n = numbers.size + 1));
return n;
});
return diffInts(enumerate(a), enumerate(b));
}
function buildChanges(ints1: Int32Array, ints2: Int32Array, startShift: number): Range[] {
const out: Range[] = [];
let index1 = startShift;
let index2 = startShift;
const builder: LCSBuilder = {
addEqual(length) {
index1 += length;
index2 += length;
},
addChange(first, second) {
out.push(range(index1, index1 + first, index2, index2 + second));
index1 += first;
index2 += second;
},
};
const reindexer = new Reindexer();
const [discarded1, discarded2] = reindexer.discardUnique(ints1, ints2);
if (discarded1.length === 0 && discarded2.length === 0) {
builder.addChange(ints1.length, ints2.length);
return out;
}
let changes: [Uint8Array, Uint8Array];
try {
const lcs = new MyersLCS(discarded1, discarded2);
lcs.executeWithThreshold();
changes = lcs.changes;
} catch (e) {
if (!(e instanceof FilesTooBig)) throw e;
const lcs = new PatienceLCS(discarded1, discarded2);
lcs.execute(true);
changes = lcs.changes;
}
reindexer.reindex(changes, builder);
return out;
}
interface LCSBuilder {
addEqual(length: number): void;
addChange(first: number, second: number): void;
}
const fill = (bits: Uint8Array, from: number, to: number, value = 1) => {
if (to > from) bits.fill(value, from, to);
};
/** Myers' O(ND) diff with linear space (MyersLCS); `changes` marks the unmatched elements. */
class MyersLCS {
private readonly vForward: Int32Array;
private readonly vBackward: Int32Array;
constructor(
private readonly first: Int32Array,
private readonly second: Int32Array,
private readonly start1 = 0,
private readonly count1 = first.length,
private readonly start2 = 0,
private readonly count2 = second.length,
private readonly changes1: Uint8Array = new Uint8Array(first.length),
private readonly changes2: Uint8Array = new Uint8Array(second.length),
) {
fill(changes1, start1, start1 + count1);
fill(changes2, start2, start2 + count2);
this.vForward = new Int32Array(count1 + count2 + 1);
this.vBackward = new Int32Array(count1 + count2 + 1);
}
get changes(): [Uint8Array, Uint8Array] {
return [this.changes1, this.changes2];
}
/** Bounds D by A + B·√N: expected O(N) under common assumptions. */
executeLinear() {
this.run(20000 + 10 * Math.floor(Math.sqrt(this.count1 + this.count2)), false);
}
executeWithThreshold() {
this.run(Math.max(20000 + 10 * Math.floor(Math.sqrt(this.count1 + this.count2)), DELTA_THRESHOLD_SIZE), true);
}
private run(threshold: number, throwException: boolean) {
if (this.count1 === 0 || this.count2 === 0) return;
this.execute(0, this.count1, 0, this.count2, Math.min(threshold, this.count1 + this.count2), throwException);
}
// LCS(old[oldStart, oldEnd), new[newStart, newEnd))
private execute(
oldStart: number,
oldEnd: number,
newStart: number,
newEnd: number,
differenceEstimate: number,
throwException: boolean,
) {
if (!(oldStart < oldEnd && newStart < newEnd)) return;
const { vForward: VF, vBackward: VB } = this;
const oldLength = oldEnd - oldStart;
const newLength = newEnd - newStart;
VF[newLength + 1] = 0;
VB[newLength + 1] = 0;
const halfD = (differenceEstimate + 1) >> 1;
let xx = -1;
let kk = -1;
let td = -1;
loop: for (let d = 0; d <= halfD; d++) {
const L = newLength + Math.max(-d, -newLength + ((d ^ newLength) & 1));
const R = newLength + Math.min(d, oldLength - ((d ^ oldLength) & 1));
for (let k = L; k <= R; k += 2) {
let x = k === L || (k !== R && VF[k - 1]! < VF[k + 1]!) ? VF[k + 1]! : VF[k - 1]! + 1;
const y = x - k + newLength;
x += this.commonForward(oldStart + x, newStart + y, Math.min(oldEnd - oldStart - x, newEnd - newStart - y));
VF[k] = x;
}
if ((oldLength - newLength) % 2 !== 0) {
for (let k = L; k <= R; k += 2) {
if (oldLength - (d - 1) <= k && k <= oldLength + (d - 1)) {
if (VF[k]! + VB[newLength + oldLength - k]! >= oldLength) {
xx = VF[k]!;
kk = k;
td = 2 * d - 1;
break loop;
}
}
}
}
for (let k = L; k <= R; k += 2) {
let x = k === L || (k !== R && VB[k - 1]! < VB[k + 1]!) ? VB[k + 1]! : VB[k - 1]! + 1;
const y = x - k + newLength;
x += this.commonBackward(
oldEnd - 1 - x,
newEnd - 1 - y,
Math.min(oldEnd - oldStart - x, newEnd - newStart - y),
);
VB[k] = x;
}
if ((oldLength - newLength) % 2 === 0) {
for (let k = L; k <= R; k += 2) {
if (oldLength - d <= k && k <= oldLength + d) {
if (VF[oldLength + newLength - k]! + VB[k]! >= oldLength) {
xx = oldLength - VB[k]!;
kk = oldLength + newLength - k;
td = 2 * d;
break loop;
}
}
}
}
}
if (td > 1) {
const yy = xx - kk + newLength;
const oldDiff = (td + 1) >> 1;
if (0 < xx && 0 < yy) this.execute(oldStart, oldStart + xx, newStart, newStart + yy, oldDiff, throwException);
if (oldStart + xx < oldEnd && newStart + yy < newEnd)
this.execute(oldStart + xx, oldEnd, newStart + yy, newEnd, td - oldDiff, throwException);
} else if (td >= 0) {
let x = oldStart;
let y = newStart;
while (x < oldEnd && y < newEnd) {
const common = this.commonForward(x, y, Math.min(oldEnd - x, newEnd - y));
if (common > 0) {
fill(this.changes1, this.start1 + x, this.start1 + x + common, 0);
fill(this.changes2, this.start2 + y, this.start2 + y + common, 0);
x += common;
y += common;
} else if (oldEnd - oldStart > newEnd - newStart) x++;
else y++;
}
} else if (throwException) {
// The difference is more than the given estimate.
throw new FilesTooBig();
}
}
private commonForward(oldIndex: number, newIndex: number, maxLength: number): number {
let x = oldIndex;
let y = newIndex;
maxLength = Math.min(maxLength, this.count1 - oldIndex, this.count2 - newIndex);
while (x - oldIndex < maxLength && this.first[this.start1 + x] === this.second[this.start2 + y]) {
x++;
y++;
}
return x - oldIndex;
}
private commonBackward(oldIndex: number, newIndex: number, maxLength: number): number {
let x = oldIndex;
let y = newIndex;
maxLength = Math.min(maxLength, Math.min(oldIndex, newIndex) + 1);
while (oldIndex - x < maxLength && this.first[this.start1 + x] === this.second[this.start2 + y]) {
x--;
y--;
}
return oldIndex - x;
}
}
const DELTA_THRESHOLD_SIZE = 20000;
/** Patience diff (PatienceIntLCS): unique common elements anchor the match, Myers fills the gaps. */
class PatienceLCS {
private readonly changes1: Uint8Array;
private readonly changes2: Uint8Array;
constructor(
private readonly first: Int32Array,
private readonly second: Int32Array,
) {
this.changes1 = new Uint8Array(first.length);
this.changes2 = new Uint8Array(second.length);
}
get changes(): [Uint8Array, Uint8Array] {
return [this.changes1, this.changes2];
}
execute(failOnSmallReduction = false) {
this.run(0, this.first.length, 0, this.second.length, failOnSmallReduction ? 2 : -1);
}
private run(start1: number, count1: number, start2: number, count2: number, thresholdCheckCounter: number) {
if (count1 === 0 && count2 === 0) return;
if (count1 === 0 || count2 === 0) return this.addChange(start1, count1, start2, count2);
let startOffset = 0;
while (
startOffset < Math.min(count1, count2) &&
this.first[start1 + startOffset] === this.second[start2 + startOffset]
)
startOffset++;
start1 += startOffset;
start2 += startOffset;
count1 -= startOffset;
count2 -= startOffset;
let endOffset = 0;
while (
endOffset < Math.min(count1, count2) &&
this.first[start1 + count1 - endOffset - 1] === this.second[start2 + count2 - endOffset - 1]
)
endOffset++;
count1 -= endOffset;
count2 -= endOffset;
if (count1 === 0 || count2 === 0) return this.addChange(start1, count1, start2, count2);
if (thresholdCheckCounter === 0) this.checkReduction(count1, count2);
thresholdCheckCounter = Math.max(-1, thresholdCheckCounter - 1);
const matching = uniqueLCS(this.first, this.second, start1, count1, start2, count2);
if (!matching) {
if (thresholdCheckCounter >= 0) this.checkReduction(count1, count2);
new MyersLCS(
this.first,
this.second,
start1,
count1,
start2,
count2,
this.changes1,
this.changes2,
).executeLinear();
return;
}
const [m1, m2] = matching;
const matched = m1.length;
this.run(start1, m1[0]!, start2, m2[0]!, thresholdCheckCounter);
for (let i = 1; i < matched; i++) {
const s1 = m1[i - 1]! + 1;
const s2 = m2[i - 1]! + 1;
const c1 = m1[i]! - s1;
const c2 = m2[i]! - s2;
if (c1 > 0 || c2 > 0) this.run(start1 + s1, c1, start2 + s2, c2, thresholdCheckCounter);
}
let s1: number, c1: number, s2: number, c2: number;
if (m1[matched - 1] === count1 - 1) [s1, c1] = [count1 - 1, 0];
else [s1, c1] = [m1[matched - 1]! + 1, count1 - m1[matched - 1]! - 1];
if (m2[matched - 1] === count2 - 1) [s2, c2] = [count2 - 1, 0];
else [s2, c2] = [m2[matched - 1]! + 1, count2 - m2[matched - 1]! - 1];
this.run(start1 + s1, c1, start2 + s2, c2, thresholdCheckCounter);
}
private addChange(start1: number, count1: number, start2: number, count2: number) {
fill(this.changes1, start1, start1 + count1);
fill(this.changes2, start2, start2 + count2);
}
private checkReduction(count1: number, count2: number) {
if (count1 * 2 < this.first.length) return;
if (count2 * 2 < this.second.length) return;
throw new FilesTooBig();
}
}
/** Longest increasing run of the elements unique on both sides (UniqueLCS), as relative indexes; null if none. */
function uniqueLCS(
first: Int32Array,
second: Int32Array,
start1: number,
count1: number,
start2: number,
count2: number,
): [Int32Array, Int32Array] | null {
// key -> (offset1 + 1), or -1 when repeated; match: offset1 -> (offset2 + 1)
const map = new Map<number, number>();
const match = new Int32Array(count1);
for (let i = 0; i < count1; i++) {
const key = first[start1 + i]!;
const value = map.get(key) ?? 0;
if (value === -1) continue;
map.set(key, value === 0 ? i + 1 : -1);
}
let count = 0;
for (let i = 0; i < count2; i++) {
const key = second[start2 + i]!;
const value = map.get(key) ?? 0;
if (value === 0 || value === -1) continue;
if (match[value - 1] === 0) {
match[value - 1] = i + 1;
count++;
} else {
match[value - 1] = 0;
map.set(key, -1);
count--;
}
}
if (count === 0) return null;
const sequence = new Int32Array(count);
const lastElement = new Int32Array(count);
const predecessor = new Int32Array(count1);
let length = 0;
for (let i = 0; i < count1; i++) {
const m = match[i]!;
if (m === 0) continue;
// first j with sequence[j] > m (elements are distinct)
let lo = 0;
let hi = length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (sequence[mid]! < m) lo = mid + 1;
else hi = mid;
}
sequence[lo] = m;
lastElement[lo] = i;
predecessor[i] = lo > 0 ? lastElement[lo - 1]! : -1;
if (lo === length) length++;
}
const ret: [Int32Array, Int32Array] = [new Int32Array(length), new Int32Array(length)];
for (let i = length - 1, curr = lastElement[length - 1]!; curr !== -1; i--, curr = predecessor[curr]!) {
ret[0][i] = curr;
ret[1][i] = match[curr]! - 1;
}
return ret;
}
/** Drops elements that can't be matched and maps the result back (Reindexer). */
class Reindexer {
private readonly oldIndices: [Int32Array, Int32Array] = [new Int32Array(0), new Int32Array(0)];
private readonly originalLengths = [-1, -1];
private readonly discardedLengths = [-1, -1];
discardUnique(ints1: Int32Array, ints2: Int32Array): [Int32Array, Int32Array] {
const discarded1 = this.discard(ints2, ints1, 0);
return [discarded1, this.discard(discarded1, ints2, 1)];
}
private discard(needed: Int32Array, toDiscard: Int32Array, arrayIndex: 0 | 1): Int32Array {
this.originalLengths[arrayIndex] = toDiscard.length;
const present = new Set(needed);
const discarded: number[] = [];
const oldIndices: number[] = [];
for (let i = 0; i < toDiscard.length; i++) {
if (present.has(toDiscard[i]!)) {
discarded.push(toDiscard[i]!);
oldIndices.push(i);
}
}
this.oldIndices[arrayIndex] = Int32Array.from(oldIndices);
this.discardedLengths[arrayIndex] = discarded.length;
return Int32Array.from(discarded);
}
reindex(discardedChanges: [Uint8Array, Uint8Array], builder: LCSBuilder) {
const [orig1, orig2] = this.originalLengths as [number, number];
const [disc1, disc2] = this.discardedLengths as [number, number];
const [old1, old2] = this.oldIndices;
let changes1: Uint8Array;
let changes2: Uint8Array;
if (disc1 === orig1 && disc2 === orig2) {
[changes1, changes2] = discardedChanges;
} else {
changes1 = new Uint8Array(orig1);
changes2 = new Uint8Array(orig2);
const increment = (indexes: Int32Array, i: number, set: Uint8Array, length: number) => {
fill(set, indexes[i]! + 1, i + 1 < indexes.length ? indexes[i + 1]! : length);
return i + 1;
};
let x = 0;
let y = 0;
while (x < disc1 || y < disc2) {
if (x < disc1 && y < disc2 && !discardedChanges[0][x] && !discardedChanges[1][y]) {
x = increment(old1, x, changes1, orig1);
y = increment(old2, y, changes2, orig2);
} else if (discardedChanges[0][x]) {
changes1[old1[x]!] = 1;
x = increment(old1, x, changes1, orig1);
} else if (discardedChanges[1][y]) {
changes2[old2[y]!] = 1;
y = increment(old2, y, changes2, orig2);
}
}
fill(changes1, 0, disc1 === 0 ? orig1 : old1[0]!);
fill(changes2, 0, disc2 === 0 ? orig2 : old2[0]!);
}
let x = 0;
let y = 0;
while (x < orig1 && y < orig2) {
const startX = x;
while (x < orig1 && y < orig2 && !changes1[x] && !changes2[y]) {
x++;
y++;
}
if (x > startX) builder.addEqual(x - startX);
let dx = 0;
let dy = 0;
while (x < orig1 && changes1[x]) {
dx++;
x++;
}
while (y < orig2 && changes2[y]) {
dy++;
y++;
}
if (dx !== 0 || dy !== 0) builder.addChange(dx, dy);
}
if (x !== orig1 || y !== orig2) builder.addChange(orig1 - x, orig2 - y);
}
}
+128
Переглянути файл
@@ -0,0 +1,128 @@
/**
* Character classes, whitespace trimming and text equality under a
* comparison policy (IntelliJ's TrimUtil, ComparisonUtil and CharacterUtils,
* ported; Apache-2.0, Copyright JetBrains s.r.o. and contributors).
*/
import { range, type Range } from "./lcs";
export type ComparisonPolicy = "default" | "trim" | "ignore";
/** Whitespace for comparison purposes: space, tab and line break only (Strings.isWhiteSpace). */
export const isSpace = (c: string | undefined) => c === " " || c === "\t" || c === "\n";
const isSpaceCode = (c: number) => c === 32 || c === 9 || c === 10;
/** ASCII punctuation, except `_`. */
export function isPunctuation(c: number): boolean {
if (c === 95) return false;
return (c >= 33 && c <= 47) || (c >= 58 && c <= 64) || (c >= 91 && c <= 96) || (c >= 123 && c <= 126);
}
export const isWhiteSpaceCodePoint = (c: number) => c < 128 && isSpaceCode(c);
export const isAlpha = (c: number) => !isWhiteSpaceCodePoint(c) && !isPunctuation(c);
const DECIMAL_DIGIT = /\p{Nd}/u;
const IDEOGRAPHIC = /\p{Ideographic}/u;
const ALPHABETIC = /\p{Alphabetic}/u;
const SPACELESS_SCRIPT = /[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Javanese}]/u;
/** Characters that are words on their own: CJK, Thai, symbols, anything outside the BMP. */
export function isContinuousScript(c: number): boolean {
if (c < 128) return false;
const s = String.fromCodePoint(c);
if (DECIMAL_DIGIT.test(s)) return false;
if (c > 0xffff) return true;
if (IDEOGRAPHIC.test(s)) return true;
if (!ALPHABETIC.test(s)) return true;
return SPACELESS_SCRIPT.test(s);
}
export const charCount = (codePoint: number) => (codePoint >= 0x10000 ? 2 : 1);
export function trimStart(text: string, start: number, end: number): number {
while (start < end && isSpace(text[start])) start++;
return start;
}
export function trimEnd(text: string, start: number, end: number): number {
while (start < end && isSpace(text[end - 1])) end--;
return end;
}
/** Both sides of a range without their surrounding whitespace. */
export function trimRange(text1: string, text2: string, r: Range): Range {
const start1 = trimStart(text1, r.start1, r.end1);
const start2 = trimStart(text2, r.start2, r.end2);
return range(start1, trimEnd(text1, start1, r.end1), start2, trimEnd(text2, start2, r.end2));
}
/** Shrinks a range by the equal whitespace at both ends (TrimUtil.expandWhitespaces). */
export function expandWhitespaces(text1: string, text2: string, r: Range): Range {
const forward = expandWhitespacesForward(text1, text2, r.start1, r.start2, r.end1, r.end2);
const start1 = r.start1 + forward;
const start2 = r.start2 + forward;
const backward = expandWhitespacesBackward(text1, text2, start1, start2, r.end1, r.end2);
return range(start1, r.end1 - backward, start2, r.end2 - backward);
}
export function expandWhitespacesForward(
text1: string,
text2: string,
start1: number,
start2: number,
end1: number,
end2: number,
): number {
const old = start1;
while (start1 < end1 && start2 < end2 && text1[start1] === text2[start2] && isSpace(text1[start1])) {
start1++;
start2++;
}
return start1 - old;
}
export function expandWhitespacesBackward(
text1: string,
text2: string,
start1: number,
start2: number,
end1: number,
end2: number,
): number {
const old = end1;
while (start1 < end1 && start2 < end2 && text1[end1 - 1] === text2[end2 - 1] && isSpace(text1[end1 - 1])) {
end1--;
end2--;
}
return old - end1;
}
/** The text without whitespace (StringsKmp.equalsIgnoreWhitespaces compares these). */
export const stripSpaces = (s: string) => s.replace(/[ \t\n]+/g, "");
/** The text without surrounding whitespace. */
export function trimSpaces(s: string): string {
const start = trimStart(s, 0, s.length);
return s.slice(start, trimEnd(s, start, s.length));
}
/** A line's identity under a policy: equal keys are equal lines (ComparisonUtil.isEquals). */
export function lineKey(s: string, policy: ComparisonPolicy): string {
return policy === "default" ? s : policy === "trim" ? trimSpaces(s) : stripSpaces(s);
}
/** Texts equal under a policy, trimming every line for "trim" (ComparisonUtil.isEqualTexts). */
export function isEqualTexts(text1: string, text2: string, policy: ComparisonPolicy): boolean {
if (policy === "default") return text1 === text2;
if (policy === "ignore") return stripSpaces(text1) === stripSpaces(text2);
const lines1 = text1.split("\n");
const lines2 = text2.split("\n");
return lines1.length === lines2.length && lines1.every((l, i) => trimSpaces(l) === trimSpaces(lines2[i]!));
}
export const isEqualsRange = (text1: string, text2: string, r: Range) =>
text1.slice(r.start1, r.end1) === text2.slice(r.start2, r.end2);
export const isEqualsIgnoreWhitespacesRange = (text1: string, text2: string, r: Range) =>
stripSpaces(text1.slice(r.start1, r.end1)) === stripSpaces(text2.slice(r.start2, r.end2));
+11 -1
Переглянути файл
@@ -5,7 +5,7 @@
*/
import { StateEffect, StateField, type Extension, type Range } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view";
import { getChunks, type Chunk, type MergeView } from "@codemirror/merge";
import { getChunks, getOriginalDoc, type Chunk, type MergeView } from "@codemirror/merge";
import { iconMarkup } from "@/ui";
import { transferChunk } from "./diffOptions";
@@ -17,6 +17,16 @@ export function applyChunk(mv: MergeView, index: number, source: "a" | "b") {
dst.dispatch({ changes: transferChunk(chunk, source, src.state.doc, dst.state.doc), userEvent: "revert" });
}
/** Reverts a unified change with the same line-boundary handling as the split viewer. */
export function revertUnifiedChunk(view: EditorView, pos: number) {
const chunk = getChunks(view.state)?.chunks.find((c) => c.fromB <= pos && c.endB >= pos);
if (!chunk) return;
view.dispatch({
changes: transferChunk(chunk, "a", getOriginalDoc(view.state), view.state.doc),
userEvent: "revert",
});
}
/** A ">>" / "<<" button; the chunk index comes from the nearest `data-chunk` (itself included). */
export function arrowButton(dir: "a-to-b" | "b-to-a", run: (chunkIndex: number) => void): HTMLButtonElement {
const btn = document.createElement("button");
+109 -133
Переглянути файл
@@ -1,10 +1,12 @@
/**
* Diff viewer settings (IDEA's diff toolbar): viewer kind, whitespace policy,
* highlighting, collapsed unchanged fragments and synchronized scrolling, plus
* the whitespace-ignoring diff algorithm and per-chunk transfer helpers.
* chunks computed by IDEA's comparison and per-chunk transfer helpers.
*/
import { Change, diff, type Chunk } from "@codemirror/merge";
import type { Text } from "@codemirror/state";
import { Change, Chunk, type DiffConfig } from "@codemirror/merge";
import type { ChangeDesc, Text } from "@codemirror/state";
import { compareTexts, type ComparisonPolicy, type LineFragment } from "./comparison";
import { DiffTooBigError } from "./comparison/lcs";
export type DiffMode = "split" | "unified";
export type IgnorePolicy = "none" | "trim" | "whitespace" | "whitespaceAndLines";
@@ -82,151 +84,125 @@ export function saveDiffOptions(o: DiffViewOptions) {
}
}
interface Line {
/** Start offset. */
from: number;
/** End offset including the line break. */
to: number;
key: string;
const IDEA = Symbol("ideaDiff");
interface IdeaDiff {
policy: ComparisonPolicy;
words: boolean;
trimChunks: boolean;
}
function lineKey(text: string, policy: IgnorePolicy): string {
if (policy === "trim") return text.trim();
if (policy === "none") return text;
return text.replace(/\s+/g, "");
}
function splitLines(s: string, policy: IgnorePolicy): Line[] {
const out: Line[] = [];
let from = 0;
for (;;) {
const nl = s.indexOf("\n", from);
const end = nl < 0 ? s.length : nl;
const key = lineKey(s.slice(from, end), policy) + (policy === "none" && nl >= 0 ? "\n" : "");
if (!(policy === "whitespaceAndLines" && key === "")) out.push({ from, to: nl < 0 ? s.length : nl + 1, key });
if (nl < 0) return out;
from = nl + 1;
}
}
/** First char code used to encode lines (skips control chars), and the surrogate gap. */
const BASE = 0x21;
function encoder() {
const codes = new Map<string, string>();
let next = BASE;
return (key: string): string | null => {
let c = codes.get(key);
if (c === undefined) {
if (next === 0xd800) next = 0xe000;
if (next > 0xffff) return null;
c = String.fromCharCode(next++);
codes.set(key, c);
}
return c;
};
}
/** Bounds the expensive diff search; larger inputs fall back to a cheaper, coarser match. */
const DIFF_CONFIG = { scanLimit: 500 };
const COMPARISON_POLICY: Record<IgnorePolicy, ComparisonPolicy> = {
none: "default",
trim: "trim",
whitespace: "ignore",
whitespaceAndLines: "ignore",
};
/**
* Diff of encoded lines (one char per line). Lines that occur exactly once on
* each side anchor the match (patience diff), and only the gaps between the
* anchors get a regular diff, so distant edits in long files stay separate
* without a quadratic search.
* A MergeView `diffConfig` whose chunks come from IDEA's comparison
* (`./comparison`) instead of `@codemirror/merge`'s own diff: lines matched as
* IDEA does, word fragments by IDEA's rules, no merging of nearby changes.
*/
function diffLines(a: string, b: string): Change[] {
const seen = new Map<string, { inA: number; inB: number; at: number }>();
for (let i = 0; i < a.length; i++) {
const e = seen.get(a[i]!);
if (e) e.inA++;
else seen.set(a[i]!, { inA: 1, inB: 0, at: i });
}
for (const c of b) {
const e = seen.get(c);
if (e) e.inB++;
}
// Unique common lines as [indexA, indexB] in A order, then their longest increasing run in B.
const pairs: [number, number][] = [];
for (let j = 0; j < b.length; j++) {
const e = seen.get(b[j]!);
if (e && e.inA === 1 && e.inB === 1) pairs.push([e.at, j]);
}
pairs.sort((x, y) => x[0] - y[0]);
const tails: number[] = [];
const prev = new Array<number>(pairs.length);
for (let i = 0; i < pairs.length; i++) {
let lo = 0;
let hi = tails.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (pairs[tails[mid]!]![1] < pairs[i]![1]) lo = mid + 1;
else hi = mid;
}
prev[i] = lo > 0 ? tails[lo - 1]! : -1;
tails[lo] = i;
}
const anchors: [number, number][] = [];
for (let i = tails.length ? tails[tails.length - 1]! : -1; i >= 0; i = prev[i]!) anchors.push(pairs[i]!);
anchors.reverse().push([a.length, b.length]);
const out: Change[] = [];
let fromA = 0;
let fromB = 0;
for (const [toA, toB] of anchors) {
if (toA > fromA || toB > fromB)
for (const c of diff(a.slice(fromA, toA), b.slice(fromB, toB), DIFF_CONFIG))
out.push(new Change(c.fromA + fromA, c.toA + fromA, c.fromB + fromB, c.toB + fromB));
fromA = toA + 1;
fromB = toB + 1;
}
return out;
export function ideaDiffConfig(ignore: IgnorePolicy, highlight: HighlightPolicy): DiffConfig {
const idea: IdeaDiff = {
policy: COMPARISON_POLICY[ignore],
words: highlight === "words",
trimChunks: ignore === "whitespaceAndLines",
};
const config: DiffConfig = {};
(config as Record<symbol, IdeaDiff>)[IDEA] = idea;
return config;
}
/** The line fragment a chunk was built from. */
const fragments = new WeakMap<Chunk, LineFragment>();
/**
* Match lines first, then compare the contents of changed blocks for word
* highlighting. The line keys also implement the whitespace policy.
* Whether the chunk has IDEA's inner fragments (its words were compared):
* such a chunk gets the lighter line background (TextDiffType "ignored"
* colour) with its `changes` in full colour.
*/
export function whitespaceDiff(policy: IgnorePolicy): (a: string, b: string) => readonly Change[] {
return (a, b) => {
const la = splitLines(a, policy);
const lb = splitLines(b, policy);
const enc = encoder();
const ea: string[] = [];
const eb: string[] = [];
for (const l of la) {
const c = enc(l.key);
if (c === null) return diff(a, b, DIFF_CONFIG);
ea.push(c);
}
for (const l of lb) {
const c = enc(l.key);
if (c === null) return diff(a, b, DIFF_CONFIG);
eb.push(c);
}
const out: Change[] = [];
const at = (lines: Line[], i: number) => (i > 0 ? lines[i - 1]!.to : 0);
for (const c of diffLines(ea.join(""), eb.join(""))) {
const fromA = c.toA > c.fromA ? la[c.fromA]!.from : at(la, c.fromA);
const toA = c.toA > c.fromA ? la[c.toA - 1]!.to : fromA;
const fromB = c.toB > c.fromB ? lb[c.fromB]!.from : at(lb, c.fromB);
const toB = c.toB > c.fromB ? lb[c.toB - 1]!.to : fromB;
if (fromA === toA || fromB === toB) {
out.push(new Change(fromA, toA, fromB, toB));
continue;
}
for (const inner of diff(a.slice(fromA, toA), b.slice(fromB, toB), DIFF_CONFIG))
out.push(new Change(inner.fromA + fromA, inner.toA + fromA, inner.fromB + fromB, inner.toB + fromB));
}
return out;
};
export const hasInnerFragments = (chunk: Chunk) => !!fragments.get(chunk)?.inner;
/** IDEA's line fragments as chunks; `changes` hold the inner fragments, or the whole block. */
export function ideaChunks(a: Text, b: Text, ignore: IgnorePolicy, highlight: HighlightPolicy): readonly Chunk[] {
return toChunks(a, b, ideaOf(ideaDiffConfig(ignore, highlight))!);
}
function toChunks(a: Text, b: Text, idea: IdeaDiff): readonly Chunk[] {
let compared: LineFragment[];
try {
compared = compareTexts(a.toString(), b.toString(), idea);
} catch (error) {
if (!(error instanceof DiffTooBigError)) throw error;
// Repeated lines can exhaust IDEA's search. Keep the viewer usable with a bounded, coarser diff.
return build.call(Chunk, a, b, { scanLimit: 500 });
}
return compared.map((f) => {
// `to` is one past the last line's end, past the document for its last line.
const toA = f.startLine1 === f.endLine1 ? f.startOffset1 : f.endLine1 === a.lines ? a.length + 1 : f.endOffset1;
const toB = f.startLine2 === f.endLine2 ? f.startOffset2 : f.endLine2 === b.lines ? b.length + 1 : f.endOffset2;
const changes = f.inner
? f.inner.map((r) => new Change(r.start1, r.end1, r.start2, r.end2))
: [new Change(0, f.endOffset1 - f.startOffset1, 0, f.endOffset2 - f.startOffset2)];
const chunk = new Chunk(changes, f.startOffset1, toA, f.startOffset2, toB);
fragments.set(chunk, f);
return chunk;
});
}
// Every chunk computation of MergeView and unifiedMergeView goes through these.
const ideaOf = (conf?: DiffConfig) => (conf as Record<symbol, IdeaDiff | undefined> | undefined)?.[IDEA];
const { build, updateA, updateB } = Chunk;
Chunk.build = (a: Text, b: Text, conf?: DiffConfig) => {
const idea = ideaOf(conf);
return idea ? toChunks(a, b, idea) : build.call(Chunk, a, b, conf);
};
Chunk.updateA = (chunks: readonly Chunk[], a: Text, b: Text, changes: ChangeDesc, conf?: DiffConfig) => {
const idea = ideaOf(conf);
return idea ? toChunks(a, b, idea) : updateA.call(Chunk, chunks, a, b, changes, conf);
};
Chunk.updateB = (chunks: readonly Chunk[], a: Text, b: Text, changes: ChangeDesc, conf?: DiffConfig) => {
const idea = ideaOf(conf);
return idea ? toChunks(a, b, idea) : updateB.call(Chunk, chunks, a, b, changes, conf);
};
/** Text of lines `[from, to)` (0-based), without the last line break. */
const linesContent = (doc: Text, from: number, to: number) => doc.sliceString(doc.line(from + 1).from, doc.line(to).to);
/**
* The change that copies a chunk's content from one side to the other
* (IDEA's ">>" / "<<" and Revert), in the destination's coordinates.
* (IDEA's ">>" / "<<" and Revert), in the destination's coordinates. Lines are
* replaced as DiffUtil.applyModification does, so a missing final line break
* stays missing.
*/
export function transferChunk(chunk: Chunk, source: "a" | "b", src: Text, dst: Text) {
const f = fragments.get(chunk);
if (!f) return transferByOffsets(chunk, source, src, dst);
const [srcFrom, srcTo, dstFrom, dstTo] =
source === "a"
? [f.startLine1, f.endLine1, f.startLine2, f.endLine2]
: [f.startLine2, f.endLine2, f.startLine1, f.endLine1];
if (dstFrom === dstTo) {
const text = linesContent(src, srcFrom, srcTo);
return dstFrom === dst.lines
? { from: dst.length, to: dst.length, insert: "\n" + text }
: { from: dst.line(dstFrom + 1).from, to: dst.line(dstFrom + 1).from, insert: text + "\n" };
}
let from = dst.line(dstFrom + 1).from;
let to = dst.line(dstTo).to;
if (srcFrom === srcTo) {
// Lines removed with a line break: the one before them, or else the one after.
if (from > 0) from--;
else if (to < dst.length) to++;
return { from, to, insert: "" };
}
return { from, to, insert: linesContent(src, srcFrom, srcTo) };
}
/** `transferChunk` for chunks not built from line fragments. */
function transferByOffsets(chunk: Chunk, source: "a" | "b", src: Text, dst: Text) {
const [srcFrom, srcTo, dstFrom, dstTo] =
source === "a"
? [chunk.fromA, chunk.toA, chunk.fromB, chunk.toB]
+5 -15
Переглянути файл
@@ -8,7 +8,7 @@
import { RangeSetBuilder, type Extension } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { getChunks, type Chunk, type MergeView } from "@codemirror/merge";
import { changedLineGutters } from "./cm";
import { changedLineGutters, chunkKind, type DiffKind } from "./cm";
import { arrowButton } from "./diffControls";
type Side = "a" | "b";
@@ -91,9 +91,6 @@ export function transferY(bands: readonly Band[], y: number, from: Side): number
return m1 > m0 ? s0 + ((y - m0) * (s1 - s0)) / (m1 - m0) : s0;
}
type ChangeKind = "inserted" | "deleted" | "modified";
const kindOf = (c: Chunk): ChangeKind => (c.fromA === c.toA ? "inserted" : c.fromB === c.toB ? "deleted" : "modified");
/** The divider band between [a0, a1] on the left and [b0, b1] on the right (DiffDrawUtil.makeCurve). */
export function bandPath(w: number, a0: number, a1: number, b0: number, b1: number): string {
// An empty side is a 2px sliver on its boundary.
@@ -104,7 +101,7 @@ export function bandPath(w: number, a0: number, a1: number, b0: number, b1: numb
return `M0 ${a0}C${c1} ${a0} ${c2} ${b0} ${w} ${b0}L${w} ${b1}C${c2} ${b1} ${c1} ${a1} 0 ${a1}Z`;
}
const gapMark = (kind: ChangeKind, end: boolean) =>
const gapMark = (kind: DiffKind, end: boolean) =>
Decoration.line({ class: `cm-diffGap cm-diffGap-${kind}${end ? " cm-diffGapEnd" : ""}` });
/** A line where the other side has lines this one lacks, as in IDEA's empty-side marker. */
@@ -122,7 +119,7 @@ function gapDeco(view: EditorView): DecorationSet {
if (from < vpFrom) continue;
// Past the end of a document without a final line break: below its last line.
const line = doc.lineAt(Math.min(from, doc.length));
builder.add(line.from, line.from, gapMark(kindOf(c), from > doc.length));
builder.add(line.from, line.from, gapMark(chunkKind(c), from > doc.length));
}
return builder.finish();
}
@@ -143,7 +140,6 @@ const gapMarks = ViewPlugin.fromClass(
const SVG = "http://www.w3.org/2000/svg";
const ARROW_HEIGHT = 16;
let gradients = 0;
export interface UnalignedPanesOptions {
/** Scrolling one pane carries the other along. */
@@ -162,7 +158,6 @@ export class UnalignedPanes {
private readonly divider = document.createElement("div");
private readonly svg = document.createElementNS(SVG, "svg");
private readonly bandLayer = document.createElementNS(SVG, "g");
private readonly gradient = `cm-diffBandGradient-${++gradients}`;
private readonly arrowEls = new Map<string, HTMLButtonElement>();
/** Scroll position each pane was last moved to by the other one, to tell its echo from the user. */
private readonly moved: Record<Side, { top: number | null; left: number | null }> = {
@@ -179,10 +174,6 @@ export class UnalignedPanes {
this.extension = [gapMarks, changedLineGutters, EditorView.updateListener.of(() => this.schedule())];
this.divider.className = "cm-diffDivider";
this.svg.setAttribute("aria-hidden", "true");
this.svg.innerHTML =
`<defs><linearGradient id="${this.gradient}" x1="0" x2="1">` +
`<stop offset="0" class="cm-diffBandStopA"/><stop offset="1" class="cm-diffBandStopB"/>` +
`</linearGradient></defs>`;
this.svg.appendChild(this.bandLayer);
this.divider.appendChild(this.svg);
}
@@ -321,12 +312,11 @@ export class UnalignedPanes {
const [b0, b1] = extent(mv.b, c.fromB, c.toB).map((y) => y + offB) as [number, number];
if (a0 > h + 1 && b0 > h + 1) break;
if (a1 < -1 && b1 < -1) continue;
const kind = kindOf(c);
const fill = kind === "modified" ? ` fill="url(#${this.gradient})"` : "";
const kind = chunkKind(c);
const mid = (a0 + a1) / 2;
const midB = (b0 + b1) / 2;
paths +=
`<path class="cm-diffBand cm-diffBand-${kind}"${fill} d="${bandPath(w, a0, a1, b0, b1)}"/>` +
`<path class="cm-diffBand cm-diffBand-${kind}" d="${bandPath(w, a0, a1, b0, b1)}"/>` +
`<path class="cm-diffBandLine cm-diffBand-${kind}" d="M0 ${mid}C${w * 0.3} ${mid} ${w * 0.7} ${midB} ${w} ${midB}"/>`;
if (arrows?.toB) this.placeArrow(shown, i, "a-to-b", arrowTop(a0, a1), h);
if (arrows?.toA) this.placeArrow(shown, i, "b-to-a", arrowTop(b0, b1), h);
+19
Переглянути файл
@@ -0,0 +1,19 @@
/** Project-host ignore writes; shared by the project menu and Find Action. */
import type { IgnoreDestination } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { reloadAll } from "@/features/project-tree/store";
import { runOp } from "./ops";
import { refreshNow } from "./store";
export async function addToIgnore(paths: string[], destination: IgnoreDestination) {
if (!paths.length) return;
await runOp(
destination === "gitignore" ? "Add to .gitignore" : "Add to .git/info/exclude",
async () => {
await call(commands.vcsAddToIgnore(paths, destination));
},
{ refresh: false },
);
// Also refresh after a partial failure in a multi-repository selection.
await Promise.all([refreshNow(), reloadAll()]);
}
+25 -17
Переглянути файл
@@ -318,13 +318,11 @@ export function setLogFilters(patch: Partial<LogFilters>) {
void reloadLog();
}
/** Drops loaded commits and loads the first page. */
export function reloadLog(): Promise<void> {
/** Reloads history, optionally keeping the current view until its replacement arrives. */
export function reloadLog({ preserve = false }: { preserve?: boolean } = {}): Promise<void> {
useGitLog.setState((s) => ({
commits: [],
rows: [],
graph: emptyGraphState(),
done: false,
...(preserve ? {} : { commits: [], rows: [], graph: emptyGraphState(), done: false }),
loading: true,
error: null,
generation: s.generation + 1,
}));
@@ -334,7 +332,7 @@ export function reloadLog(): Promise<void> {
void currentUser().then((user) => {
if (useGitLog.getState().generation === generation) useGitLog.setState({ user });
});
return loadMore();
return loadPage(true);
}
async function loadOutgoing() {
@@ -376,16 +374,21 @@ export function isPushed(id: string): boolean {
}
export function loadMore(): Promise<void> {
return loadPage(false);
}
function loadPage(replace: boolean): Promise<void> {
const s = useGitLog.getState();
if (s.done) return Promise.resolve();
if (!replace && s.done) return Promise.resolve();
if (loadPromise) return loadPromise;
const gen = s.generation;
const f = s.filters;
// Settings › Version Control › Limit history to N rows (file / folder history).
const vcs = workflowSettings().vcs;
const cap = f.path && vcs.limitHistory ? vcs.historyLimit : Infinity;
if (s.commits.length >= cap) {
useGitLog.setState({ done: true });
const loaded = replace ? 0 : s.commits.length;
if (loaded >= cap) {
useGitLog.setState({ done: true, loading: false });
return Promise.resolve();
}
useGitLog.setState({ loading: true });
@@ -402,7 +405,7 @@ export function loadMore(): Promise<void> {
: useVcs.getState().roots.length
? useVcs.getState().roots
: [currentRepo()];
const limit = Math.min(PAGE, cap - s.commits.length);
const limit = Math.min(replace ? Math.max(PAGE, s.commits.length) : PAGE, cap - loaded);
const refs = await branchesByRepo(roots.filter((r): r is string => !!r));
const knownRefs = new Set(
Object.values(refs)
@@ -430,7 +433,7 @@ export function loadMore(): Promise<void> {
textRegex: f.regex,
textMatchCase: f.matchCase,
range: null,
skip: s.commits.filter((c) => commitRepo(c) === repo).length,
skip: replace ? 0 : s.commits.filter((c) => commitRepo(c) === repo).length,
limit,
order: o.sort,
firstParent: o.firstParent,
@@ -455,16 +458,21 @@ export function loadMore(): Promise<void> {
const page = mergeRepoLogs(streams, limit);
const cur = useGitLog.getState();
if (cur.generation !== gen) return;
const { rows, state } = computeGraph(page.map(graphCommit), cur.graph);
if (replace && failures.length === results.length && cur.commits.length) {
useGitLog.setState({ error: failures.join("\n") });
return;
}
const { rows, state } = computeGraph(page.map(graphCommit), replace ? emptyGraphState() : cur.graph);
useGitLog.setState({
commits: cur.commits.concat(page),
rows: cur.rows.concat(rows),
commits: replace ? page : cur.commits.concat(page),
rows: replace ? rows : cur.rows.concat(rows),
graph: state,
done: page.length < PAGE || cur.commits.length + page.length >= cap,
done: page.length < limit || loaded + page.length >= cap,
error: failures.join("\n") || null,
});
} catch (e) {
if (useGitLog.getState().generation === gen) useGitLog.setState({ error: errorMessage(e), done: true });
if (useGitLog.getState().generation === gen)
useGitLog.setState({ error: errorMessage(e), done: replace && s.commits.length ? s.done : true });
} finally {
if (useGitLog.getState().generation === gen) {
useGitLog.setState({ loading: false });
+15 -1
Переглянути файл
@@ -1033,6 +1033,7 @@
"Log filters": "日志筛选器",
"Long tasks": "长任务",
"Looking for references…": "正在查找引用…",
"Finding navigation target…": "正在查找跳转目标…",
"Looks for TODO and FIXME in added lines.": "在新增的行中查找 TODO 和 FIXME。",
"Macros": "宏",
"Main Menu": "主菜单",
@@ -2152,6 +2153,7 @@
"Underscored": "下划线",
"Underwaved": "波浪线",
"Undo": "撤消",
"Unread": "未读",
"Undo Commit": "撤消提交",
"Undo Commit…": "撤消提交…",
"Undo Move / Rename": "撤消移动/重命名",
@@ -3244,6 +3246,7 @@
"Also remove its worktree folder": "同时删除它的 worktree 目录",
"needs input": "等待输入",
"running": "正在运行",
"unread": "未读",
"This agent task no longer exists": "这个 Agent 任务已不存在",
"Local checkout": "当前工作区",
"Needs input": "等待输入",
@@ -4734,5 +4737,16 @@
"Add New Interpreter…": "添加新的解释器…",
"Interpreter Settings…": "解释器设置…",
"Cannot select Python interpreter": "无法选择 Python 解释器",
"Python Interpreter: {label}": "Python 解释器:{label}"
"Python Interpreter: {label}": "Python 解释器:{label}",
"Add to .gitignore": "添加到 .gitignore",
"Add to .git/info/exclude": "添加到 .git/info/exclude",
"Delete Agent Tasks": "删除 Agent 任务",
"Open Agent Task": "打开 Agent 任务",
"Archive Agent Tasks": "归档 Agent 任务",
"Delete {count} agent tasks? Their branches and files outside worktrees are kept.": "是否删除这 {count} 个 Agent 任务?它们的分支及 worktree 以外的文件将保留。",
"Also remove their worktree folders": "同时删除它们的 worktree 目录",
"Cannot delete agent tasks": "无法删除 Agent 任务",
"Cannot archive agent tasks": "无法归档 Agent 任务",
"Archive ({count})": "归档({count})",
"Delete ({count})…": "删除({count})…"
}
+4 -1
Переглянути файл
@@ -18,7 +18,10 @@ describe("remote invoke", () => {
});
it("routes served commands, keeps opening / closing local and sets global settings on both sides", () => {
const served = new Set(["fs_read_dir", "open_project", "close_project", "settings_set"]);
const served = new Set(["vcs_add_to_ignore", "fs_read_dir", "open_project", "close_project", "settings_set"]);
expect(remoteRouting("vcs_add_to_ignore", { paths: ["/remote/file"], destination: "localExclude" }, served)).toBe(
"remote",
);
expect(remoteRouting("fs_read_dir", { path: "/a" }, served)).toBe("remote");
expect(remoteRouting("window_open_settings", {}, served)).toBe("local");
expect(remoteRouting("open_project", { path: "/a" }, served)).toBe("local");
+13
Переглянути файл
@@ -73,6 +73,10 @@ html {
--gutter-modified: #375fad;
--gutter-added: #549159;
--gutter-deleted: #868a91;
/* diff viewer change types (IDEA DIFF_MODIFIED / INSERTED / DELETED) */
--diff-modified: #385570;
--diff-inserted: #294436;
--diff-deleted: #484a4a;
/* coverage (IDEA LINE_FULL / PARTIAL / NONE_COVERAGE), following the theme's status colours */
--coverage-covered: var(--gutter-added);
@@ -448,6 +452,9 @@ html {
--gutter-modified: #88adf7;
--gutter-added: #7fc784;
--gutter-deleted: #767a8a;
--diff-modified: #c2d8f2;
--diff-inserted: #bee6be;
--diff-deleted: #d6d6d6;
/* syntax (Light scheme + Default / Python defaults) */
--syn-keyword: #0033b3;
@@ -699,6 +706,9 @@ html {
--gutter-modified: #6e95e8;
--gutter-added: #6fb875;
--gutter-deleted: #a5a8ae;
--diff-modified: #000099;
--diff-inserted: #00400f;
--diff-deleted: #4d2e08;
--syn-keyword: #e8a885;
--syn-string: #8ccc94;
@@ -976,6 +986,9 @@ html {
--info: var(--palette-blue);
--vcs-modified: var(--palette-blue);
--gutter-modified: var(--palette-blue);
--diff-modified: color-mix(in srgb, var(--palette-blue) 30%, var(--palette-bg));
--diff-inserted: color-mix(in srgb, var(--palette-green) 30%, var(--palette-bg));
--diff-deleted: color-mix(in srgb, var(--palette-fg) 18%, var(--palette-bg));
--syn-link: var(--palette-blue);
--link-hover: var(--palette-cyan);
--danger: var(--palette-red);
+1
Переглянути файл
@@ -267,6 +267,7 @@ export function Tree<T>(props: TreeProps<T>) {
commitSelection(next, row.key);
} else {
const a = anchor != null ? (indexOfKey.get(anchor) ?? i) : leadIndex >= 0 ? leadIndex : i;
setAnchor(rows[a]!.key);
const [s, e] = a < i ? [a, i] : [i, a];
const next = new Set<string>();
for (let j = s; j <= e; j++) if (!rows[j]!.loading) next.add(rows[j]!.key);
+3
Переглянути файл
@@ -63,6 +63,9 @@
"--gutter-modified": "#469e98",
"--gutter-added": "#549159",
"--gutter-deleted": "#75869d",
"--diff-modified": "#2f4f63",
"--diff-inserted": "#294436",
"--diff-deleted": "#43494f",
// Shadows and window controls
"--shadow-popup": "0 6px 20px rgba(0, 0, 0, 0.45)",