Compare commits

..
50 changed files with 402 additions and 1716 deletions

No files matched your search

+1 -1
View File
@@ -51,7 +51,7 @@ async fn run_once(
move || launch.resolve_for_launch_with_copilot_env(&root, strip_ambient)
})
.await
.map_err(|e| e.to_string())??;
.map_err(|e| e.to_string())?;
let cwd = dunce::canonicalize(&root).unwrap_or(root);
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() });
let client = Dialect::wrap(updates.clone());
+11 -28
View File
@@ -132,7 +132,6 @@ pub type McpExecutableFn = dyn Fn() -> Option<PathBuf> + Send + Sync;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct CopilotBinaryKey {
command: String,
github_account: Option<String>,
modified: Option<std::time::SystemTime>,
len: Option<u64>,
}
@@ -194,7 +193,6 @@ impl Shared {
let metadata = std::fs::metadata(&executable).ok();
CopilotBinaryKey {
command: executable.to_string_lossy().into_owned(),
github_account: provider::copilot_github_account(&spec.env),
modified: metadata.as_ref().and_then(|m| m.modified().ok()),
len: metadata.as_ref().map(std::fs::Metadata::len),
}
@@ -1128,16 +1126,6 @@ impl AgentManager {
/// Changes a session setting (model, mode…): right away when the agent runs, else when it next starts.
pub async fn set_config(&self, id: &str, option: &str, value: String) -> IdeResult<()> {
let task = self.task(id)?;
let provider = task.state.lock().task.provider.clone();
let discovered = self
.shared
.paths
.catalogs
.cached(&self.shared, &provider)
.config
.iter()
.find(|o| o.id == option && o.category.as_deref() == Some("model"))
.cloned();
let (target, change) = {
let mut s = task.state.lock();
let busy = s.busy;
@@ -1158,19 +1146,17 @@ impl AgentManager {
task.emit_task();
return Ok(());
}
let session_target = s.task.config.iter().find(|o| o.id == option).cloned();
let recovered_model = session_target.is_none();
let target = match session_target {
Some(target) => target,
None if discovered.is_some() => discovered.unwrap(),
None => return Err(IdeError::not_found("no such setting")),
};
let target = s
.task
.config
.iter()
.find(|o| o.id == option)
.ok_or_else(|| IdeError::not_found("no such setting"))?
.clone();
if s.pending_model.is_some() && config::is_per_model_option(&target) {
return Err(IdeError::invalid("This setting is not available on the selected model"));
}
if recovered_model {
(target, None)
} else if !target.values.iter().any(|v| v.value == value) {
if !target.values.iter().any(|v| v.value == value) {
if target.category.as_deref() != Some("model") {
return Err(IdeError::invalid(format!("{} has no value {value}", target.name)));
}
@@ -2813,12 +2799,9 @@ impl Task {
pending_model: Option<&PendingModel>,
) -> Result<Live, SessionOpenError> {
let launch_cwd = cwd.to_path_buf();
let mut spec = tokio::task::spawn_blocking(move || {
spec.resolve_for_launch_with_copilot_env(&launch_cwd, provider::prefer_stored_copilot_auth())
})
.await
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?
.map_err(|e| SessionOpenError { message: e, allow_acp_fallback: false })?;
let mut spec = tokio::task::spawn_blocking(move || spec.resolve_for_launch(&launch_cwd))
.await
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?;
if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(provider_id) {
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
for name in self.shared.mcp_servers_off_for_session(provider_id, &mcp_overrides) {
+1 -2
View File
@@ -144,8 +144,7 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) ->
move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient)
})
.await
.map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })?
.map_err(|e| DiscoverError { message: e, allow_acp_fallback: false })?;
.map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })?;
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
let args = headless_args(&launch.args);
let peer = Peer::spawn_framed(
+2 -14
View File
@@ -312,7 +312,7 @@ impl Settings {
}
/// Parses `models.list` + optional `models.listTokenPriceUnits` into catalog entries,
/// prepending `"auto"` when direct models are present or Copilot advertises an enabled Auto tier.
/// prepending `"auto"` when not already in the list.
pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<ModelEntry> {
let units = parse_price_units(price_units);
let raw = list
@@ -322,7 +322,7 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
.map(Vec::as_slice)
.unwrap_or_default();
let mut out = Vec::new();
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && (!raw.is_empty() || auto_model_available(list)) {
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && !raw.is_empty() {
out.push(ModelEntry {
id: "auto".into(),
name: "Auto".into(),
@@ -344,18 +344,6 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
out
}
fn auto_model_available(list: &Value) -> bool {
let Some(auto) = list.get("auto") else { return false };
if auto.get("enabled").or_else(|| auto.pointer("/status/enabled")).and_then(Value::as_bool) == Some(false) {
return false;
}
let Some(tiers) = auto.get("tiers").and_then(Value::as_array) else { return auto.is_object() };
tiers.is_empty()
|| tiers.iter().any(|tier| {
tier.get("enabled").or_else(|| tier.pointer("/status/enabled")).and_then(Value::as_bool) != Some(false)
})
}
fn parse_model(m: &Value, units: &HashMap<String, PriceUnit>) -> Option<ModelEntry> {
let id = str_of(m, "id")?.to_owned();
if m.get("model_picker_enabled").and_then(Value::as_bool) == Some(false)
@@ -110,72 +110,6 @@ fn sample_price_units() -> Value {
})
}
#[test]
fn parses_an_enabled_auto_only_catalog() {
let list = json!({
"models": [],
"auto": {
"defaultTier": "balance",
"tiers": [
{
"id": "balance",
"displayName": "Standard",
"type": "auto",
"fusionTier": "standard",
"status": { "enabled": true, "pickerVisible": true }
},
{
"id": "hydrafusion",
"displayName": "High",
"type": "fusion",
"fusionTier": "high",
"status": {
"enabled": false,
"pickerVisible": true,
"reason": "user_not_eligible"
}
},
{
"id": "fast",
"displayName": "Fast",
"type": "auto",
"status": { "enabled": true, "pickerVisible": false }
}
],
"providerId": "copilot"
},
"imageModels": []
});
let catalog = models::parse_catalog(&list, None);
assert_eq!(catalog.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["auto"]);
assert_eq!(Settings::new(&catalog, &UserDefaults::default()).model, "auto");
let options =
config::parse_options(&models::config_options(&catalog, &Settings::new(&catalog, &UserDefaults::default())));
let model = options.iter().find(|option| option.id == MODEL).unwrap();
assert_eq!(model.current.as_deref(), Some("auto"));
assert_eq!(model.values.iter().map(|value| value.value.as_str()).collect::<Vec<_>>(), ["auto"]);
}
#[test]
fn rejects_an_auto_only_catalog_when_every_tier_is_disabled() {
let list = json!({
"models": [],
"auto": {
"defaultTier": "balance",
"tiers": [
{
"id": "balance",
"status": { "enabled": false, "pickerVisible": true }
}
]
}
});
assert!(models::parse_catalog(&list, None).is_empty());
}
#[test]
fn parses_tiered_context_windows_pricing_and_uses_copilots_own_defaults() {
let catalog = models::parse_catalog(&sample_models_list(), Some(&sample_price_units()));
+2 -129
View File
@@ -9,8 +9,6 @@ use serde_json::Value;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
pub(crate) const COPILOT_GITHUB_ACCOUNT_ENV: &str = "OPENIDEA_COPILOT_GITHUB_ACCOUNT";
/// The protocol an agent speaks. Native ones run behind an in-process ACP endpoint
/// (`native`), so tasks see every agent as ACP and read features from its capabilities.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -140,31 +138,15 @@ impl ProviderSpec {
/// Resolve once before connecting, so authentication guidance names that same install.
pub(crate) fn resolve_for_launch(self, cwd: &Path) -> Self {
let strip = prefer_stored_copilot_auth();
self.resolve_for_launch_base(cwd, strip)
self.resolve_for_launch_with_copilot_env(cwd, strip)
}
pub(crate) fn resolve_for_launch_with_copilot_env(
self,
cwd: &Path,
strip_ambient_tokens: bool,
) -> Result<Self, String> {
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
if let Some(account) = account {
let token = github_token_for_account(&account)?;
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
}
Ok(resolved)
}
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
pub(crate) fn resolve_for_launch_with_copilot_env(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
if self.driver != Driver::Acp {
self.command = crate::native::newest_install(&self.command);
}
if is_copilot_provider(&self.id) {
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
}
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
self.command =
@@ -182,50 +164,6 @@ pub(crate) fn is_copilot_provider(id: &str) -> bool {
id == "copilot" || id.starts_with("copilot-")
}
pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String> {
env.iter()
.rev()
.find(|(name, _)| name == COPILOT_GITHUB_ACCOUNT_ENV)
.map(|(_, value)| value.trim())
.filter(|value| !value.is_empty())
.map(str::to_owned)
}
fn github_token_for_account(account: &str) -> Result<String, String> {
let path = ide_core::process::shell_env()
.find(|(name, _)| name == "PATH")
.map(|(_, value)| value)
.or_else(|| ide_core::process::host_var_os("PATH"));
let program = path
.as_deref()
.and_then(|path| ide_core::process::find_executable("gh", path))
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
let mut command = std::process::Command::new(program);
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
for name in AMBIENT_COPILOT_AUTH_VARS {
command.env_remove(name);
}
let output = command
.output()
.map_err(|error| format!("Couldn't read GitHub authentication for account {account}: {error}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let detail = stderr.trim();
return Err(if detail.is_empty() {
format!("GitHub CLI has no authenticated account named {account}")
} else {
format!("Couldn't use GitHub account {account}: {detail}")
});
}
let token = String::from_utf8(output.stdout)
.map_err(|_| format!("GitHub CLI returned a non-text token for account {account}"))?;
let token = token.trim();
if token.is_empty() {
return Err(format!("GitHub CLI returned no token for account {account}"));
}
Ok(token.to_owned())
}
pub(crate) fn prefer_stored_copilot_auth() -> bool {
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
}
@@ -401,31 +339,6 @@ pub(crate) fn set_builtin_env(
id: &str,
env: BTreeMap<String, String>,
) -> IdeResult<()> {
if id == "copilot" {
let file = custom_dir.join("copilot.toml");
if file.try_exists()?
&& let mut agent = CustomAgent::read_with(&file, id, secrets).map_err(IdeError::invalid)?
&& agent.registry.is_some()
{
let existing = agent.env.clone();
let mut existing_launch_env = existing.clone();
let mut next_launch_env = env.clone();
existing_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
next_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
if existing_launch_env != next_launch_env {
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
}
match env.get(COPILOT_GITHUB_ACCOUNT_ENV).filter(|value| !value.trim().is_empty()) {
Some(account) => {
agent.env.insert(COPILOT_GITHUB_ACCOUNT_ENV.into(), account.trim().into());
}
None => {
agent.env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
}
}
return agent.write(&file).map_err(Into::into);
}
}
update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env)
}
@@ -1042,46 +955,6 @@ mod tests {
set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err();
}
#[test]
fn registry_copilot_allows_only_the_github_account_override() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("copilot.toml");
CustomAgent {
name: Some("GitHub Copilot".into()),
driver: Driver::Acp,
command: "/tools/copilot".into(),
args: vec!["--acp".into()],
env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]),
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }),
}
.write(&file)
.unwrap();
set_builtin_env(
dir.path(),
None,
"copilot",
BTreeMap::from([
("REGISTRY_SETTING".into(), "kept".into()),
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
]),
)
.unwrap();
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
.unwrap_err();
}
#[test]
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
let mut spec = builtin_spec("copilot").unwrap();
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
let resolved = spec.resolve_for_launch(Path::new("."));
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
}
#[test]
fn acp_adapters_of_native_agents_are_unlisted_until_customized() {
let dir = tempfile::tempdir().unwrap();
-8
View File
@@ -537,14 +537,6 @@ fn install_entry_with(
return Err(e);
}
};
let github_account = (entry.id == "copilot")
.then(|| CustomAgent::read(&file).ok())
.flatten()
.and_then(|agent| agent.env.get(provider::COPILOT_GITHUB_ACCOUNT_ENV).cloned());
let mut env = env;
if let Some(account) = github_account {
env.insert(provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account);
}
let agent = CustomAgent {
name: Some(entry.name.clone()),
driver: Driver::Acp,
-50
View File
@@ -2333,56 +2333,6 @@ async fn idle_model_switches_discover_controls_and_no_control_models_without_ano
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn session_without_a_model_option_can_select_from_a_recovered_catalog() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.model_options.lock() = HashMap::from([
("big".into(), effort_options(&["low", "high"], "high")),
("small".into(), effort_options(&["minimal", "medium"], "minimal")),
]);
let mgr = manager(tmp.path(), agent);
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude-acp".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let spec = mgr.shared.spec("claude-acp").unwrap();
let (_, flight) = mgr.shared.paths.catalogs.request(&mgr.shared, spec, true, None);
if let Some(mut ready) = flight {
tokio::time::timeout(Duration::from_secs(5), async {
while !*ready.borrow_and_update() {
ready.changed().await.unwrap();
}
})
.await
.unwrap();
}
{
let task = mgr.task(&task.id).unwrap();
let mut state = task.state.lock();
state.task.config.retain(|option| option.category.as_deref() != Some("model"));
state.task.model = Some("stale-model".into());
}
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
let task = mgr.task(&task.id).unwrap();
{
let state = task.state.lock();
assert_eq!(state.task.model.as_deref(), Some("small"));
let model = state.task.config.iter().find(|option| option.category.as_deref() == Some("model")).unwrap();
assert_eq!(model.current.as_deref(), Some("small"));
assert!(model.values.iter().any(|value| value.value == "small"));
}
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn idle_model_discovery_failure_restores_the_previous_choice_without_claiming_no_controls() {
let tmp = tempfile::tempdir().unwrap();
-71
View File
@@ -1,71 +0,0 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("Branch comparison keeps both commit ranges and the diff action visible", async ({ workbench: page }) => {
const branch = "feature/settlement-reconciliation-and-international-ledger-reporting";
const current = "feature/review-quarterly-settlement-audit";
const incomingSubject = "Keep regional settlement references stable during the report export";
const outgoingSubject = "Preserve the audit trail for settlement retries";
await page.setViewportSize({ width: 1120, height: 760 });
await stubDesktop(page);
await page.evaluate(
async ({ branch, current, incomingSubject, outgoingSubject }) => {
const root = "/dev/acme-api";
const branchInfo = {
head: current,
headCommit: "b".repeat(40),
upstream: null,
ahead: 0,
behind: 0,
operation: null,
};
const entry = (letter: string, summary: string) => ({
id: letter.repeat(40),
shortId: letter.repeat(8),
parents: ["a".repeat(40)],
refs: [],
summary,
message: summary + "\n\nUpdate the audit report context.",
author: "Sam Rivera",
email: "[email protected]",
timeMs: 1795100000000,
});
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, ...branchInfo }];
h.vcs_branch_info = () => branchInfo;
h.vcs_status = () => [];
h.vcs_log = ({ query }) =>
(query as { range: string }).range === `HEAD..${branch}`
? [entry("c", incomingSubject)]
: [entry("b", outgoingSubject)];
h.window_open_comparison = () => null;
const store = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ store);
useVcs.setState({ available: true, root, repo: root, roots: [root], branch: branchInfo });
const path = "/src/features/vcs/CompareBranches.tsx";
(await import(/* @vite-ignore */ path)).showCompareBranches(branch);
},
{ branch, current, incomingSubject, outgoingSubject },
);
const dialog = page.getByRole("dialog", { name: new RegExp(`Compare ${current}`) });
await expect(dialog.getByRole("listbox")).toHaveCount(2);
const incoming = dialog.getByRole("listbox", { name: `In ${branch}, not in ${current}` });
const outgoing = dialog.getByRole("listbox", { name: `In ${current}, not in ${branch}` });
await expect(incoming.getByText(incomingSubject, { exact: true })).toBeVisible();
await expect(outgoing.getByText(outgoingSubject, { exact: true })).toBeVisible();
const divider = dialog.getByRole("separator", { name: "Resize branch comparison panes" });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const start = (await divider.boundingBox())!.y;
await divider.focus();
await page.keyboard.press("ArrowDown");
await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThan(start + 1);
await page.setViewportSize({ width: 440, height: 660 });
const heading = dialog.getByRole("heading", { name: new RegExp(`In ${branch}`) });
await expect.poll(() => heading.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(incoming.getByRole("option")).toBeVisible();
await expect(outgoing.getByRole("option")).toBeVisible();
await dialog.getByRole("button", { name: "Show Diff", exact: true }).click();
await expect
.poll(() => ipcCalls(page, "window_open_comparison"))
.toMatchObject([{ comparison: { from: { rev: branch }, to: { rev: "HEAD" }, repo: "/dev/acme-api" } }]);
});
-40
View File
@@ -1,40 +0,0 @@
import { expect, test } from "./fixtures";
test("Color Scheme keeps the preview visible while editing an attribute in narrow Settings", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1120, height: 760 });
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("Language Defaults");
await settings.getByRole("treeitem", { name: "Language Defaults", exact: true }).click();
await search.clear();
const divider = settings.getByRole("separator", { name: "Resize color scheme preview", exact: true });
const tree = settings.getByRole("tree", { name: "Color scheme attributes", exact: true });
const options = settings.getByRole("region", { name: "Color scheme options", exact: true });
const preview = settings.getByLabel("Color scheme preview", { exact: true });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
expect((await tree.boundingBox())!.x).toBeLessThan((await options.boundingBox())!.x);
await page.setViewportSize({ width: 520, height: 660 });
await expect.poll(async () => (await tree.boundingBox())!.y).toBeLessThan((await options.boundingBox())!.y);
const previewTop = (await preview.boundingBox())!.y;
const token = preview.getByText("class", { exact: true }).first();
await token.click();
await expect(tree.getByRole("treeitem", { name: "Keyword", exact: true, selected: true })).toBeVisible();
await options.getByRole("textbox", { name: "Foreground hex", exact: true }).fill("#118899");
await expect(token).toHaveCSS("color", "rgb(17, 136, 153)");
await expect(preview).toBeInViewport();
expect((await preview.boundingBox())!.y).toBeCloseTo(previewTop, 0);
await expect
.poll(() => settings.locator("[class*='pageBody']").evaluate((el) => el.scrollWidth - el.clientWidth))
.toBeLessThanOrEqual(1);
await options.getByRole("checkbox", { name: "Semantic highlighting" }).scrollIntoViewIfNeeded();
expect((await preview.boundingBox())!.y).toBeCloseTo(previewTop, 0);
const before = (await divider.boundingBox())!.y;
await divider.press("ArrowUp");
await expect.poll(async () => (await divider.boundingBox())!.y).toBeLessThan(before - 1);
});
-75
View File
@@ -1,75 +0,0 @@
import { expect, stubDesktop, test } from "./fixtures";
const functionName = "calculateRegionalSettlementFromExternalOrderBeforeReconciliation";
const sourcePath = "/dev/acme-api/build.gradle.kts";
test("keeps frame sources and the keyboard selection visible in a narrow debug dock", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 540 });
await stubDesktop(page);
await page.evaluate(
async ({ functionName, sourcePath }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const servicesModule = "/src/workbench/contributions.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
const { toolWindowService } = await import(/* @vite-ignore */ servicesModule);
const workerFrame = {
id: 51,
name: "processOrder",
path: sourcePath,
line: 5,
column: 0,
presentationHint: null,
};
window.__ipc.handlers.debug_scopes = () => [];
window.__ipc.handlers.debug_stack_trace = () => [workerFrame];
adoptSession(91, {
name: "Reconciliation",
adapter: "debugpy",
status: "paused",
stoppedThread: 1,
selectedThread: 1,
threads: [
{ id: 1, name: "MainThread" },
{ id: 2, name: "Order worker" },
],
selectedFrame: 1,
frames: Array.from({ length: 32 }, (_, index) => ({
id: index + 1,
name: index === 0 ? functionName : index === 1 ? "runBatch" : `reconcile(${index})`,
path: sourcePath,
line: index === 0 ? 41 : index,
column: 0,
presentationHint: null,
})),
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 420);
toolWindowService().show("debug", true);
},
{ functionName, sourcePath },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
const thread = debug.getByRole("button", { name: "Thread", exact: true });
const frames = debug.getByRole("listbox", { name: "Frames", exact: true });
const first = frames.getByRole("option", { selected: true });
await expect(first.getByText(functionName, { exact: true })).toBeVisible();
expect(await frames.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(first.getByText(":42", { exact: true })).toBeInViewport({ ratio: 1 });
expect(await first.getByText(/build\.gradle\.kts/).evaluate((el) => el.clientWidth)).toBeGreaterThan(25);
const shortName = frames.getByText("runBatch", { exact: true });
expect(await shortName.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await frames.focus();
for (let i = 0; i < 25; i++) await page.keyboard.press("ArrowDown");
const selected = frames.getByRole("option", { selected: true });
await expect(selected.getByText("reconcile(25)", { exact: true })).toBeInViewport({ ratio: 0.95 });
expect(await frames.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
await thread.click();
await page.getByRole("option", { name: "Order worker", exact: true }).click();
await expect(thread).toContainText("Order worker");
await expect(frames.getByRole("option", { selected: true })).toContainText("processOrder");
});
-42
View File
@@ -1,42 +0,0 @@
import { expect, test } from "./fixtures";
test("Editor Font keeps the preview in view while editing and resizing the controls", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1200, height: 760 });
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("Show only monospaced fonts");
await settings.getByRole("treeitem", { name: "Font", exact: true, level: 2 }).click();
await search.clear();
const divider = settings.getByRole("separator", { name: "Resize font preview" });
const options = settings.getByRole("region", { name: "Font options", exact: true });
const preview = settings.getByRole("textbox", { name: "Font preview", exact: true });
const font = options.getByRole("combobox", { name: "Font", exact: true });
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
expect((await font.boundingBox())!.x).toBeLessThan((await preview.boundingBox())!.x);
await expect.poll(() => preview.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await preview.fill("function main() { return 42; }");
await options.getByRole("textbox", { name: "Size", exact: true }).fill("18");
await options.getByRole("textbox", { name: "Line height", exact: true }).fill("25");
await expect(preview).toHaveCSS("font-size", "18px");
await expect(preview).toHaveCSS("line-height", "25px");
await page.setViewportSize({ width: 520, height: 620 });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
expect((await font.boundingBox())!.y).toBeLessThan((await preview.boundingBox())!.y);
await expect(preview).toHaveValue("function main() { return 42; }");
const y = (await divider.boundingBox())!.y;
await divider.press("ArrowDown");
await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThan(y + 1);
await search.fill("Fallback font");
const fallback = options.getByRole("combobox", { name: "Fallback font", exact: true });
await fallback.scrollIntoViewIfNeeded();
await expect(fallback).toBeInViewport();
await fallback.fill("Consolas");
await expect(preview).toHaveCSS("font-family", /Consolas/);
await expect(preview).toBeInViewport();
await expect.poll(() => options.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
});
-62
View File
@@ -1,62 +0,0 @@
import { expect, stubDesktop, test } from "./fixtures";
test("File Types keeps association editors usable and opens ignored rules from search", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 760 });
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(settings).toBeVisible();
await stubDesktop(page);
await page.evaluate(() => {
window.__ipc.handlers.languages = () => [
{ id: "javascript", name: "JavaScript", extensions: ["js"] },
{ id: "python", name: "Python", extensions: ["py", "pyi", "pyw"], filenames: ["SConstruct", "SConscript"] },
];
});
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("File Types");
await settings.getByRole("treeitem", { name: "File Types", exact: true }).click();
await search.clear();
const tabs = settings.getByRole("tablist", { name: "File Types" });
const recognized = tabs.getByRole("tab", { name: "Recognized File Types" });
const ignored = tabs.getByRole("tab", { name: "Ignored Files and Folders" });
await expect(recognized).toHaveAttribute("aria-selected", "true");
const divider = settings.getByRole("separator", { name: "Resize file type panes" });
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await page.setViewportSize({ width: 520, height: 660 });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const types = settings.getByRole("listbox", { name: "Recognized file types", exact: true });
await types.getByRole("option", { name: "Python", exact: true }).click();
const patterns = settings.getByRole("listbox", { name: "File name patterns of Python" });
const hashbangLabel = settings.getByText("Hashbang patterns", { exact: true });
await expect
.poll(async () => {
const nameList = await patterns.boundingBox();
const hashbangHeading = await hashbangLabel.boundingBox();
return nameList && hashbangHeading ? hashbangHeading.y - (nameList.y + nameList.height) : -1;
})
.toBeGreaterThan(0);
await expect
.poll(() => settings.locator("[class*='_patterns_']").evaluate((el) => el.scrollWidth - el.clientWidth))
.toBeLessThanOrEqual(1);
const toolbar = settings.locator(`[role="toolbar"][aria-controls="${await patterns.getAttribute("id")}"]`);
await toolbar.getByRole("button", { name: "Add" }).click();
const pattern = patterns.getByRole("textbox", { name: "Pattern" });
await pattern.fill("*.layout-demo");
await pattern.press("Enter");
await expect(patterns.getByRole("option", { name: "*.layout-demo", exact: true })).toBeVisible();
await expect
.poll(() => settings.locator("[class*='pageBody']").evaluate((el) => el.scrollWidth - el.clientWidth))
.toBeLessThanOrEqual(1);
await search.fill("Exclude patterns");
await expect(ignored).toHaveAttribute("aria-selected", "true");
await expect(settings.getByRole("listbox", { name: "Exclude patterns" })).toBeVisible();
await expect(patterns).toBeHidden();
await ignored.click();
await search.clear();
await ignored.press("ArrowLeft");
await expect(recognized).toHaveAttribute("aria-selected", "true");
await expect(patterns.getByRole("option", { name: "*.layout-demo", exact: true })).toBeVisible();
});
-65
View File
@@ -1,65 +0,0 @@
import { expect, openFromTree, test } from "./fixtures";
test("Switcher keeps the open file list and path visible in a narrow workbench", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
await openFromTree(page, "App.tsx");
await page.keyboard.down("Control");
await page.keyboard.press("Tab");
const switcher = page.getByRole("dialog", { name: "Switcher", exact: true });
const files = switcher.getByRole("listbox", { name: "Open files" });
const tools = switcher.getByRole("listbox", { name: "Tool windows" });
const selected = files.getByRole("option", { selected: true });
await expect(selected).toHaveText("README.md");
expect((await switcher.boundingBox())!.width).toBeLessThan(600);
await page.setViewportSize({ width: 400, height: 500 });
await expect.poll(async () => (await files.boundingBox())!.width).toBeGreaterThan(225);
const footer = switcher.locator("footer");
await expect(footer).toHaveText(/README\.md$/);
await expect(footer).toBeInViewport({ ratio: 1 });
await expect(footer).toHaveCSS("font-size", "12px");
expect(await tools.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
expect(await files.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
const structure = tools.getByText("Structure", { exact: true });
expect(await structure.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await page.keyboard.press("Tab");
const activeTool = tools.getByRole("option", { selected: true });
await expect(activeTool).toBeInViewport({ ratio: 1 });
const firstTool = await activeTool.getAttribute("aria-posinset");
await page.keyboard.press("PageDown");
await page.keyboard.press("PageDown");
await expect(activeTool).not.toHaveAttribute("aria-posinset", firstTool!);
await expect(activeTool).toBeInViewport({ ratio: 0.98 });
expect(await tools.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
await page.keyboard.press("Shift+Tab");
await expect(selected).toHaveText("README.md");
await page.keyboard.up("Control");
await expect(switcher).toBeHidden();
await expect(page.getByRole("tab", { name: "README.md", exact: true })).toHaveAttribute("aria-selected", "true");
});
test("Switcher takes up less space when both lists have only a few entries", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
await openFromTree(page, "App.tsx");
await page.evaluate(async () => {
const path = "/src/workbench/contributions.ts";
const { useContributions } = (await import(
/* @vite-ignore */ path
)) as typeof import("../src/workbench/contributions");
useContributions.setState(({ toolWindows }) => ({
toolWindows: new Map([...toolWindows].filter(([id]) => id === "project" || id === "terminal")),
}));
});
await page.keyboard.down("Control");
await page.keyboard.press("Tab");
const switcher = page.getByRole("dialog", { name: "Switcher", exact: true });
const tools = switcher.getByRole("listbox", { name: "Tool windows" });
await expect(tools.getByRole("option")).toHaveCount(2);
await expect.poll(async () => (await switcher.boundingBox())!.height).toBeLessThan(380);
await expect(switcher.locator("footer")).toHaveText(/README\.md$/);
await page.keyboard.press("Escape");
await page.keyboard.up("Control");
});
-5
View File
@@ -394,11 +394,6 @@ describe("language modes", () => {
return found;
}
it("colours Go's `default` branch like the other keywords", async () => {
const support = await loadSupport(findLanguageDescription("Go", "/p/main.go")!);
expect(keywords(support!.language, "switch x {\ncase 1:\ndefault:\n}")).toEqual(["switch", "case", "default"]);
});
it("colours TOML keys as keywords in files, lock files and ```toml code blocks", async () => {
for (const path of ["/p/Cargo.toml", "/p/uv.lock"]) {
const support = await loadSupport(findLanguageDescription("TOML", path)!);
-4
View File
@@ -420,9 +420,6 @@ export const JAVA_TAGS: Parameters<typeof styleTags>[0] = {
this: t.keyword,
};
// @lezer/go leaves `default` uncoloured, unlike `case` and `switch`.
const GO_TAGS: Parameters<typeof styleTags>[0] = { default: t.controlKeyword };
/** Highlighting the stock grammars lack or colour unlike IntelliJ. */
const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
JavaScript: JS_TAGS,
@@ -440,7 +437,6 @@ const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
"MethodDeclaration/Name FunctionDefinition/Name": t.function(t.definition(t.variableName)),
"PropertyDeclaration/VariableDeclarator/VariableName": t.definition(t.propertyName),
},
Go: GO_TAGS,
CSS: CSS_TAGS,
SCSS: CSS_TAGS,
Sass: CSS_TAGS,
+2 -40
View File
@@ -35,10 +35,6 @@ import {
import styles from "./AgentList.module.css";
const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
const COPILOT_GITHUB_ACCOUNT_ENV = "OPENIDEA_COPILOT_GITHUB_ACCOUNT";
const launchEnv = (env: Record<string, string>) =>
Object.fromEntries(Object.entries(env).filter(([name]) => name !== COPILOT_GITHUB_ACCOUNT_ENV));
/** How often the page checks on installs it did not start. */
const BACKGROUND_POLL_MS = 1500;
@@ -823,26 +819,13 @@ function ProviderSettings({
onChanged?.();
return command === agent.defaultProgram ? "" : (command ?? "");
});
const accountBase = agent.env[COPILOT_GITHUB_ACCOUNT_ENV] ?? "";
const account = form.useExternal(`agents.${agent.id}.githubAccount`, accountBase, async (draft) => {
const next = { ...agent.env };
const value = draft.trim();
if (value) next[COPILOT_GITHUB_ACCOUNT_ENV] = value;
else delete next[COPILOT_GITHUB_ACCOUNT_ENV];
await backend.setEnv(agent.id, next);
await refresh();
onChanged?.();
return value;
});
const envBase = formatEnv(launchEnv(agent.env));
const envBase = formatEnv(agent.env);
const env = form.useExternal(`agents.${agent.id}.env`, envBase, async (draft) => {
const parsed = parseEnv(draft);
const account = agent.env[COPILOT_GITHUB_ACCOUNT_ENV];
if (account) parsed[COPILOT_GITHUB_ACCOUNT_ENV] = account;
await backend.setEnv(agent.id, parsed);
await refresh();
onChanged?.();
return formatEnv(launchEnv(parsed));
return formatEnv(parsed);
});
const [error, setError] = useState<string | null>(null);
// An edit can have been staged by a previous page instance. Its Apply callback
@@ -866,27 +849,6 @@ function ProviderSettings({
</Section>
<Section title="Launch">
<div className={styles.form}>
{agent.id === "copilot" && (
<Row
label={<T>GitHub account</T>}
htmlFor={`agent-github-account-${agent.id}`}
hint={
<T>
Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never
stores it.
</T>
}
>
<Input
id={`agent-github-account-${agent.id}`}
mono
value={account.value}
disabled={account.saving}
placeholder="github-username"
onChange={(e) => account.set(e.target.value)}
/>
</Row>
)}
<Row label={<T>Command</T>}>
<code className={styles.launch} title={launch}>
{launch}
+1 -1
View File
@@ -284,7 +284,7 @@ function ModelPicker({
const pinnedModels = useAgents((s) => s.pinnedModels);
const anchor = useRef<HTMLButtonElement>(null);
const selectedModel = selected(model, modelValue);
const unavailable = !!modelRefresh && modelValue !== null && !selectedModel;
const unavailable = modelRefresh?.draft && modelValue !== null && !selectedModel;
const modelName = unavailable
? tx`${modelValue} (unavailable)`
: (selectedModel?.name ?? (modelRefresh ? modelValue : null) ?? tx("Default"));
+2 -34
View File
@@ -469,7 +469,7 @@ describe("Built-in executable overrides", () => {
dispose();
});
const openCommands = async (commands: FakeCommands, onChanged = vi.fn(), name = "Claude Code") => {
const openCommands = async (commands: FakeCommands, onChanged = vi.fn()) => {
const backend = new FakeBackend();
dispose = registerSettingsPage({
id: REGISTRY_PAGE,
@@ -478,7 +478,7 @@ describe("Built-in executable overrides", () => {
component: () => <RegistryPage backend={backend} commandBackend={commands} onChanged={onChanged} />,
});
render(<SettingsDialog />);
return screen.findByRole("region", { name });
return screen.findByRole("region", { name: "Claude Code" });
};
const apply = () => screen.getByRole("button", { name: "Apply" });
const field = () => screen.getByRole("textbox", { name: "Executable" });
@@ -564,38 +564,6 @@ describe("Built-in executable overrides", () => {
expect(commands.savedEnv.at(-1)).toEqual(["claude", {}]);
});
it("writes a Copilot GitHub account without storing a token or exposing the control variable", async () => {
const commands = new FakeCommands();
commands.list = [
{
...claudeProvider("copilot"),
id: "copilot",
name: "GitHub Copilot",
command: "copilot --acp",
defaultProgram: "copilot",
commandReadOnlyReason: "registry",
env: { COPILOT_TELEMETRY_OPTOUT: "1" },
},
];
await openCommands(commands, vi.fn(), "GitHub Copilot");
const account = screen.getByRole("textbox", { name: "GitHub account" });
expect(screen.queryByRole("textbox", { name: "Environment variables" })).toBeNull();
fireEvent.change(account, { target: { value: "dengliu_microsoft" } });
await act(async () => fireEvent.click(apply()));
expect(commands.savedEnv).toEqual([
[
"copilot",
{
COPILOT_TELEMETRY_OPTOUT: "1",
OPENIDEA_COPILOT_GITHUB_ACCOUNT: "dengliu_microsoft",
},
],
]);
expect(JSON.stringify(commands.savedEnv)).not.toMatch(/gho_|ghp_|token/i);
});
it("Cancel discards command edits without writing", async () => {
const commands = new FakeCommands();
commands.list = [
-38
View File
@@ -251,44 +251,6 @@ it("refreshes an existing chat's searchable model choices and switches through i
expect(useAgents.getState().draft).toBe(draft);
});
it("recovers a model picker after a Copilot ACP fallback removed the session option", async () => {
const task: AgentTask = {
id: "fallback-task",
title: "Recovered chat",
provider: "first",
status: "ready",
isolation: "local",
model: "stale-model",
cwd: "/models",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [{ ...option("mode", "mode", ["plan", "act"]), name: "Mode" }],
commands: [],
usage: null,
queue: [],
};
const input = { kind: SESSION_KIND, key: sessionKey(task.id), data: { task: task.id } };
backend.providers[0]!.config = [];
backend.tasks = [task];
backend.activeInput = input;
await connect();
backend.refresh.mockResolvedValueOnce(ok(catalog("first", { config: [option("model", "model", ["auto"])] })));
render(<SessionEditor input={input} />);
const modelButton = screen.getByRole("button", { name: "Model" });
expect(modelButton).toHaveTextContent("stale-model (unavailable)");
fireEvent.click(modelButton);
expect(await screen.findByRole("option", { name: "auto" })).toBeVisible();
fireEvent.click(screen.getByRole("option", { name: "auto" }));
expect(backend.refresh).toHaveBeenCalledWith("first", false, null);
expect(backend.setConfig).toHaveBeenCalledExactlyOnceWith("fallback-task", "model", "auto");
});
it("keeps cached choices usable while refreshing and shares the completion/cooldown from another window", async () => {
backend.refresh.mockImplementation(async (id: string) => ok(catalog(id, { refreshing: true })));
render(<HomeEditor />);
@@ -1,4 +1,4 @@
import type { AgentChange, AgentCommit, AgentConfigOption, AgentEntry, AgentTask } from "@/bindings";
import type { AgentChange, AgentCommit, AgentEntry, AgentTask } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { tx, useTx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
@@ -161,37 +161,18 @@ export function SessionComposer({
const catalog = useAgents((s) => s.modelCatalogs.get(task.provider));
const requestingModels = useAgents((s) => s.modelRequests.has(task.provider));
const model = task.config.find((o) => o.category === "model");
const catalogModel = (catalog?.config ?? provider?.config)?.find((o) => o.category === "model");
const canRefreshModels =
task.status !== "archived" &&
(!!model || !!task.model || !!catalogModel) &&
!!provider?.installed &&
project?.trusted !== false;
const canRefreshModels = task.status !== "archived" && !!model && !!provider?.installed && project?.trusted !== false;
const candidateModels = canRefreshModels
? (catalog?.config ?? provider?.config)?.find((o) => o.category === "model")?.values
: undefined;
const pickerConfig = useMemo(() => {
if (!canRefreshModels) return task.config;
if (!model) {
const recovered: AgentConfigOption =
catalogModel === undefined
? {
id: "model",
name: "Model",
description: null,
category: "model",
current: task.model,
values: [],
via: "option",
}
: { ...catalogModel, current: task.model ?? catalogModel.current };
return [...task.config, recovered];
}
const candidateModels = catalogModel?.values;
if (!candidateModels?.length) return task.config;
if (!model || !candidateModels?.length) return task.config;
const sessionModels = new Set(model.values.map((v) => v.value));
const extra = candidateModels.filter((v) => !sessionModels.has(v.value));
if (!extra.length) return task.config;
const pickerModel = { ...model, values: [...model.values, ...extra] };
return task.config.map((o) => (o === model ? pickerModel : o));
}, [task.config, task.model, model, catalogModel, canRefreshModels]);
}, [task.config, model, candidateModels]);
const [sending, setSending] = useState(false);
const configChange = useRef<{ loadingModel: boolean } | null>(null);
const [configuring, setConfiguring] = useState<typeof configChange.current>(null);
+1 -1
View File
@@ -421,7 +421,7 @@ export async function refreshModels(
export async function refreshTaskModels(id: string, force = true): Promise<void> {
const { tasks, providers } = useAgents.getState();
const task = tasks.get(id);
if (!task || task.status === "archived" || (!task.model && !task.config.some((o) => o.category === "model"))) return;
if (!task || task.status === "archived" || !task.config.some((o) => o.category === "model")) return;
const provider = providers.find((p) => p.id === task.provider);
if (!provider?.installed || useProject.getState().project?.trusted === false) return;
await refreshProviderModels(provider, force, null, null);
@@ -292,7 +292,7 @@ describe("debug tool window", () => {
expect(screen.getByRole("tab", { name: /main/ })).toBeTruthy();
expect(screen.getByRole("tab", { name: "Threads & Variables" })).toBeTruthy();
expect(screen.getByRole("tab", { name: "Console" })).toBeTruthy();
expect(screen.getByRole("option", { selected: true })).toHaveTextContent("main:12, main.py");
expect(screen.getByText(", main.py:12")).toBeTruthy();
expect(screen.getByPlaceholderText("Evaluate expression (↩) or add a watch (⇧⌘↩)")).toBeTruthy();
expect(await screen.findByText("{int}")).toBeTruthy();
expect(screen.getByText("'hi'")).toBeTruthy();
@@ -102,20 +102,11 @@
display: flex;
flex-direction: column;
min-height: 0;
padding-bottom: var(--space-1);
}
.threadHeader {
display: flex;
align-items: center;
flex: none;
height: 30px;
padding: 0 var(--space-1);
border-bottom: 1px solid var(--border);
padding: 4px 0;
}
.threadSelect {
max-width: 100%;
margin: 0 8px 4px;
}
.frameList {
@@ -125,7 +116,7 @@
display: flex;
flex-direction: column;
outline: none;
padding: var(--space-1) var(--space-1) 0;
padding: 0 4px;
}
.frame {
@@ -159,36 +150,24 @@
flex: none;
}
.frameText,
.frameLabel {
display: flex;
align-items: baseline;
min-width: 0;
}
.frameText {
flex: 1;
}
.frameLine {
.frameName {
flex: none;
}
.frameName,
.frameFile {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.frameFile {
flex: 0 1000 auto;
min-width: min(12ch, 32%);
flex: 1;
min-width: 0;
/* ", File.java:12" hugs the name, cancelling the row gap. */
margin-left: -6px;
color: var(--fg-subtle);
font-size: var(--fs-small);
overflow: hidden;
text-overflow: ellipsis;
}
.hiddenFrames {
display: block;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
font-style: italic;
}
+18 -33
View File
@@ -1,6 +1,6 @@
/** Debug tool window: toolbar, Threads & Variables (frames + variables), Console. */
import { writeClipboardText } from "@/platform/clipboard";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { basename, useProject } from "@/platform/project";
@@ -22,7 +22,6 @@ import {
type TabItem,
T,
} from "@/ui";
import { revealVertically } from "@/ui/Tabs";
import { setMuted, useBreakpoints } from "../breakpoints/store";
import { frameLabel, groupFrames } from "../frames";
import { blurDebugView, focusDebugView } from "./focusedView";
@@ -348,15 +347,10 @@ function ThreadsAndVariables({ session }: { session: DebugSession }) {
function FramesPane({ session }: { session: DebugSession }) {
const root = useProject((s) => s.project?.root ?? null);
const [showAll, setShowAll] = useState(false);
const list = useRef<HTMLDivElement>(null);
const selectedRow = useRef<HTMLButtonElement>(null);
const items = useMemo(
() => groupFrames(session.frames, root, session.selectedFrame, showAll),
[session.frames, root, session.selectedFrame, showAll],
);
useLayoutEffect(() => {
if (list.current && selectedRow.current) revealVertically(list.current, selectedRow.current);
}, [items]);
const paused = session.status === "paused";
const onKeyDown = (e: KeyboardEvent) => {
if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
@@ -371,24 +365,19 @@ function FramesPane({ session }: { session: DebugSession }) {
return (
<div className={styles.frames}>
{session.threads.length > 0 && (
<div className={styles.threadHeader}>
<Select
value={session.selectedThread != null ? String(session.selectedThread) : null}
options={session.threads.map((t) => ({
value: String(t.id),
label: t.name,
verbatim: true,
detail: t.id === session.stoppedThread ? "suspended" : undefined,
}))}
onChange={(v) => void selectThread(session.id, +v)}
aria-label="Thread"
variant="ghost"
className={styles.threadSelect}
/>
</div>
<Select
value={session.selectedThread != null ? String(session.selectedThread) : null}
options={session.threads.map((t) => ({
value: String(t.id),
label: t.name,
detail: t.id === session.stoppedThread ? "suspended" : undefined,
}))}
onChange={(v) => void selectThread(session.id, +v)}
aria-label="Thread"
className={styles.threadSelect}
/>
)}
<div
ref={list}
className={styles.frameList}
role="listbox"
aria-label={tx("Frames")}
@@ -426,11 +415,9 @@ function FramesPane({ session }: { session: DebugSession }) {
) : (
<button
key={item.frame.id}
ref={item.frame.id === session.selectedFrame ? selectedRow : undefined}
type="button"
role="option"
aria-selected={item.frame.id === session.selectedFrame}
title={item.frame.path ? `${frameLabel(item.frame)}, ${basename(item.frame.path)}` : item.frame.name}
className={clsx(
styles.frame,
item.frame.id === session.selectedFrame && styles.frameSelected,
@@ -472,15 +459,13 @@ function FramesPane({ session }: { session: DebugSession }) {
}}
>
<Icon name="method" size={16} className={styles.frameIcon} />
<span className={styles.frameText}>
<span className={styles.frameLabel}>
<span className={styles.frameName}>{item.frame.name}</span>
{item.frame.path && item.frame.line >= 0 && (
<span className={styles.frameLine}>:{item.frame.line + 1}</span>
)}
<span className={styles.frameName}>{item.frame.name}</span>
{item.frame.path && (
<span className={styles.frameFile}>
, {basename(item.frame.path)}
{item.frame.line >= 0 ? `:${item.frame.line + 1}` : ""}
</span>
{item.frame.path && <span className={styles.frameFile}>, {basename(item.frame.path)}</span>}
</span>
)}
</button>
),
)}
+1 -1
View File
@@ -265,7 +265,7 @@ function HeaderTable({ headers }: { headers: Array<[string, string]> }) {
export function HttpClientView() {
const history = useHttpClient((s) => s.history);
const selected = useHttpClient((s) => s.selected);
const exchange = useHttpClient((s) => s.exchanges.find((e) => e.entry.id === s.selected));
const exchange = useHttpClient((s) => (s.selected ? s.exchanges[s.selected] : undefined));
const running = useHttpClient((s) => s.running);
useEffect(() => {
void refreshHistory();
@@ -39,11 +39,11 @@ const exchange: HttpExchange = {
};
describe("HTTP response find", () => {
afterEach(() => useHttpClient.setState({ history: [], exchanges: [], selected: null }));
afterEach(() => useHttpClient.setState({ history: [], exchanges: {}, selected: null }));
it("opens a find bar with ⌘F in the response and marks the matches", () => {
Element.prototype.scrollIntoView ??= () => {};
useHttpClient.setState({ history: [exchange.entry], exchanges: [exchange], selected: "e1" });
useHttpClient.setState({ history: [exchange.entry], exchanges: { e1: exchange }, selected: "e1" });
render(<HttpClientView />);
const body = screen.getByLabelText("Response body");
fireEvent.keyDown(body, { key: "f", metaKey: true, ctrlKey: true });
+2 -8
View File
@@ -237,12 +237,6 @@ function annotation(p: Param, name: string): Annotation | undefined {
const isMap = (type: string) =>
/^(java\.util\.)?(Map|MultiValueMap|HttpHeaders|LinkedMultiValueMap|HashMap)\b/.test(type);
/** `name=value` of a `params`/`headers` condition. Only the first "=" divides it: `Accept=text/plain;charset=UTF-8`. */
function condition(cond: string): [name: string, value: string | undefined] {
const at = cond.indexOf("=");
return at < 0 ? [cond, undefined] : [cond.slice(0, at), cond.slice(at + 1)];
}
function endpoint(cls: ClassDecl, method: ClassDecl["methods"][number], c: Constants): Endpoint | null {
const m = mapping(method.annotations);
if (!m) return null;
@@ -273,12 +267,12 @@ function endpoint(cls: ClassDecl, method: ClassDecl["methods"][number], c: Const
}
// `params = "a=1"` / `headers = "X-Api=1"` narrow the mapping: the request must carry them.
for (const cond of [...c.strings(classMapping?.args.get("params")), ...c.strings(m.ann.args.get("params"))]) {
const [name, value] = condition(cond);
const [name, value] = cond.split("=", 2);
if (name && !cond.includes("!") && !query.some((q) => q.name === name.trim()))
query.push({ name: name.trim(), value: value?.trim() ?? null });
}
for (const cond of [...c.strings(classMapping?.args.get("headers")), ...c.strings(m.ann.args.get("headers"))]) {
const [name, value] = condition(cond);
const [name, value] = cond.split("=", 2);
if (name && !cond.includes("!") && value !== undefined) headers.push({ name: name.trim(), value: value.trim() });
}
const first = (key: string) =>
@@ -198,32 +198,6 @@ describe("Spring mappings (Kotlin)", () => {
});
});
describe("mapping conditions", () => {
it("keeps a value that has its own '='", () => {
const [controller] = springControllers(`package demo;
import org.springframework.web.bind.annotation.*;
@RestController
public class ReportController {
@GetMapping(path = "/report", headers = "Accept=text/plain;charset=UTF-8", params = "range=a=b")
public String report() { return ""; }
@PostMapping(path = "/upload", headers = {"Content-Type=multipart/form-data; boundary=xyz", "X-Token=YWJj=="})
public void upload() {}
}
`);
const [report, upload] = controller!.endpoints;
expect(report).toMatchObject({
query: [{ name: "range", value: "a=b" }],
headers: [{ name: "Accept", value: "text/plain;charset=UTF-8" }],
});
expect(upload!.headers).toEqual([
{ name: "Content-Type", value: "multipart/form-data; boundary=xyz" },
{ name: "X-Token", value: "YWJj==" },
]);
});
});
describe("non-controllers", () => {
it("ignores classes that are not controllers and files without any", () => {
expect(springControllers('@Service class A { @GetMapping("/x") void a() {} }')).toEqual([]);
+1 -39
View File
@@ -1,11 +1,10 @@
import { beforeEach, expect, it, vi } from "vitest";
import type { HttpExchange, HttpRequestBlock } from "@/platform/ipc";
import { runAll, runRequest, selectEntry, setEnvironment, useHttpClient } from "./store";
import { runAll, runRequest, setEnvironment, useHttpClient } from "./store";
const backend = vi.hoisted(() => ({
httpEnvironments: vi.fn(),
httpExecute: vi.fn(),
httpHistoryGet: vi.fn(),
httpRequests: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
@@ -96,40 +95,3 @@ it.each(["A", "missing"])("validates the starting choice %s once when environmen
expect(backend.httpExecute).toHaveBeenNthCalledWith(1, expect.any(Number), path, text, 0, environment);
expect(backend.httpExecute).toHaveBeenNthCalledWith(2, expect.any(Number), path, text, 1, environment);
});
function response(id: string): HttpExchange {
return { ...exchange, entry: { ...exchange.entry, id } };
}
it("keeps 100 history rows and the four most recently used exchanges", async () => {
for (let n = 0; n < 101; n++) {
backend.httpExecute.mockResolvedValueOnce(ok(response(String(n))));
await runRequest(null, text, 0);
}
const state = useHttpClient.getState();
expect(state.history).toHaveLength(100);
expect(state.history.at(-1)?.id).toBe("1");
expect(state.exchanges).toHaveLength(4);
await selectEntry("97"); // Touch the oldest resident before opening a cold row.
backend.httpHistoryGet.mockResolvedValueOnce(ok(response("1")));
await selectEntry("1");
await selectEntry("97");
expect(backend.httpHistoryGet.mock.calls).toEqual([["1"]]);
expect(useHttpClient.getState().exchanges.map((e) => e.entry.id)).toEqual(["97", "1", "100", "99"]);
});
it("keeps the latest selection when two cold reads finish out of order", async () => {
let finishFirst!: (result: ReturnType<typeof ok<HttpExchange>>) => void;
const first = new Promise<ReturnType<typeof ok<HttpExchange>>>((resolve) => {
finishFirst = resolve;
});
backend.httpHistoryGet.mockReturnValueOnce(first).mockResolvedValueOnce(ok(response("b")));
const pending = selectEntry("a");
await selectEntry("b");
finishFirst(ok(response("a")));
await pending;
const { selected, exchanges } = useHttpClient.getState();
expect(selected).toBe("b");
expect(exchanges).toEqual([response("b")]);
});
+9 -22
View File
@@ -14,9 +14,6 @@ import { writeClipboardText } from "@/platform/clipboard";
import { editorService, notifications, showServiceView, showStatusInfo } from "@/workbench/contributions";
export const SERVICE_VIEW = "httpClient";
// Same bound as ide_http::history::MAX_ENTRIES. Only recent rows keep their bodies in the UI.
const HISTORY_LIMIT = 100;
const EXCHANGE_LIMIT = 4;
const ENV_KEY = "openidea.httpClient.environments";
function readEnvChoices(): Record<string, string> {
@@ -44,8 +41,8 @@ interface HttpClientState {
environments: Record<string, string[]>;
/** History entries, newest first (this session's runs included). */
history: HttpHistoryEntry[];
/** Loaded exchanges, most recently viewed first. */
exchanges: HttpExchange[];
/** Loaded exchanges by entry id. */
exchanges: Record<string, HttpExchange>;
selected: string | null;
running: Running | null;
}
@@ -54,7 +51,7 @@ export const useHttpClient = create<HttpClientState>(() => ({
envByFile: readEnvChoices(),
environments: {},
history: [],
exchanges: [],
exchanges: {},
selected: null,
running: null,
}));
@@ -99,10 +96,6 @@ function effectiveEnvironment(path: string | null, selection?: string | null): s
return null;
}
function rememberExchange(exchange: HttpExchange, recent: HttpExchange[]) {
return [exchange, ...recent.filter((e) => e.entry.id !== exchange.entry.id)].slice(0, EXCHANGE_LIMIT);
}
export async function refreshHistory() {
try {
const history = await call(commands.httpHistory());
@@ -113,18 +106,12 @@ export async function refreshHistory() {
}
export async function selectEntry(id: string) {
const { exchanges } = useHttpClient.getState();
const cached = exchanges.find((e) => e.entry.id === id);
if (cached) {
useHttpClient.setState({ selected: id, exchanges: rememberExchange(cached, exchanges) });
return;
}
useHttpClient.setState({ selected: id });
if (useHttpClient.getState().exchanges[id]) return;
try {
const ex = await call(commands.httpHistoryGet(id));
useHttpClient.setState((s) => (s.selected === id ? { exchanges: rememberExchange(ex, s.exchanges) } : s));
useHttpClient.setState((s) => ({ exchanges: { ...s.exchanges, [id]: ex } }));
} catch (e) {
if (useHttpClient.getState().selected !== id) return;
notifications().notify({
level: "error",
title: "Cannot open the response",
@@ -135,7 +122,7 @@ export async function selectEntry(id: string) {
export async function clearHistory() {
await call(commands.httpHistoryClear());
useHttpClient.setState({ history: [], exchanges: [], selected: null });
useHttpClient.setState({ history: [], exchanges: {}, selected: null });
}
export function parseRequests(text: string): Promise<HttpRequestBlock[]> {
@@ -172,8 +159,8 @@ export async function runRequest(
const env = batchEnvironment === undefined ? effectiveEnvironment(path) : batchEnvironment;
const ex = await call(commands.httpExecute(request, path, text, index, env));
useHttpClient.setState((s) => ({
history: [ex.entry, ...s.history.filter((h) => h.id !== ex.entry.id)].slice(0, HISTORY_LIMIT),
exchanges: rememberExchange(ex, s.exchanges),
history: [ex.entry, ...s.history.filter((h) => h.id !== ex.entry.id)],
exchanges: { ...s.exchanges, [ex.entry.id]: ex },
selected: ex.entry.id,
}));
return true;
@@ -248,5 +235,5 @@ export function cancelRunning() {
/** The window switched projects: history, responses and environments belong to the previous one. */
export function resetHttpClient() {
cancelRunning();
useHttpClient.setState({ environments: {}, history: [], exchanges: [], selected: null, running: null });
useHttpClient.setState({ environments: {}, history: [], exchanges: {}, selected: null, running: null });
}
@@ -102,20 +102,6 @@
.locations > * {
flex: 1;
}
.switcher {
min-height: min(350px, 80vh);
}
.switcher .columns {
flex: auto;
height: auto;
max-height: 440px;
}
.switcher .tools {
width: clamp(112px, 32%, 184px);
}
.switcher .footer {
font-size: var(--fs-small);
}
.locationsLink {
flex: none;
display: flex;
@@ -281,13 +267,6 @@
.tools .shortcut {
display: none;
}
.switcher .columns {
--list-inset: var(--space-1);
}
.switcher .columns [role="option"] {
gap: var(--space-1);
padding-inline: var(--space-1);
}
.locationsLink {
margin-inline: var(--space-1);
}
+2 -2
View File
@@ -325,9 +325,9 @@ function RecentFilesDialog() {
open
onClose={hideRecentPopup}
restoreFocus={keepFocus}
width={switcher ? 560 : 720}
width={720}
aria-label={title}
className={clsx(styles.dialog, switcher && styles.switcher)}
className={styles.dialog}
>
<header className={styles.header}>
<span className={styles.title}>
@@ -1,35 +1,25 @@
.tabs {
margin-bottom: var(--space-3);
}
.fileTypes {
container: file-types / inline-size;
height: clamp(382px, 67vh, 500px);
display: grid;
grid-template-columns: minmax(180px, 260px) minmax(0, 1fr);
gap: var(--space-3);
min-width: 0;
}
.split {
height: 100%;
}
.types {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
height: 100%;
padding-inline-end: var(--space-2);
min-width: 0;
}
.filter {
flex: none;
width: 100%;
}
.typeList {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
max-height: 420px;
overflow: auto;
padding: 2px 0;
border-radius: var(--radius-small);
@@ -37,12 +27,11 @@
}
.type {
flex: none;
display: flex;
align-items: center;
gap: var(--space-1-5);
height: var(--h-row);
padding: 0 var(--space-2);
padding: 0 8px;
border: none;
background: none;
color: var(--fg);
@@ -76,20 +65,6 @@
flex-direction: column;
gap: var(--space-1);
min-width: 0;
height: 100%;
overflow: auto;
padding-inline-start: var(--space-3);
}
.patterns > .patternRow {
flex: none;
margin-inline: 0;
padding-inline: 0;
}
.patterns [role="listbox"] {
min-height: 72px;
max-height: 128px;
}
.note {
@@ -99,17 +74,10 @@
.code {
font-family: var(--font-mono);
overflow-wrap: anywhere;
}
@container file-types (width < 530px) {
.types {
padding-inline-end: 0;
padding-block-end: var(--space-2);
}
.patterns {
padding-inline-start: 0;
padding-block-start: var(--space-2);
@media (max-width: 640px) {
.fileTypes {
grid-template-columns: minmax(0, 1fr);
}
}
+62 -88
View File
@@ -4,9 +4,9 @@
* user's) and hashbang patterns, stored in `files.fileTypes`. The backend
* detects languages with them; open editors re-detect when they change.
*/
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import clsx from "clsx";
import { Icon, Input, SplitGroup, SplitHandle, SplitPanel, T, fileIconName } from "@/ui";
import { Icon, Input, T, fileIconName } from "@/ui";
import { commands, isTauri, type LanguageInfo_Serialize as LanguageInfo } from "@/platform/ipc";
import {
addPattern,
@@ -52,19 +52,6 @@ export function applyPatternEdit(
}
export function RecognizedFileTypes() {
const desktop = isTauri();
const container = useRef<HTMLDivElement>(null);
const [stacked, setStacked] = useState(true);
useLayoutEffect(() => {
const element = container.current;
if (!element) return;
const measure = () => setStacked(element.clientWidth < 530);
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(element);
return () => observer.disconnect();
}, [desktop]);
const langs = useLanguages();
const [assoc, setAssoc] = useSetting<FileTypeAssociations>("files.fileTypes");
const [filter, setFilter] = useState("");
@@ -81,87 +68,74 @@ export function RecognizedFileTypes() {
}, [langs, filter, assoc]);
// Keep the last explicit choice for when it becomes visible again.
const selected = shown.find((l) => l.id === selectedId) ?? shown[0] ?? null;
if (!desktop) return null;
if (!isTauri()) return null;
const current = assoc ?? {};
const patterns = selected ? effectivePatterns(selected, current).map((p) => p.pattern) : [];
const hashbangs = selected ? (current[selected.id]?.hashbangs ?? []) : [];
return (
<div className={styles.fileTypes} ref={container}>
<SplitGroup orientation={stacked ? "vertical" : "horizontal"} className={styles.split}>
<SplitPanel defaultSize="34%" minSize={stacked ? "106px" : "148px"}>
<div className={styles.types}>
<Input
className={styles.filter}
value={filter}
placeholder="Filter file types"
aria-label="Filter file types"
onChange={(e) => setFilter(e.target.value)}
<div className={styles.fileTypes}>
<div className={styles.types}>
<Input
className={styles.filter}
value={filter}
placeholder="Filter file types"
aria-label="Filter file types"
onChange={(e) => setFilter(e.target.value)}
/>
<div className={styles.typeList} role="listbox" aria-label={tx("Recognized file types")}>
{shown.map((l) => {
const sample = sampleFileName(l);
return (
<button
key={l.id}
type="button"
role="option"
aria-selected={l.id === selected?.id}
className={clsx(styles.type, l.id === selected?.id && styles.typeSelected)}
onClick={() => setSelectedId(l.id)}
>
<Icon name={sample ? fileIconName(sample) : "file-text"} size={16} />
<span className={styles.typeName}>{l.name}</span>
{current[l.id] && (
<span className={styles.modified}>
<T>modified</T>
</span>
)}
</button>
);
})}
</div>
</div>
{selected && (
<div className={styles.patterns} key={selected.id}>
<Row label="File name patterns" stacked hint="* matches any characters, ? one (e.g. *.foo, Jenkinsfile).">
<GlobListEditor
value={patterns}
onChange={(next) => setAssoc(applyPatternEdit(current, langs, selected, next))}
placeholder="*.ext"
aria-label={tx`File name patterns of ${selected.name}`}
/>
<div className={styles.typeList} role="listbox" aria-label={tx("Recognized file types")}>
{shown.map((l) => {
const sample = sampleFileName(l);
return (
<button
key={l.id}
type="button"
role="option"
aria-selected={l.id === selected?.id}
className={clsx(styles.type, l.id === selected?.id && styles.typeSelected)}
onClick={() => setSelectedId(l.id)}
>
<Icon name={sample ? fileIconName(sample) : "file-text"} size={16} />
<span className={styles.typeName}>{l.name}</span>
{current[l.id] && (
<span className={styles.modified}>
<T>modified</T>
</span>
)}
</button>
);
})}
</div>
</div>
</SplitPanel>
<SplitHandle aria-label={tx("Resize file type panes")} />
<SplitPanel defaultSize="66%" minSize={stacked ? "196px" : "190px"}>
{selected && (
<div className={styles.patterns} key={selected.id}>
<Row
className={styles.patternRow}
label="File name patterns"
stacked
hint="* matches any characters, ? one (e.g. *.foo, Jenkinsfile)."
>
<GlobListEditor
value={patterns}
onChange={(next) => setAssoc(applyPatternEdit(current, langs, selected, next))}
placeholder="*.ext"
aria-label={tx`File name patterns of ${selected.name}`}
/>
</Row>
<Row
className={styles.patternRow}
label="Hashbang patterns"
stacked
hint="Interpreters run by a #! first line, e.g. node for #!/usr/bin/env node."
>
<GlobListEditor
value={hashbangs}
onChange={(next) => setAssoc(setHashbangs(current, selected.id, next))}
placeholder="interpreter"
aria-label={tx`Hashbang patterns of ${selected.name}`}
/>
</Row>
{selected.firstLine && (
<div className={styles.note}>
<T>Also recognized by its first line:</T> <code className={styles.code}>{selected.firstLine}</code>
</div>
)}
</Row>
<Row
label="Hashbang patterns"
stacked
hint="Interpreters run by a #! first line, e.g. node for #!/usr/bin/env node."
>
<GlobListEditor
value={hashbangs}
onChange={(next) => setAssoc(setHashbangs(current, selected.id, next))}
placeholder="interpreter"
aria-label={tx`Hashbang patterns of ${selected.name}`}
/>
</Row>
{selected.firstLine && (
<div className={styles.note}>
<T>Also recognized by its first line:</T> <code className={styles.code}>{selected.firstLine}</code>
</div>
)}
</SplitPanel>
</SplitGroup>
</div>
)}
</div>
);
}
+17 -88
View File
@@ -1,14 +1,9 @@
/** Built-in settings pages (IDEA layout: Appearance & Behavior, Keymap, Editor). */
import { useId, useState } from "react";
import { Tabs } from "@/ui";
import { GlobListEditor, Row } from "../components/Form";
import { useSearchQuery, useSetting } from "../components/context";
import { useSetting } from "../components/context";
import { keymapSearchLabels } from "../keymap/model";
import { labelMatches, queryTerms } from "../model/pages";
import { lazyPage } from "./lazyPage";
import { OptionsPage } from "./OptionsPage";
import { specLabels, type PageSpec, type SectionSpec } from "./spec";
import styles from "./FileTypes.module.css";
import type { PageSpec } from "./spec";
export const EDITOR_GROUP = "Editor";
const KeymapPage = lazyPage("keymap", () => import("../keymap/KeymapPage").then((m) => m.KeymapPage));
@@ -43,10 +38,22 @@ function IgnoredNamesRow() {
);
}
const FILE_TYPE_TABS: { id: string; label: string; sections: SectionSpec[] }[] = [
export const BUILTIN_PAGES: PageSpec[] = [
{
id: "recognized",
label: "Recognized File Types",
id: "keymap",
title: "Keymap",
order: 10,
keywords: ["shortcut", "keyboard", "hotkey", "binding", "preset", "vs code", "intellij"],
component: KeymapPage,
dynamicLabels: keymapSearchLabels,
},
{
id: "editor.files",
title: "File Types",
group: EDITOR_GROUP,
order: 29,
projectScope: true,
keywords: ["ignore", "ignored", "excluded", "glob", "exclude patterns", "associate", "association", "extension"],
sections: [
{
title: "Recognized File Types",
@@ -70,12 +77,6 @@ const FILE_TYPE_TABS: { id: string; label: string; sections: SectionSpec[] }[] =
},
],
},
],
},
{
id: "ignored",
label: "Ignored Files and Folders",
sections: [
{
title: "Ignored Files and Folders",
options: [
@@ -86,75 +87,3 @@ const FILE_TYPE_TABS: { id: string; label: string; sections: SectionSpec[] }[] =
],
},
];
const FILE_TYPES: PageSpec = {
id: "editor.files",
title: "File Types",
group: EDITOR_GROUP,
order: 29,
projectScope: true,
keywords: ["ignore", "ignored", "excluded", "glob", "exclude patterns", "associate", "association", "extension"],
sections: FILE_TYPE_TABS.flatMap((tab) => tab.sections),
component: FileTypesPage,
};
function FileTypesPage() {
const prefix = useId();
const query = useSearchQuery();
const [selection, select] = useState({ id: "recognized", query: "" });
let active = selection.id;
if (query !== selection.query) {
const terms = queryTerms(query);
let best = 0;
for (const tab of FILE_TYPE_TABS) {
const labels = specLabels({ ...FILE_TYPES, keywords: [], sections: tab.sections });
const score = terms.filter((term) => labels.some((label) => labelMatches(label, term))).length;
if (score > best) {
best = score;
active = tab.id;
}
}
}
return (
<>
<Tabs
aria-label="File Types"
variant="compact"
layout="wrap"
className={styles.tabs}
items={FILE_TYPE_TABS.map(({ id, label }) => ({ id, label }))}
activeId={active}
panelIdPrefix={prefix}
onSelect={(id) => select({ id, query })}
/>
{FILE_TYPE_TABS.map(({ id, sections }) => (
<div
key={id}
role="tabpanel"
id={`${prefix}-panel-${id}`}
aria-labelledby={`${prefix}-tab-${id}`}
hidden={id !== active}
>
<OptionsPage
spec={{
...FILE_TYPES,
sections: sections.map((section, i) => (i === 0 ? { ...section, title: undefined } : section)),
}}
/>
</div>
))}
</>
);
}
export const BUILTIN_PAGES: PageSpec[] = [
{
id: "keymap",
title: "Keymap",
order: 10,
keywords: ["shortcut", "keyboard", "hotkey", "binding", "preset", "vs code", "intellij"],
component: KeymapPage,
dynamicLabels: keymapSearchLabels,
},
FILE_TYPES,
];
@@ -5,20 +5,8 @@ import { SCHEME_SUBPAGES, languagePageId } from "./colorSchemeMeta";
* italic / effects editor, and a live preview. Edits are staged in
* `editor.colorOverrides[scheme][attribute]`; `editor/core` injects them.
*/
import { useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
import {
Button,
Checkbox,
Icon,
Input,
SplitGroup,
SplitHandle,
SplitPanel,
Tree,
type SelectOption,
type TreeHandle,
T,
} from "@/ui";
import { useEffect, useMemo, useRef, useState, type CSSProperties } from "react";
import { Button, Checkbox, Icon, Input, Tree, type SelectOption, type TreeHandle, T } from "@/ui";
import { fontWeightVars, type CustomColorSchemes, type TextAttributesOverride } from "@/platform/editorSettings";
import {
ATTRIBUTES,
@@ -1380,15 +1368,7 @@ function GitPreview({
);
}
export function ColorSchemePage({
scopes,
landing,
children,
}: {
scopes: readonly string[];
landing?: boolean;
children?: ReactNode;
}) {
export function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landing?: boolean }) {
const translate = useTx();
const [scheme, setScheme] = useSetting<string>("editor.colorScheme", "global");
const [overrides, setOverrides] = useSetting<Overrides>("editor.colorOverrides", "global");
@@ -1600,7 +1580,7 @@ export function ColorSchemePage({
[],
);
return (
<div className={landing ? styles.page : styles.schemePage}>
<div className={styles.page}>
<div className={styles.schemeRow}>
<Row label="Scheme">
<Select value={scheme} options={options} onChange={setScheme} aria-label="Scheme" />
@@ -1651,88 +1631,84 @@ export function ColorSchemePage({
))}
</nav>
) : (
<SplitGroup orientation="vertical" className={styles.schemeSplit}>
<SplitPanel defaultSize="62%" minSize="154px">
<div className={styles.schemeBody} style={baseVars}>
<div className={styles.attrTree}>
<Tree<Node>
aria-label="Color scheme attributes"
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => translate(n.label)}
getChildren={(n) => n.children}
isExpandable={(n) => !!n.children?.length}
expanded={expanded}
onExpandedChange={setExpanded}
handleRef={treeRef}
multiSelect={false}
selected={new Set([selected])}
onSelectionChange={(_s, lead) => lead?.attr && setSelected(lead.attr.id)}
renderNode={(n) => (
<span
className={`${styles.treeLabel} ${(n.attr ? mine?.[n.attr.id] : modifiedKeys.has(n.key)) ? styles.attrModified : ""}`}
>
{translate(n.label)}
</span>
)}
speedSearch
<>
<div className={styles.schemeBody} style={baseVars}>
<div className={styles.attrTree}>
<Tree<Node>
aria-label="Color scheme attributes"
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => translate(n.label)}
getChildren={(n) => n.children}
isExpandable={(n) => !!n.children?.length}
expanded={expanded}
onExpandedChange={setExpanded}
handleRef={treeRef}
multiSelect={false}
selected={new Set([selected])}
onSelectionChange={(_s, lead) => lead?.attr && setSelected(lead.attr.id)}
renderNode={(n) => (
<span
className={`${styles.treeLabel} ${(n.attr ? mine?.[n.attr.id] : modifiedKeys.has(n.key)) ? styles.attrModified : ""}`}
>
{translate(n.label)}
</span>
)}
speedSearch
/>
</div>
{attr ? (
<div className={styles.attrPanel}>
<AttributeEditor
key={`${id}/${attr.id}`}
attr={attr}
inherited={inherited}
value={mine?.[attr.id]}
onChange={(v) => update(attr.id, v)}
/>
</div>
<section className={styles.attrPanel} aria-label={tx("Color scheme options")}>
{attr && (
<AttributeEditor
key={`${id}/${attr.id}`}
attr={attr}
inherited={inherited}
value={mine?.[attr.id]}
onChange={(v) => update(attr.id, v)}
/>
)}
{children && <div className={styles.schemeExtraOptions}>{children}</div>}
</section>
</div>
</SplitPanel>
<SplitHandle aria-label={tx("Resize color scheme preview")} />
<SplitPanel defaultSize="38%" minSize="88px">
{scopes[0] === "Git" ? (
<GitPreview vars={vars} ids={ids} reveal={reveal} />
) : (
<pre className={styles.schemePreview} style={vars} aria-label={tx("Color scheme preview")}>
{sample.code.map((line, i) => (
<div key={i} className={`${styles.previewLine} ${i === sample.caret ? styles.previewCaretLine : ""}`}>
<span className={styles.previewGutter}>{i + 1}</span>
<code>
{line.map(([text, attrId], j) => {
const attr = attrId !== undefined ? A(attrId) : undefined;
const inPage = attr !== undefined && ids.has(attrId!);
return (
<span
key={j}
style={tokenStyle(attr)}
className={attr ? styles.clickable : undefined}
onClick={
attr
? () => {
if (inPage) reveal(attrId!);
else {
crossPageReveal = attrId!;
selectPage(attrPageId(attr));
}
}
: undefined
}
>
{text}
</span>
);
})}
</code>
</div>
))}
</pre>
<div />
)}
</SplitPanel>
</SplitGroup>
</div>
{scopes[0] === "Git" ? (
<GitPreview vars={vars} ids={ids} reveal={reveal} />
) : (
<pre className={styles.schemePreview} style={vars} aria-label={tx("Color scheme preview")}>
{sample.code.map((line, i) => (
<div key={i} className={`${styles.previewLine} ${i === sample.caret ? styles.previewCaretLine : ""}`}>
<span className={styles.previewGutter}>{i + 1}</span>
<code>
{line.map(([text, attrId], j) => {
const attr = attrId !== undefined ? A(attrId) : undefined;
const inPage = attr !== undefined && ids.has(attrId!);
return (
<span
key={j}
style={tokenStyle(attr)}
className={attr ? styles.clickable : undefined}
onClick={
attr
? () => {
if (inPage) reveal(attrId!);
else {
crossPageReveal = attrId!;
selectPage(attrPageId(attr));
}
}
: undefined
}
>
{text}
</span>
);
})}
</code>
</div>
))}
</pre>
)}
</>
)}
</div>
);
@@ -121,24 +121,6 @@
}
/* Font page */
.fontPage {
height: 100%;
min-height: 240px;
min-width: 0;
overflow: hidden;
border: 1px solid var(--border);
border-radius: var(--radius-small);
}
.fontSplit {
height: 100%;
}
.fontOptions {
container: font-options / inline-size;
height: 100%;
min-height: 0;
overflow-y: auto;
padding: var(--space-2) var(--space-3) var(--space-3);
}
.fontFamily {
display: flex;
align-items: center;
@@ -146,51 +128,29 @@
gap: var(--space-2);
min-width: 0;
}
.fontSelect,
.fontWeight {
.fontSelect {
width: 240px;
max-width: 100%;
}
@container font-options (max-width: 380px) {
.fontRow {
display: flex;
flex-direction: column;
align-items: stretch;
gap: var(--space-1);
margin-bottom: var(--space-1);
}
.fontRow > label {
padding-top: 0;
overflow-wrap: anywhere;
white-space: normal;
}
}
.previewTitle {
flex: none;
padding: var(--space-1) var(--space-3);
border-bottom: 1px solid var(--border);
color: var(--fg-secondary);
font-size: var(--fs-small);
margin: 18px 0 6px;
color: var(--fg-strong);
}
.previewArea {
flex: 1;
font-weight: var(--fw-code);
width: 100%;
min-height: 0;
resize: none;
min-height: 240px;
resize: vertical;
box-sizing: border-box;
padding: var(--space-2) var(--space-3);
padding: 8px 10px;
border: none;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border-strong);
background: var(--bg-editor, var(--bg-island));
color: var(--fg-editor, var(--fg));
white-space: pre-wrap;
overflow-wrap: anywhere;
white-space: pre;
outline: none;
}
.previewArea:focus-visible {
outline: 1px solid var(--focus-ring);
outline-offset: -1px;
}
/* Color Scheme page */
.schemeRow {
@@ -223,38 +183,13 @@
}
.schemeBody {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 280px);
gap: var(--space-2);
height: 100%;
min-height: 0;
padding-bottom: var(--space-2);
}
.schemePage {
display: flex;
flex-direction: column;
height: 100%;
min-height: 340px;
min-width: 0;
}
.schemeSplit {
flex: 1;
}
.schemePage > :not(.schemeSplit) {
flex: none;
}
.schemeExtraOptions {
margin-top: var(--space-4);
}
@container settings-content (max-width: 610px) {
.schemeBody {
grid-template-columns: minmax(0, 1fr);
grid-template-rows: minmax(72px, 2fr) minmax(0, 3fr);
}
grid-template-columns: minmax(180px, 1fr) minmax(220px, 260px);
gap: 14px;
min-height: 320px;
}
.attrTree {
min-height: 0;
min-width: 0;
overflow: hidden;
max-height: 360px;
overflow: auto;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border-strong);
padding: 2px 0;
@@ -272,9 +207,9 @@
box-shadow: inset 0 0 0 1px var(--border-strong);
border-radius: var(--radius-small);
padding: 10px;
min-width: 0;
min-height: 0;
align-self: start;
overflow: auto;
max-height: 360px;
}
.attrEditor {
display: flex;
@@ -284,7 +219,6 @@
.attrRow {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-2);
min-height: 28px;
}
@@ -300,7 +234,7 @@
}
.swatchInput {
flex: 1 1 90px;
min-width: min(90px, 100%);
min-width: 90px;
}
.colorBox {
position: relative;
@@ -324,9 +258,7 @@
font-size: var(--fs-small);
}
.schemePreview {
flex: 1;
min-height: 0;
margin: var(--space-2) 0 0;
margin: 14px 0 0;
padding: 8px 0;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border-strong);
@@ -337,6 +269,7 @@
font-size: var(--fs-code);
line-height: var(--lh-code);
overflow: auto;
max-height: 260px;
}
.previewLine {
display: flex;
@@ -365,13 +298,12 @@
/* Git preview mirrors the two real surfaces: the editor inline blame widget and
the project tree root branch suffix. Only the Git page uses these. */
.gitPreview {
flex: 1;
min-height: 0;
margin: var(--space-2) 0 0;
margin: 14px 0 0;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border-strong);
background: var(--bg-editor, var(--bg-island));
overflow: auto;
max-height: 260px;
}
.gitSection {
padding: 8px 0;
@@ -2,34 +2,24 @@ import { ATTRIBUTES, SCHEMES } from "@/platform/colorScheme";
import { lazyPage } from "../lazyPage";
import type { PageSpec } from "../spec";
import { LANGUAGES, SCHEME_SUBPAGES, languagePageId } from "./colorSchemeMeta";
import { editorPage, EditorSections, sectionLabels, type EditorSection } from "./kit";
import { editorPage } from "./kit";
const ALL_COLOR_SCHEME_PAGE_IDS = ["editor.colorScheme", ...SCHEME_SUBPAGES.map((p) => p.id)];
const LazyColorSchemePage = lazyPage(ALL_COLOR_SCHEME_PAGE_IDS, () =>
import("./ColorSchemeBody").then((m) => m.ColorSchemePage),
);
function colorSchemePage(
spec: Pick<PageSpec, "id" | "title" | "order" | "keywords">,
scope: string,
extraSections: EditorSection[] = [],
): PageSpec {
const scopes = [scope];
const labels = [
"Scheme",
...ATTRIBUTES.filter((a) => a.path[0] === scope).map((a) => a.name),
...sectionLabels(extraSections),
];
/** The scope chooser, import/export buttons and preview are identical on every sub-page. */
function colorSchemeSection(scopes: readonly string[]) {
return {
...spec,
group: "Editor",
projectScope: false,
dynamicLabels: () => labels,
component: () => (
<LazyColorSchemePage scopes={scopes}>
{extraSections.length > 0 && <EditorSections sections={extraSections} />}
</LazyColorSchemePage>
),
items: [
{
t: "custom" as const,
label: "Scheme",
keywords: ATTRIBUTES.filter((a) => scopes.includes(a.path[0]!)).map((a) => a.name),
component: () => <LazyColorSchemePage scopes={scopes} />,
},
],
};
}
@@ -65,23 +55,22 @@ const COLOR_SCHEME_PAGE = editorPage({
/** JetBrains layout: scopes and languages live in the settings tree under Color Scheme, one page each. */
export const COLOR_SCHEME_PAGES: PageSpec[] = [
COLOR_SCHEME_PAGE,
colorSchemePage(
{
id: "editor.colorScheme.general",
title: "General",
order: 1,
},
"General",
),
colorSchemePage(
{
id: "editor.colorScheme.language-defaults",
title: "Language Defaults",
order: 2,
keywords: ["semantic highlighting", "rainbow"],
},
"Language Defaults",
[
editorPage({
id: "editor.colorScheme.general",
title: "General",
order: 1,
projectScope: false,
keywords: ATTRIBUTES.filter((a) => a.path[0] === "General").map((a) => a.name),
sections: [colorSchemeSection(["General"])],
}),
editorPage({
id: "editor.colorScheme.language-defaults",
title: "Language Defaults",
order: 2,
projectScope: false,
keywords: ["semantic highlighting", "rainbow"],
sections: [
colorSchemeSection(["Language Defaults"]),
{
title: "Language Defaults",
items: [
@@ -112,42 +101,39 @@ export const COLOR_SCHEME_PAGES: PageSpec[] = [
],
},
],
),
colorSchemePage(
{
id: "editor.colorScheme.debugger",
title: "Debugger",
order: 3,
keywords: ["breakpoint", "inline values"],
},
"Debugger",
),
colorSchemePage(
{
id: "editor.colorScheme.console-colors",
title: "Console Colors",
order: 4,
keywords: ["terminal", "ansi", "console", "background"],
},
"Console Colors",
),
colorSchemePage(
{
id: "editor.colorScheme.git",
title: "Git",
order: 5,
keywords: ["git", "blame", "branch", "inline blame", "project view", "decoration"],
},
"Git",
),
}),
editorPage({
id: "editor.colorScheme.debugger",
title: "Debugger",
order: 3,
projectScope: false,
keywords: ["breakpoint", "inline values"],
sections: [colorSchemeSection(["Debugger"])],
}),
editorPage({
id: "editor.colorScheme.console-colors",
title: "Console Colors",
order: 4,
projectScope: false,
keywords: ["terminal", "ansi", "console", "background"],
sections: [colorSchemeSection(["Console Colors"])],
}),
editorPage({
id: "editor.colorScheme.git",
title: "Git",
order: 5,
projectScope: false,
keywords: ["git", "blame", "branch", "inline blame", "project view", "decoration"],
sections: [colorSchemeSection(["Git"])],
}),
...LANGUAGES.map((language, i) =>
colorSchemePage(
{
id: languagePageId(language),
title: language,
order: 6 + i,
},
language,
),
editorPage({
id: languagePageId(language),
title: language,
order: 6 + i,
projectScope: false,
keywords: ATTRIBUTES.filter((a) => a.path[0] === language).map((a) => a.name),
sections: [colorSchemeSection([language])],
}),
),
];
+29 -74
View File
@@ -4,15 +4,14 @@
*/
import { FontPicker } from "../../components/FontPicker";
import { useId, useLayoutEffect, useRef, useState } from "react";
import { Checkbox, type SelectOption, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui";
import { useId, useState } from "react";
import { Checkbox, type SelectOption, T } from "@/ui";
import { monoFontFamily } from "@/platform/fonts";
import { NumberInput, Row, SearchLabel, Select } from "../../components/Form";
import { useLabelMatch, usePageContext, useSetting } from "../../components/context";
import { FONT_WEIGHTS, fontWeightOf, fontWeightVars } from "@/platform/editorSettings";
import { LIMITS } from "../../model/schema";
import type { PageSpec } from "../spec";
import { EditorSections, type EditorSection, sectionLabels } from "./kit";
import { editorPage } from "./kit";
import styles from "./Editor.module.css";
import { tx } from "@/platform/i18n";
@@ -21,12 +20,11 @@ function FontRow() {
const [monoSetting, setMonoOnly] = useSetting<boolean>("editor.onlyMonospacedFonts");
const monoOnly = monoSetting !== false;
const matched = useLabelMatch("Show only monospaced fonts");
const id = useId();
return (
<Row label="Font" htmlFor={id} className={styles.fontRow}>
<Row label="Font">
<span className={styles.fontFamily}>
<span className={styles.fontSelect}>
<FontPicker id={id} value={family} onChange={setFamily} label="Font" monoOnly={monoOnly} />
<FontPicker value={family} onChange={setFamily} label="Font" monoOnly={monoOnly} />
</span>
<span className={matched ? styles.matched : undefined}>
<Checkbox
@@ -43,11 +41,10 @@ function FontRow() {
function SizeRow() {
const [size, setSize] = useSetting<number>("editor.fontSize");
const [line, setLine] = useSetting<number>("editor.lineHeight");
const sizeId = useId();
const lineId = useId();
return (
<Row label="Size" htmlFor={sizeId} className={styles.fontRow}>
<NumberInput id={sizeId} value={size} onChange={setSize} {...LIMITS.fontSize} aria-label="Size" unit="px" />
<Row label="Size">
<NumberInput value={size} onChange={setSize} {...LIMITS.fontSize} aria-label="Size" unit="px" />
<span className={styles.inline}>
<label htmlFor={lineId} className={styles.inlineLabel}>
<SearchLabel text="Line height" />
@@ -67,17 +64,9 @@ function SizeRow() {
function FallbackRow() {
const [fallback, setFallback] = useSetting<string>("editor.fallbackFont");
const id = useId();
return (
<Row
label="Fallback font"
htmlFor={id}
hint="For symbols not supported by the main font"
className={styles.fontRow}
>
<span className={styles.fontSelect}>
<FontPicker id={id} value={fallback} onChange={setFallback} label="Fallback font" allowEmpty />
</span>
<Row label="Fallback font" hint="For symbols not supported by the main font">
<FontPicker value={fallback} onChange={setFallback} label="Fallback font" allowEmpty />
</Row>
);
}
@@ -104,9 +93,8 @@ function WeightRow({
const weight = fontWeightOf(value, defaultWeight);
const custom = customSelected || !FONT_WEIGHTS.some(([w]) => w === weight);
return (
<Row label={label} hint={hint} className={styles.fontRow}>
<Row label={label} hint={hint}>
<Select
className={styles.fontWeight}
value={custom ? "custom" : String(weight)}
options={WEIGHT_OPTIONS}
onChange={(v) => {
@@ -199,60 +187,27 @@ function Preview() {
);
}
const FONT_SECTIONS: EditorSection[] = [
{
items: [
{ t: "custom", label: "Font", keywords: ["font family", "Show only monospaced fonts"], component: FontRow },
{ t: "custom", label: "Size", keywords: ["Line height"], component: SizeRow },
{ t: "check", key: "editor.ligatures", label: "Enable ligatures" },
],
},
{
title: "Typography Settings",
items: [
{ t: "custom", label: "Main font weight", keywords: ["Bold font weight"], component: WeightRows },
{ t: "custom", label: "Fallback font", component: FallbackRow },
],
},
];
function FontPage() {
const page = useRef<HTMLDivElement>(null);
const [stacked, setStacked] = useState(true);
useLayoutEffect(() => {
const el = page.current;
if (!el) return;
const measure = () => setStacked(el.clientWidth < 620);
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(el);
return () => observer.disconnect();
}, []);
return (
<div className={styles.fontPage} ref={page}>
<SplitGroup orientation={stacked ? "vertical" : "horizontal"} className={styles.fontSplit}>
<SplitPanel defaultSize={stacked ? "52%" : "45%"} minSize={stacked ? "96px" : "220px"}>
<section className={styles.fontOptions} aria-label={tx("Font options")}>
<EditorSections sections={FONT_SECTIONS} />
</section>
</SplitPanel>
<SplitHandle aria-label={tx("Resize font preview")} />
<SplitPanel defaultSize={stacked ? "48%" : "55%"} minSize={stacked ? "96px" : "200px"}>
<Preview />
</SplitPanel>
</SplitGroup>
</div>
);
}
export const FONT_PAGE: PageSpec = {
export const FONT_PAGE = editorPage({
id: "editor.font",
title: "Font",
group: "Editor",
order: 22,
projectScope: true,
keywords: ["typeface", "monospace", "ligatures", "font size", "line spacing", "font weight", "bold"],
component: FontPage,
dynamicLabels: () => sectionLabels(FONT_SECTIONS),
};
sections: [
{
items: [
{ t: "custom", label: "Font", keywords: ["font family", "Show only monospaced fonts"], component: FontRow },
{ t: "custom", label: "Size", keywords: ["Line height"], component: SizeRow },
{ t: "check", key: "editor.ligatures", label: "Enable ligatures" },
],
},
{
title: "Typography Settings",
items: [
{ t: "custom", label: "Main font weight", keywords: ["Bold font weight"], component: WeightRows },
{ t: "custom", label: "Fallback font", component: FallbackRow },
],
},
],
footer: Preview,
});
@@ -1,81 +0,0 @@
.dialog {
height: min(540px, calc(100vh - 48px));
}
.ranges {
flex: 1;
min-height: 0;
}
.range,
.list {
display: flex;
flex-direction: column;
min-height: 0;
}
.range {
height: 100%;
}
.list {
flex: 1;
}
.rangeHeader {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: var(--space-2);
padding: var(--space-2) var(--space-3);
border-bottom: 1px solid var(--border-strong);
background: var(--bg-elev);
}
.rangeHeader h3 {
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
font-size: var(--fs-ui);
font-weight: 500;
}
.count,
.metadata {
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.count {
font-variant-numeric: tabular-nums;
}
.commit {
display: flex;
flex: 1;
flex-direction: column;
gap: var(--space-0-5);
min-width: 0;
}
.subject,
.author {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.metadata {
display: flex;
align-items: baseline;
gap: var(--space-2);
}
.date {
flex-shrink: 0;
}
.error {
padding: var(--space-3);
overflow-wrap: anywhere;
}
+41 -70
View File
@@ -3,13 +3,12 @@ import { useEffect, useState } from "react";
import type { Commit } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { Dialog, List, Spinner, SplitGroup, SplitHandle, SplitPanel, T, tooltipAttrs } from "@/ui";
import { Dialog, List, Spinner, Tabs, T, tooltipAttrs } from "@/ui";
import { openDialog } from "./dialogs";
import { formatTime } from "./model";
import { showCompareRevisions } from "./operations";
import { currentRepo, useVcs } from "./store";
import styles from "./common.module.css";
import compareStyles from "./CompareBranches.module.css";
import { tx } from "@/platform/i18n";
import { useRowHeight } from "@/ui/density";
@@ -70,18 +69,16 @@ function RangeDialog(props: { title: string; from: string; to: string; repo: str
function CommitList({
commits,
error = null,
rangeLabel,
error,
onClose,
}: {
commits: Commit[] | null;
error?: string | null;
rangeLabel?: string;
error: string | null;
onClose: () => void;
}) {
const rowHeight = useRowHeight(rangeLabel ? 42 : 22);
const rowHeight = useRowHeight(22);
return (
<div className={rangeLabel ? compareStyles.list : styles.commitListBody}>
<div className={styles.commitListBody}>
{error ? (
<div className={styles.error} style={{ padding: 14 }}>
{error}
@@ -95,7 +92,7 @@ function CommitList({
items={commits}
getKey={(c) => c.id}
rowHeight={rowHeight}
aria-label={rangeLabel ?? "Commits"}
aria-label="Commits"
className={styles.grow}
empty={
<span>
@@ -106,53 +103,27 @@ function CommitList({
onClose();
void executeAction("vcs.showCommit", c);
}}
renderItem={(c) =>
rangeLabel ? (
<div className={compareStyles.commit}>
<span className={compareStyles.subject} {...tooltipAttrs(c.message || c.summary, undefined, true)}>
{c.summary}
</span>
<div className={compareStyles.metadata}>
<span className={styles.commitHash}>{c.shortId}</span>
<span className={compareStyles.author}>{c.author}</span>
<span className={compareStyles.date}>{formatTime(c.timeMs)}</span>
</div>
</div>
) : (
<span className={styles.commitRow} style={{ flex: 1, minWidth: 0, padding: 0 }}>
<span className={styles.commitHash}>{c.shortId}</span>
<span className={styles.commitSubject} {...tooltipAttrs(c.message || c.summary, undefined, true)}>
{c.summary}
</span>
<span className={styles.commitMeta}>{c.author}</span>
<span className={styles.commitMeta}>{formatTime(c.timeMs)}</span>
renderItem={(c) => (
<span className={styles.commitRow} style={{ flex: 1, minWidth: 0, padding: 0 }}>
<span className={styles.commitHash}>{c.shortId}</span>
<span className={styles.commitSubject} {...tooltipAttrs(c.message || c.summary, undefined, true)}>
{c.summary}
</span>
)
}
<span className={styles.commitMeta}>{c.author}</span>
<span className={styles.commitMeta}>{formatTime(c.timeMs)}</span>
</span>
)}
/>
)}
</div>
);
}
function CompareRange({ label, commits, onClose }: { label: string; commits: Commit[] | null; onClose: () => void }) {
return (
<SplitPanel defaultSize="50%" minSize="25%">
<div className={compareStyles.range}>
<div className={compareStyles.rangeHeader}>
<h3>{label}</h3>
{commits && <span className={compareStyles.count}>{commits.length}</span>}
</div>
<CommitList rangeLabel={label} commits={commits} onClose={onClose} />
</div>
</SplitPanel>
);
}
function CompareDialog({ branch, current, onClose }: { branch: string; current: string; onClose: () => void }) {
const [repo] = useState(currentRepo);
const [data, setData] = useState<{ incoming: Commit[]; outgoing: Commit[] } | null>(null);
const [error, setError] = useState<string | null>(null);
const [tab, setTab] = useState("incoming");
useEffect(() => {
let alive = true;
Promise.all([commitsBetween("HEAD", branch, repo), commitsBetween(branch, "HEAD", repo)])
@@ -163,17 +134,17 @@ function CompareDialog({ branch, current, onClose }: { branch: string; current:
return () => {
alive = false;
};
}, [branch, repo]);
}, [branch]);
const list = data ? (tab === "incoming" ? data.incoming : data.outgoing) : [];
return (
<Dialog
open
title={tx`Compare ${current} with ${branch}`}
onClose={onClose}
width={800}
minWidth={360}
minHeight={360}
width={640}
minWidth={420}
resizable="both"
className={`${styles.listDialog} ${compareStyles.dialog}`}
className={styles.listDialog}
buttons={[
{
label: "Show Diff",
@@ -181,31 +152,31 @@ function CompareDialog({ branch, current, onClose }: { branch: string; current:
onClick: () => {
onClose();
// Whole-project diff: every file that differs between the branches.
showCompareRevisions(branch, "HEAD", branch, current, repo);
showCompareRevisions(branch, "HEAD", branch, current);
},
},
{ label: "Close", role: "cancel" },
]}
>
{error ? (
<div className={`${styles.error} ${compareStyles.error}`} role="alert">
{error}
</div>
) : (
<SplitGroup orientation="vertical" className={compareStyles.ranges}>
<CompareRange
label={tx`In ${branch}, not in ${current}`}
commits={data?.incoming ?? null}
onClose={onClose}
/>
<SplitHandle aria-label={tx("Resize branch comparison panes")} />
<CompareRange
label={tx`In ${current}, not in ${branch}`}
commits={data?.outgoing ?? null}
onClose={onClose}
/>
</SplitGroup>
)}
<Tabs
variant="compact"
activeId={tab}
onSelect={setTab}
aria-label="Direction"
items={[
{
id: "incoming",
label: tx`In ${branch}, not in ${current}`,
trailing: data ? String(data.incoming.length) : undefined,
},
{
id: "outgoing",
label: tx`In ${current}, not in ${branch}`,
trailing: data ? String(data.outgoing.length) : undefined,
},
]}
/>
<CommitList commits={data ? list : null} error={error} onClose={onClose} />
</Dialog>
);
}
+1 -1
View File
@@ -332,7 +332,7 @@ describe("markdown preview re-rendering", () => {
same(render, doc(blocks));
});
it("renders a large document as a whole, sanitizing only what an edit changed", { timeout: 20_000 }, () => {
it("renders a large document as a whole, sanitizing only what an edit changed", () => {
const asWritten = readFileSync(resolve(import.meta.dirname, "../../../../plugins/README.md"), "utf8");
// As written, a bare `<title>` swallows the rest of the file, so it is rendered as a whole.
for (const [readme, reuses] of [
+1 -10
View File
@@ -1,15 +1,9 @@
{
"Inspection details": "Inspection details",
"Resize inspection panes": "Resize inspection panes",
"Resize branch comparison panes": "Resize branch comparison panes",
"Resize inspection description": "Resize inspection description",
"Color scheme options": "Color scheme options",
"Resize color scheme preview": "Resize color scheme preview",
"Font options": "Font options",
"Resize font preview": "Resize font preview",
"Table actions": "Table actions",
"Table pages": "Table pages",
"Resize file type panes": "Resize file type panes",
"Problems actions": "Problems actions",
"TODO actions": "TODO actions",
"Same as the existing configuration '{existing}'": "Same as the existing configuration '{existing}'",
@@ -2713,8 +2707,5 @@
"Shelve Silently": "Shelve Silently",
"Unshelve Silently": "Unshelve Silently",
"Fold Lines Like This": "Fold Lines Like This",
"Remove All Watches": "Remove All Watches",
"GitHub account": "GitHub account",
"Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.",
"github-username": "github-username"
"Remove All Watches": "Remove All Watches"
}
+1
View File
@@ -679,6 +679,7 @@
"Detecting…": "Detectando…",
"Diff": "Diferencias",
"Different tool window background": "Fondo diferente para las ventanas de herramientas",
"Direction": "Dirección",
"Directory": "Directorio",
"Staging State": "Estado de preparación (stage)",
"Staged Changes": "Cambios preparados (staged)",
+1
View File
@@ -620,6 +620,7 @@
"Detecting…": "Détection…",
"Diff": "Diff",
"Different tool window background": "Arrière-plan distinct pour les fenêtres d'outils",
"Direction": "Sens",
"Directory": "Répertoire",
"Directory (relative to project root)": "Répertoire (relatif à la racine du projet)",
"Directory Mappings": "Associations de répertoires",
+1
View File
@@ -715,6 +715,7 @@
"Detecting installations": "설치 항목 감지 중",
"Detecting…": "감지 중…",
"Different tool window background": "도구 창 배경을 다르게 표시",
"Direction": "방향",
"Directory": "디렉터리",
"Staging State": "스테이징 상태",
"Staged Changes": "스테이징된 변경 사항",
+1
View File
@@ -671,6 +671,7 @@
"Detecting…": "Wykrywanie…",
"Diff": "Różnice (Diff)",
"Different tool window background": "Inne tło okien narzędziowych",
"Direction": "Kierunek",
"Directory": "Katalog",
"Staging State": "Stan poczekalni (Staging)",
"Staged Changes": "Zmiany w poczekalni (Staged)",
+1
View File
@@ -671,6 +671,7 @@
"Detecting…": "Detectando…",
"Diff": "Diff",
"Different tool window background": "Plano de fundo diferente para janelas de ferramentas",
"Direction": "Direção",
"Directory": "Diretório",
"Staging State": "Estado de staging",
"Staged Changes": "Alterações no stage",
+2 -10
View File
@@ -1,15 +1,9 @@
{
"Inspection details": "检查详情",
"Resize inspection panes": "调整检查窗格大小",
"Resize branch comparison panes": "调整分支比较窗格大小",
"Resize inspection description": "调整检查说明窗格大小",
"Color scheme options": "配色方案选项",
"Resize color scheme preview": "调整配色方案预览大小",
"Font options": "字体选项",
"Resize font preview": "调整字体预览大小",
"Table actions": "表数据操作",
"Table pages": "表数据分页",
"Resize file type panes": "调整文件类型窗格大小",
"Problems actions": "问题操作",
"Windows file and folder names cannot end with a period or space": "Windows 文件和文件夹名称不能以句点或空格结尾",
"Use URL template": "使用 URL 模板",
@@ -1278,6 +1272,7 @@
"Detecting…": "正在检测…",
"Diff": "差异",
"Different tool window background": "不同的工具窗口背景",
"Direction": "方向",
"Directory": "目录",
"Staging State": "暂存状态",
"Staged Changes": "已暂存的更改",
@@ -9079,8 +9074,5 @@
"Database and schema": "数据库和 schema",
"Shelve Silently": "静默搁置",
"Unshelve Silently": "静默取消搁置",
"Remove All Watches": "移除所有监视",
"GitHub account": "GitHub 账号",
"Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "留空则使用 GitHub CLI 当前登录的账号。OpenIDEA 在启动时获取令牌,不会保存它。",
"github-username": "GitHub 用户名"
"Remove All Watches": "移除所有监视"
}