дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 10:07:11 +02:00
Порівняти коміти
40
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
a244e7b48e | ||
|
|
3b614dda7a | ||
|
|
5acd778340 | ||
|
|
7c682a580f | ||
|
|
dc07691279 | ||
|
|
2d04a3d9bc | ||
|
|
8f9b9b1016 | ||
|
|
096964c798 | ||
|
|
f1bfd5db52 | ||
|
|
a17af582f3 | ||
|
|
47f018d8b5 | ||
|
|
94aa62430c | ||
|
|
4242c94bfc | ||
|
|
8864ff595d | ||
|
|
0a08d9f4ce | ||
|
|
7dbfe8852e | ||
|
|
ae97d5f1c2 | ||
|
|
4340a96c59 | ||
|
|
0af7bcc7cf | ||
|
|
4f52f5ebfa | ||
|
|
f284633162 | ||
|
|
0ceda2c385 | ||
|
|
8b3f55dfb4 | ||
|
|
c0e888dd2f | ||
|
|
04bed01942 | ||
|
|
dfafe6c767 | ||
|
|
461c71a50b | ||
|
|
82085a227e | ||
|
|
c3f420374c | ||
|
|
6bf7bc8c2b | ||
|
|
34dfc166db | ||
|
|
64632dc4d7 | ||
|
|
f484fd6802 | ||
|
|
8121dc87f1 | ||
|
|
97f78908a1 | ||
|
|
e7aec17d46 | ||
|
|
cb24f252c5 | ||
|
|
8557b8d21e | ||
|
|
99a8f8feaa | ||
|
|
4b76566af4 |
No files matched your search
@@ -194,14 +194,14 @@ impl AgentCatalogs {
|
||||
(shared.paths.models_file.clone(), shared.paths.project_root.clone(), provider.to_owned())
|
||||
}
|
||||
|
||||
fn fallback(shared: &Shared, provider: &str) -> CatalogData {
|
||||
/// The catalog saved for this project, for before this run looked anything up.
|
||||
fn saved(shared: &Shared, provider: &str) -> CatalogData {
|
||||
let cache = shared.known.lock();
|
||||
let Some(known) = cache.get(provider) else { return CatalogData::default() };
|
||||
known.catalogs.get(&shared.root_key()).map(|saved| saved.catalog.clone()).unwrap_or_else(|| CatalogData {
|
||||
config: known.config.clone(),
|
||||
thought_levels: known.thought_levels.clone(),
|
||||
refreshed_at_ms: None,
|
||||
})
|
||||
cache
|
||||
.get(provider)
|
||||
.and_then(|known| known.catalogs.get(&shared.root_key()))
|
||||
.map(|saved| saved.catalog.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn cached(&self, shared: &Shared, provider: &str) -> CatalogData {
|
||||
@@ -210,32 +210,14 @@ impl AgentCatalogs {
|
||||
.entries
|
||||
.get(&Self::key(shared, provider))
|
||||
.and_then(|e| e.catalog.clone())
|
||||
.unwrap_or_else(|| Self::fallback(shared, provider))
|
||||
.unwrap_or_else(|| Self::saved(shared, provider))
|
||||
}
|
||||
|
||||
/// Availability for an explicit session switch must come from a recent discovery for this
|
||||
/// launch, not from the display fallback or a different project's session report.
|
||||
pub(super) fn fresh_model(
|
||||
&self,
|
||||
shared: &Shared,
|
||||
spec: &provider::ProviderSpec,
|
||||
model: &str,
|
||||
) -> Option<crate::AgentConfigValue> {
|
||||
let context = LaunchContext::new(spec.clone(), &shared.paths.project_root);
|
||||
let select = |catalog: &CatalogData| {
|
||||
let age = self.epoch_ms() - catalog.refreshed_at_ms?;
|
||||
if !(0.0..FRESH_FOR.as_millis() as f64).contains(&age) {
|
||||
return None;
|
||||
}
|
||||
catalog.model_option()?.values.iter().find(|value| value.value == model).cloned()
|
||||
};
|
||||
let state = self.state.lock();
|
||||
if let Some(entry) = state.entries.get(&Self::key(shared, &spec.id)) {
|
||||
return select(entry.catalog.as_ref().filter(|_| entry.context == context)?);
|
||||
}
|
||||
let cache = shared.known.lock();
|
||||
let saved = cache.get(&spec.id)?.catalogs.get(&shared.root_key())?;
|
||||
(saved.fingerprint == context.fingerprint()).then(|| select(&saved.catalog)).flatten()
|
||||
/// The entry a chat may switch to: exactly what the picker offers from the cached catalog,
|
||||
/// however long ago it was read. Refreshing keeps that catalog current; a listed model is
|
||||
/// never refused because the catalog aged.
|
||||
pub(super) fn listed_model(&self, shared: &Shared, provider: &str, model: &str) -> Option<crate::AgentConfigValue> {
|
||||
self.cached(shared, provider).model_option()?.values.iter().find(|value| value.value == model).cloned()
|
||||
}
|
||||
|
||||
pub(crate) fn levels(&self, shared: &Shared, provider: &str, model: &str) -> Option<Vec<AgentConfigOption>> {
|
||||
@@ -246,14 +228,7 @@ impl AgentCatalogs {
|
||||
}
|
||||
drop(state);
|
||||
let cache = shared.known.lock();
|
||||
let known = cache.get(provider)?;
|
||||
known
|
||||
.catalogs
|
||||
.get(&shared.root_key())
|
||||
.map(|saved| &saved.catalog.thought_levels)
|
||||
.unwrap_or(&known.thought_levels)
|
||||
.get(model)
|
||||
.cloned()
|
||||
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
|
||||
}
|
||||
|
||||
pub(super) async fn load_levels(
|
||||
@@ -297,7 +272,7 @@ impl AgentCatalogs {
|
||||
}
|
||||
|
||||
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
|
||||
let catalog = entry.catalog.clone().unwrap_or_else(|| Self::fallback(shared, provider));
|
||||
let catalog = entry.catalog.clone().unwrap_or_default();
|
||||
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
|
||||
let unknown_model = entry
|
||||
.requested_model
|
||||
@@ -382,12 +357,11 @@ impl AgentCatalogs {
|
||||
},
|
||||
);
|
||||
}
|
||||
let fallback =
|
||||
state.entries.get(&key).filter(|entry| entry.catalog.is_none()).map(|_| Self::fallback(shared, &spec.id));
|
||||
state.generation += 1;
|
||||
let generation = state.generation;
|
||||
let entry = state.entries.get_mut(&key).expect("catalog entry");
|
||||
let catalog = entry.catalog.as_ref().or(fallback.as_ref()).expect("cached catalog");
|
||||
let empty = CatalogData::default();
|
||||
let catalog = entry.catalog.as_ref().unwrap_or(&empty);
|
||||
let fresh = entry.successful.is_some_and(|at| now.duration_since(at) < FRESH_FOR);
|
||||
let target = model
|
||||
.filter(|model| {
|
||||
@@ -496,7 +470,7 @@ impl AgentCatalogs {
|
||||
entry.flight_model = None;
|
||||
let success = match result {
|
||||
Ok(found) => {
|
||||
let previous = entry.catalog.take().unwrap_or_else(|| Self::fallback(shared, &key.2));
|
||||
let previous = entry.catalog.take().unwrap_or_default();
|
||||
let mut cache = shared.known.lock();
|
||||
let known = cache.entry(key.2.clone()).or_default();
|
||||
let mut catalog = CatalogData {
|
||||
@@ -510,13 +484,9 @@ impl AgentCatalogs {
|
||||
catalog.thought_levels.insert(model, levels);
|
||||
}
|
||||
}
|
||||
known.config = catalog.config.clone();
|
||||
known.thought_levels = catalog.thought_levels.clone();
|
||||
if let Some(commands) = found.commands {
|
||||
known.commands.insert(shared.root_key(), commands);
|
||||
}
|
||||
known.authoritative = true;
|
||||
known.refreshed_at_ms = catalog.refreshed_at_ms;
|
||||
known.catalogs.insert(
|
||||
shared.root_key(),
|
||||
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
|
||||
|
||||
@@ -230,11 +230,9 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
|
||||
let manager = make_manager(tmp.path(), catalogs.clone(), &harness);
|
||||
let mut events = events(&manager);
|
||||
let old = config::options_of(&response(&["old", "retained"], &["low", "high"]));
|
||||
manager.shared.remember(PROVIDER, Some(&old), None, Some("old"));
|
||||
let cached = manager.refresh_models(PROVIDER, false, None).unwrap();
|
||||
assert!(cached.refreshing);
|
||||
assert_eq!(model_values(&cached), ["old", "retained"]);
|
||||
assert!(cached.refreshed_at_ms.is_none(), "session reports are not fresh discovery");
|
||||
assert!(model_values(&cached).is_empty(), "nothing is offered before the first discovery");
|
||||
let pending = harness.next().await;
|
||||
assert_eq!(pending.params["mcpServers"], json!([]));
|
||||
pending.reply.send(Ok(response(&["retained", "new"], &["medium"]))).unwrap();
|
||||
@@ -258,7 +256,10 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
|
||||
assert_eq!(provider.config, fresh.config);
|
||||
restored.shared.remember(PROVIDER, Some(&old), None, Some("old"));
|
||||
assert_eq!(restored.shared.known_config(PROVIDER), fresh.config);
|
||||
assert_eq!(restored.shared.known.lock()[PROVIDER].refreshed_at_ms, fresh.refreshed_at_ms);
|
||||
assert_eq!(
|
||||
restored.shared.paths.catalogs.cached(&restored.shared, PROVIDER).refreshed_at_ms,
|
||||
fresh.refreshed_at_ms
|
||||
);
|
||||
assert!(!tmp.path().join("store").exists(), "refresh never creates tasks");
|
||||
}
|
||||
|
||||
@@ -308,6 +309,11 @@ async fn discovered_model_reloads_the_same_session_on_the_next_message() {
|
||||
switch_chat_model(ChatSwitch::Resume).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovered_model_from_an_aged_catalog_can_still_be_selected() {
|
||||
switch_chat_model(ChatSwitch::Aged).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovered_model_leaves_the_original_session_intact_after_resume_failure() {
|
||||
switch_chat_model(ChatSwitch::ResumeFails).await;
|
||||
@@ -356,6 +362,7 @@ async fn discovered_model_lookup_does_not_overwrite_a_newer_selection() {
|
||||
#[derive(Clone, Copy)]
|
||||
enum ChatSwitch {
|
||||
Live,
|
||||
Aged,
|
||||
Resume,
|
||||
ResumeFails,
|
||||
Unavailable,
|
||||
@@ -376,7 +383,8 @@ async fn switch_chat_model(scenario: ChatSwitch) {
|
||||
let mut harness = Harness::with_initialize(json!({
|
||||
"protocolVersion": 1, "agentCapabilities": { "loadSession": true }
|
||||
}));
|
||||
let mut manager = make_manager(tmp.path(), Arc::default(), &harness);
|
||||
let catalogs = Arc::new(AgentCatalogs::default());
|
||||
let mut manager = make_manager(tmp.path(), catalogs.clone(), &harness);
|
||||
let task = manager
|
||||
.create(NewAgentTask {
|
||||
prompt: AgentPrompt { text: "first".into(), ..Default::default() },
|
||||
@@ -443,7 +451,11 @@ async fn switch_chat_model(scenario: ChatSwitch) {
|
||||
}
|
||||
assert_eq!(manager.task(&task.id).unwrap().state.lock().task.config, before_config);
|
||||
|
||||
let live = matches!(scenario, ChatSwitch::Live);
|
||||
let live = matches!(scenario, ChatSwitch::Live | ChatSwitch::Aged);
|
||||
if matches!(scenario, ChatSwitch::Aged) {
|
||||
// The catalog stays what the picker offers however long ago it was read.
|
||||
advance(&catalogs, 20 * 60);
|
||||
}
|
||||
let resumed_launch = if missing_settings { 3 } else { 2 };
|
||||
let load_fails = matches!(scenario, ChatSwitch::ResumeFails);
|
||||
let unavailable = matches!(scenario, ChatSwitch::Unavailable);
|
||||
@@ -684,7 +696,7 @@ async fn next_chat_request(
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_cache_loads_without_claiming_authoritative_freshness() {
|
||||
async fn a_cache_from_before_project_catalogs_offers_nothing_until_discovery_succeeds() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
configure(tmp.path(), "one");
|
||||
let options = config::options_of(&response(&["legacy"], &["low"]));
|
||||
@@ -700,12 +712,11 @@ async fn legacy_cache_loads_without_claiming_authoritative_freshness() {
|
||||
let manager = make_manager(tmp.path(), Arc::default(), &harness);
|
||||
let mut events = events(&manager);
|
||||
let cached = manager.refresh_models(PROVIDER, false, None).unwrap();
|
||||
assert_eq!(model_values(&cached), ["legacy"]);
|
||||
assert!(model_values(&cached).is_empty());
|
||||
assert!(cached.refreshing && cached.refreshed_at_ms.is_none());
|
||||
harness.next().await.reply.send(Err("Sign in required".into())).unwrap();
|
||||
let failed = completed(&mut events).await;
|
||||
assert_eq!(failed.config, cached.config);
|
||||
assert!(failed.error.as_deref().unwrap().contains("Sign in required"));
|
||||
harness.next().await.reply.send(Ok(response(&["current"], &["low"]))).unwrap();
|
||||
let found = completed(&mut events).await;
|
||||
assert_eq!(model_values(&found), ["current"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -174,23 +174,13 @@ struct Shared {
|
||||
attention_seq: AtomicU64,
|
||||
}
|
||||
|
||||
/// What an agent offered in its last session, for the New Task page.
|
||||
/// What an agent offered, for the New Task page.
|
||||
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||
struct Known {
|
||||
#[serde(default)]
|
||||
config: Vec<AgentConfigOption>,
|
||||
/// Thinking levels reported for each model value, including its last choice.
|
||||
#[serde(default, rename = "thoughtLevels")]
|
||||
thought_levels: BTreeMap<String, Vec<AgentConfigOption>>,
|
||||
/// By project root: skills and custom commands differ per project.
|
||||
#[serde(default, rename = "projectCommands")]
|
||||
commands: HashMap<String, Vec<AgentCommand>>,
|
||||
/// Successful discovery, unlike a session report, owns availability.
|
||||
#[serde(default)]
|
||||
authoritative: bool,
|
||||
#[serde(default, rename = "refreshedAtMs")]
|
||||
refreshed_at_ms: Option<f64>,
|
||||
/// Authoritative availability and freshness are scoped to project and launch context.
|
||||
/// Model catalogs by project root, valid for the launch context they were read with.
|
||||
#[serde(default, rename = "projectCatalogs")]
|
||||
catalogs: HashMap<String, catalogs::SavedCatalog>,
|
||||
}
|
||||
@@ -308,7 +298,8 @@ impl Shared {
|
||||
self.paths.project_root.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Cache levels only when `model` confirms which model the session reported them for.
|
||||
/// Keeps the commands a session offered and the effort levels it reported for `model`, the
|
||||
/// only model whose levels it describes.
|
||||
fn remember(
|
||||
&self,
|
||||
provider: &str,
|
||||
@@ -317,43 +308,22 @@ impl Shared {
|
||||
model: Option<&str>,
|
||||
) {
|
||||
let acp = self.spec(provider).is_some_and(|spec| spec.driver == provider::Driver::Acp);
|
||||
let mut cache = self.known.lock();
|
||||
let known = cache.entry(provider.to_owned()).or_default();
|
||||
let mut changed = false;
|
||||
// Running tasks retain their own reported settings. Once discovery has
|
||||
// succeeded, a session's older list/defaults cannot change New Task choices.
|
||||
if !known.authoritative
|
||||
&& let Some(config) = config.filter(|c| !c.is_empty())
|
||||
{
|
||||
if let Some(model) = model {
|
||||
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
|
||||
if known.thought_levels.get(model) != Some(&levels) {
|
||||
known.thought_levels.insert(model.to_owned(), levels);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if known.config != config {
|
||||
known.config = config.to_vec();
|
||||
if let Some(commands) = commands.filter(|c| !c.is_empty()) {
|
||||
let mut cache = self.known.lock();
|
||||
let known = cache.entry(provider.to_owned()).or_default();
|
||||
if known.commands.get(&self.root_key()).map(Vec::as_slice) != Some(commands) {
|
||||
known.commands.insert(self.root_key(), commands.to_vec());
|
||||
self.persist_known(&cache);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
// Discovery reads one model's options; a session on another model reports that model's.
|
||||
let learned = model.filter(|_| acp && known.authoritative).zip(config).map(|(model, config)| {
|
||||
if acp && let Some((model, config)) = model.zip(config) {
|
||||
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
|
||||
(model, levels)
|
||||
});
|
||||
if let Some(commands) = commands.filter(|c| !c.is_empty())
|
||||
&& known.commands.get(&self.root_key()).map(Vec::as_slice) != Some(commands)
|
||||
{
|
||||
known.commands.insert(self.root_key(), commands.to_vec());
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
self.persist_known(&cache);
|
||||
}
|
||||
drop(cache);
|
||||
if let Some((model, levels)) = learned.filter(|(_, levels)| !levels.is_empty()) {
|
||||
self.paths.catalogs.learn_levels(self, provider, model, levels);
|
||||
if !levels.is_empty() {
|
||||
self.paths.catalogs.learn_levels(self, provider, model, levels);
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
self.emit(AgentEvent::Providers);
|
||||
@@ -2537,8 +2507,7 @@ impl Task {
|
||||
|
||||
async fn switch_discovered_model(&self, target: AgentConfigOption, value: String) -> IdeResult<()> {
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
let spec = self.shared.spec(&provider).ok_or_else(|| IdeError::not_found("no such agent"))?;
|
||||
let candidate = self.shared.paths.catalogs.fresh_model(&self.shared, &spec, &value).ok_or_else(|| {
|
||||
let candidate = self.shared.paths.catalogs.listed_model(&self.shared, &provider, &value).ok_or_else(|| {
|
||||
IdeError::invalid(format!("{} has no value {value} in the current model catalog", target.name))
|
||||
})?;
|
||||
let selection = {
|
||||
|
||||
@@ -711,6 +711,8 @@ pub struct AgentChange {
|
||||
pub removed: u32,
|
||||
/// Path before a rename; the left side of its diff reads this path.
|
||||
pub old_path: Option<String>,
|
||||
/// The repository the file is in, when the task's project holds nested repositories.
|
||||
pub repo: Option<IpcPath>,
|
||||
}
|
||||
|
||||
/// A commit made while the task ran, with the files it changed against its first parent.
|
||||
|
||||
@@ -1010,7 +1010,6 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
// Another project shares the settings but not the commands.
|
||||
let mgr_b = manager_at(&b, &models, Arc::new(FakeAgent::default()));
|
||||
let claude = mgr_b.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
assert_eq!(claude.config.len(), 2);
|
||||
assert!(claude.commands.is_empty());
|
||||
assert!(mgr_b.commands("claude", None).await.unwrap().is_empty());
|
||||
let mgr_a = manager_at(&a, &models, Arc::new(FakeAgent::default()));
|
||||
@@ -1197,7 +1196,6 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
}
|
||||
let providers = mgr.providers();
|
||||
let claude = providers.iter().find(|p| p.id == "claude").unwrap();
|
||||
assert_eq!(claude.config.iter().map(|o| o.id.as_str()).collect::<Vec<_>>(), ["model", "mode"]);
|
||||
assert_eq!(claude.commands.len(), 1);
|
||||
|
||||
// A new manager (IDE restart) finds the task and resumes its session without duplicating history.
|
||||
@@ -1206,7 +1204,6 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
let mgr2 = manager(tmp.path(), agent2.clone());
|
||||
assert_eq!(mgr2.entries(&task.id, None).unwrap().len(), 5);
|
||||
assert_eq!(mgr2.task(&task.id).unwrap().state.lock().task.title, "Lexer fix");
|
||||
assert_eq!(mgr2.providers().iter().find(|p| p.id == "claude").unwrap().config.len(), 2);
|
||||
mgr2.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
|
||||
@@ -2167,52 +2164,6 @@ async fn usage_limits_and_late_settings() {
|
||||
assert!(agent.calls.lock().iter().any(|c| c == "session/set_config_option \"high\""));
|
||||
let config = mgr.task(&task.id).unwrap().state.lock().task.config.clone();
|
||||
assert_eq!(config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("high"));
|
||||
for _ in 0..100 {
|
||||
if mgr
|
||||
.shared
|
||||
.known
|
||||
.lock()
|
||||
.get("claude")
|
||||
.and_then(|k| k.thought_levels.get("big"))
|
||||
.and_then(|levels| levels.first())
|
||||
.and_then(|o| o.current.as_deref())
|
||||
== Some("high")
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(mgr.shared.known.lock()["claude"].thought_levels["big"][0].current.as_deref(), Some("high"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn remembered_settings_drop_per_model_choices_for_the_next_task() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
// The effort list depends on the model: what the last session ran means nothing once
|
||||
// the user picks another model, so provider-wide defaults never include it.
|
||||
*agent.extra_options.lock() = vec![json!({"id": "effort", "category": "thought_level",
|
||||
"type": "select", "currentValue": "high",
|
||||
"options": [{"value": "low", "name": "Low"}, {"value": "high", "name": "High"}]})];
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let provider = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
assert!(provider.config.iter().all(|o| o.id != "effort"), "a per-model option isn't offered stale");
|
||||
let model = provider.config.iter().find(|o| o.id == "model").unwrap();
|
||||
assert_eq!(model.current.as_deref(), Some("big"), "the model choice survives");
|
||||
}
|
||||
|
||||
fn effort_options(levels: &[&str], current: &str) -> Vec<Value> {
|
||||
@@ -2220,51 +2171,6 @@ fn effort_options(levels: &[&str], current: &str) -> Vec<Value> {
|
||||
"options": levels.iter().map(|v| json!({"value": v, "name": v})).collect::<Vec<_>>()})]
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn thinking_levels_are_remembered_per_provider_and_model() {
|
||||
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")),
|
||||
("plain".into(), vec![]),
|
||||
]);
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
|
||||
mgr.set_config(&task.id, "effort", "medium".into()).await.unwrap();
|
||||
mgr.set_config(&task.id, "model", "plain".into()).await.unwrap();
|
||||
let p = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
let big = &p.thought_levels["big"][0];
|
||||
assert_eq!(big.current.as_deref(), Some("high"));
|
||||
assert_eq!(big.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["low", "high"]);
|
||||
let small = &p.thought_levels["small"][0];
|
||||
assert_eq!(small.current.as_deref(), Some("medium"));
|
||||
assert_eq!(small.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["minimal", "medium"]);
|
||||
assert!(p.thought_levels["plain"].is_empty());
|
||||
assert!(!p.thought_levels.contains_key("unknown"));
|
||||
assert!(mgr.providers().iter().find(|p| p.id == "codex").unwrap().thought_levels.is_empty());
|
||||
let saved: HashMap<String, Known> =
|
||||
serde_json::from_slice(&std::fs::read(&mgr.shared.paths.models_file).unwrap()).unwrap();
|
||||
assert_eq!(saved["claude"].thought_levels, p.thought_levels);
|
||||
mgr.shutdown();
|
||||
let restored = manager(tmp.path(), agent);
|
||||
assert_eq!(restored.providers().into_iter().find(|p| p.id == "claude").unwrap().thought_levels, p.thought_levels);
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn changing_an_idle_tasks_settings_keeps_its_models_effort_levels() {
|
||||
// Idle selections use cached model controls or discover them before the next prompt.
|
||||
@@ -2303,12 +2209,9 @@ async fn changing_an_idle_tasks_settings_keeps_its_models_effort_levels() {
|
||||
}
|
||||
restored.set_config(&task.id, "model", "big".into()).await.unwrap();
|
||||
restored.set_config(&task.id, option, value.into()).await.unwrap();
|
||||
let p = restored.providers().into_iter().find(|p| p.id == "claude-acp").unwrap();
|
||||
let big = p.thought_levels.get("big").and_then(|levels| levels.first());
|
||||
assert_eq!(big.map(|o| o.values.len()), Some(2), "{option}: {:?}", p.thought_levels);
|
||||
let saved: HashMap<String, Known> =
|
||||
serde_json::from_slice(&std::fs::read(&restored.shared.paths.models_file).unwrap()).unwrap();
|
||||
assert_eq!(saved["claude-acp"].thought_levels, p.thought_levels, "{option}");
|
||||
let levels = restored.shared.paths.catalogs.cached(&restored.shared, "claude-acp").thought_levels;
|
||||
let big = levels.get("big").and_then(|levels| levels.first());
|
||||
assert_eq!(big.map(|o| o.values.len()), Some(2), "{option}: {levels:?}");
|
||||
restored.shutdown();
|
||||
}
|
||||
}
|
||||
@@ -2541,100 +2444,6 @@ async fn upfront_effort_is_validated_after_changing_model_before_the_prompt() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn unreported_model_switch_does_not_cache_the_previous_models_levels() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.extra_options.lock() = effort_options(&["low", "high"], "high");
|
||||
let mgr = manager(tmp.path(), agent);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
|
||||
let p = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
assert!(!p.thought_levels.contains_key("small"));
|
||||
assert_eq!(p.thought_levels["big"][0].current.as_deref(), Some("high"));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cached_effort_is_not_sent_without_real_session_options() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.extra_options.lock() = effort_options(&["low", "high"], "low");
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let new = |config| NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config,
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
};
|
||||
let warm = mgr.create(new(vec![])).await.unwrap();
|
||||
wait_for(&mgr, &warm.id, AgentStatus::Ready).await;
|
||||
agent.calls.lock().clear();
|
||||
agent.empty_config.store(true, Ordering::Release);
|
||||
let task = mgr
|
||||
.create(new(vec![
|
||||
AgentConfigChoice { id: "model".into(), value: "big".into() },
|
||||
AgentConfigChoice { id: "effort".into(), value: "high".into() },
|
||||
]))
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(!agent.calls.lock().iter().any(|c| c == "session/set_config_option \"high\""));
|
||||
assert!(
|
||||
mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "effort"),
|
||||
"remembered session settings remain visible until the agent refreshes them"
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn reported_levels_refresh_even_without_a_model_option() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.extra_options.lock() = effort_options(&["low", "high"], "high");
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
for levels in [effort_options(&["minimal", "medium"], "medium"), vec![]] {
|
||||
agent.update("s1", json!({"sessionUpdate": "config_option_update", "configOptions": levels}));
|
||||
let expected = config::parse_options(&json!(levels));
|
||||
for _ in 0..100 {
|
||||
if mgr.shared.known.lock()["claude"].thought_levels["big"] == expected {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(mgr.shared.known.lock()["claude"].thought_levels["big"], expected);
|
||||
}
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_updates_become_a_countdown() {
|
||||
let update =
|
||||
@@ -3192,49 +3001,6 @@ async fn a_failed_probe_is_retried_instead_of_remembered() {
|
||||
assert!(!mgr.shared.probes.lock().contains_key("claude"));
|
||||
}
|
||||
|
||||
/// A session report that changes the cached provider config notifies subscribers,
|
||||
/// so the composer re-lists models without waiting for the next task (#1490).
|
||||
/// Reports that change nothing stay silent.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn remembered_config_changes_notify_subscribers_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
|
||||
events.lock().clear();
|
||||
|
||||
let reported = config::options_of(&json!({ "configOptions": [
|
||||
{ "id": "model", "category": "model", "type": "select", "currentValue": "default",
|
||||
"options": [{ "value": "default" }, { "value": "custom-opus" }] },
|
||||
] }));
|
||||
mgr.shared.remember("claude", Some(&reported), None, Some("default"));
|
||||
assert!(
|
||||
events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)),
|
||||
"a first report changing the cache notifies subscribers"
|
||||
);
|
||||
events.lock().clear();
|
||||
|
||||
// The same report again: the cache is unchanged, so subscribers hear nothing.
|
||||
mgr.shared.remember("claude", Some(&reported), None, Some("default"));
|
||||
assert!(events.lock().is_empty(), "an unchanged report must stay silent");
|
||||
|
||||
// A changed model list notifies again, and providers() serves the new list.
|
||||
let updated = config::options_of(&json!({ "configOptions": [
|
||||
{ "id": "model", "category": "model", "type": "select", "currentValue": "default",
|
||||
"options": [{ "value": "default" }, { "value": "custom-opus" }, { "value": "custom-sonnet" }] },
|
||||
] }));
|
||||
mgr.shared.remember("claude", Some(&updated), None, Some("default"));
|
||||
assert!(
|
||||
events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)),
|
||||
"a changed model list notifies subscribers"
|
||||
);
|
||||
let claude = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
let model = claude.config.iter().find(|o| o.category.as_deref() == Some("model")).unwrap();
|
||||
let values: Vec<_> = model.values.iter().map(|v| v.value.as_str()).collect();
|
||||
assert_eq!(values, ["default", "custom-opus", "custom-sonnet"]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn idle_agents_stop_and_resume_their_session_on_the_next_message() {
|
||||
let new = || NewAgentTask {
|
||||
@@ -3868,6 +3634,123 @@ async fn turn_changed(mgr: &AgentManager, id: &str) -> Vec<(String, ide_vcs::Cha
|
||||
changes.into_iter().map(|c| (c.rel_path, c.kind, c.added, c.removed)).collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_task_lists_what_it_changed_in_a_nested_repository() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
for repo in [root.clone(), root.join("libs/validation")] {
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
for args in [&["init", "-q", "-b", "main"][..], &["add", "a.txt"], &["commit", "-q", "-m", "init"]] {
|
||||
let ok = std::process::Command::new("git")
|
||||
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
|
||||
.args(args)
|
||||
.current_dir(&repo)
|
||||
.status()
|
||||
.unwrap()
|
||||
.success();
|
||||
assert!(ok, "{args:?}");
|
||||
}
|
||||
}
|
||||
let mgr = manager(&base.join("ide"), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: Some(IpcPath(root.clone())),
|
||||
prompt: text("Hello"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
one_turn(&mgr, &task.id, None, || {
|
||||
std::fs::write(root.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(root.join("libs/validation/b.txt"), "new\n").unwrap();
|
||||
})
|
||||
.await;
|
||||
let changed: Vec<(String, Option<IpcPath>)> =
|
||||
mgr.changes(&task.id).await.unwrap().into_iter().map(|c| (c.rel_path, c.repo)).collect();
|
||||
assert_eq!(
|
||||
changed,
|
||||
[
|
||||
("a.txt".to_owned(), Some(IpcPath(root.clone()))),
|
||||
("libs/validation/b.txt".to_owned(), Some(IpcPath(root.join("libs/validation")))),
|
||||
]
|
||||
);
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(root.join("a.txt")).unwrap(), "one\n");
|
||||
assert!(!root.join("libs/validation/b.txt").exists());
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_last_turn_of_a_task_spans_nested_repositories() {
|
||||
use ide_vcs::ChangeKind::{Added, Modified};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let nested = root.join("libs/validation");
|
||||
let git = |repo: &Path, args: &[&str]| {
|
||||
let ok = std::process::Command::new("git")
|
||||
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
|
||||
.args(args)
|
||||
.current_dir(repo)
|
||||
.status()
|
||||
.unwrap()
|
||||
.success();
|
||||
assert!(ok, "{args:?}");
|
||||
};
|
||||
for repo in [&root, &nested] {
|
||||
std::fs::create_dir_all(repo).unwrap();
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
git(repo, &["init", "-q", "-b", "main"]);
|
||||
git(repo, &["add", "a.txt"]);
|
||||
git(repo, &["commit", "-q", "-m", "init"]);
|
||||
}
|
||||
let mgr = manager(&base.join("ide"), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: Some(IpcPath(root.clone())),
|
||||
prompt: text("Hello"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
one_turn(&mgr, &task.id, None, || std::fs::write(root.join("a.txt"), "two\n").unwrap()).await;
|
||||
one_turn(&mgr, &task.id, Some("more"), || {
|
||||
std::fs::write(nested.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
|
||||
// Committed in the nested repository: still the turn's.
|
||||
std::fs::write(nested.join("c.txt"), "committed\n").unwrap();
|
||||
git(&nested, &["add", "c.txt"]);
|
||||
git(&nested, &["commit", "-q", "-m", "c"]);
|
||||
})
|
||||
.await;
|
||||
|
||||
// Only the second turn's files, from the nested repository, named from the project.
|
||||
assert_eq!(
|
||||
turn_changed(&mgr, &task.id).await,
|
||||
[
|
||||
("libs/validation/a.txt".into(), Modified, 1, 1),
|
||||
("libs/validation/b.txt".into(), Added, 1, 0),
|
||||
("libs/validation/c.txt".into(), Added, 1, 0),
|
||||
]
|
||||
);
|
||||
let repos: Vec<_> = mgr.turn_changes(&task.id).await.unwrap().into_iter().map(|c| c.repo).collect();
|
||||
assert_eq!(repos, [Some(IpcPath(nested.clone())), Some(IpcPath(nested.clone())), Some(IpcPath(nested.clone()))]);
|
||||
let then = mgr.base_text(&task.id, nested.join("a.txt"), AgentChangesView::LastTurn).await.unwrap();
|
||||
assert_eq!(then.as_deref(), Some("one\n"));
|
||||
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::LastTurn).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(nested.join("a.txt")).unwrap(), "one\n");
|
||||
assert!(!nested.join("b.txt").exists());
|
||||
assert_eq!(std::fs::read_to_string(root.join("a.txt")).unwrap(), "two\n", "the first turn's change stays");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_last_turn_lists_and_rolls_back_only_its_own_changes() {
|
||||
use ide_vcs::ChangeKind::{Added, Deleted, Modified};
|
||||
|
||||
@@ -25,6 +25,98 @@ fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
Ok(repo)
|
||||
}
|
||||
|
||||
/// The repositories of a project with nested ones (an own `.git` under the project root, not a
|
||||
/// submodule), with the folder their files are named from: the root of the repository holding
|
||||
/// `cwd`, else `cwd`. `None` when only the repository holding `cwd` (if any) is there.
|
||||
fn nested_repos(cwd: &Path) -> IdeResult<Option<(PathBuf, Vec<Repo>)>> {
|
||||
let Ok(cwd) = dunce::canonicalize(cwd) else { return Ok(None) };
|
||||
let found = ide_vcs::Repos::discover(&cwd, &|_| false)?;
|
||||
if found.all().iter().all(|r| cwd.starts_with(r.root())) {
|
||||
return Ok(None);
|
||||
}
|
||||
let base = found.all().iter().map(|r| r.root()).filter(|r| cwd.starts_with(r)).max().unwrap_or(&cwd).to_path_buf();
|
||||
let mut repos = Vec::new();
|
||||
for r in found.all() {
|
||||
repos.extend(discover(r.root())?);
|
||||
}
|
||||
Ok(Some((base, repos)))
|
||||
}
|
||||
|
||||
/// Whether the project at `cwd` holds repositories nested in it: its changes are each one's.
|
||||
pub(crate) fn spans_repos(cwd: &Path) -> bool {
|
||||
nested_repos(cwd).is_ok_and(|r| r.is_some())
|
||||
}
|
||||
|
||||
/// The repositories a turn's files are in, and the folder those files are named from.
|
||||
struct TurnRepos {
|
||||
base: PathBuf,
|
||||
repos: Vec<Repo>,
|
||||
/// The project holds nested repositories: each one's `HEAD` is recorded on its own.
|
||||
nested: bool,
|
||||
}
|
||||
|
||||
impl TurnRepos {
|
||||
fn of(cwd: &Path) -> IdeResult<Option<Self>> {
|
||||
if let Some((base, repos)) = nested_repos(cwd)? {
|
||||
return Ok(Some(Self { base, repos, nested: true }));
|
||||
}
|
||||
Ok(discover(cwd)?.map(|repo| Self { base: repo.root().to_path_buf(), repos: vec![repo], nested: false }))
|
||||
}
|
||||
|
||||
/// The innermost repository holding `path`.
|
||||
fn owner(&self, path: &Path) -> Option<&Repo> {
|
||||
self.repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
|
||||
}
|
||||
|
||||
/// `repo`'s `HEAD` as the turn `start` began.
|
||||
fn head_then<'a>(&self, start: &'a TurnStart, repo: &Repo) -> Option<&'a str> {
|
||||
if self.nested { start.heads.get(&root_key(repo.root())) } else { start.head.as_ref() }.map(String::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
fn root_key(root: &Path) -> String {
|
||||
root.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// `path` as a task in `base` names it, if it is not in a repository nested below `repo` (that
|
||||
/// one lists it itself; to `repo` its folder is untracked).
|
||||
fn nested_rel(base: &Path, repo: &Repo, roots: &[PathBuf], path: &Path) -> Option<String> {
|
||||
let rel = path.strip_prefix(base).ok()?;
|
||||
if path.is_dir()
|
||||
|| roots.iter().any(|n| n.as_path() != repo.root() && n.starts_with(repo.root()) && path.starts_with(n))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(rel.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
/// The uncommitted changes in every repository of the project, against each one's `HEAD`.
|
||||
fn nested_changes(cwd: &Path) -> IdeResult<Vec<AgentChange>> {
|
||||
let Some((base, repos)) = nested_repos(cwd)? else { return Ok(Vec::new()) };
|
||||
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
|
||||
let mut out: Vec<AgentChange> = Vec::new();
|
||||
for repo in &repos {
|
||||
let listed = match repo.head()?.1 {
|
||||
Some(head) => changes(repo.root(), &head)?,
|
||||
None => {
|
||||
repo.status()?.into_iter().filter(|s| s.path.is_file()).map(|s| added(s.path, s.rel_path)).collect()
|
||||
}
|
||||
};
|
||||
for mut c in listed {
|
||||
let Some(rel) = nested_rel(&base, repo, &roots, &c.path.0) else { continue };
|
||||
if out.iter().any(|o| o.path == c.path) {
|
||||
continue;
|
||||
}
|
||||
c.rel_path = rel;
|
||||
c.old_path = None;
|
||||
c.repo = Some(IpcPath(repo.root().to_path_buf()));
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn repo_at(path: &Path) -> IdeResult<Repo> {
|
||||
discover(path)?.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", path.display())))
|
||||
}
|
||||
@@ -38,6 +130,9 @@ pub(crate) fn head_of(path: &Path) -> IdeResult<(String, String)> {
|
||||
|
||||
/// `HEAD`'s commit in `cwd`, `None` outside a repository or before its first commit.
|
||||
pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
|
||||
if spans_repos(cwd) {
|
||||
return Ok(Some("HEAD".to_owned()));
|
||||
}
|
||||
match discover(cwd)? {
|
||||
Some(repo) => Ok(repo.head()?.1),
|
||||
None => Ok(None),
|
||||
@@ -127,6 +222,7 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
added,
|
||||
removed,
|
||||
old_path: f.old_path,
|
||||
repo: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -143,6 +239,9 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
/// Files renamed since `rev`, by their new repository-relative path: the old path, as a deletion
|
||||
/// to roll back along with the rename.
|
||||
pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String, AgentChange>> {
|
||||
if spans_repos(cwd) {
|
||||
return Ok(BTreeMap::new());
|
||||
}
|
||||
let Some(repo) = discover(cwd)? else { return Ok(BTreeMap::new()) };
|
||||
let root = repo.root().to_path_buf();
|
||||
Ok(repo
|
||||
@@ -157,6 +256,7 @@ pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String
|
||||
added: 0,
|
||||
removed: 0,
|
||||
old_path: None,
|
||||
repo: None,
|
||||
};
|
||||
Some((f.path, source))
|
||||
})
|
||||
@@ -165,7 +265,7 @@ pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String
|
||||
|
||||
fn added(path: IpcPath, rel_path: String) -> AgentChange {
|
||||
let added = std::fs::read_to_string(&*path).map_or(0, |t| t.lines().count() as u32);
|
||||
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None }
|
||||
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None, repo: None }
|
||||
}
|
||||
|
||||
/// The commits from `base` (exclusive) to `head` (inclusive) in `cwd`, newest first, each
|
||||
@@ -201,6 +301,7 @@ pub(crate) fn commits(cwd: &Path, base: &str, head: &str) -> IdeResult<Vec<Agent
|
||||
added,
|
||||
removed,
|
||||
old_path: f.old_path,
|
||||
repo: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -266,6 +367,9 @@ impl TaskBase {
|
||||
pub(crate) fn changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<Vec<AgentChange>> {
|
||||
let (cwd, start) = match self {
|
||||
Self::Worktree { cwd, base } => return Ok(without_untouched(changes(cwd, base)?, before)),
|
||||
Self::Local { cwd, .. } if spans_repos(cwd) => {
|
||||
return Ok(without_untouched(nested_changes(cwd)?, before));
|
||||
}
|
||||
Self::Local { cwd, start } => (cwd, start.as_deref()),
|
||||
};
|
||||
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
|
||||
@@ -324,6 +428,9 @@ impl TaskBase {
|
||||
/// reads cannot put a file in both lists.
|
||||
pub(crate) fn grouped_changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<AgentChanges> {
|
||||
let cwd = self.cwd();
|
||||
if spans_repos(cwd) {
|
||||
return Ok(AgentChanges { uncommitted: self.changes(before)?, commits: Vec::new() });
|
||||
}
|
||||
let Some(repo) = discover(cwd)? else { return Ok(AgentChanges::default()) };
|
||||
let head = repo.head()?.1;
|
||||
let uncommitted = match &head {
|
||||
@@ -353,6 +460,8 @@ impl TaskBase {
|
||||
pub(crate) fn rev(&self) -> IdeResult<Option<String>> {
|
||||
let (cwd, start) = match self {
|
||||
Self::Worktree { base, .. } => return Ok(Some(base.clone())),
|
||||
// Each repository goes back to its own `HEAD`.
|
||||
Self::Local { cwd, .. } if spans_repos(cwd) => return Ok(Some("HEAD".to_owned())),
|
||||
Self::Local { cwd, start } => (cwd, start.as_deref()),
|
||||
};
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
@@ -545,6 +654,18 @@ pub(crate) fn stamp(path: &Path) -> Stamp {
|
||||
pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
|
||||
// Paths and stamps only: no diff and no line counts, which read every untracked file
|
||||
// and held up starting a task in a checkout with many of them.
|
||||
if let Some((base, repos)) = nested_repos(cwd)? {
|
||||
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
|
||||
let mut out = BTreeMap::new();
|
||||
for repo in &repos {
|
||||
for s in repo.status()? {
|
||||
if let Some(rel) = nested_rel(&base, repo, &roots, &s.path) {
|
||||
out.insert(rel, stamp(&s.path));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
let Some(repo) = Repo::discover(cwd)? else { return Ok(BTreeMap::new()) };
|
||||
Ok(repo.status()?.into_iter().map(|s| (s.rel_path, stamp(&s.path))).collect())
|
||||
}
|
||||
@@ -587,10 +708,16 @@ fn saved_name(rel: &str) -> String {
|
||||
/// into `dir`, so rolling back the task's changes to them restores the user's own edits.
|
||||
/// Whether anything was saved.
|
||||
pub(crate) fn save_before(cwd: &Path, before: &BTreeMap<String, Stamp>, dir: &Path) -> IdeResult<bool> {
|
||||
let Some(repo) = Repo::discover(cwd)? else { return Ok(false) };
|
||||
let root = match nested_repos(cwd)? {
|
||||
Some((base, _)) => base,
|
||||
None => match Repo::discover(cwd)? {
|
||||
Some(repo) => repo.root().to_path_buf(),
|
||||
None => return Ok(false),
|
||||
},
|
||||
};
|
||||
let mut saved = false;
|
||||
for (rel, stamp) in before {
|
||||
let path = repo.root().join(rel);
|
||||
let path = root.join(rel);
|
||||
if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
|
||||
continue;
|
||||
}
|
||||
@@ -625,7 +752,8 @@ pub(crate) fn restore(
|
||||
}
|
||||
None => match rev {
|
||||
Some(rev) => {
|
||||
let repo = Repo::discover(cwd)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
|
||||
let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
|
||||
let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
|
||||
repo.file_bytes_at(&change.path.0, Some(rev))?
|
||||
}
|
||||
None => None,
|
||||
@@ -665,6 +793,9 @@ pub(crate) struct TurnStart {
|
||||
/// `HEAD` then (`None` outside a repository or before its first commit).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub head: Option<String>,
|
||||
/// With nested repositories, each one's `HEAD` then, by its root.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub heads: BTreeMap<String, String>,
|
||||
/// The files already changed then, stamped.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub before: BTreeMap<String, Stamp>,
|
||||
@@ -680,8 +811,16 @@ pub(crate) struct TurnStart {
|
||||
/// The copies `previous` saved of files unchanged since are kept rather than made again, so
|
||||
/// starting a turn copies little more than what the turn before it changed.
|
||||
pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -> IdeResult<TurnStart> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(TurnStart::default()) };
|
||||
let head = repo.head()?.1;
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart::default()) };
|
||||
let mut heads = BTreeMap::new();
|
||||
let head = if at.nested {
|
||||
for repo in &at.repos {
|
||||
heads.extend(repo.head()?.1.map(|h| (root_key(repo.root()), h)));
|
||||
}
|
||||
None
|
||||
} else {
|
||||
at.repos[0].head()?.1
|
||||
};
|
||||
// As the turn's end is read, so the two compare.
|
||||
let before = snapshot(cwd)?;
|
||||
let mut saved = BTreeSet::new();
|
||||
@@ -702,7 +841,7 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
|
||||
}
|
||||
}
|
||||
for (rel, stamp) in &before {
|
||||
let path = repo.root().join(rel);
|
||||
let path = at.base.join(rel);
|
||||
if stamp.is_none()
|
||||
|| saved.contains(rel)
|
||||
|| !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
|
||||
@@ -715,7 +854,7 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
|
||||
saved.insert(rel.clone());
|
||||
}
|
||||
}
|
||||
Ok(TurnStart { head, before, saved, changed: None })
|
||||
Ok(TurnStart { head, heads, before, saved, changed: None })
|
||||
}
|
||||
|
||||
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
|
||||
@@ -724,20 +863,25 @@ pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec<S
|
||||
let end = snapshot(cwd)?;
|
||||
let worktree = changed_between(&start.before, &end);
|
||||
let mut all: BTreeSet<String> = worktree.iter().cloned().collect();
|
||||
if let Some(repo) = discover(cwd)?
|
||||
&& let (Some(from), Some(to)) = (&start.head, repo.head()?.1)
|
||||
&& *from != to
|
||||
{
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok((worktree, all)) };
|
||||
for repo in &at.repos {
|
||||
let (Some(from), Some(to)) = (at.head_then(start, repo), repo.head()?.1) else { continue };
|
||||
if from == to {
|
||||
continue;
|
||||
}
|
||||
// Named from the base, as the working tree's files are.
|
||||
let prefix = rel_in(&at.base, repo.root())?;
|
||||
let named = |rel: String| if prefix.is_empty() { rel } else { format!("{prefix}/{rel}") };
|
||||
for f in repo.diff_revisions(from, &to)? {
|
||||
all.extend(f.old_path);
|
||||
all.insert(f.path);
|
||||
all.extend(f.old_path.map(named));
|
||||
all.insert(named(f.path));
|
||||
}
|
||||
}
|
||||
Ok((worktree, all))
|
||||
}
|
||||
|
||||
/// The content of `rel` as the turn `start` began (`None`: no file), its copies in `dir`.
|
||||
fn at_turn_start(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
|
||||
fn at_turn_start(at: &TurnRepos, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
|
||||
match start.before.get(rel) {
|
||||
Some(None) => Ok(None),
|
||||
Some(Some(_)) => match start.saved.contains(rel).then(|| saved_copy(dir, rel)).flatten() {
|
||||
@@ -746,10 +890,13 @@ fn at_turn_start(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeRe
|
||||
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
|
||||
))),
|
||||
},
|
||||
None => match &start.head {
|
||||
Some(head) => repo.file_bytes_at(&repo.root().join(rel), Some(head)),
|
||||
None => Ok(None),
|
||||
},
|
||||
None => {
|
||||
let path = at.base.join(rel);
|
||||
match at.owner(&path).and_then(|repo| Some((repo, at.head_then(start, repo)?))) {
|
||||
Some((repo, head)) => repo.file_bytes_at(&path, Some(head)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -771,13 +918,13 @@ pub(crate) fn turn_changes(
|
||||
dir: &Path,
|
||||
changed: &BTreeSet<String>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
|
||||
let mut out = Vec::new();
|
||||
for rel in changed {
|
||||
let path = repo.root().join(rel);
|
||||
let path = at.base.join(rel);
|
||||
// A folder (a submodule, say) or a file that can't be read has nothing to compare.
|
||||
let Some(now) = existing(&path) else { continue };
|
||||
let (kind, (added, removed)) = match at_turn_start(&repo, rel, start, dir) {
|
||||
let (kind, (added, removed)) = match at_turn_start(&at, rel, start, dir) {
|
||||
Ok(then) if then == now => continue,
|
||||
Ok(then) => {
|
||||
let kind = match (&then, &now) {
|
||||
@@ -790,19 +937,29 @@ pub(crate) fn turn_changes(
|
||||
// Its start wasn't saved: listed, without counts.
|
||||
Err(_) => (ChangeKind::Modified, (0, 0)),
|
||||
};
|
||||
out.push(AgentChange { path: IpcPath(path), rel_path: rel.clone(), kind, added, removed, old_path: None });
|
||||
out.push(AgentChange {
|
||||
rel_path: rel.clone(),
|
||||
kind,
|
||||
added,
|
||||
removed,
|
||||
old_path: None,
|
||||
repo: at.nested.then(|| at.owner(&path).map(|r| IpcPath(r.root().to_path_buf()))).flatten(),
|
||||
path: IpcPath(path),
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The text of `path` as the turn `start` began, `None` when there was no file.
|
||||
pub(crate) fn turn_text(cwd: &Path, path: &Path, start: &TurnStart, dir: &Path) -> IdeResult<Option<String>> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
let rel = rel_in(repo.root(), path)?;
|
||||
if let (None, Some(head)) = (start.before.get(&rel), &start.head) {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(None) };
|
||||
let rel = rel_in(&at.base, path)?;
|
||||
if !start.before.contains_key(&rel)
|
||||
&& let Some(head) = at.owner(&at.base.join(&rel)).and_then(|repo| at.head_then(start, repo))
|
||||
{
|
||||
return file_at(cwd, path, head);
|
||||
}
|
||||
let Some(bytes) = at_turn_start(&repo, &rel, start, dir)? else { return Ok(None) };
|
||||
let Some(bytes) = at_turn_start(&at, &rel, start, dir)? else { return Ok(None) };
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
|
||||
Err(_) => ide_vfs::detect_encoding(&bytes, None),
|
||||
@@ -828,12 +985,15 @@ fn rel_in(root: &Path, path: &Path) -> IdeResult<String> {
|
||||
|
||||
/// Puts `change` back as it was when the turn `start` began.
|
||||
pub(crate) fn restore_turn(cwd: &Path, start: &TurnStart, dir: &Path, change: &AgentChange) -> IdeResult<()> {
|
||||
let repo = repo_at(cwd)?;
|
||||
put(&change.path.0, at_turn_start(&repo, &change.rel_path, start, dir)?)
|
||||
let at = TurnRepos::of(cwd)?
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", cwd.display())))?;
|
||||
put(&change.path.0, at_turn_start(&at, &change.rel_path, start, dir)?)
|
||||
}
|
||||
|
||||
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
// With nested repositories, the file's own one.
|
||||
let at = if spans_repos(cwd) { path.parent().unwrap_or(cwd) } else { cwd };
|
||||
let Some(repo) = discover(at)? else { return Ok(None) };
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
|
||||
Err(_) => ide_vfs::detect_encoding(&repo.file_bytes_at(path, Some(rev))?.unwrap_or_default(), None),
|
||||
@@ -962,6 +1122,54 @@ mod tests {
|
||||
assert!(ok, "git {args:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_with_nested_repositories_sees_changes_in_each_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (nested, deeper) = (root.join("libs/validation"), root.join("libs/validation/pkg/sdk"));
|
||||
for repo in [&root, &nested, &deeper] {
|
||||
std::fs::create_dir_all(repo).unwrap();
|
||||
git(repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
git(repo, &["add", "a.txt"]);
|
||||
git(repo, &["commit", "-q", "-m", "init"]);
|
||||
}
|
||||
assert!(spans_repos(&root));
|
||||
std::fs::write(root.join("mine.txt"), "the user's\n").unwrap();
|
||||
let before = snapshot(&root).unwrap();
|
||||
assert_eq!(before.keys().collect::<Vec<_>>(), ["mine.txt"]);
|
||||
|
||||
std::fs::write(root.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(nested.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
|
||||
std::fs::write(deeper.join("a.txt"), "two\n").unwrap();
|
||||
let at = TaskBase::Local { cwd: root.clone(), start: None };
|
||||
let changed = at.changes(&before).unwrap();
|
||||
let listed: Vec<(&str, &Path)> =
|
||||
changed.iter().map(|c| (c.rel_path.as_str(), c.repo.as_ref().unwrap().0.as_path())).collect();
|
||||
assert_eq!(
|
||||
listed,
|
||||
[
|
||||
("a.txt", root.as_path()),
|
||||
("libs/validation/a.txt", nested.as_path()),
|
||||
("libs/validation/b.txt", nested.as_path()),
|
||||
("libs/validation/pkg/sdk/a.txt", deeper.as_path()),
|
||||
]
|
||||
);
|
||||
assert_eq!(at.grouped_changes(&before).unwrap().uncommitted.len(), 4);
|
||||
assert_eq!(file_at(&root, &nested.join("a.txt"), "HEAD").unwrap().as_deref(), Some("one\n"));
|
||||
|
||||
let rev = at.rev().unwrap();
|
||||
for change in &changed {
|
||||
restore(&root, rev.as_deref(), change, &before, None).unwrap();
|
||||
}
|
||||
for repo in [&root, &nested, &deeper] {
|
||||
assert_eq!(std::fs::read_to_string(repo.join("a.txt")).unwrap(), "one\n");
|
||||
}
|
||||
assert!(!nested.join("b.txt").exists());
|
||||
assert!(root.join("mine.txt").exists(), "the user's own change stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worktree_changes_are_listed_against_the_base() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -151,6 +151,7 @@ pub struct CommitSettings {
|
||||
/// Commit from the Commit tool window; off = Local Changes in the Git tool
|
||||
/// window and a Commit dialog.
|
||||
pub non_modal: bool,
|
||||
pub include_changes_by_default: bool,
|
||||
/// Start with an empty message instead of the last one / the changelist's.
|
||||
pub clear_initial_message: bool,
|
||||
pub analyze_code: bool,
|
||||
@@ -190,6 +191,7 @@ impl Default for CommitSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
non_modal: true,
|
||||
include_changes_by_default: true,
|
||||
clear_initial_message: false,
|
||||
analyze_code: true,
|
||||
check_todo: true,
|
||||
|
||||
@@ -1337,6 +1337,10 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
cfg.args = vec!["--lsp".into(), "--stdio".into()];
|
||||
cfg.display_name = Some("TypeScript 7".into());
|
||||
cfg.initialization_options = None;
|
||||
// Completing a JSX prop adds `=""` or `={}` by its type, as vtsls does by default;
|
||||
// TypeScript 7 adds no value unless asked.
|
||||
let jsx = json!({ "preferences": { "jsxAttributeCompletionStyle": "auto" } });
|
||||
merge_init_options(cfg, json!({ "typescript": jsx, "javascript": jsx }));
|
||||
cfg.tsserver_project = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1725,7 +1725,15 @@ fn typescript_7_runs_its_own_language_server() {
|
||||
assert_eq!(Path::new(&cfg.command), native, "{name}");
|
||||
assert_eq!(cfg.args, ["--lsp", "--stdio"]);
|
||||
assert_eq!(cfg.display_name.as_deref(), Some("TypeScript 7"));
|
||||
assert!(cfg.initialization_options.is_none());
|
||||
// The tsserver-based server's options don't apply; JSX prop completion adds a value.
|
||||
let options = serde_json::to_value(cfg.initialization_options.as_ref().unwrap()).unwrap();
|
||||
for language in ["typescript", "javascript"] {
|
||||
assert_eq!(
|
||||
options[language],
|
||||
serde_json::json!({ "preferences": { "jsxAttributeCompletionStyle": "auto" } })
|
||||
);
|
||||
}
|
||||
assert_eq!(options.as_object().unwrap().len(), 2, "{options}");
|
||||
}
|
||||
// Picked as a directory (its `lib`, as for older versions), too.
|
||||
s.languages.typescript.version = modules.join("typescript/lib").to_string_lossy().into_owned();
|
||||
|
||||
@@ -315,6 +315,41 @@ mod tests {
|
||||
assert_eq!(skipped.all().len(), 2);
|
||||
}
|
||||
|
||||
/// A workspace: members in repositories of their own (one with a nested repository, not a
|
||||
/// submodule), a plain folder, and a member that is a subfolder of a bigger repository; the
|
||||
/// container's agent folder links to each member and must not add a repository again.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn workspace_members_bring_their_repositories_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (api, web, plain, mono) = (base.join("api"), base.join("web"), base.join("plain"), base.join("mono"));
|
||||
git_init(&api);
|
||||
git_init(&api.join("libs/sdk"));
|
||||
git_init(&web);
|
||||
std::fs::create_dir_all(&plain).unwrap();
|
||||
git_init(&mono);
|
||||
let docs = mono.join("docs");
|
||||
std::fs::create_dir_all(&docs).unwrap();
|
||||
let container = base.join("ws");
|
||||
let links = container.join(".openidea/agent-root");
|
||||
std::fs::create_dir_all(&links).unwrap();
|
||||
for (name, target) in [("api", &api), ("web", &web), ("plain", &plain), ("docs", &docs)] {
|
||||
std::os::unix::fs::symlink(target, links.join(name)).unwrap();
|
||||
// A link elsewhere in the container: never followed either.
|
||||
std::os::unix::fs::symlink(target, container.join(name)).unwrap();
|
||||
}
|
||||
|
||||
let roots = [container.clone(), api.clone(), web.clone(), plain.clone(), docs.clone()];
|
||||
let repos = Repos::discover_roots(&roots, &|_| false).unwrap();
|
||||
let found: Vec<&Path> = repos.all().iter().map(|r| r.root()).collect();
|
||||
assert_eq!(found, [api.as_path(), &api.join("libs/sdk"), &mono, &web]);
|
||||
let file = api.join("libs/sdk/lib.rs");
|
||||
assert_eq!(repos.for_path(&file).unwrap().root(), api.join("libs/sdk"), "a nested file is its own repo's");
|
||||
assert_eq!(repos.for_path(&docs.join("a.md")).unwrap().root(), mono, "a subfolder member is its repo's");
|
||||
assert!(repos.for_path(&plain.join("x")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn side_by_side_repositories_without_an_enclosing_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -898,6 +898,16 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commit_default_inclusion_persists() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let store = SettingsStore::load(tmp.path(), None);
|
||||
assert!(store.effective().vcs.commit.include_changes_by_default);
|
||||
let settings = store.set(SettingsScope::Global, "vcs.commit.includeChangesByDefault", json!(false)).unwrap();
|
||||
assert!(!settings.vcs.commit.include_changes_by_default);
|
||||
assert!(!SettingsStore::load(tmp.path(), None).effective().vcs.commit.include_changes_by_default);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspection_profiles_live_in_their_layers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -83,6 +83,8 @@ On your own messages you can **Edit** (the messages after it are replaced; files
|
||||
|
||||
In an existing chat, open **Model › Refresh models** to discover newly available models without sending a message or changing the selection. If the agent can't switch in place, the choice stays pending. You can choose an effort level as soon as the provider reports the new model's options. On your next message, OpenIDEA reopens the same session and applies the model and any effort you selected before sending. If the session can't be reopened or rejects either choice, OpenIDEA restores the previous selection and reports the error without sending the message.
|
||||
|
||||
The model picker of an existing chat offers the agent's current model list, the same one New Task uses, plus the model the chat runs. It doesn't depend on what that chat's session reported when it started, so a model found by a refresh in any chat or in New Task can be chosen in every chat of that agent.
|
||||
|
||||
**Focus Agent Input** defaults to `⌘L` on macOS and `Ctrl+L` on Windows / Linux in every built-in keymap. When focus is inside your writable task conversation, in either an editor tab or the tool window, it returns focus to the message input without changing your draft, caret position or selection—even when pressed repeatedly. It does not send a message or jump through message history.
|
||||
|
||||
With focus anywhere else, the same shortcut jumps to the message input of the task shown in an editor tab or the tool window (the one you used last, if several are shown), unless a panel claims the shortcut there: in a code editor `⌘L` / `Ctrl+L` keeps its editor meaning (for example Go to Line), and in a terminal on Windows / Linux `Ctrl+L` still reaches the shell. It does not apply to archived tasks, subagent conversations or the New Task page, and does not take focus from open popups or dialogs. To change or remove the binding, open **Settings › Keymap › Agents › Focus Agent Input**.
|
||||
|
||||
@@ -36,7 +36,7 @@ Enable or disable postfix completion, individual templates, `Tab` expansion and
|
||||
|
||||
## Emmet
|
||||
|
||||
In HTML, Vue and Svelte files, and in CSS, SCSS, Less and Sass, `⇥` / `Tab` expands Emmet abbreviations, for example `ul>li*3` or `m10`. In markup files, the editor context menu also has **Update Tag with Emmet**, which rewrites the tag at the caret from an abbreviation.
|
||||
In HTML, Vue, Svelte, JSX and TSX files, and in CSS, SCSS, Less and Sass, `⇥` / `Tab` expands Emmet abbreviations, for example `ul>li*3` or `m10`. In markup files, the editor context menu also has **Update Tag with Emmet**, which rewrites the tag at the caret from an abbreviation.
|
||||
|
||||
## Write your own templates
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ With **Do not step into library scripts** (**Settings › Build, Execution, Depl
|
||||
|
||||
## Framework support
|
||||
|
||||
- **React**: JSX and TSX get their own highlighting modes and full TypeScript server support. There is no React-specific tooling beyond that.
|
||||
- **React**: JSX and TSX get their own highlighting modes and full TypeScript server support. Typing `>` closes the tag, renaming an opening or closing tag renames its partner, and completing a prop name or typing `=` after one inserts `""` for string props or `{}` for others (from the prop's type). `⇥` / `Tab` expands Emmet abbreviations among an element's children or after `return` / `=>`: `.card` becomes `<div className="card"></div>`.
|
||||
- **Vue**: `.vue` files are highlighted per block and served by Vue Language Server in hybrid mode. In a Vue CLI project without `tsconfig.json`, webpack's `resolve.alias` entries (such as `@/`) are read so imports resolve. Prettier formats `.vue` files. Emmet works in templates.
|
||||
- **Svelte**: Svelte Language Server; highlighting uses the HTML mode (script as TypeScript, style as CSS). Emmet works in markup.
|
||||
- **Astro**: Astro Language Server with its own highlighting mode. It needs Node.js; if it can't find one, select it in **Settings › Languages & Frameworks › JavaScript Runtime**.
|
||||
@@ -109,4 +109,3 @@ With **Do not step into library scripts** (**Settings › Build, Execution, Depl
|
||||
- Bun runs but can't be debugged: its inspector uses the WebKit protocol, which vscode-js-debug can't attach to.
|
||||
- Deno has run and debug support but no Deno language server; Deno files use the TypeScript servers.
|
||||
- Coverage of Deno tasks is not supported.
|
||||
- Emmet expands in HTML, Vue and Svelte, not in JSX.
|
||||
@@ -83,6 +83,8 @@ Codex 有自己的项目信任设置。如果它禁用了当前项目的 `.codex
|
||||
|
||||
在已有对话中,打开**模型 › 刷新模型**即可查找新上线的模型,不会发送消息或更改当前选择。如果 agent 无法直接切换,所选模型会保持待应用状态。提供商返回新模型支持的思考强度后,你就可以选择强度。发送下一条消息时,OpenIDEA 会先恢复原会话并应用所选模型和思考强度,再发送消息。如果无法恢复会话,或原会话不接受其中任何一项,OpenIDEA 会还原之前的选择并提示错误,不会发送该消息。
|
||||
|
||||
已有对话的模型选择器会列出该 agent 当前的模型列表(与新任务使用的相同),外加该对话正在使用的模型。它不依赖该对话会话启动时报告的列表,因此在任一对话或新任务中通过刷新找到的模型,可在该 agent 的所有对话中选用。
|
||||
|
||||
所有内置按键映射中,**聚焦 Agent 输入框** 的默认快捷键都是 macOS 上的 `⌘L`、Windows / Linux 上的 `Ctrl+L`。焦点位于你自己的可输入任务对话中时,无论对话显示在编辑器标签页还是工具窗口中,它都会将焦点移回消息输入框,保留草稿、光标位置和选区;重复按下也不会改变这些内容。它不会发送消息,也不会跳转消息历史。
|
||||
|
||||
焦点位于其他位置时,同一快捷键会跳转到编辑器标签页或工具窗口中显示的任务的消息输入框(显示多个时,选择你最近使用的那个),除非该位置有面板占用此快捷键:在代码编辑器中,`⌘L` / `Ctrl+L` 保留编辑器含义(例如“转到行”);在 Windows / Linux 的终端中,`Ctrl+L` 仍会发送给 shell。此快捷键不适用于已归档任务、子 agent 对话或“新建任务”页面,也不会从打开的弹出窗口或对话框中抢走焦点。要修改或移除绑定,请打开 **设置 › 按键映射 › 智能体 › 聚焦 Agent 输入框**。
|
||||
|
||||
@@ -36,7 +36,7 @@ items.for → for (var item : items) { … }
|
||||
|
||||
## Emmet
|
||||
|
||||
在 HTML、Vue、Svelte 文件以及 CSS、SCSS、Less、Sass 中,`⇥` / `Tab` 会展开 Emmet 缩写,例如 `ul>li*3` 或 `m10`。在标记语言文件中,编辑器右键菜单还提供 **使用 Emmet 更新标签**,用一个缩写改写光标所在的标签。
|
||||
在 HTML、Vue、Svelte、JSX、TSX 文件以及 CSS、SCSS、Less、Sass 中,`⇥` / `Tab` 会展开 Emmet 缩写,例如 `ul>li*3` 或 `m10`。在标记语言文件中,编辑器右键菜单还提供 **使用 Emmet 更新标签**,用一个缩写改写光标所在的标签。
|
||||
|
||||
## 编写自己的模板
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ Jest 和 Vitest 的输出会解析成测试树,支持 **重新运行失败的
|
||||
|
||||
## 框架支持
|
||||
|
||||
- **React**:JSX 和 TSX 有各自的高亮模式,并获得完整的 TypeScript 服务器支持;除此之外没有 React 专属功能。
|
||||
- **React**:JSX 和 TSX 有各自的高亮模式,并获得完整的 TypeScript 服务器支持。输入 `>` 会自动闭合标签,修改开始或结束标签名会同步修改另一端,补全属性名或在属性名后输入 `=` 会按属性类型插入 `""`(字符串)或 `{}`(其他类型)。在元素的子内容中或 `return` / `=>` 之后,`⇥` / `Tab` 会展开 Emmet 缩写:`.card` 会变成 `<div className="card"></div>`。
|
||||
- **Vue**:`.vue` 文件按块高亮,由 Vue Language Server 以 hybrid 模式提供支持。没有 `tsconfig.json` 的 Vue CLI 项目会读取 webpack 的 `resolve.alias`(如 `@/`),让 import 能正确解析。Prettier 可格式化 `.vue` 文件,模板中可用 Emmet。
|
||||
- **Svelte**:使用 Svelte Language Server;高亮沿用 HTML 模式(script 按 TypeScript、style 按 CSS),标记部分可用 Emmet。
|
||||
- **Astro**:使用 Astro Language Server,有专门的高亮模式。它需要 Node.js,找不到时请在 **设置 › 语言和框架 › JavaScript 运行时** 中选择。
|
||||
@@ -109,4 +109,3 @@ Jest 和 Vitest 的输出会解析成测试树,支持 **重新运行失败的
|
||||
- Bun 可以运行但无法调试:它的 inspector 使用 WebKit 协议,vscode-js-debug 无法附加。
|
||||
- Deno 支持运行和调试,但没有 Deno 语言服务器,Deno 文件使用 TypeScript 服务器。
|
||||
- 不支持 Deno task 的覆盖率。
|
||||
- Emmet 只在 HTML、Vue 和 Svelte 中展开,JSX 中不可用。
|
||||
@@ -0,0 +1,74 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("Appearance keeps themes and UI font controls grouped across Settings widths", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 800 });
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("Use custom font");
|
||||
await dialog.getByRole("treeitem", { name: "Appearance", exact: true }).click();
|
||||
await search.clear();
|
||||
|
||||
const theme = dialog.getByRole("button", { name: "Theme", exact: true });
|
||||
const sync = dialog.getByRole("checkbox", { name: "Sync with OS", exact: true });
|
||||
const preferences = dialog.getByRole("button", { name: "Preferred themes", exact: true });
|
||||
const more = dialog.getByRole("button", { name: "Get more themes", exact: true });
|
||||
const font = dialog.getByRole("combobox", { name: "UI font", exact: true });
|
||||
const fallback = dialog.getByRole("combobox", { name: "UI fallback font", exact: true });
|
||||
const size = dialog.getByRole("textbox", { name: "UI font size", exact: true });
|
||||
const custom = dialog.getByRole("checkbox", { name: "Use custom font:", exact: true });
|
||||
await expect(preferences).toBeDisabled();
|
||||
await expect(font).toBeDisabled();
|
||||
await expect(size).toBeDisabled();
|
||||
await expect(fallback).toBeDisabled();
|
||||
|
||||
const [themeBox, gearBox, linkBox, fontBox, sizeBox, fallbackBox] = await Promise.all(
|
||||
[theme, preferences, more, font, size, fallback].map((control) => control.boundingBox()),
|
||||
);
|
||||
if (!themeBox || !gearBox || !linkBox || !fontBox || !sizeBox || !fallbackBox) {
|
||||
throw new Error("Missing Appearance control bounds");
|
||||
}
|
||||
expect(linkBox.y).toBeGreaterThan(themeBox.y + themeBox.height);
|
||||
expect(gearBox.x).toBeGreaterThan(themeBox.x + themeBox.width);
|
||||
expect(gearBox.y + gearBox.height / 2).toBeCloseTo(themeBox.y + themeBox.height / 2, 0);
|
||||
expect(sizeBox.y).toBeCloseTo(fontBox.y, 0);
|
||||
expect(sizeBox.x).toBeGreaterThan(fontBox.x + fontBox.width);
|
||||
expect(fallbackBox.x).toBeCloseTo(fontBox.x, 0);
|
||||
expect(fallbackBox.y).toBeGreaterThan(fontBox.y);
|
||||
|
||||
await sync.check();
|
||||
await expect(theme).toBeDisabled();
|
||||
for (const width of [580, 520]) {
|
||||
await page.setViewportSize({ width, height: 800 });
|
||||
await preferences.click();
|
||||
const popup = page.getByRole("dialog", { name: "Preferred themes", exact: true });
|
||||
const light = popup.getByRole("button", { name: "Preferred light theme", exact: true });
|
||||
const dark = popup.getByRole("button", { name: "Preferred dark theme", exact: true });
|
||||
await expect(light).toBeInViewport({ ratio: 1 });
|
||||
await expect(dark).toBeInViewport({ ratio: 1 });
|
||||
const [lightBox, darkBox] = await Promise.all([light.boundingBox(), dark.boundingBox()]);
|
||||
if (!lightBox || !darkBox) throw new Error("Missing preferred theme bounds");
|
||||
expect(lightBox.x).toBeCloseTo(darkBox.x, 0);
|
||||
expect(lightBox.width).toBeCloseTo(darkBox.width, 0);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(popup).toBeHidden();
|
||||
for (const field of [font, size, fallback]) await expect(field).toBeInViewport({ ratio: 1 });
|
||||
const [narrowFont, narrowSize, narrowFallback] = await Promise.all(
|
||||
[font, size, fallback].map((control) => control.boundingBox()),
|
||||
);
|
||||
if (!narrowFont || !narrowSize || !narrowFallback) throw new Error("Missing narrow font control bounds");
|
||||
expect(narrowSize.y).toBeGreaterThan(narrowFont.y);
|
||||
expect(narrowFallback.x).toBeCloseTo(narrowFont.x, 0);
|
||||
}
|
||||
|
||||
await custom.check();
|
||||
await font.fill("Inter");
|
||||
await size.fill("15");
|
||||
await fallback.fill("Noto Sans CJK SC");
|
||||
await fallback.press("Enter");
|
||||
await expect(font).toHaveValue("Inter");
|
||||
await expect(size).toHaveValue("15");
|
||||
await expect(fallback).toHaveValue("Noto Sans CJK SC");
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { PatchFile } from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const repo = "/dev/billing";
|
||||
const path = "/tmp/release-2026/requests/adjust-invoices.patch";
|
||||
const patch = "diff --git a/ledger/invoice.ts b/ledger/invoice.ts";
|
||||
const invoice: PatchFile = {
|
||||
path: "ledger/invoice.ts",
|
||||
oldPath: null,
|
||||
kind: "modified",
|
||||
added: 3,
|
||||
removed: 1,
|
||||
binary: false,
|
||||
applies: true,
|
||||
};
|
||||
|
||||
async function openPatch(page: Page, source: "file" | "clipboard", files: PatchFile[]) {
|
||||
await page.evaluate(
|
||||
async ({ source, repo, path, patch, files }) => {
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.fs_read_text = () => patch;
|
||||
handlers.clipboard_text = () => patch;
|
||||
handlers.vcs_patch_preview = () => files;
|
||||
handlers.vcs_apply_patch = () => ({ applied: [files[0]?.path], conflicts: [] });
|
||||
const store = "/src/features/vcs/store.ts";
|
||||
const context = "/src/platform/context.ts";
|
||||
const actions = "/src/platform/actions.ts";
|
||||
(await import(/* @vite-ignore */ store)).useVcs.setState({ available: true, root: repo, repo, roots: [repo] });
|
||||
(await import(/* @vite-ignore */ context)).setContext("vcsAvailable", true);
|
||||
const { executeAction } = await import(/* @vite-ignore */ actions);
|
||||
await executeAction(source === "file" ? "vcs.applyPatch" : "vcs.applyPatchFromClipboard", path);
|
||||
},
|
||||
{ source, repo, path, patch, files },
|
||||
);
|
||||
}
|
||||
|
||||
test("Apply Patch keeps the source, repository and file status aligned in a narrow dialog", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 485, height: 490 });
|
||||
await stubDesktop(page);
|
||||
await openPatch(page, "file", [
|
||||
invoice,
|
||||
{ ...invoice, path: "apps/batch/ledger/international/settlement/settle-invoice.ts", applies: false },
|
||||
...Array.from({ length: 20 }, (_, i) => ({ ...invoice, path: `ledger/settlement-${i + 1}.ts` })),
|
||||
]);
|
||||
const dialog = page.getByRole("dialog", { name: "Apply Patch: adjust-invoices.patch", exact: true });
|
||||
const source = dialog.getByRole("textbox", { name: "Patch source", exact: true });
|
||||
const target = dialog.getByRole("textbox", { name: "Repository", exact: true });
|
||||
const list = dialog.getByRole("listbox", { name: "Patch files", exact: true });
|
||||
|
||||
await expect(source).toHaveValue(path);
|
||||
await expect(source).not.toBeEditable();
|
||||
await expect(target).toHaveValue(repo);
|
||||
await expect(dialog.getByRole("heading", { name: "Patch files", exact: true })).toBeVisible();
|
||||
await expect(dialog.getByText("22 files", { exact: true })).toBeVisible();
|
||||
expect((await source.boundingBox())!.y).toBeLessThan((await target.boundingBox())!.y);
|
||||
expect((await target.boundingBox())!.y).toBeLessThan((await list.boundingBox())!.y);
|
||||
|
||||
const stats = list.getByText("+3 −1", { exact: true });
|
||||
const first = (await stats.nth(0).boundingBox())!;
|
||||
const second = (await stats.nth(1).boundingBox())!;
|
||||
expect(Math.abs(first.x - second.x)).toBeLessThan(1);
|
||||
await expect(list.getByLabel("Does not apply cleanly", { exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await expect(dialog.getByRole("status")).toHaveText("1 file will be merged; conflicts open in the merge tool");
|
||||
await list.press("End");
|
||||
await expect(list.getByText("settlement-20.ts", { exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await expect(dialog.getByRole("button", { name: "Apply", exact: true })).toBeInViewport({ ratio: 1 });
|
||||
expect(await dialog.locator("[data-dialog-body]").evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
expect(await ipcCalls(page, "vcs_apply_patch")).toEqual([]);
|
||||
});
|
||||
|
||||
test("Apply Patch previews clipboard contents and applies them to the previewed repository", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await openPatch(page, "clipboard", []);
|
||||
const dialog = page.getByRole("dialog", { name: "Apply Patch: Clipboard", exact: true });
|
||||
await expect(dialog.getByRole("textbox", { name: "Patch source", exact: true })).toHaveValue("Clipboard");
|
||||
await expect(dialog.getByText("No changes", { exact: true })).toBeVisible();
|
||||
const apply = dialog.getByRole("button", { name: "Apply", exact: true });
|
||||
await expect(apply).toBeDisabled();
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
|
||||
await openPatch(page, "clipboard", [invoice]);
|
||||
await expect(dialog.getByText("1 file", { exact: true })).toBeVisible();
|
||||
await expect(apply).toBeEnabled();
|
||||
await apply.click();
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect.poll(() => ipcCalls(page, "vcs_apply_patch")).toEqual([{ repo, patch }]);
|
||||
});
|
||||
@@ -76,6 +76,34 @@ test("⌘K commits the checked changes with the typed message", async ({ workben
|
||||
await expect(changes.getByRole("checkbox", { name: "Include build.gradle.kts in commit" })).toBeHidden();
|
||||
});
|
||||
|
||||
test("turning off default inclusion starts Commit with all files unchecked", async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const label = "Include changes in the commit by default";
|
||||
await settings.getByRole("textbox", { name: "Search settings" }).fill(label);
|
||||
await settings.getByRole("treeitem", { name: "Commit", exact: true }).click();
|
||||
const toggle = settings.getByRole("checkbox", { name: label, exact: true });
|
||||
await expect(toggle).toBeChecked();
|
||||
await toggle.click();
|
||||
await settings.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await expect(settings).not.toBeVisible();
|
||||
|
||||
await stubRepository(page);
|
||||
await page.keyboard.press("Meta+k");
|
||||
const panel = page.getByRole("region", { name: "Commit", exact: true });
|
||||
const changes = panel.getByRole("tree", { name: "Changes" });
|
||||
const tracked = changes.getByRole("checkbox", { name: "Include build.gradle.kts in commit" });
|
||||
await expect(tracked).toHaveAttribute("aria-checked", "false");
|
||||
await expect(changes.getByRole("checkbox", { name: "Include Unversioned Files in commit" })).not.toBeChecked();
|
||||
await tracked.click();
|
||||
await expect(tracked).toBeChecked();
|
||||
await panel.getByRole("textbox", { name: "Commit message" }).fill("Commit the selected file");
|
||||
await panel.getByRole("button", { name: "Commit", exact: true }).click();
|
||||
await expect.poll(() => ipcCalls(page, "vcs_commit")).toHaveLength(1);
|
||||
const [committed] = await ipcCalls(page, "vcs_commit");
|
||||
expect(committed!.options).toMatchObject({ stage: [`${ROOT}/build.gradle.kts`] });
|
||||
});
|
||||
|
||||
test("commit message history opens above the message without an empty icon column", async ({ workbench: page }) => {
|
||||
await stubRepository(page);
|
||||
await page.keyboard.press("Meta+k");
|
||||
|
||||
@@ -2,7 +2,7 @@ import { expect, test } from "./fixtures";
|
||||
|
||||
for (const [id, selector] of [
|
||||
["general", "[class*='radios'] label"],
|
||||
["notifications", "table tbody td:first-child"],
|
||||
["notifications", "[role='listbox'] [role='option'] > [class*='notificationGroupLabel']"],
|
||||
["keymap", "[class*='presetLabel']"],
|
||||
["editor.inspections", "[class*='profileControls'] > span:first-child"],
|
||||
["vcs.issueNavigation", "[class*='pageBody'] button:not([aria-label])"],
|
||||
|
||||
@@ -39,3 +39,55 @@ test("Compare With… compares against a file picked in the browser", async ({ w
|
||||
const tabs = page.getByRole("tablist", { name: "Editor tabs" });
|
||||
await expect(tabs.getByRole("tab", { name: /other\.md/ })).toBeVisible({ timeout: 15_000 });
|
||||
});
|
||||
|
||||
for (const fragment of [false, true]) {
|
||||
test(`clipboard comparison labels the ${fragment ? "selection" : "file"} and its origin`, async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.evaluate(async (fragment) => {
|
||||
const path = "/dev/acme-api/src/estimate.ts";
|
||||
const source = "const estimate = 4;\nconst total = estimate + 1;\n";
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
(await import(/* @vite-ignore */ backend)).docBackend().files.set(path, source);
|
||||
const service = "/src/workbench/contributions.ts";
|
||||
await (await import(/* @vite-ignore */ service)).editorService().openFile(path);
|
||||
const editor = "/src/editor/api.ts";
|
||||
const { view } = (await import(/* @vite-ignore */ editor)).activeEditor()!;
|
||||
view.dispatch({ selection: { anchor: 0, head: fragment ? source.indexOf("\n") : 0 } });
|
||||
view.focus();
|
||||
Object.defineProperty(navigator, "clipboard", {
|
||||
value: { readText: async () => "const estimate = 3;\n" },
|
||||
configurable: true,
|
||||
});
|
||||
localStorage.setItem("openidea.vcs.diffOptions", JSON.stringify({ mode: "split", collapse: false }));
|
||||
const actions = "/src/platform/actions.ts";
|
||||
await (await import(/* @vite-ignore */ actions)).executeAction("diff.compareWithClipboard");
|
||||
}, fragment);
|
||||
|
||||
const toolbar = page.getByRole("toolbar", { name: "Diff", exact: true });
|
||||
const viewer = toolbar.locator("..");
|
||||
const file = fragment ? "Selection from estimate.ts" : "estimate.ts";
|
||||
const caption = viewer.getByTitle(`${file} src`, { exact: true });
|
||||
const clipboard = viewer.getByTitle("From Clipboard", { exact: true });
|
||||
await expect(clipboard).toBeVisible();
|
||||
await expect(caption.getByText("src", { exact: true })).toBeVisible();
|
||||
await expect(caption.getByText(file, { exact: true })).toHaveCSS("font-size", "13px");
|
||||
await expect(caption.getByText("src", { exact: true })).toHaveCSS("font-size", "12px");
|
||||
const sides = viewer.locator(".cm-content");
|
||||
await expect(sides.first()).toContainText("const estimate = 3;");
|
||||
await expect(sides.last()).toContainText("const estimate = 4;");
|
||||
const remainingLine = sides.last().getByText("const total =", { exact: false });
|
||||
if (fragment) await expect(remainingLine).toBeHidden();
|
||||
else await expect(remainingLine).toBeVisible();
|
||||
const tabs = page.getByRole("tablist", { name: "Editor tabs" });
|
||||
const title = `Clipboard ↔ estimate.ts${fragment ? " (selection)" : ""}`;
|
||||
await expect(tabs.getByRole("tab", { name: title, exact: true })).toBeVisible();
|
||||
|
||||
await toolbar.getByRole("button", { name: "Swap Sides", exact: true }).click();
|
||||
await expect(caption).toBeVisible();
|
||||
expect((await caption.boundingBox())!.x).toBeLessThan((await clipboard.boundingBox())!.x);
|
||||
await toolbar.getByRole("button", { name: "Settings", exact: true }).click();
|
||||
await page.getByRole("menuitemcheckbox", { name: "Unified Viewer", exact: true }).click();
|
||||
await expect(viewer.getByTitle(`${file} src → From Clipboard`, { exact: true })).toBeVisible();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
async function openConsoleSettings(page: Page) {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("Fold console lines that contain");
|
||||
await dialog.getByRole("treeitem", { name: "Console", exact: true }).click();
|
||||
await search.clear();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
test("Console settings put folding between the basic controls and log colors", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 740 });
|
||||
const dialog = await openConsoleSettings(page);
|
||||
const wrap = dialog.getByRole("checkbox", { name: "Use soft wraps in console", exact: true });
|
||||
const override = dialog.getByRole("checkbox", { name: /^Override console cycle buffer size/ });
|
||||
const size = dialog.getByRole("textbox", { name: "Override console cycle buffer size", exact: true });
|
||||
const encoding = dialog.getByRole("button", { name: "Default encoding", exact: true });
|
||||
const list = dialog.getByRole("listbox", { name: "Fold console lines that contain", exact: true });
|
||||
const colors = dialog.getByRole("checkbox", { name: "Colour log lines by level", exact: true });
|
||||
await expect(list).toBeVisible();
|
||||
expect((await list.boundingBox())!.width).toBeGreaterThan(480);
|
||||
const controls = [wrap, override, encoding, list, colors];
|
||||
const positions = await Promise.all(controls.map(async (control) => (await control.boundingBox())!.y));
|
||||
positions.forEach((y, index) => {
|
||||
if (index > 0) expect(y).toBeGreaterThan(positions[index - 1]!);
|
||||
});
|
||||
|
||||
for (const width of [580, 520]) {
|
||||
await page.setViewportSize({ width, height: 740 });
|
||||
for (const control of [...controls, size]) await expect(control).toBeInViewport({ ratio: 1 });
|
||||
expect(await list.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
}
|
||||
});
|
||||
|
||||
test("Console settings keep the stored buffer size and fold rules across Apply and reopen", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const dialog = await openConsoleSettings(page);
|
||||
const override = dialog.getByRole("checkbox", { name: /^Override console cycle buffer size/ });
|
||||
const size = dialog.getByRole("textbox", { name: "Override console cycle buffer size", exact: true });
|
||||
const list = dialog.getByRole("listbox", { name: "Fold console lines that contain", exact: true });
|
||||
await override.check();
|
||||
await expect(size).toBeEnabled();
|
||||
await size.fill("2048");
|
||||
await override.uncheck();
|
||||
await expect(size).toBeDisabled();
|
||||
await expect(size).toHaveValue("2048");
|
||||
|
||||
await dialog.getByRole("button", { name: "Add", exact: true }).click();
|
||||
const pattern = list.getByRole("textbox", { name: "Pattern", exact: true });
|
||||
await pattern.fill("at example.retry");
|
||||
await pattern.press("Enter");
|
||||
await expect(list.getByRole("option", { name: "at example.retry", exact: true })).toBeVisible();
|
||||
const apply = dialog.getByRole("button", { name: "Apply", exact: true });
|
||||
await apply.click();
|
||||
await expect(apply).toBeDisabled();
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
|
||||
await openConsoleSettings(page);
|
||||
await expect(override).not.toBeChecked();
|
||||
await expect(size).toBeDisabled();
|
||||
await expect(size).toHaveValue("2048");
|
||||
await expect(list.getByRole("option", { name: "at example.retry", exact: true })).toBeVisible();
|
||||
await override.check();
|
||||
await expect(size).toBeEnabled();
|
||||
await expect(size).toHaveValue("2048");
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("Date Formats keeps its preview beside the formatting controls and updates it while editing", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.clock.setFixedTime(new Date(2026, 0, 16, 14, 35));
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
const openPage = async () => {
|
||||
await search.fill("Date Formats");
|
||||
await dialog.getByRole("treeitem", { name: "Date Formats", exact: true }).click();
|
||||
await search.clear();
|
||||
};
|
||||
await openPage();
|
||||
|
||||
const override = dialog.getByRole("checkbox", { name: "Override system date and time format" });
|
||||
const pattern = dialog.getByRole("textbox", { name: /^Date format/ });
|
||||
const hour = dialog.getByRole("checkbox", { name: "Use 24-hour time format" });
|
||||
const pretty = dialog.getByRole("checkbox", { name: "Use pretty formatting" });
|
||||
const hint = dialog.getByText("Placeholders: yyyy, yy, MMMM, MMM, MM, M, dd, d", { exact: true });
|
||||
const initialPreview = dialog.getByText(/Today .* · /);
|
||||
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 680 });
|
||||
await expect(async () => {
|
||||
const [hourBox, previewBox, prettyBox, patternBox, hintBox] = await Promise.all(
|
||||
[hour, initialPreview, pretty, pattern, hint].map((control) => control.boundingBox()),
|
||||
);
|
||||
expect(previewBox!.y).toBeGreaterThan(hourBox!.y + hourBox!.height);
|
||||
expect(prettyBox!.y).toBeGreaterThan(previewBox!.y + previewBox!.height);
|
||||
if (width === 1120) {
|
||||
expect(hintBox!.x).toBeGreaterThan(patternBox!.x + patternBox!.width);
|
||||
expect(hintBox!.y + hintBox!.height).toBeLessThanOrEqual(patternBox!.y + patternBox!.height + 1);
|
||||
} else {
|
||||
expect(hintBox!.y).toBeGreaterThanOrEqual(patternBox!.y + patternBox!.height);
|
||||
}
|
||||
}).toPass({ timeout: 3000 });
|
||||
}
|
||||
|
||||
const preview = dialog.getByRole("status", { name: /^Preview/ });
|
||||
await expect(pattern).toBeDisabled();
|
||||
await expect(hour).toBeDisabled();
|
||||
await expect(pretty).toBeEnabled();
|
||||
await override.check();
|
||||
await pattern.fill("yyyy-MM-dd");
|
||||
await expect(preview).toHaveText("Today 12:35 · 2026-01-13 14:35");
|
||||
await hour.uncheck();
|
||||
await expect(preview).toHaveText("Today 12:35 PM · 2026-01-13 2:35 PM");
|
||||
await pretty.uncheck();
|
||||
await expect(preview).toHaveText("2026-01-16 12:35 PM · 2026-01-13 2:35 PM");
|
||||
|
||||
await dialog.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await page.keyboard.press("Meta+,");
|
||||
await openPage();
|
||||
await expect(override).toBeChecked();
|
||||
await expect(pattern).toHaveValue("yyyy-MM-dd");
|
||||
await expect(hour).not.toBeChecked();
|
||||
await expect(pretty).not.toBeChecked();
|
||||
await expect(preview).toHaveText("2026-01-16 12:35 PM · 2026-01-13 2:35 PM");
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Debugger Data Views keeps the hover delay with its setting at each window width", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 740 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
window.__ipc.handlers.settings_get_global = () => ({});
|
||||
});
|
||||
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("value tooltip delay");
|
||||
await settings.getByRole("treeitem", { name: "Data Views", exact: true }).click();
|
||||
await search.clear();
|
||||
|
||||
const hover = settings.getByRole("checkbox", { name: "Show value tooltip on mouse hover", exact: true });
|
||||
const delay = settings.getByRole("textbox", { name: "Value tooltip delay (ms)", exact: true });
|
||||
const selection = settings.getByRole("checkbox", { name: "Show value tooltip on code selection", exact: true });
|
||||
const sort = settings.getByRole("checkbox", { name: "Sort values alphabetically", exact: true });
|
||||
const editor = settings.getByRole("region", { name: "Editor", exact: true });
|
||||
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 740 });
|
||||
await expect(delay).toBeInViewport({ ratio: 1 });
|
||||
const [toggleBox, delayBox, selectionBox] = await Promise.all(
|
||||
[hover, delay, selection].map((control) => control.boundingBox()),
|
||||
);
|
||||
if (!toggleBox || !delayBox || !selectionBox) throw new Error("Missing Data Views control bounds");
|
||||
expect(delayBox.y + delayBox.height).toBeLessThan(selectionBox.y);
|
||||
if (width === 1120) {
|
||||
expect(delayBox.x).toBeGreaterThan(toggleBox.x + toggleBox.width);
|
||||
expect(Math.abs(delayBox.y + delayBox.height / 2 - toggleBox.y - toggleBox.height / 2)).toBeLessThan(3);
|
||||
} else {
|
||||
expect(delayBox.y).toBeGreaterThan(toggleBox.y + toggleBox.height);
|
||||
}
|
||||
}
|
||||
await expect(editor.getByRole("checkbox", { name: "Show values inline", exact: true })).toBeVisible();
|
||||
await expect(editor.getByRole("checkbox", { name: "Sort values alphabetically", exact: true })).toHaveCount(0);
|
||||
await expect(sort).toBeVisible();
|
||||
|
||||
await expect(hover).toBeChecked();
|
||||
await expect(delay).toHaveValue("700");
|
||||
await delay.fill("900");
|
||||
await selection.uncheck();
|
||||
await hover.uncheck();
|
||||
await expect(delay).toBeDisabled();
|
||||
await expect(delay).toHaveValue("900");
|
||||
await selection.check();
|
||||
await expect(hover).not.toBeChecked();
|
||||
await hover.check();
|
||||
await expect(delay).toBeEnabled();
|
||||
await expect(delay).toHaveValue("900");
|
||||
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(settings).toBeHidden();
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import type { Locator } from "@playwright/test";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function expectAligned(grid: Locator, names: string[]) {
|
||||
await expect(grid.getByRole("columnheader")).toHaveText(names);
|
||||
await expect
|
||||
.poll(() =>
|
||||
grid.evaluate((element) => {
|
||||
const head = [...element.querySelectorAll('[role="columnheader"]')].filter(
|
||||
(cell) => cell.getClientRects().length,
|
||||
);
|
||||
const row = element.querySelector('[aria-rowindex="2"]');
|
||||
const cells = [...(row?.querySelectorAll('[role="gridcell"]') ?? [])].filter(
|
||||
(cell) => cell.getClientRects().length,
|
||||
);
|
||||
return (
|
||||
cells.length === head.length &&
|
||||
head.every((cell, index) => {
|
||||
const header = cell.getBoundingClientRect();
|
||||
const value = cells[index]!.getBoundingClientRect();
|
||||
return Math.abs(header.x - value.x) < 1 && Math.abs(header.width - value.width) < 1;
|
||||
})
|
||||
);
|
||||
}),
|
||||
)
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
test("directory comparison mirrors both sides and keeps the headers aligned while the list scrolls", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1220, height: 780 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const entry = {
|
||||
leftKind: "file",
|
||||
rightKind: "file",
|
||||
status: "different",
|
||||
leftSize: 120,
|
||||
rightSize: 144,
|
||||
leftModified: Date.UTC(2026, 9, 8, 12),
|
||||
rightModified: Date.UTC(2026, 9, 9, 12),
|
||||
};
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.fs_entry_kind = ({ path }) => (String(path).endsWith(".txt") ? "file" : "dir");
|
||||
handlers.cancel_request = () => null;
|
||||
handlers.fs_read_text = () => "";
|
||||
handlers.fs_compare_directories = () => [
|
||||
{ ...entry, path: "00-configuration.txt" },
|
||||
...Array.from({ length: 65 }, (_, index) => ({ ...entry, path: `log-${index}.txt` })),
|
||||
{ ...entry, path: "only-left.txt", rightKind: null, rightSize: null, status: "leftOnly" },
|
||||
{ ...entry, path: "shared.txt", status: "equal" },
|
||||
];
|
||||
const actions = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actions);
|
||||
await executeAction("toolwindow.hideAll");
|
||||
await executeAction("diff.compareDirectories", ["/dev/acme-api/source", "/dev/acme-api/target"]);
|
||||
});
|
||||
|
||||
const grid = page.getByRole("grid", { name: "Compared files" });
|
||||
const filter = page.getByRole("textbox", { name: "Filter by name" });
|
||||
const source = page.getByText("Left: source", { exact: true });
|
||||
const target = page.getByText("Right: target", { exact: true });
|
||||
await expect(source).toBeVisible();
|
||||
await expect(target).toBeVisible();
|
||||
const [pathBox, filterBox] = await Promise.all([source.boundingBox(), filter.boundingBox()]);
|
||||
if (!pathBox || !filterBox) throw new Error("Missing comparison toolbar bounds");
|
||||
expect(pathBox.y).toBeGreaterThanOrEqual(filterBox.y + filterBox.height);
|
||||
await expectAligned(grid, ["Name", "Size", "Date", "", "Date", "Size", "Name"]);
|
||||
const first = grid.getByRole("row").filter({ has: page.getByRole("gridcell", { name: "00-configuration.txt" }) });
|
||||
const values = await first.getByRole("gridcell").allTextContents();
|
||||
expect(values.at(0)).toBe("00-configuration.txt");
|
||||
expect(values.at(1)).toBe("120 B");
|
||||
expect(values.at(-2)).toBe("144 B");
|
||||
expect(values.at(-1)).toBe("00-configuration.txt");
|
||||
const rows = grid.locator('[role="rowgroup"][tabindex="0"]');
|
||||
expect(await rows.evaluate((el) => el.scrollHeight)).toBeGreaterThan(await rows.evaluate((el) => el.clientHeight));
|
||||
|
||||
await page.setViewportSize({ width: 630, height: 740 });
|
||||
await expectAligned(grid, ["Name", "Size", "", "Size", "Name"]);
|
||||
await expect(first.getByRole("gridcell").first()).toHaveAttribute("title", /00-configuration.txt.*120 B/);
|
||||
const setContainerType = (value: string) =>
|
||||
filter.evaluate((el, type) => {
|
||||
const container = el.parentElement?.parentElement;
|
||||
if (!container) throw new Error("Missing directory comparison container");
|
||||
container.style.containerType = type;
|
||||
}, value);
|
||||
await setContainerType("normal");
|
||||
await expectAligned(grid, ["Name", "Size", "Date", "", "Date", "Size", "Name"]);
|
||||
await expect(first.getByRole("gridcell").first()).toBeInViewport({ ratio: 1 });
|
||||
await setContainerType("");
|
||||
await page.setViewportSize({ width: 360, height: 740 });
|
||||
await expectAligned(grid, ["Name", "", "Name"]);
|
||||
|
||||
await page.setViewportSize({ width: 630, height: 740 });
|
||||
await filter.fill("shared");
|
||||
await expect(page.getByText("No matching differences", { exact: true })).toBeVisible();
|
||||
await page.getByRole("button", { name: "Show identical files" }).click();
|
||||
const shared = grid.getByRole("gridcell", { name: "shared.txt", exact: true });
|
||||
await expect(shared).toHaveCount(2);
|
||||
await shared.first().click();
|
||||
await expect(page.getByRole("button", { name: "Copy to Right", exact: true })).toBeEnabled();
|
||||
await expect(page.getByRole("toolbar", { name: "Diff", exact: true })).toBeVisible();
|
||||
});
|
||||
@@ -121,3 +121,82 @@ test("Git Log keeps filters and actions inside the commit pane at the minimum wi
|
||||
await toolbar.getByRole("button", { name: "More Filters" }).click();
|
||||
await expect(page.getByRole("menuitem", { name: "Paths" })).toBeVisible();
|
||||
});
|
||||
|
||||
test("the Paths filter replaces the repository filter and can be cleared from overflow", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.evaluate(async () => {
|
||||
const storeModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ storeModule);
|
||||
const root = "/dev/acme-api";
|
||||
const other = "/dev/tools";
|
||||
const branch = (name: string) => ({
|
||||
name,
|
||||
current: true,
|
||||
remote: false,
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
lastCommitMs: 0,
|
||||
commit: "",
|
||||
});
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.vcs_branches = ({ repo }) => [branch(repo === other ? "tools-main" : "api-main")];
|
||||
useVcs.setState({ roots: [root, other], branches: [branch("api-main")] });
|
||||
handlers.fs_read_dir = ({ path }) =>
|
||||
path === root ? [{ name: "api.ts", path: root + "/api.ts", kind: "file", size: 0, mtimeMs: 0 }] : [];
|
||||
const log = handlers.vcs_log!;
|
||||
handlers.vcs_log = (args) => {
|
||||
const { paths } = args.query as { paths?: string[] };
|
||||
return log({ ...args, query: { ...(args.query as object), skip: paths?.includes(root + "/api.ts") ? 1 : 0 } });
|
||||
};
|
||||
});
|
||||
await page.setViewportSize({ width: 600, height: 550 });
|
||||
const toolbar = page.getByRole("toolbar", { name: "Log filters" });
|
||||
const overflow = toolbar.getByRole("button", { name: "More Filters" });
|
||||
await overflow.click();
|
||||
await page.getByRole("menuitem", { name: "Paths", exact: true }).click();
|
||||
const acme = page.getByRole("menuitemcheckbox", { name: "acme-api" });
|
||||
await expect(acme).toHaveAttribute("aria-checked", "true");
|
||||
await acme.click();
|
||||
await overflow.click();
|
||||
await page.getByRole("menuitem", { name: "Paths: tools", exact: true }).click();
|
||||
await expect(acme).toHaveAttribute("aria-checked", "false");
|
||||
await page.getByRole("menuitem", { name: "Select in Tree…" }).click();
|
||||
const picker = page.getByRole("dialog", { name: "Filter by Paths" });
|
||||
const pathTree = picker.getByRole("tree", { name: "Files and folders" });
|
||||
const repo = pathTree.getByRole("checkbox", { name: "acme-api" });
|
||||
await expect(repo).toBeVisible();
|
||||
const tree = await pathTree.boundingBox();
|
||||
const row = await repo.locator("xpath=ancestor::label").boundingBox();
|
||||
expect(tree!.x + tree!.width).toBeGreaterThanOrEqual(row!.x + row!.width);
|
||||
await repo.check();
|
||||
await picker.getByRole("button", { name: "OK" }).click();
|
||||
await page.setViewportSize({ width: 1100, height: 720 });
|
||||
const branches = page.getByRole("tree", { name: "Branches", exact: true });
|
||||
await expect(branches.getByText("api-main", { exact: true })).toBeVisible();
|
||||
await expect(branches.getByText("tools-main", { exact: true })).toHaveCount(0);
|
||||
await page.setViewportSize({ width: 600, height: 550 });
|
||||
|
||||
await overflow.click();
|
||||
await page.getByRole("menuitem", { name: /^Paths:/ }).click();
|
||||
await page.getByRole("menuitem", { name: "Select in Tree…" }).click();
|
||||
await repo.uncheck();
|
||||
await repo.locator("xpath=ancestor::*[@data-row]").locator("[data-tree-toggle]").click();
|
||||
await picker.getByRole("checkbox", { name: "api.ts" }).check();
|
||||
await picker.getByRole("button", { name: "OK" }).click();
|
||||
const firstCommit = page.getByRole("listbox", { name: "Commits" }).getByRole("option").first();
|
||||
await expect(firstCommit.getByText("Commit 1", { exact: true })).toBeVisible();
|
||||
await overflow.click();
|
||||
await page.getByRole("menuitem", { name: /^Paths:/ }).click();
|
||||
await page.getByRole("menuitem", { name: "All" }).click();
|
||||
await expect(firstCommit.getByText("Commit 0", { exact: true })).toBeVisible();
|
||||
|
||||
await overflow.click();
|
||||
await page.getByRole("menuitem", { name: "Paths", exact: true }).click();
|
||||
await expect(page.getByRole("menuitemcheckbox", { name: "api.ts" })).toBeVisible();
|
||||
await page.getByRole("menuitem", { name: "Select…", exact: true }).click();
|
||||
await picker.getByRole("textbox", { name: "Paths" }).fill("acme-api/api.ts");
|
||||
await picker.getByRole("button", { name: "OK" }).click();
|
||||
await expect(firstCommit.getByText("Commit 1", { exact: true })).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Git settings keep the executable and Test button together at narrow widths", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 560, height: 740 });
|
||||
await stubDesktop(page);
|
||||
const gitPath = "C:/Program Files/Git/cmd/git.exe";
|
||||
const longPath = `C:/${"long-directory-name".repeat(20)}/git.exe`;
|
||||
await page.evaluate(
|
||||
({ gitPath, longPath }) => {
|
||||
window.__ipc.handlers.vcs_detected_git = () => gitPath;
|
||||
window.__ipc.handlers.vcs_git_version = ({ path }) => ({ path: path || longPath, version: "git version 2.49.0" });
|
||||
window.__ipc.handlers.git_credentials = () => [];
|
||||
},
|
||||
{ gitPath, longPath },
|
||||
);
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("Path to Git executable");
|
||||
await dialog.getByRole("treeitem", { name: "Git", exact: true }).click();
|
||||
await search.clear();
|
||||
|
||||
const path = dialog.getByRole("textbox", { name: /^Path to Git executable:?$/ });
|
||||
const testButton = dialog.getByRole("button", { name: "Test", exact: true });
|
||||
const branches = dialog.getByRole("textbox", { name: /^Protected branches:?$/ });
|
||||
await expect(path).toHaveAttribute("placeholder", `Auto-detected: ${gitPath}`);
|
||||
for (const width of [560, 580, 1120]) {
|
||||
await page.setViewportSize({ width, height: 740 });
|
||||
await path.scrollIntoViewIfNeeded();
|
||||
const [field, button, patterns] = await Promise.all([
|
||||
path.boundingBox(),
|
||||
testButton.boundingBox(),
|
||||
branches.boundingBox(),
|
||||
]);
|
||||
if (!field || !button || !patterns) throw new Error("Missing Git settings control bounds");
|
||||
expect(field.y).toBeCloseTo(button.y, 0);
|
||||
if (width <= 580) {
|
||||
const label = await dialog.getByText("Path to Git executable", { exact: true }).boundingBox();
|
||||
if (!label) throw new Error("Missing Git executable label bounds");
|
||||
expect(label.y + label.height).toBeLessThan(field.y);
|
||||
expect(field.width).toBeGreaterThan(150);
|
||||
}
|
||||
expect(field.x + field.width).toBeLessThan(button.x);
|
||||
expect(button.x + button.width).toBeCloseTo(patterns.x + patterns.width, 0);
|
||||
}
|
||||
|
||||
await page.setViewportSize({ width: 560, height: 740 });
|
||||
await testButton.click();
|
||||
const result = dialog.getByRole("status").filter({ hasText: "Git version is 2.49.0" });
|
||||
await expect(result).toContainText(longPath);
|
||||
await expect(result).toBeInViewport({ ratio: 1 });
|
||||
await path.fill(gitPath);
|
||||
await expect(result).toHaveCount(0);
|
||||
await testButton.click();
|
||||
await expect(result).toContainText(gitPath);
|
||||
expect(await ipcCalls(page, "vcs_git_version")).toEqual([{ path: "" }, { path: gitPath }]);
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
|
||||
const update = dialog.getByRole("radiogroup", { name: "Update method" });
|
||||
const merge = update.getByRole("radio", { name: "Merge" });
|
||||
const rebase = update.getByRole("radio", { name: "Rebase" });
|
||||
await expect(merge).toBeChecked();
|
||||
await merge.press("ArrowRight");
|
||||
await expect(rebase).toBeChecked();
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Gradle keeps the local installation with Distribution and saves edits in project scope", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1120, height: 760 });
|
||||
await stubDesktop(page);
|
||||
const gradleHome = "C:/Tools/Gradle 8.14";
|
||||
await page.evaluate((path) => {
|
||||
window.__ipc.handlers.settings_get_global = () => ({});
|
||||
window.__ipc.handlers.settings_get = () => ({});
|
||||
window.__ipc.handlers.settings_set = () => ({});
|
||||
window.__ipc.handlers.sdk_detect = () => [];
|
||||
window.__ipc.handlers["plugin:dialog|open"] = () => path;
|
||||
}, gradleHome);
|
||||
|
||||
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("Gradle JVM");
|
||||
await settings.getByRole("treeitem", { name: "Gradle", exact: true }).click();
|
||||
await search.clear();
|
||||
|
||||
const userHome = settings.getByRole("textbox", { name: /^Gradle user home:?$/ });
|
||||
const runUsing = settings.getByRole("button", { name: "Build and run using", exact: true });
|
||||
const distribution = settings.getByRole("button", { name: "Distribution", exact: true });
|
||||
const jvm = settings.getByRole("button", { name: "Gradle JVM", exact: true });
|
||||
const installation = settings.getByRole("textbox", { name: "Gradle home", exact: true });
|
||||
const [user, run, distro, sdk] = await Promise.all(
|
||||
[userHome, runUsing, distribution, jvm].map((el) => el.boundingBox()),
|
||||
);
|
||||
if (!user || !run || !distro || !sdk) throw new Error("Missing Gradle settings fields");
|
||||
expect(user.y).toBeLessThan(run.y);
|
||||
expect(run.y).toBeLessThan(distro.y);
|
||||
expect(distro.y).toBeLessThan(sdk.y);
|
||||
await expect(
|
||||
settings
|
||||
.getByRole("region", { name: "Build and Run", exact: true })
|
||||
.getByRole("button", { name: "Build and run using" }),
|
||||
).toBeVisible();
|
||||
const runtime = settings.getByRole("region", { name: "Gradle runtime", exact: true });
|
||||
await expect(runtime.getByRole("button", { name: "Distribution", exact: true })).toBeVisible();
|
||||
await expect(runtime.getByRole("button", { name: "Gradle JVM", exact: true })).toBeVisible();
|
||||
|
||||
await expect(distribution).toHaveText("Gradle wrapper");
|
||||
await expect(installation).toHaveCount(0);
|
||||
await distribution.click();
|
||||
await page.getByRole("option", { name: "Local installation", exact: true }).click();
|
||||
const browse = installation.locator("..").getByRole("button", { name: /^Browse/ });
|
||||
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 760 });
|
||||
await expect(browse).toBeInViewport({ ratio: 1 });
|
||||
const [choice, path, button, java] = await Promise.all(
|
||||
[distribution, installation, browse, jvm].map((el) => el.boundingBox()),
|
||||
);
|
||||
if (!choice || !path || !button || !java) throw new Error("Missing local installation controls");
|
||||
expect(path.width).toBeGreaterThan(120);
|
||||
expect(path.y + path.height / 2).toBeCloseTo(button.y + button.height / 2, 0);
|
||||
expect(path.y + path.height).toBeLessThan(java.y);
|
||||
if (width === 1120) {
|
||||
expect(path.x).toBeGreaterThan(choice.x + choice.width);
|
||||
expect(path.y).toBeCloseTo(choice.y, 0);
|
||||
} else {
|
||||
expect(path.x).toBeCloseTo(choice.x, 0);
|
||||
expect(path.y).toBeGreaterThan(choice.y + choice.height);
|
||||
}
|
||||
}
|
||||
|
||||
await browse.click();
|
||||
await expect(installation).toHaveValue(gradleHome);
|
||||
await userHome.fill("C:/Build Cache/Gradle");
|
||||
await distribution.click();
|
||||
await page.getByRole("option", { name: "Gradle wrapper", exact: true }).click();
|
||||
await expect(installation).toHaveCount(0);
|
||||
await distribution.click();
|
||||
await page.getByRole("option", { name: "Local installation", exact: true }).click();
|
||||
await expect(installation).toHaveValue(gradleHome);
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
await settings.getByRole("button", { name: "Apply", exact: true }).click();
|
||||
await expect
|
||||
.poll(async () => (await ipcCalls(page, "settings_set")).sort((a, b) => String(a.key).localeCompare(String(b.key))))
|
||||
.toEqual([
|
||||
{ scope: "project", key: "languages.java.gradle.distribution", value: JSON.stringify("local") },
|
||||
{ scope: "project", key: "languages.java.gradle.home", value: JSON.stringify(gradleHome) },
|
||||
{ scope: "project", key: "languages.java.gradle.userHome", value: JSON.stringify("C:/Build Cache/Gradle") },
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function openProxySettings(page: Page) {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("HTTP Proxy");
|
||||
await dialog.getByRole("treeitem", { name: "HTTP Proxy", exact: true }).click();
|
||||
await search.clear();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
test("HTTP Proxy keeps server and authentication fields aligned in narrow settings", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 740 });
|
||||
const dialog = await openProxySettings(page);
|
||||
const auto = dialog.getByRole("radio", { name: "Auto-detect proxy settings", exact: true });
|
||||
const manual = dialog.getByRole("radio", { name: "Manual proxy configuration", exact: true });
|
||||
const host = dialog.getByRole("textbox", { name: "Host name:", exact: true });
|
||||
const port = dialog.getByRole("textbox", { name: /^Port number:?$/ });
|
||||
const exceptions = dialog.getByRole("textbox", { name: "No proxy for:", exact: true });
|
||||
const auth = dialog.getByRole("checkbox", { name: "Proxy authentication", exact: true });
|
||||
const login = dialog.getByRole("textbox", { name: "Login:", exact: true });
|
||||
const password = dialog.getByLabel("Password", { exact: true });
|
||||
await expect(auto).toBeChecked();
|
||||
for (const control of [host, port, exceptions, auth, login, password]) await expect(control).toBeDisabled();
|
||||
|
||||
await auto.press("ArrowDown");
|
||||
await expect(manual).toBeChecked();
|
||||
await host.fill("127.0.0.1");
|
||||
await expect(login).toBeDisabled();
|
||||
await auth.check();
|
||||
await login.fill("layout-user");
|
||||
await password.fill("layout-password");
|
||||
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 740 });
|
||||
for (const control of [host, port, exceptions, login, password]) {
|
||||
await expect(control).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
const [hostBox, portBox, exceptionsBox, loginBox, passwordBox] = await Promise.all(
|
||||
[host, port, exceptions, login, password].map((control) => control.boundingBox()),
|
||||
);
|
||||
if (!hostBox || !portBox || !exceptionsBox || !loginBox || !passwordBox) {
|
||||
throw new Error("Missing HTTP Proxy field bounds");
|
||||
}
|
||||
expect(hostBox.y).toBeLessThan(portBox.y);
|
||||
expect(portBox.y).toBeLessThan(exceptionsBox.y);
|
||||
expect(hostBox.x).toBeCloseTo(portBox.x, 0);
|
||||
expect(hostBox.x).toBeCloseTo(exceptionsBox.x, 0);
|
||||
expect(hostBox.width).toBeCloseTo(exceptionsBox.width, 0);
|
||||
expect(loginBox.x).toBeCloseTo(passwordBox.x, 0);
|
||||
expect(loginBox.width).toBeCloseTo(passwordBox.width, 0);
|
||||
}
|
||||
|
||||
await auto.check();
|
||||
await expect(password).toBeDisabled();
|
||||
await manual.check();
|
||||
await expect(host).toHaveValue("127.0.0.1");
|
||||
await expect(login).toHaveValue("layout-user");
|
||||
await expect(password).toHaveValue("layout-password");
|
||||
});
|
||||
|
||||
test("HTTP Proxy checks a URL with the staged manual settings in a narrow window", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 540, height: 680 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
window.__ipc.handlers.proxy_check_connection = () => "200 OK";
|
||||
});
|
||||
const dialog = await openProxySettings(page);
|
||||
const check = dialog.getByRole("button", { name: "Check connection…", exact: true });
|
||||
const manual = dialog.getByRole("radio", { name: "Manual proxy configuration", exact: true });
|
||||
await manual.check();
|
||||
await expect(check).toBeDisabled();
|
||||
await dialog.getByRole("textbox", { name: "Host name:", exact: true }).fill("proxy.example.test");
|
||||
const port = dialog.getByRole("textbox", { name: /^Port number:?$/ });
|
||||
await port.fill("8079");
|
||||
await port.press("ArrowUp");
|
||||
await expect(port).toHaveValue("8080");
|
||||
await check.click();
|
||||
const target = page.getByRole("textbox", { name: "Enter any URL to check connection to:", exact: true });
|
||||
const submit = page.getByRole("button", { name: "Check", exact: true });
|
||||
await target.fill("http://example.test/health");
|
||||
await expect(target).toBeInViewport({ ratio: 1 });
|
||||
await expect(submit).toBeInViewport({ ratio: 1 });
|
||||
await submit.click();
|
||||
await expect(page.getByRole("status").filter({ hasText: "Connection successful: 200 OK" })).toBeVisible();
|
||||
expect(await ipcCalls(page, "proxy_check_connection")).toEqual([
|
||||
{
|
||||
proxy: expect.objectContaining({ mode: "manual", kind: "http", host: "proxy.example.test", port: 8080 }),
|
||||
url: "http://example.test/health",
|
||||
},
|
||||
]);
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Maven groups environment and runner settings while keeping paths and thread count editable", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1120, height: 900 });
|
||||
await stubDesktop(page);
|
||||
const settingsPath = "C:/Build Config/settings.xml";
|
||||
const jdk = "C:/SDKs/jdk-21";
|
||||
await page.evaluate(
|
||||
({ settingsPath, jdk }) => {
|
||||
window.__ipc.handlers.settings_get_global = () => ({});
|
||||
window.__ipc.handlers.settings_get = () => ({});
|
||||
window.__ipc.handlers.settings_set = () => ({});
|
||||
window.__ipc.handlers.sdk_detect = ({ kind }) =>
|
||||
kind === "jdk" ? [{ path: jdk, home: jdk, name: "JDK 21", version: "21", source: "system", extra: null }] : [];
|
||||
window.__ipc.handlers["plugin:dialog|open"] = () => settingsPath;
|
||||
},
|
||||
{ settingsPath, jdk },
|
||||
);
|
||||
|
||||
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("thread count");
|
||||
await settings.getByRole("treeitem", { name: "Maven", exact: true }).click();
|
||||
await search.clear();
|
||||
|
||||
const threads = settings.getByRole("textbox", { name: "Thread count", exact: true });
|
||||
const maven = settings.getByRole("button", { name: "Maven home path", exact: true });
|
||||
const user = settings.getByRole("textbox", { name: /^User settings file:?$/ });
|
||||
const repository = settings.getByRole("textbox", { name: /^Local repository:?$/ });
|
||||
const userBrowse = user.locator("..").getByRole("button", { name: /^Browse/ });
|
||||
const repoBrowse = repository.locator("..").getByRole("button", { name: /^Browse/ });
|
||||
const java = settings.getByRole("button", { name: "JRE", exact: true });
|
||||
const download = settings.getByRole("checkbox", { name: "Automatically download sources", exact: true });
|
||||
const [count, home] = await Promise.all([threads.boundingBox(), maven.boundingBox()]);
|
||||
if (!count || !home) throw new Error("Missing Maven controls");
|
||||
expect(count.y).toBeLessThan(home.y);
|
||||
|
||||
const environment = settings.getByRole("region", { name: "Environment", exact: true });
|
||||
const importing = settings.getByRole("region", { name: "Importing", exact: true });
|
||||
const runner = settings.getByRole("region", { name: "Runner", exact: true });
|
||||
await expect(environment.getByRole("button", { name: "Maven home path", exact: true })).toBeVisible();
|
||||
await expect(importing.getByRole("checkbox", { name: "Automatically download sources", exact: true })).toBeVisible();
|
||||
await expect(runner.getByRole("button", { name: "JRE", exact: true })).toBeVisible();
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await threads.scrollIntoViewIfNeeded();
|
||||
const [threadBox, mavenBox, userBox, userButton, repoBox, repoButton, importBox, javaBox] = await Promise.all(
|
||||
[threads, maven, user, userBrowse, repository, repoBrowse, download, java].map((control) =>
|
||||
control.boundingBox(),
|
||||
),
|
||||
);
|
||||
if (!threadBox || !mavenBox || !userBox || !userButton || !repoBox || !repoButton || !importBox || !javaBox)
|
||||
throw new Error("Missing Maven layout bounds");
|
||||
expect(threadBox.width).toBeLessThan(121);
|
||||
expect(mavenBox.x).toBeCloseTo(userBox.x, 0);
|
||||
expect(userBox.x).toBeCloseTo(repoBox.x, 0);
|
||||
expect(userBox.width).toBeGreaterThan(120);
|
||||
expect(userBox.y + userBox.height / 2).toBeCloseTo(userButton.y + userButton.height / 2, 0);
|
||||
expect(userButton.x + userButton.width).toBeCloseTo(repoButton.x + repoButton.width, 0);
|
||||
expect(repoBox.y + repoBox.height).toBeLessThan(importBox.y);
|
||||
expect(importBox.y).toBeLessThan(javaBox.y);
|
||||
await expect(userBrowse).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
|
||||
await userBrowse.click();
|
||||
await expect(user).toHaveValue(settingsPath);
|
||||
await java.click();
|
||||
await page.getByRole("option", { name: /JDK 21/ }).click();
|
||||
await expect(java).toHaveText("JDK 21");
|
||||
await threads.fill("2X");
|
||||
await expect(threads).toHaveAttribute("aria-invalid", "true");
|
||||
await expect(settings.getByRole("alert")).toContainText("Not a thread count Maven accepts");
|
||||
await threads.fill("2.5C");
|
||||
await expect(settings.getByRole("alert")).toHaveCount(0);
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
await settings.getByRole("button", { name: "Apply", exact: true }).click();
|
||||
await expect
|
||||
.poll(async () => (await ipcCalls(page, "settings_set")).sort((a, b) => String(a.key).localeCompare(String(b.key))))
|
||||
.toEqual([
|
||||
{ scope: "project", key: "languages.java.maven.runnerJre", value: JSON.stringify(jdk) },
|
||||
{ scope: "project", key: "languages.java.maven.threads", value: JSON.stringify("2.5C") },
|
||||
{ scope: "project", key: "languages.java.maven.userSettings", value: JSON.stringify(settingsPath) },
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { expect, openFromTree, test } from "./fixtures";
|
||||
|
||||
test("Quick Definition keeps the source font and toolbar while switching previews", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 780 });
|
||||
await openFromTree(page, "App.tsx");
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/editor/lsp/popupStore.ts";
|
||||
const { openPopup } = await import(/* @vite-ignore */ path);
|
||||
const editor = document.querySelector<HTMLElement>(".cm-editor")!;
|
||||
const content = editor.querySelector<HTMLElement>(".cm-content")!;
|
||||
content.style.fontSize = "19px";
|
||||
content.style.lineHeight = "27px";
|
||||
const { fontFamily, fontSize, fontWeight, lineHeight, tabSize } = getComputedStyle(content);
|
||||
openPopup({
|
||||
kind: "definition",
|
||||
anchor: { x: 320, y: 160 },
|
||||
targets: ["shipping", "billing"].map((group) => ({
|
||||
name: "formatTotal",
|
||||
firstLine: 2,
|
||||
location: {
|
||||
path: `/work/acme-api/src/${group}/totals.ts`,
|
||||
range: { start: { line: 2, col: 0 }, end: { line: 2, col: 11 } },
|
||||
},
|
||||
text: `export const formatTotal = "${group}";`,
|
||||
language: "typescript",
|
||||
})),
|
||||
index: 0,
|
||||
themeClasses: editor.className,
|
||||
codeStyle: { fontFamily, fontSize, fontWeight, lineHeight, tabSize },
|
||||
});
|
||||
});
|
||||
|
||||
const popup = page.getByRole("dialog", { name: "Definition", exact: true });
|
||||
const code = popup.locator("pre");
|
||||
await expect(code).toContainText("shipping");
|
||||
await expect(code).toHaveCSS("font-size", "19px");
|
||||
await expect(code).toHaveCSS("line-height", "27px");
|
||||
await expect(popup).toHaveCSS("height", "400px");
|
||||
const header = popup.locator("button").filter({ hasText: "formatTotal" });
|
||||
await expect(header).toBeVisible();
|
||||
await expect(popup.getByText(/shipping[/]totals\.ts:3/)).toBeVisible();
|
||||
|
||||
await popup.getByRole("button", { name: "Next Definition" }).click();
|
||||
await expect(code).toContainText("billing");
|
||||
await expect(popup.getByText(/billing[/]totals\.ts:3/)).toBeVisible();
|
||||
await expect(popup.getByText("2/2")).toBeVisible();
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(code).toContainText("shipping");
|
||||
|
||||
const handle = popup.getByRole("separator", { name: "Resize" });
|
||||
const bounds = (await handle.boundingBox())!;
|
||||
await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(bounds.x + 56, bounds.y + 50, { steps: 4 });
|
||||
await page.mouse.up();
|
||||
expect((await popup.boundingBox())!.height).toBeGreaterThan(430);
|
||||
await expect(popup.getByRole("button", { name: "Edit Source" })).toBeInViewport({ ratio: 1 });
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { expect, openFromTree, test } from "./fixtures";
|
||||
|
||||
test("Quick Switch Scheme stays centered and opens its numbered choices without leaving the editor", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const editor = await openFromTree(page, "build.gradle.kts");
|
||||
const content = editor.locator(".cm-content");
|
||||
await content.focus();
|
||||
const root = page.locator("html");
|
||||
const theme = await root.getAttribute("data-theme");
|
||||
const colorTheme = await root.getAttribute("data-color-theme");
|
||||
await page.keyboard.press("Control+Backquote");
|
||||
const menu = page.getByRole("menu", { name: /^(Switch Scheme|Context menu)$/ });
|
||||
await expect(menu).toBeVisible();
|
||||
for (const { width, height } of [
|
||||
{ width: 1120, height: 680 },
|
||||
{ width: 620, height: 540 },
|
||||
]) {
|
||||
await page.setViewportSize({ width, height });
|
||||
await expect(async () => {
|
||||
const bounds = await menu.locator("xpath=..").boundingBox();
|
||||
expect(Math.abs(bounds!.x + bounds!.width / 2 - width / 2)).toBeLessThan(1);
|
||||
expect(Math.abs(bounds!.y + bounds!.height / 2 - height / 2)).toBeLessThan(1);
|
||||
}).toPass({ timeout: 3000 });
|
||||
}
|
||||
await expect(menu.getByText("Switch Scheme", { exact: true })).toBeVisible();
|
||||
await expect(menu.getByRole("menuitem", { name: "Editor Color Scheme" })).toBeFocused();
|
||||
await expect(menu.locator("[data-menu-number]")).toHaveText(["1", "2", "3", "4"]);
|
||||
await page.keyboard.press("4");
|
||||
const light = page.getByRole("menuitemcheckbox", { name: "Solarized Light" });
|
||||
await light.hover();
|
||||
await expect(root).toHaveAttribute("data-color-theme", "solarized-light");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(light).toBeHidden();
|
||||
await expect(menu).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(menu).toBeHidden();
|
||||
await expect(content).toBeFocused();
|
||||
await expect.poll(() => root.getAttribute("data-theme")).toBe(theme);
|
||||
await expect.poll(() => root.getAttribute("data-color-theme")).toBe(colorTheme);
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
async function openRefactorList(page: Page) {
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/editor/lsp/popupStore.ts";
|
||||
const { openPopup } = await import(/* @vite-ignore */ path);
|
||||
const run = (action: string) => () => {
|
||||
document.body.dataset.selectedRefactoring = action;
|
||||
};
|
||||
openPopup({
|
||||
kind: "list",
|
||||
title: "Refactor This",
|
||||
anchor: { x: 300, y: 140 },
|
||||
compact: true,
|
||||
numbered: true,
|
||||
items: [
|
||||
{ id: "rename", label: "Rename…", shortcut: "Shift+F6", run: run("rename") },
|
||||
{
|
||||
id: "extractVariable",
|
||||
label: "Introduce Variable…",
|
||||
shortcut: "Ctrl+Alt+V",
|
||||
section: { id: "extract", label: "Extract/Introduce" },
|
||||
run: run("extractVariable"),
|
||||
},
|
||||
{ id: "inline", label: "Inline…", section: { id: "inline" }, run: run("inline") },
|
||||
],
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("the compact Refactor This list groups actions without numbering or selecting its captions", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await openRefactorList(page);
|
||||
const popup = page.getByRole("dialog", { name: "Refactor This", exact: true });
|
||||
const group = popup.getByText("Extract/Introduce", { exact: true });
|
||||
await expect(group).toBeVisible();
|
||||
expect((await popup.boundingBox())!.width).toBeLessThan(360);
|
||||
await expect(popup.getByRole("option")).toHaveCount(3);
|
||||
const introduce = popup.getByRole("option", { name: /Introduce Variable/ });
|
||||
await expect(introduce.getByText("2", { exact: true })).toBeVisible();
|
||||
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await expect(introduce).toHaveAttribute("aria-selected", "true");
|
||||
await page.keyboard.press("2");
|
||||
await expect(popup).toBeHidden();
|
||||
await expect(page.locator("body")).toHaveAttribute("data-selected-refactoring", "extractVariable");
|
||||
});
|
||||
|
||||
test("filtering keeps captions only for groups with a matching action", async ({ workbench: page }) => {
|
||||
await openRefactorList(page);
|
||||
const popup = page.getByRole("dialog", { name: "Refactor This", exact: true });
|
||||
const list = popup.getByRole("listbox");
|
||||
const group = popup.getByText("Extract/Introduce", { exact: true });
|
||||
await expect(list).toBeFocused();
|
||||
await expect(group).toBeVisible();
|
||||
|
||||
await page.keyboard.type("variable");
|
||||
await expect(group).toBeVisible();
|
||||
await expect(popup.getByRole("option")).toHaveCount(1);
|
||||
await expect(popup.getByRole("option")).toHaveAttribute("aria-selected", "true");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.locator("body")).toHaveAttribute("data-selected-refactoring", "extractVariable");
|
||||
|
||||
await openRefactorList(page);
|
||||
await expect(list).toBeFocused();
|
||||
await page.keyboard.type("rename");
|
||||
await expect(group).toBeHidden();
|
||||
await expect(popup.getByRole("option", { name: /Rename/ })).toHaveAttribute("aria-selected", "true");
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
const primary = "Prepare invoices for the payments staging environment";
|
||||
|
||||
async function seedConfigurations(page: Page, mode: "select" | "run") {
|
||||
await page.evaluate(
|
||||
async ({ name, mode }) => {
|
||||
const path = "/src/features/run/store.ts";
|
||||
const { useRun } = await import(/* @vite-ignore */ path);
|
||||
const configs = [name, ...Array.from({ length: 19 }, (_, i) => `Payments check ${i + 1}`)].map((label, i) => ({
|
||||
id: `user:chooser-${i}`,
|
||||
name: label,
|
||||
kind: "shell",
|
||||
command: "node",
|
||||
args: ["src/index.ts"],
|
||||
cwd: null,
|
||||
env: {},
|
||||
detected: false,
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
}));
|
||||
useRun.setState({ configs, selectedId: configs[0]!.id, chooserMode: mode, chooserOpen: true, loaded: true });
|
||||
},
|
||||
{ name: primary, mode },
|
||||
);
|
||||
}
|
||||
|
||||
test("the run chooser fits a long name beside its inline actions and keeps its width while filtering", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1120, height: 680 });
|
||||
await seedConfigurations(page, "select");
|
||||
const chooser = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true });
|
||||
const label = chooser.getByText(primary, { exact: true });
|
||||
await expect(label).toBeVisible();
|
||||
const width = (await chooser.boundingBox())!.width;
|
||||
expect(width).toBeGreaterThan(340);
|
||||
expect(width).toBeLessThanOrEqual(500);
|
||||
await expect(chooser.getByRole("button", { name: `Run '${primary}'`, exact: true })).toBeVisible();
|
||||
const nameOverflow = await label.evaluate(async (el) => {
|
||||
await document.fonts.ready;
|
||||
const text = document.createRange();
|
||||
text.selectNodeContents(el);
|
||||
return text.getBoundingClientRect().width - el.getBoundingClientRect().width;
|
||||
});
|
||||
expect(nameOverflow).toBeLessThanOrEqual(0);
|
||||
|
||||
const search = chooser.getByRole("textbox", { name: "Search configurations" });
|
||||
await search.fill("Payments check 19");
|
||||
await expect(chooser.getByText("Payments check 19", { exact: true })).toBeVisible();
|
||||
expect((await chooser.boundingBox())!.width).toBeCloseTo(width);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(chooser).toBeHidden();
|
||||
await expect(page.locator("[data-run-chooser]")).toContainText("Payments check 19");
|
||||
});
|
||||
|
||||
test("in a short window only the list scrolls, leaving the search and shortcuts visible", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 780, height: 280 });
|
||||
await seedConfigurations(page, "run");
|
||||
const chooser = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true });
|
||||
const list = chooser.getByRole("listbox", { name: "Configurations" });
|
||||
const search = chooser.getByRole("textbox", { name: "Search configurations" });
|
||||
const hint = chooser.getByText("Hold Shift to Debug, F4 to edit, Delete to remove", { exact: true });
|
||||
await expect(search).toBeFocused();
|
||||
await expect(hint).toBeInViewport({ ratio: 1 });
|
||||
expect(await chooser.evaluate((el) => el.scrollHeight - el.clientHeight)).toBeLessThanOrEqual(1);
|
||||
expect(await list.evaluate((el) => el.scrollHeight - el.clientHeight)).toBeGreaterThan(0);
|
||||
|
||||
await page.keyboard.press("End");
|
||||
await expect(chooser.getByRole("option", { name: /Edit Configurations/ })).toBeInViewport({ ratio: 1 });
|
||||
await expect.poll(() => list.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
|
||||
await expect(search).toBeInViewport({ ratio: 1 });
|
||||
await expect(hint).toBeInViewport({ ratio: 1 });
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("Select In names the chooser and reveals the file in the requested project view", async ({ workbench: page }) => {
|
||||
const tree = page.getByRole("tree", { name: "Project", exact: true });
|
||||
await tree.getByRole("treeitem", { name: "settings.gradle.kts", exact: true }).dblclick();
|
||||
await expect(page.locator(".cm-content")).toBeVisible();
|
||||
|
||||
const openChooser = () =>
|
||||
page.evaluate(async () => {
|
||||
const actions = "/src/platform/actions.ts";
|
||||
await (await import(/* @vite-ignore */ actions)).executeAction("navigate.selectIn");
|
||||
});
|
||||
await openChooser();
|
||||
const menu = page.getByRole("menu", { name: "Select In", exact: true });
|
||||
await expect(menu.getByText("Select In", { exact: true })).toBeVisible();
|
||||
const project = menu.getByRole("menuitem", { name: "Project View", exact: true });
|
||||
await expect(project).toBeFocused();
|
||||
await expect(project.locator('[data-menu-number="1"]')).toBeVisible();
|
||||
|
||||
await page.keyboard.press("ArrowRight");
|
||||
const projectFiles = page.getByRole("menuitem", { name: "Project Files", exact: true });
|
||||
await expect(project).toHaveAttribute("aria-expanded", "true");
|
||||
await expect(projectFiles).toBeVisible();
|
||||
await expect(page.getByRole("menuitem", { name: "Open Files", exact: true })).toBeEnabled();
|
||||
await expect(page.getByRole("menuitem", { name: "All Changed Files", exact: true })).toBeDisabled();
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
await expect(projectFiles).toBeHidden();
|
||||
await expect(project).toBeFocused();
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await expect(projectFiles).toBeFocused();
|
||||
await page.keyboard.press("Enter");
|
||||
|
||||
await expect(menu).toBeHidden();
|
||||
await expect(page.getByRole("button", { name: "Project Files", exact: true })).toBeVisible();
|
||||
const file = tree.getByRole("treeitem", { name: "settings.gradle.kts", exact: true });
|
||||
await expect(file).toHaveAttribute("aria-selected", "true");
|
||||
|
||||
await page.locator(".cm-content").focus();
|
||||
await openChooser();
|
||||
await expect(project).toBeFocused();
|
||||
await project.locator("[data-menu-submenu-arrow]").click();
|
||||
await expect(projectFiles).toBeVisible();
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
await expect(project).toBeFocused();
|
||||
await page.keyboard.press("1");
|
||||
await expect(menu).toBeHidden();
|
||||
await expect(page.getByRole("button", { name: "Project Files", exact: true })).toBeVisible();
|
||||
await expect(file).toHaveAttribute("aria-selected", "true");
|
||||
});
|
||||
@@ -1,5 +1,59 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("System Settings groups file controls before caches and keeps the idle timeout unit beside its field", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const system = dialog.getByRole("treeitem", { name: "System Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("Autosave");
|
||||
await expect(system).toBeVisible();
|
||||
await search.clear();
|
||||
await system.click();
|
||||
const exit = dialog.getByRole("checkbox", { name: "Confirm before exiting the IDE" });
|
||||
const reopen = dialog.getByRole("checkbox", { name: "Reopen projects on startup" });
|
||||
const project = dialog.getByRole("region", { name: "Project", exact: true });
|
||||
const directory = project.getByRole("textbox", { name: /^Default directory/ });
|
||||
const browse = project.getByRole("button", { name: "Browse", exact: true });
|
||||
const idle = dialog.getByRole("checkbox", { name: "Save files if the IDE is idle for" });
|
||||
const timeout = dialog.getByRole("textbox", { name: "Idle seconds" });
|
||||
const unit = dialog.getByText("seconds", { exact: true });
|
||||
const caches = dialog.getByRole("region", { name: "Caches", exact: true });
|
||||
for (const width of [1120, 580]) {
|
||||
await page.setViewportSize({ width, height: 760 });
|
||||
await expect(async () => {
|
||||
const [exitBox, projectBox, idleBox, timeoutBox, unitBox, cacheBox] = await Promise.all(
|
||||
[exit, reopen, idle, timeout, unit, caches].map((item) => item.boundingBox()),
|
||||
);
|
||||
expect(exitBox!.y).toBeLessThan(projectBox!.y);
|
||||
expect(projectBox!.y).toBeLessThan(idleBox!.y);
|
||||
expect(idleBox!.y).toBeLessThan(cacheBox!.y);
|
||||
expect(unitBox!.x).toBeGreaterThanOrEqual(timeoutBox!.x + timeoutBox!.width);
|
||||
expect(unitBox!.y).toBeGreaterThan(timeoutBox!.y);
|
||||
expect(unitBox!.y + unitBox!.height).toBeLessThanOrEqual(timeoutBox!.y + timeoutBox!.height + 1);
|
||||
const [directoryBox, browseBox] = await Promise.all([directory.boundingBox(), browse.boundingBox()]);
|
||||
expect(browseBox!.x).toBeGreaterThanOrEqual(directoryBox!.x + directoryBox!.width);
|
||||
expect(browseBox!.y).toBeGreaterThanOrEqual(directoryBox!.y);
|
||||
expect(browseBox!.y + browseBox!.height).toBeLessThanOrEqual(directoryBox!.y + directoryBox!.height + 1);
|
||||
}).toPass({ timeout: 3000 });
|
||||
}
|
||||
|
||||
const files = dialog.getByRole("region", { name: "Files", exact: true });
|
||||
const sync = files
|
||||
.getByRole("group", { name: "Synchronization", exact: true })
|
||||
.getByRole("checkbox", { name: "Synchronize external changes when switching to the IDE window" });
|
||||
await idle.check();
|
||||
await timeout.fill("22");
|
||||
await sync.uncheck();
|
||||
await dialog.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await page.keyboard.press("Meta+,");
|
||||
await system.click();
|
||||
await expect(idle).toBeChecked();
|
||||
await expect(timeout).toHaveValue("22");
|
||||
await expect(sync).not.toBeChecked();
|
||||
});
|
||||
|
||||
test("Add Python Interpreter keeps environment labels and fields inside their rows", async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
@@ -120,15 +174,53 @@ test("Directory Mappings keeps the controls and headers visible while scrolling
|
||||
name: "VCS of integrations/finance-and-order-reconciliation/ledger-adapter-32",
|
||||
exact: true,
|
||||
});
|
||||
await vcs.click();
|
||||
await page.getByRole("option", { name: "<none>", exact: true }).click();
|
||||
await expect(vcs).toHaveText("<none>");
|
||||
await name.click();
|
||||
const remove = toolbar.getByRole("button", { name: "Remove", exact: true });
|
||||
await expect(remove).toBeEnabled();
|
||||
await remove.click();
|
||||
const unregistered = table.getByRole("rowgroup", { name: "Unregistered roots" });
|
||||
await expect(unregistered.getByRole("row").last()).toContainText("ledger-adapter-32");
|
||||
await expect(repo).toHaveAttribute("aria-selected", "true");
|
||||
await expect(repo.getByRole("cell", { name: "Git", exact: true })).toBeVisible();
|
||||
await expect(remove).toBeDisabled();
|
||||
|
||||
await toolbar.getByRole("button", { name: "Add", exact: true }).click();
|
||||
const add = toolbar.getByRole("button", { name: "Add", exact: true });
|
||||
await add.click();
|
||||
await expect(vcs).toHaveText("Git");
|
||||
await expect(unregistered).toHaveCount(0);
|
||||
await expect(table.getByText("billing-audit-adapter", { exact: true })).toHaveCount(0);
|
||||
|
||||
const ledger = (n: number) => table.getByText(`ledger-adapter-${n}`, { exact: true });
|
||||
const selectedNames = () => table.locator("tr[aria-selected=true] td:first-child").allTextContents();
|
||||
await ledger(29).click();
|
||||
await ledger(31).click({ modifiers: ["Meta"] });
|
||||
expect(await selectedNames()).toEqual([
|
||||
"integrations/finance-and-order-reconciliation/ledger-adapter-29",
|
||||
"integrations/finance-and-order-reconciliation/ledger-adapter-31",
|
||||
]);
|
||||
await ledger(29).click();
|
||||
await ledger(31).click({ modifiers: ["Shift"] });
|
||||
await expect(table.locator("tr[aria-selected=true]")).toHaveCount(3);
|
||||
expect(await page.evaluate(() => window.getSelection()?.toString())).toBe("");
|
||||
await remove.click();
|
||||
await expect(unregistered.getByRole("row")).toHaveCount(4);
|
||||
await expect(unregistered.locator("tr[aria-selected=true]")).toHaveCount(3);
|
||||
await expect(unregistered.getByText("ledger-adapter-29", { exact: true })).toBeVisible();
|
||||
await expect(unregistered.getByText("ledger-adapter-30", { exact: true })).toBeVisible();
|
||||
await expect(unregistered.getByText("ledger-adapter-31", { exact: true })).toBeVisible();
|
||||
await ledger(32).click({ modifiers: ["Meta"] });
|
||||
await expect(remove).toBeDisabled();
|
||||
await expect(add).toBeDisabled();
|
||||
await ledger(32).click({ modifiers: ["Meta"] });
|
||||
await add.click();
|
||||
await expect(unregistered).toHaveCount(0);
|
||||
await expect(table.locator("tr[aria-selected=true]")).toHaveCount(3);
|
||||
|
||||
await add.click();
|
||||
const added = table.getByRole("row").filter({ hasText: "billing-audit-adapter" });
|
||||
await expect(added.getByText("billing-audit-adapter", { exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await expect(added).toHaveAttribute("aria-selected", "true");
|
||||
await toolbar.getByRole("button", { name: "Remove", exact: true }).click();
|
||||
await remove.click();
|
||||
await expect(added).toHaveCount(0);
|
||||
|
||||
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
|
||||
@@ -1,5 +1,59 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("External Tools pairs metadata and separates command fields from advanced options", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
const openPage = async () => {
|
||||
await search.fill("External Tools");
|
||||
await dialog.getByRole("treeitem", { name: "External Tools", exact: true }).click();
|
||||
await search.clear();
|
||||
};
|
||||
await openPage();
|
||||
await dialog.getByRole("toolbar", { name: "External tools actions" }).getByRole("button", { name: "Add" }).click();
|
||||
const name = dialog.getByRole("textbox", { name: /^Name/ });
|
||||
const group = dialog.getByRole("textbox", { name: /^Group/ });
|
||||
const description = dialog.getByRole("textbox", { name: /^Description/ });
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 760 });
|
||||
await expect(async () => {
|
||||
const [nameBox, groupBox, descriptionBox] = await Promise.all(
|
||||
[name, group, description].map((field) => field.boundingBox()),
|
||||
);
|
||||
if (width === 1120) {
|
||||
expect(groupBox!.y).toBe(nameBox!.y);
|
||||
expect(groupBox!.x).toBeGreaterThan(nameBox!.x + nameBox!.width);
|
||||
} else {
|
||||
expect(groupBox!.y).toBeGreaterThan(nameBox!.y);
|
||||
}
|
||||
expect(descriptionBox!.x).toBe(nameBox!.x);
|
||||
expect(descriptionBox!.y).toBeGreaterThan(groupBox!.y);
|
||||
}).toPass({ timeout: 3000 });
|
||||
}
|
||||
const command = dialog.getByRole("region", { name: "Tool Settings", exact: true });
|
||||
await expect(command.getByRole("textbox", { name: /^Program/ })).toBeVisible();
|
||||
await expect(command.getByRole("textbox", { name: /^Arguments/ })).toBeVisible();
|
||||
await expect(command.getByRole("textbox", { name: /^Working directory/ })).toBeVisible();
|
||||
const sync = dialog.getByRole("checkbox", { name: "Synchronize files after execution" });
|
||||
await expect(sync).toBeHidden();
|
||||
await search.fill("Synchronize files after execution");
|
||||
await expect(sync).toBeVisible();
|
||||
await search.clear();
|
||||
await expect(sync).toBeHidden();
|
||||
await dialog.getByText("Advanced options", { exact: true }).click();
|
||||
await name.fill("Validate project");
|
||||
await sync.setChecked(!(await sync.isChecked()));
|
||||
const enabled = await sync.isChecked();
|
||||
await dialog.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await page.keyboard.press("Meta+,");
|
||||
await openPage();
|
||||
await expect(name).toHaveValue("Validate project");
|
||||
await dialog.getByText("Advanced options", { exact: true }).click();
|
||||
await expect(sync).toBeChecked({ checked: enabled });
|
||||
});
|
||||
|
||||
for (const kind of ["external", "ssh", "target"] as const) {
|
||||
test(`${kind} settings keep long names and details inside their selection row`, async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Spelling puts dictionary files first and keeps accepted words in separate scopes", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1120, height: 820 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
window.__ipc.handlers.settings_get_global = () => ({});
|
||||
window.__ipc.handlers.settings_get = () => ({});
|
||||
window.__ipc.handlers.settings_set = () => ({});
|
||||
});
|
||||
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("Spelling");
|
||||
await settings.getByRole("treeitem", { name: "Spelling", exact: true }).click();
|
||||
await search.clear();
|
||||
|
||||
const files = settings.getByRole("region", { name: "Custom dictionaries", exact: true });
|
||||
const words = settings.getByRole("region", { name: "Accepted words", exact: true });
|
||||
const filesList = files.getByRole("listbox", { name: "Custom dictionaries", exact: true });
|
||||
const project = words.getByRole("tab", { name: "Project dictionary", exact: true });
|
||||
const application = words.getByRole("tab", { name: "Application dictionary", exact: true });
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 820 });
|
||||
const [filesBox, wordsBox] = await Promise.all([files.boundingBox(), words.boundingBox()]);
|
||||
if (!filesBox || !wordsBox) throw new Error("Missing Spelling sections");
|
||||
expect(filesBox.y + filesBox.height).toBeLessThan(wordsBox.y);
|
||||
const [paths, accepted] = await Promise.all([filesList.boundingBox(), words.getByRole("listbox").boundingBox()]);
|
||||
if (!paths || !accepted) throw new Error("Missing dictionary lists");
|
||||
expect(paths.width).toBeCloseTo(accepted.width, 0);
|
||||
if (width === 1120) expect(paths.width).toBeGreaterThan(480);
|
||||
await expect(project).toBeInViewport({ ratio: 1 });
|
||||
await expect(application).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
|
||||
await files.getByRole("button", { name: "Add", exact: true }).click();
|
||||
await files.getByRole("textbox", { name: "Dictionary path" }).fill("dictionaries/team.dic");
|
||||
await files.getByRole("textbox", { name: "Dictionary path" }).press("Enter");
|
||||
await expect(filesList.getByRole("option", { name: "dictionaries/team.dic" })).toBeVisible();
|
||||
|
||||
await expect(project).toHaveAttribute("aria-selected", "true");
|
||||
await words.getByRole("button", { name: "Add", exact: true }).click();
|
||||
await words.getByRole("textbox", { name: "Word", exact: true }).fill("checkoutable");
|
||||
await words.getByRole("textbox", { name: "Word", exact: true }).press("Enter");
|
||||
await project.press("ArrowRight");
|
||||
await expect(application).toHaveAttribute("aria-selected", "true");
|
||||
await expect(words.getByRole("option", { name: "checkoutable" })).toHaveCount(0);
|
||||
await words.getByRole("button", { name: "Add", exact: true }).click();
|
||||
await words.getByRole("textbox", { name: "Word", exact: true }).fill("worktree");
|
||||
await words.getByRole("textbox", { name: "Word", exact: true }).press("Enter");
|
||||
|
||||
await project.click();
|
||||
await expect(words.getByRole("option", { name: "checkoutable" })).toBeVisible();
|
||||
await expect(words.getByRole("option", { name: "worktree" })).toHaveCount(0);
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
await settings.getByRole("button", { name: "Apply", exact: true }).click();
|
||||
await expect
|
||||
.poll(async () => (await ipcCalls(page, "settings_set")).sort((a, b) => String(a.key).localeCompare(String(b.key))))
|
||||
.toEqual([
|
||||
{ scope: "global", key: "spelling.customDictionaries", value: JSON.stringify(["dictionaries/team.dic"]) },
|
||||
{ scope: "global", key: "spelling.ideWords", value: JSON.stringify(["worktree"]) },
|
||||
{ scope: "project", key: "spelling.projectWords", value: JSON.stringify(["checkoutable"]) },
|
||||
]);
|
||||
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await page.evaluate(async () => {
|
||||
const actionModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionModule);
|
||||
await executeAction("file.newProjectsSettings", "editor.naturalLanguages.spelling");
|
||||
});
|
||||
const defaults = page.getByRole("dialog", { name: "Settings for New Projects", exact: true });
|
||||
await expect(defaults.getByRole("listbox", { name: "Application dictionary", exact: true })).toBeVisible();
|
||||
await expect(defaults.getByRole("tablist", { name: "Accepted words" })).toHaveCount(0);
|
||||
await expect(defaults.getByRole("listbox", { name: "Project dictionary", exact: true })).toHaveCount(0);
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Terminal settings keep shell controls and font groups readable as the window narrows", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1120, height: 900 });
|
||||
await stubDesktop(page);
|
||||
const shellPath = "C:/Program Files/Shell/bin/bash.exe";
|
||||
await page.evaluate((path) => {
|
||||
window.__ipc.handlers.settings_get_global = () => ({});
|
||||
window.__ipc.handlers.term_default_shell = () => "/bin/zsh";
|
||||
window.__ipc.handlers.term_available_shells = () => ["/bin/zsh", path];
|
||||
}, shellPath);
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("Shell path");
|
||||
await dialog.getByRole("treeitem", { name: "Terminal", exact: true }).click();
|
||||
await search.clear();
|
||||
|
||||
const directory = dialog.getByRole("textbox", { name: /^Start directory:?$/ });
|
||||
const shell = dialog.getByRole("textbox", { name: /^Shell path:?$/ });
|
||||
const tab = dialog.getByRole("textbox", { name: /^Default Tab name:?$/ });
|
||||
const shells = dialog.getByRole("button", { name: "Installed Shells", exact: true });
|
||||
const browse = dialog.getByRole("button", { name: "Browse", exact: true });
|
||||
const font = dialog.getByRole("combobox", { name: "Terminal font", exact: true });
|
||||
const fallback = dialog.getByRole("combobox", { name: "Terminal fallback font", exact: true });
|
||||
const size = dialog.getByRole("textbox", { name: "Terminal font size", exact: true });
|
||||
const lineHeight = dialog.getByRole("textbox", { name: "Terminal line height", exact: true });
|
||||
const column = dialog.getByRole("textbox", { name: "Terminal column width", exact: true });
|
||||
const bell = dialog.getByRole("checkbox", { name: "Audible bell", exact: true });
|
||||
const shortcuts = dialog.getByRole("checkbox", { name: "Override IDE shortcuts", exact: true });
|
||||
await expect(shell).toHaveAttribute("placeholder", "/bin/zsh");
|
||||
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await shell.scrollIntoViewIfNeeded();
|
||||
await expect(shells).toBeInViewport({ ratio: 1 });
|
||||
await expect(browse).toBeInViewport({ ratio: 1 });
|
||||
const [dir, command, name, menu, chooseFile, main, secondary, fontSize, line, col, left, right] = await Promise.all(
|
||||
[directory, shell, tab, shells, browse, font, fallback, size, lineHeight, column, bell, shortcuts].map(
|
||||
(control) => control.boundingBox(),
|
||||
),
|
||||
);
|
||||
if (
|
||||
!dir ||
|
||||
!command ||
|
||||
!name ||
|
||||
!menu ||
|
||||
!chooseFile ||
|
||||
!main ||
|
||||
!secondary ||
|
||||
!fontSize ||
|
||||
!line ||
|
||||
!col ||
|
||||
!left ||
|
||||
!right
|
||||
)
|
||||
throw new Error("Missing Terminal settings bounds");
|
||||
expect(command.y + command.height / 2).toBeCloseTo(menu.y + menu.height / 2, 0);
|
||||
expect(menu.y).toBeCloseTo(chooseFile.y, 0);
|
||||
expect(command.width).toBeGreaterThan(100);
|
||||
expect(command.x).toBeCloseTo(name.x, 0);
|
||||
expect(chooseFile.x + chooseFile.width).toBeCloseTo(name.x + name.width, 0);
|
||||
expect(dir.x + dir.width).toBeCloseTo(name.x + name.width, 0);
|
||||
expect(main.y).toBeLessThan(command.y);
|
||||
if (width === 1120) {
|
||||
expect(main.y).toBeCloseTo(secondary.y, 0);
|
||||
expect(fontSize.y).toBeCloseTo(line.y, 0);
|
||||
expect(fontSize.y).toBeCloseTo(col.y, 0);
|
||||
expect(right.x).toBeGreaterThan(left.x);
|
||||
} else {
|
||||
expect(command.x).toBeCloseTo(dir.x, 0);
|
||||
expect(secondary.y).toBeGreaterThan(main.y);
|
||||
expect(right.x).toBeCloseTo(left.x, 0);
|
||||
expect(right.y).toBeGreaterThan(left.y);
|
||||
}
|
||||
}
|
||||
|
||||
await shells.click();
|
||||
await page.getByRole("menuitemcheckbox", { name: shellPath, exact: true }).click();
|
||||
await expect(shell).toHaveValue(`"${shellPath}"`);
|
||||
await expect(font).toBeDisabled();
|
||||
await dialog.getByRole("checkbox", { name: "Use editor font", exact: true }).uncheck();
|
||||
await font.fill("Cascadia Mono");
|
||||
await size.fill("15");
|
||||
await expect(font).toHaveValue("Cascadia Mono");
|
||||
await expect(size).toHaveValue("15");
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("Customize Main Toolbar keeps layout actions above the groups and stacks them in a narrow window", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const open = () =>
|
||||
page.evaluate(async () => {
|
||||
const path = "/src/platform/actions.ts";
|
||||
await (await import(/* @vite-ignore */ path)).executeAction("toolbar.customize");
|
||||
});
|
||||
await open();
|
||||
const dialog = page.getByRole("dialog", { name: "Customize Main Toolbar", exact: true });
|
||||
const left = dialog.getByRole("listbox", { name: "Left group" });
|
||||
const right = dialog.getByRole("listbox", { name: "Right group" });
|
||||
const add = dialog.getByRole("button", { name: "Add…", exact: true });
|
||||
const restore = dialog.getByRole("button", { name: "Restore Defaults", exact: true });
|
||||
await expect(left).toBeFocused();
|
||||
|
||||
for (const width of [1120, 460]) {
|
||||
await page.setViewportSize({ width, height: 620 });
|
||||
await expect(async () => {
|
||||
const [addBox, restoreBox, leftBox, rightBox] = await Promise.all(
|
||||
[add, restore, left, right].map((el) => el.boundingBox()),
|
||||
);
|
||||
expect(addBox!.y + addBox!.height).toBeLessThan(leftBox!.y);
|
||||
expect(restoreBox!.y).toBe(addBox!.y);
|
||||
if (width === 1120) {
|
||||
expect(rightBox!.y).toBe(leftBox!.y);
|
||||
expect(rightBox!.x).toBeGreaterThan(leftBox!.x + leftBox!.width);
|
||||
} else {
|
||||
expect(rightBox!.y).toBeGreaterThan(leftBox!.y + leftBox!.height);
|
||||
expect(rightBox!.width).toBe(leftBox!.width);
|
||||
}
|
||||
}).toPass({ timeout: 3000 });
|
||||
}
|
||||
|
||||
const actions = dialog.getByRole("toolbar", { name: "Toolbar actions" });
|
||||
const project = (group: typeof left) => group.getByRole("option", { name: "Project Widget", exact: true });
|
||||
await expect(project(left)).toHaveAttribute("aria-selected", "true");
|
||||
await actions.getByRole("button", { name: "Move Down" }).click();
|
||||
await expect(left.getByRole("option").nth(1)).toHaveText("Project Widget");
|
||||
await actions.getByRole("button", { name: "Move to Right" }).click();
|
||||
await expect(project(right)).toBeVisible();
|
||||
await actions.getByRole("button", { name: "Remove", exact: true }).click();
|
||||
await expect(project(right)).toHaveCount(0);
|
||||
|
||||
await add.click();
|
||||
const search = dialog.getByRole("textbox", { name: "Search actions" });
|
||||
await expect(search).toBeFocused();
|
||||
await search.fill("Project Widget");
|
||||
const available = dialog.getByRole("listbox", { name: "Actions and widgets to add" });
|
||||
await available.getByRole("option", { name: /Project Widget/ }).click();
|
||||
await expect(project(right)).toBeVisible();
|
||||
await expect(search).toHaveCount(0);
|
||||
|
||||
await restore.click();
|
||||
await expect(left.getByRole("option").first()).toHaveText("Project Widget");
|
||||
await expect(project(right)).toHaveCount(0);
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
});
|
||||
@@ -71,12 +71,17 @@ test("⌘1 focuses, hides and re-shows the Project tool window", async ({ workbe
|
||||
|
||||
test("⌘4 toggles Run; Shift+Escape hides the active tool window", async ({ workbench: page }) => {
|
||||
const run = page.getByRole("region", { name: "Run" });
|
||||
// The shortcut hides the window only once it is active: activation focuses it a frame after it shows.
|
||||
const focusedInRun = () =>
|
||||
expect.poll(() => page.evaluate(() => !!document.activeElement?.closest('[data-toolwindow="run"]'))).toBe(true);
|
||||
await page.keyboard.press("Meta+4");
|
||||
await expect(run).toBeVisible();
|
||||
await focusedInRun();
|
||||
await page.keyboard.press("Meta+4");
|
||||
await expect(run).toBeHidden();
|
||||
await page.keyboard.press("Meta+4");
|
||||
await expect(run).toBeVisible();
|
||||
await focusedInRun();
|
||||
await page.keyboard.press("Shift+Escape");
|
||||
await expect(run).toBeHidden();
|
||||
});
|
||||
|
||||
@@ -39,6 +39,7 @@ for (const windowKind of ["project", "welcome", "lightEdit"]) {
|
||||
test("Updates shows check status and keeps manual checks available when automatic checks are off", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1120, height: 680 });
|
||||
await page.evaluate(async () => {
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const actionsPath = "/src/platform/actions.ts";
|
||||
@@ -62,11 +63,33 @@ test("Updates shows check status and keeps manual checks available when automati
|
||||
await expect(dialog.getByText("0.1.39", { exact: true })).toBeVisible();
|
||||
await expect(dialog.getByText("Never", { exact: true })).toBeVisible();
|
||||
const automatic = dialog.getByRole("checkbox", { name: "Check for updates automatically" });
|
||||
const source = dialog.getByRole("button", { name: "Update source", exact: true });
|
||||
const check = dialog.getByRole("button", { name: "Check Now", exact: true });
|
||||
const checked = dialog.getByText("Never", { exact: true });
|
||||
const whatsNew = dialog.getByRole("checkbox", { name: "Show What's New after an update", exact: true });
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 680 });
|
||||
const [automaticBox, sourceBox, checkBox, statusBox, whatsNewBox] = await Promise.all(
|
||||
[automatic, source, check, checked, whatsNew].map((item) => item.boundingBox()),
|
||||
);
|
||||
if (!automaticBox || !sourceBox || !checkBox || !statusBox || !whatsNewBox)
|
||||
throw new Error("Missing Updates controls");
|
||||
expect(checkBox.y).toBeGreaterThan(sourceBox.y + sourceBox.height);
|
||||
expect(sourceBox.y).toBeGreaterThan(automaticBox.y + automaticBox.height);
|
||||
expect(whatsNewBox.y).toBeGreaterThan(checkBox.y + checkBox.height);
|
||||
expect(statusBox.x).toBeGreaterThan(checkBox.x + checkBox.width);
|
||||
expect(Math.abs(statusBox.y + statusBox.height / 2 - checkBox.y - checkBox.height / 2)).toBeLessThan(1.5);
|
||||
await expect(check).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
await expect(automatic).toBeChecked();
|
||||
await automatic.uncheck();
|
||||
await expect(source).toBeEnabled();
|
||||
await source.click();
|
||||
await page.getByRole("option", { name: "CNB (China mirror)", exact: true }).click();
|
||||
await dialog.getByRole("button", { name: "Apply", exact: true }).click();
|
||||
await expect(automatic).not.toBeChecked();
|
||||
await dialog.getByRole("button", { name: "Check Now", exact: true }).click();
|
||||
await expect(source).toHaveText("CNB (China mirror)");
|
||||
await check.click();
|
||||
await expect(page.locator("body")).toHaveAttribute("data-update-checked", "true");
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function openConfirmation(page: Page) {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("Remove silently");
|
||||
await dialog.getByRole("treeitem", { name: "Confirmation", exact: true }).click();
|
||||
await search.clear();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
test("VCS confirmation aligns the file policy selectors and keeps edits scoped", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 740 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
const global = { onCreate: "ask", onDelete: "ask" };
|
||||
const project: Partial<typeof global> = {};
|
||||
const effective = () => ({ vcs: { confirmation: { ...global, ...project } } });
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.settings_get_global = () => ({ vcs: { confirmation: global } });
|
||||
handlers.settings_get = effective;
|
||||
handlers.settings_set = ({ scope, key, value }) => {
|
||||
const policy = String(key).split(".").at(-1);
|
||||
if (policy !== "onCreate" && policy !== "onDelete") throw new Error("Unexpected confirmation setting");
|
||||
const layer = scope === "project" ? project : global;
|
||||
layer[policy] = JSON.parse(String(value));
|
||||
return effective();
|
||||
};
|
||||
});
|
||||
const dialog = await openConfirmation(page);
|
||||
const create = dialog.getByRole("button", { name: "When files are created", exact: true });
|
||||
const remove = dialog.getByRole("button", { name: "When files are deleted", exact: true });
|
||||
const global = dialog.getByRole("radio", { name: "Global", exact: true });
|
||||
const project = dialog.getByRole("radio", { name: "This project", exact: true });
|
||||
const apply = dialog.getByRole("button", { name: "Apply", exact: true });
|
||||
const cancel = dialog.getByRole("button", { name: "Cancel", exact: true });
|
||||
await expect(create).toHaveText("Ask");
|
||||
await expect(remove).toHaveText("Ask");
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 740 });
|
||||
await expect(create).toBeInViewport({ ratio: 1 });
|
||||
await expect(remove).toBeInViewport({ ratio: 1 });
|
||||
const [createBox, removeBox] = await Promise.all([create.boundingBox(), remove.boundingBox()]);
|
||||
if (!createBox || !removeBox) throw new Error("Missing confirmation selector bounds");
|
||||
expect(createBox.y).toBeLessThan(removeBox.y);
|
||||
expect(createBox.x).toBeCloseTo(removeBox.x, 0);
|
||||
expect(createBox.width).toBeCloseTo(removeBox.width, 0);
|
||||
}
|
||||
|
||||
await create.press("Enter");
|
||||
await expect(page.getByRole("listbox", { name: "When files are created", exact: true })).toBeVisible();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(create).toHaveText("Add silently");
|
||||
await remove.click();
|
||||
await page.getByRole("option", { name: "Remove silently", exact: true }).click();
|
||||
await expect(remove).toHaveText("Remove silently");
|
||||
|
||||
await project.click();
|
||||
await create.click();
|
||||
await page.getByRole("option", { name: "Do not add", exact: true }).click();
|
||||
await remove.click();
|
||||
await page.getByRole("option", { name: "Do not remove", exact: true }).click();
|
||||
await expect(create).toHaveText("Do not add");
|
||||
await expect(remove).toHaveText("Do not remove");
|
||||
await global.click();
|
||||
await expect(create).toHaveText("Add silently");
|
||||
await expect(remove).toHaveText("Remove silently");
|
||||
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
await apply.click();
|
||||
await expect(apply).toBeDisabled();
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([
|
||||
{ scope: "global", key: "vcs.confirmation.onCreate", value: '"silently"' },
|
||||
{ scope: "global", key: "vcs.confirmation.onDelete", value: '"silently"' },
|
||||
{ scope: "project", key: "vcs.confirmation.onCreate", value: '"never"' },
|
||||
{ scope: "project", key: "vcs.confirmation.onDelete", value: '"never"' },
|
||||
]);
|
||||
await cancel.click();
|
||||
await openConfirmation(page);
|
||||
await global.click();
|
||||
await expect(create).toHaveText("Add silently");
|
||||
await expect(remove).toHaveText("Remove silently");
|
||||
await project.click();
|
||||
await expect(create).toHaveText("Do not add");
|
||||
await expect(remove).toHaveText("Do not remove");
|
||||
await remove.click();
|
||||
await page.getByRole("option", { name: "Ask", exact: true }).click();
|
||||
await cancel.click();
|
||||
await openConfirmation(page);
|
||||
await project.click();
|
||||
await expect(remove).toHaveText("Do not remove");
|
||||
});
|
||||
+170
-33
@@ -22,7 +22,7 @@ use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use tauri::menu::{CheckMenuItem, IsMenuItem, Menu, MenuItem, MenuItemKind, PredefinedMenuItem, Submenu};
|
||||
use tauri::menu::{CheckMenuItem, IsMenuItem, Menu, MenuItem, MenuItemKind, NativeIcon, PredefinedMenuItem, Submenu};
|
||||
use tauri::{AppHandle, Runtime};
|
||||
|
||||
/// Event emitted to the focused window when an IDE menu item is clicked.
|
||||
@@ -805,16 +805,12 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
"toolWindowLayouts",
|
||||
"Tool Window Layouts",
|
||||
vec![
|
||||
act("layout.saveCurrent", "Save Changes in Current Layout"),
|
||||
act("layout.restoreCurrent", "Restore Current Layout"),
|
||||
SEP,
|
||||
act("layout.save", "Save Current Layout as…"),
|
||||
act("layout.restoreDefault", "Restore Default Layout"),
|
||||
SEP,
|
||||
toggle("layout.restoreDefault", "Restore Default Layout"),
|
||||
Entry::Dynamic(DYNAMIC_LAYOUTS),
|
||||
SEP,
|
||||
act("layout.rename", "Rename Layout…"),
|
||||
act("layout.delete", "Delete Layout…"),
|
||||
act("layout.restoreCurrent", "Restore Current Layout"),
|
||||
act("layout.saveCurrent", "Save Changes in Current Layout"),
|
||||
act("layout.save", "Save Current Layout as…"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
@@ -1008,6 +1004,32 @@ impl DynamicItem {
|
||||
None => format!("{DYNAMIC_PREFIX}{}", self.action),
|
||||
}
|
||||
}
|
||||
|
||||
fn model(&self) -> MenuNode {
|
||||
MenuNode::Action {
|
||||
id: self.action.clone(),
|
||||
label: self.label.clone(),
|
||||
hint: None,
|
||||
arg: self.arg.clone(),
|
||||
checked: self.checked,
|
||||
}
|
||||
}
|
||||
|
||||
fn render(&self, config: &MenuConfig) -> RenderedItem {
|
||||
RenderedItem::Action {
|
||||
id: self.item_id(),
|
||||
text: self.label.clone(),
|
||||
accel: config.dynamic_accelerator(self).map(Into::into),
|
||||
checked: self.checked,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct LayoutMenu<'a> {
|
||||
id: String,
|
||||
name: &'a str,
|
||||
current: bool,
|
||||
items: Vec<Option<DynamicItem>>,
|
||||
}
|
||||
|
||||
impl MenuConfig {
|
||||
@@ -1019,6 +1041,38 @@ impl MenuConfig {
|
||||
self.dynamic.get(slot).map(Vec::as_slice).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn layout_menus(&self) -> Vec<LayoutMenu<'_>> {
|
||||
self.dynamic_items(DYNAMIC_LAYOUTS)
|
||||
.iter()
|
||||
.filter_map(|layout| {
|
||||
let name = layout.arg.as_deref()?;
|
||||
let current = layout.checked.unwrap_or_default();
|
||||
let command = |action: &str, label_key, fallback| {
|
||||
Some(DynamicItem {
|
||||
action: action.into(),
|
||||
arg: Some(name.into()),
|
||||
label: self.label(label_key, fallback),
|
||||
checked: None,
|
||||
})
|
||||
};
|
||||
let mut items = if current {
|
||||
vec![
|
||||
command("layout.restore", "layout.restoreNamed", "Restore"),
|
||||
command("layout.saveCurrent", "layout.saveNamed", "Save Changes"),
|
||||
]
|
||||
} else {
|
||||
vec![command("layout.restore", "layout.applyNamed", "Apply")]
|
||||
};
|
||||
items.extend([
|
||||
command("layout.rename", "layout.renameNamed", "Rename…"),
|
||||
None,
|
||||
command("layout.delete", "layout.deleteNamed", "Delete…"),
|
||||
]);
|
||||
Some(LayoutMenu { id: format!("layout:{name}"), name, current, items })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The keymap accelerator shown on the item of action `id`.
|
||||
fn accelerator(&self, id: &str) -> Option<&str> {
|
||||
self.accelerators.get(id).map(String::as_str).filter(|a| !a.is_empty())
|
||||
@@ -1149,8 +1203,9 @@ struct RenderedMenu {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum RenderedItem {
|
||||
Submenu {
|
||||
id: &'static str,
|
||||
id: String,
|
||||
title: String,
|
||||
current: bool,
|
||||
items: Vec<RenderedItem>,
|
||||
},
|
||||
/// `accel` is the spec's accelerator, or else the keymap's from [`MenuConfig::accelerators`].
|
||||
@@ -1199,8 +1254,9 @@ fn render_items(entries: &[Entry], config: &MenuConfig, recent: &[RecentItem]) -
|
||||
for entry in entries {
|
||||
match entry {
|
||||
Entry::Submenu { id, label, children } => out.push(RenderedItem::Submenu {
|
||||
id,
|
||||
id: (*id).into(),
|
||||
title: config.label(id, label),
|
||||
current: false,
|
||||
items: render_items(children, config, recent),
|
||||
}),
|
||||
Entry::Action { id, label, accel, hint, check } => out.push(RenderedItem::Action {
|
||||
@@ -1209,16 +1265,25 @@ fn render_items(entries: &[Entry], config: &MenuConfig, recent: &[RecentItem]) -
|
||||
accel: accel.or_else(|| config.accelerator(id)).map(Into::into),
|
||||
checked: check.then(|| config.checked.iter().any(|c| c == id)),
|
||||
}),
|
||||
Entry::Dynamic(slot) => {
|
||||
for item in config.dynamic_items(slot) {
|
||||
out.push(RenderedItem::Action {
|
||||
id: item.item_id(),
|
||||
text: item.label.clone(),
|
||||
accel: config.dynamic_accelerator(item).map(Into::into),
|
||||
checked: item.checked,
|
||||
});
|
||||
Entry::Dynamic(DYNAMIC_LAYOUTS) => {
|
||||
let layouts = config.layout_menus();
|
||||
if !layouts.is_empty() {
|
||||
out.push(RenderedItem::Separator);
|
||||
}
|
||||
out.extend(layouts.into_iter().map(|layout| {
|
||||
RenderedItem::Submenu {
|
||||
id: layout.id,
|
||||
title: layout.name.replace('&', "&&"),
|
||||
current: layout.current,
|
||||
items: layout
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.map_or(RenderedItem::Separator, |item| item.render(config)))
|
||||
.collect(),
|
||||
}
|
||||
}));
|
||||
}
|
||||
Entry::Dynamic(slot) => out.extend(config.dynamic_items(slot).iter().map(|item| item.render(config))),
|
||||
Entry::Native(kind) => {
|
||||
out.push(RenderedItem::Native { kind: *kind, text: config.label(kind.key(), kind.default_label()) })
|
||||
}
|
||||
@@ -1244,7 +1309,7 @@ fn render_items(entries: &[Entry], config: &MenuConfig, recent: &[RecentItem]) -
|
||||
|
||||
fn structure_key(item: &RenderedItem) -> (u8, &str) {
|
||||
match item {
|
||||
RenderedItem::Submenu { id, .. } => (0, *id),
|
||||
RenderedItem::Submenu { id, .. } => (0, id.as_str()),
|
||||
RenderedItem::Action { id, checked: None, .. } => (1, id.as_str()),
|
||||
RenderedItem::Action { id, checked: Some(_), .. } => (5, id.as_str()),
|
||||
RenderedItem::Placeholder { id, .. } => (2, id.as_str()),
|
||||
@@ -1301,8 +1366,14 @@ fn append_rendered<R: Runtime>(
|
||||
) -> tauri::Result<()> {
|
||||
for item in items {
|
||||
match item {
|
||||
RenderedItem::Submenu { id, title, items } => {
|
||||
let child = Submenu::with_id(app, format!("submenu:{id}"), title, true)?;
|
||||
RenderedItem::Submenu { id, title, current, items } => {
|
||||
let child = Submenu::with_id_and_native_icon(
|
||||
app,
|
||||
format!("submenu:{id}"),
|
||||
title,
|
||||
true,
|
||||
current.then_some(NativeIcon::MenuOnState),
|
||||
)?;
|
||||
append_rendered(app, &child, items, disabled)?;
|
||||
parent.append(&child)?;
|
||||
}
|
||||
@@ -1420,12 +1491,17 @@ fn sync_item<R: Runtime>(
|
||||
match (existing, previous, next) {
|
||||
(
|
||||
MenuItemKind::Submenu(submenu),
|
||||
RenderedItem::Submenu { title: previous_title, items: previous_items, .. },
|
||||
RenderedItem::Submenu { title, items, .. },
|
||||
RenderedItem::Submenu { title: previous_title, current: previous_current, items: previous_items, .. },
|
||||
RenderedItem::Submenu { title, current, items, .. },
|
||||
) => {
|
||||
if previous_title != title && submenu.set_text(title).is_err() {
|
||||
return false;
|
||||
}
|
||||
if previous_current != current
|
||||
&& submenu.set_native_icon(current.then_some(NativeIcon::MenuOnState)).is_err()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
sync_children(app, submenu, previous_items, items, disabled, true)
|
||||
}
|
||||
(
|
||||
@@ -1496,6 +1572,9 @@ pub enum MenuNode {
|
||||
Submenu {
|
||||
id: String,
|
||||
label: String,
|
||||
/// Saved layout selection, unset for ordinary submenus.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
current: Option<bool>,
|
||||
children: Vec<MenuNode>,
|
||||
},
|
||||
/// Runs `id` with `arg`. Items with an `arg` (Open Recent) carry their final label.
|
||||
@@ -1525,15 +1604,28 @@ pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec<
|
||||
Entry::Submenu { id, label, children } => out.push(MenuNode::Submenu {
|
||||
id: (*id).into(),
|
||||
label: (*label).into(),
|
||||
current: None,
|
||||
children: model(children, recent, config),
|
||||
}),
|
||||
Entry::Dynamic(slot) => out.extend(config.dynamic_items(slot).iter().map(|d| MenuNode::Action {
|
||||
id: d.action.clone(),
|
||||
label: d.label.clone(),
|
||||
hint: None,
|
||||
arg: d.arg.clone(),
|
||||
checked: d.checked,
|
||||
})),
|
||||
Entry::Dynamic(DYNAMIC_LAYOUTS) => {
|
||||
let layouts = config.layout_menus();
|
||||
if !layouts.is_empty() {
|
||||
out.push(MenuNode::Separator);
|
||||
}
|
||||
out.extend(layouts.into_iter().map(|layout| {
|
||||
MenuNode::Submenu {
|
||||
id: layout.id,
|
||||
label: layout.name.into(),
|
||||
current: Some(layout.current),
|
||||
children: layout
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.map_or(MenuNode::Separator, |item| item.model()))
|
||||
.collect(),
|
||||
}
|
||||
}));
|
||||
}
|
||||
Entry::Dynamic(slot) => out.extend(config.dynamic_items(slot).iter().map(DynamicItem::model)),
|
||||
Entry::Action { id, label, hint, .. } => out.push(MenuNode::Action {
|
||||
id: (*id).into(),
|
||||
label: (*label).into(),
|
||||
@@ -2222,6 +2314,53 @@ mod tests {
|
||||
assert_eq!(route(&spec, "dyn:"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_layout_submenus_group_commands_by_selection() {
|
||||
let mut config = MenuConfig::default();
|
||||
let mut review = dynamic_item("layout.restore", Some("Review | wide"), "Review | wide");
|
||||
review.checked = Some(true);
|
||||
config
|
||||
.dynamic
|
||||
.insert(DYNAMIC_LAYOUTS.into(), vec![dynamic_item("layout.restore", Some("Focus"), "Focus"), review]);
|
||||
config.labels.insert("menu.layout.applyNamed".into(), "Apply layout".into());
|
||||
let layout_spec = [act("layout.restoreDefault", "Restore Default Layout"), Entry::Dynamic(DYNAMIC_LAYOUTS)];
|
||||
let nodes = model(&layout_spec, &[], &config);
|
||||
assert!(matches!(&nodes[0], MenuNode::Action { id, .. } if id == "layout.restoreDefault"));
|
||||
assert!(matches!(&nodes[1], MenuNode::Separator));
|
||||
let MenuNode::Submenu { label, current: Some(false), children, .. } = &nodes[2] else {
|
||||
panic!("expected an inactive named layout");
|
||||
};
|
||||
assert_eq!(label, "Focus");
|
||||
assert!(matches!(&children[0], MenuNode::Action { label, .. } if label == "Apply layout"));
|
||||
assert_eq!(children.len(), 4);
|
||||
let MenuNode::Submenu { label, current: Some(true), children, .. } = &nodes[3] else {
|
||||
panic!("expected an active named layout");
|
||||
};
|
||||
assert_eq!(label, "Review | wide");
|
||||
let ids: Vec<_> = children
|
||||
.iter()
|
||||
.filter_map(|node| match node {
|
||||
MenuNode::Action { id, arg: Some(name), .. } => {
|
||||
assert_eq!(name, "Review | wide");
|
||||
Some(id.as_str())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(ids, ["layout.restore", "layout.saveCurrent", "layout.rename", "layout.delete"]);
|
||||
|
||||
let rendered = render_items(&layout_spec, &config, &[]);
|
||||
let RenderedItem::Submenu { current: true, items, .. } = &rendered[3] else {
|
||||
panic!("expected an active native named layout");
|
||||
};
|
||||
let RenderedItem::Action { id, .. } = &items[2] else { panic!("expected Rename") };
|
||||
assert_eq!(
|
||||
route(&layout_spec, id),
|
||||
Some(MenuRoute { action: "layout.rename".into(), arg: Some("Review | wide".into()) }),
|
||||
);
|
||||
assert_eq!(model(&layout_spec, &[], &MenuConfig::default()).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_windows_and_layouts_are_listed_by_the_frontend() {
|
||||
fn slots(entries: &[Entry], out: &mut Vec<&'static str>) {
|
||||
@@ -2384,8 +2523,6 @@ mod tests {
|
||||
"layout.restoreCurrent",
|
||||
"layout.save",
|
||||
"layout.restoreDefault",
|
||||
"layout.rename",
|
||||
"layout.delete",
|
||||
"toolwindow.hideActive",
|
||||
"editor.closeOtherTabs",
|
||||
"toolbar.customize",
|
||||
|
||||
@@ -137,7 +137,7 @@ pub struct ComparisonLaunch {
|
||||
|
||||
/// One side of a diff window's comparison (the UI's `DiffSide`, `diffInput.ts`).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum DiffSide {
|
||||
/// File content at a Git revision (`HEAD`, `:0` = index, a commit id).
|
||||
Rev {
|
||||
@@ -151,6 +151,8 @@ pub enum DiffSide {
|
||||
Worktree {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
label: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
label_detail: Option<String>,
|
||||
},
|
||||
/// Another file (Compare With…, Compare Files).
|
||||
File {
|
||||
@@ -158,8 +160,13 @@ pub enum DiffSide {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
label: Option<String>,
|
||||
},
|
||||
/// Literal text: a side that does not exist.
|
||||
Text { text: String, label: String },
|
||||
/// Literal text, such as clipboard contents or an editor selection.
|
||||
Text {
|
||||
text: String,
|
||||
label: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
label_detail: Option<String>,
|
||||
},
|
||||
/// A Local History revision.
|
||||
History { id: String, label: String },
|
||||
}
|
||||
@@ -2215,7 +2222,7 @@ mod tests {
|
||||
let mut diff = DiffLaunch {
|
||||
path: "/p/a.txt".into(),
|
||||
left: DiffSide::Rev { rev: "HEAD".into(), path: None, label: None },
|
||||
right: DiffSide::Worktree { label: None },
|
||||
right: DiffSide::Worktree { label: None, label_detail: None },
|
||||
line: None,
|
||||
};
|
||||
let id = diff_window_id(&diff);
|
||||
@@ -2227,6 +2234,18 @@ mod tests {
|
||||
assert_ne!(diff_window_id(&diff), id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_window_keeps_file_and_selection_label_details() {
|
||||
for side in [
|
||||
serde_json::json!({"type": "worktree", "label": "file.rs", "labelDetail": "src"}),
|
||||
serde_json::json!({"type": "text", "text": "let x = 1;", "label": "Selection from file.rs", "labelDetail": ""}),
|
||||
serde_json::json!({"type": "text", "text": "let x = 2;", "label": "From Clipboard"}),
|
||||
] {
|
||||
let parsed = serde_json::from_value::<DiffSide>(side.clone()).unwrap();
|
||||
assert_eq!(serde_json::to_value(parsed).unwrap(), side);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_window_starts_with_the_header_its_page_draws() {
|
||||
let mut a = AppearanceSettings::default();
|
||||
|
||||
+44
-16
@@ -1040,7 +1040,7 @@ export const commands = {
|
||||
*/
|
||||
menuConfigure: (config: MenuConfig) => __TAURI_INVOKE<void>("menu_configure", { config }),
|
||||
/** The menu bar for a title bar drawn by the frontend (Windows). */
|
||||
menuModel: () => __TAURI_INVOKE<MenuNode[]>("menu_model"),
|
||||
menuModel: () => __TAURI_INVOKE<MenuNode_Serialize[]>("menu_model"),
|
||||
/**
|
||||
* Updates the menu after the recent-projects list changed. Only the Open Recent
|
||||
* submenu is rewritten when the rest of the menu is unchanged.
|
||||
@@ -2205,6 +2205,8 @@ export type AgentChange = {
|
||||
removed: number,
|
||||
/** Path before a rename; the left side of its diff reads this path. */
|
||||
oldPath: string | null,
|
||||
/** The repository the file is in, when the task's project holds nested repositories. */
|
||||
repo: IpcPath | null,
|
||||
};
|
||||
|
||||
/** A task's uncommitted files and the commits made since it started. */
|
||||
@@ -3906,6 +3908,7 @@ export type CommitSettings = {
|
||||
* window and a Commit dialog.
|
||||
*/
|
||||
nonModal?: boolean,
|
||||
includeChangesByDefault?: boolean,
|
||||
/** Start with an empty message instead of the last one / the changelist's. */
|
||||
clearInitialMessage?: boolean,
|
||||
analyzeCode?: boolean,
|
||||
@@ -5280,28 +5283,28 @@ export type DiffSide = DiffSide_Serialize | DiffSide_Deserialize;
|
||||
/** One side of a diff window's comparison (the UI's `DiffSide`, `diffInput.ts`). */
|
||||
export type DiffSide_Deserialize =
|
||||
/** File content at a Git revision (`HEAD`, `:0` = index, a commit id). */
|
||||
({ type: "rev"; rev: string; path?: string | null; label?: string | null }) & { id?: never; text?: never } |
|
||||
({ type: "rev"; rev: string; path?: string | null; label?: string | null }) & { id?: never; labelDetail?: never; text?: never } |
|
||||
/** The working file (unsaved editor buffer included). */
|
||||
({ type: "worktree"; label?: string | null }) & { id?: never; path?: never; rev?: never; text?: never } |
|
||||
({ type: "worktree"; label?: string | null; labelDetail?: string | null }) & { id?: never; path?: never; rev?: never; text?: never } |
|
||||
/** Another file (Compare With…, Compare Files). */
|
||||
({ type: "file"; path: string; label?: string | null }) & { id?: never; rev?: never; text?: never } |
|
||||
/** Literal text: a side that does not exist. */
|
||||
({ type: "text"; text: string; label: string }) & { id?: never; path?: never; rev?: never } |
|
||||
({ type: "file"; path: string; label?: string | null }) & { id?: never; labelDetail?: never; rev?: never; text?: never } |
|
||||
/** Literal text, such as clipboard contents or an editor selection. */
|
||||
({ type: "text"; text: string; label: string; labelDetail?: string | null }) & { id?: never; path?: never; rev?: never } |
|
||||
/** A Local History revision. */
|
||||
({ type: "history"; id: string; label: string }) & { path?: never; rev?: never; text?: never };
|
||||
({ type: "history"; id: string; label: string }) & { labelDetail?: never; path?: never; rev?: never; text?: never };
|
||||
|
||||
/** One side of a diff window's comparison (the UI's `DiffSide`, `diffInput.ts`). */
|
||||
export type DiffSide_Serialize =
|
||||
/** File content at a Git revision (`HEAD`, `:0` = index, a commit id). */
|
||||
({ type: "rev"; rev: string; path?: string | null; label?: string | null }) & { id?: never; text?: never } |
|
||||
({ type: "rev"; rev: string; path?: string | null; label?: string | null }) & { id?: never; labelDetail?: never; text?: never } |
|
||||
/** The working file (unsaved editor buffer included). */
|
||||
({ type: "worktree"; label?: string | null }) & { id?: never; path?: never; rev?: never; text?: never } |
|
||||
({ type: "worktree"; label?: string | null; labelDetail?: string | null }) & { id?: never; path?: never; rev?: never; text?: never } |
|
||||
/** Another file (Compare With…, Compare Files). */
|
||||
({ type: "file"; path: string; label?: string | null }) & { id?: never; rev?: never; text?: never } |
|
||||
/** Literal text: a side that does not exist. */
|
||||
({ type: "text"; text: string; label: string }) & { id?: never; path?: never; rev?: never } |
|
||||
({ type: "file"; path: string; label?: string | null }) & { id?: never; labelDetail?: never; rev?: never; text?: never } |
|
||||
/** Literal text, such as clipboard contents or an editor selection. */
|
||||
({ type: "text"; text: string; label: string; labelDetail?: string | null }) & { id?: never; path?: never; rev?: never } |
|
||||
/** A Local History revision. */
|
||||
({ type: "history"; id: string; label: string }) & { path?: never; rev?: never; text?: never };
|
||||
({ type: "history"; id: string; label: string }) & { labelDetail?: never; path?: never; rev?: never; text?: never };
|
||||
|
||||
export type DirectoryCompareEntry = {
|
||||
path: string,
|
||||
@@ -8965,16 +8968,41 @@ export type MenuConfig = {
|
||||
* A menu entry for a menu bar drawn by the frontend (Windows title bar).
|
||||
* Labels are the English defaults; the frontend localises them like the native menu.
|
||||
*/
|
||||
export type MenuNode = { kind: "submenu"; id: string; label: string; children: MenuNode[] } |
|
||||
export type MenuNode = MenuNode_Serialize | MenuNode_Deserialize;
|
||||
|
||||
/**
|
||||
* A menu entry for a menu bar drawn by the frontend (Windows title bar).
|
||||
* Labels are the English defaults; the frontend localises them like the native menu.
|
||||
*/
|
||||
export type MenuNode_Deserialize = ({ kind: "submenu"; id: string; label: string;
|
||||
/** Saved layout selection, unset for ordinary submenus. */
|
||||
current: boolean | null; children: MenuNode_Deserialize[] }) & { arg?: never; checked?: never; hint?: never } |
|
||||
/**
|
||||
* Runs `id` with `arg`. Items with an `arg` (Open Recent) carry their final label.
|
||||
* `checked` is the state of a frontend-listed toggle (Status Bar Widgets). Spec toggles
|
||||
* leave it unset: the frontend menu reads their state from the action (`toggled`), the
|
||||
* source [`MenuConfig::checked`] is built from for the native menu.
|
||||
*/
|
||||
{ kind: "action"; id: string; label: string; hint: string | null; arg: string | null; checked: boolean | null } |
|
||||
({ kind: "action"; id: string; label: string; hint: string | null; arg: string | null; checked: boolean | null }) & { children?: never; current?: never } |
|
||||
/** A disabled placeholder such as "No Recent Projects". */
|
||||
{ kind: "placeholder"; id: string; label: string } | { kind: "separator" };
|
||||
({ kind: "placeholder"; id: string; label: string }) & { arg?: never; checked?: never; children?: never; current?: never; hint?: never } | ({ kind: "separator" }) & { arg?: never; checked?: never; children?: never; current?: never; hint?: never; id?: never; label?: never };
|
||||
|
||||
/**
|
||||
* A menu entry for a menu bar drawn by the frontend (Windows title bar).
|
||||
* Labels are the English defaults; the frontend localises them like the native menu.
|
||||
*/
|
||||
export type MenuNode_Serialize = ({ kind: "submenu"; id: string; label: string;
|
||||
/** Saved layout selection, unset for ordinary submenus. */
|
||||
current?: boolean | null; children: MenuNode_Serialize[] }) & { arg?: never; checked?: never; hint?: never } |
|
||||
/**
|
||||
* Runs `id` with `arg`. Items with an `arg` (Open Recent) carry their final label.
|
||||
* `checked` is the state of a frontend-listed toggle (Status Bar Widgets). Spec toggles
|
||||
* leave it unset: the frontend menu reads their state from the action (`toggled`), the
|
||||
* source [`MenuConfig::checked`] is built from for the native menu.
|
||||
*/
|
||||
({ kind: "action"; id: string; label: string; hint: string | null; arg: string | null; checked: boolean | null }) & { children?: never; current?: never } |
|
||||
/** A disabled placeholder such as "No Recent Projects". */
|
||||
({ kind: "placeholder"; id: string; label: string }) & { arg?: never; checked?: never; children?: never; current?: never; hint?: never } | ({ kind: "separator" }) & { arg?: never; checked?: never; children?: never; current?: never; hint?: never; id?: never; label?: never };
|
||||
|
||||
/** Merge dialog › Modify options (shared by the Pull dialog). */
|
||||
export type MergeOptions = {
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { closeBrackets } from "@codemirror/autocomplete";
|
||||
import { insertNewlineAndIndent } from "@codemirror/commands";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { validateEditorExtras } from "@/platform/editorSettings";
|
||||
import { prefsExtension } from "./prefs";
|
||||
import { findLanguageDescription, loadSupport } from "./languages";
|
||||
|
||||
const views: EditorView[] = [];
|
||||
afterEach(() => views.splice(0).forEach((v) => v.destroy()));
|
||||
|
||||
/** A TSX editor wired as the real one: language support (with `autoCloseTags`), closeBrackets and prefs. */
|
||||
function make(text: string) {
|
||||
const at = text.indexOf("|");
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: text.replace("|", ""),
|
||||
selection: EditorSelection.cursor(at),
|
||||
extensions: [
|
||||
javascript({ jsx: true, typescript: true }),
|
||||
closeBrackets(),
|
||||
prefsExtension({
|
||||
prefs: validateEditorExtras({}),
|
||||
path: "",
|
||||
softWrap: false,
|
||||
showWhitespace: false,
|
||||
hardWrapAt: 120,
|
||||
readOnly: false,
|
||||
language: "typescriptreact",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
return view;
|
||||
}
|
||||
|
||||
function show(view: EditorView): string {
|
||||
const doc = view.state.doc.toString();
|
||||
const head = view.state.selection.main.head;
|
||||
return doc.slice(0, head) + "|" + doc.slice(head);
|
||||
}
|
||||
|
||||
/** Types `text` one character at a time through the real input handlers. */
|
||||
function type(v: EditorView, text: string) {
|
||||
for (const ch of text) {
|
||||
const r = v.state.selection.main;
|
||||
const insert = () => v.state.update(v.state.replaceSelection(ch), { userEvent: "input.type" });
|
||||
if (!v.state.facet(EditorView.inputHandler).some((h) => h(v, r.from, r.to, ch, insert))) v.dispatch(insert());
|
||||
}
|
||||
}
|
||||
|
||||
describe("JSX tag auto-close", () => {
|
||||
it("closes an opening tag on `>`", () => {
|
||||
const v = make("const a = |;");
|
||||
type(v, "<div>");
|
||||
expect(show(v)).toBe("const a = <div>|</div>;");
|
||||
});
|
||||
|
||||
it("closes components, member names and fragments", () => {
|
||||
const v = make("const a = |;");
|
||||
type(v, "<Foo.Bar>");
|
||||
expect(show(v)).toBe("const a = <Foo.Bar>|</Foo.Bar>;");
|
||||
const f = make("const a = |;");
|
||||
type(f, "<>");
|
||||
expect(show(f)).toBe("const a = <>|</>;");
|
||||
});
|
||||
|
||||
it("closes after attributes, but not self-closing tags", () => {
|
||||
const v = make("const a = |;");
|
||||
type(v, '<div id="x">');
|
||||
expect(show(v)).toBe('const a = <div id="x">|</div>;');
|
||||
const s = make("const a = |;");
|
||||
type(s, "<Foo />");
|
||||
expect(show(s)).toBe("const a = <Foo />|;");
|
||||
});
|
||||
|
||||
it("completes the closing tag on `</`", () => {
|
||||
const v = make("const a = <div>x|;");
|
||||
type(v, "</");
|
||||
expect(show(v)).toBe("const a = <div>x</div>|;");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Enter between JSX tags", () => {
|
||||
/** Presses Enter at `|` with the editor's TSX / JSX mode (its grammar patches included). */
|
||||
async function enter(mode: "TSX" | "JSX", text: string) {
|
||||
const support = await loadSupport(findLanguageDescription(mode, `/p/a.${mode.toLowerCase()}`)!);
|
||||
const at = text.indexOf("|");
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: text.replace("|", ""),
|
||||
selection: EditorSelection.cursor(at),
|
||||
extensions: support!,
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
insertNewlineAndIndent(view);
|
||||
return show(view);
|
||||
}
|
||||
|
||||
it("puts the caret on an indented line with the closing tag below, at the opening tag's indent", async () => {
|
||||
expect(await enter("TSX", "function A() {\n return (\n <div>|</div>\n );\n}")).toBe(
|
||||
"function A() {\n return (\n <div>\n |\n </div>\n );\n}",
|
||||
);
|
||||
expect(await enter("JSX", 'const a = <Foo.Bar id="x">|</Foo.Bar>;')).toBe(
|
||||
'const a = <Foo.Bar id="x">\n |\n</Foo.Bar>;',
|
||||
);
|
||||
});
|
||||
|
||||
it("only splits a tag pair", async () => {
|
||||
expect(await enter("TSX", "const a = <div>x|</div>;")).toBe("const a = <div>x\n|</div>;");
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
language as languageFacet,
|
||||
type StreamParser,
|
||||
} from "@codemirror/language";
|
||||
import { NodeProp } from "@lezer/common";
|
||||
import { styleTags, tags as t } from "@lezer/highlight";
|
||||
import { languages as languageData } from "@codemirror/language-data";
|
||||
import type { DocBackend, LanguageInfo } from "../backend";
|
||||
@@ -450,8 +451,19 @@ const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
|
||||
|
||||
const bracedIndent = delimitedIndent({ closing: "}" });
|
||||
|
||||
/** Grammar props the stock languages lack: indentation that follows the language's usual style. */
|
||||
/**
|
||||
* JSX tags pair up as HTML's do: Enter between `<div>` and `</div>` puts the caret on an
|
||||
* indented line of its own with the closing tag below, and the tags match each other.
|
||||
*/
|
||||
const JSX_TAG_PAIRS = [
|
||||
NodeProp.closedBy.add({ JSXOpenTag: ["JSXCloseTag"] }),
|
||||
NodeProp.openedBy.add({ JSXCloseTag: ["JSXOpenTag"] }),
|
||||
];
|
||||
|
||||
/** Grammar props the stock languages lack: indentation that follows the language's usual style, JSX tag pairs. */
|
||||
const EXTRA_PROPS: Record<string, NonNullable<Parameters<LRLanguage["configure"]>[0]["props"]>> = {
|
||||
JSX: JSX_TAG_PAIRS,
|
||||
TSX: JSX_TAG_PAIRS,
|
||||
// clang-format's built-in styles (NamespaceIndentation: None, no extern block indent) keep the
|
||||
// contents of `namespace x { … }` and `extern "C" { … }` at the level of the braces' line.
|
||||
"C++": [
|
||||
|
||||
@@ -3,6 +3,7 @@ import { EditorSelection, EditorState, type Extension } from "@codemirror/state"
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { history, redo, undo } from "@codemirror/commands";
|
||||
import { html } from "@codemirror/lang-html";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { linkedTags } from "./linkedTags";
|
||||
import { prefsExtension } from "./prefs";
|
||||
import { angular } from "./angular";
|
||||
@@ -221,6 +222,53 @@ describe("linked html tags", () => {
|
||||
}
|
||||
});
|
||||
|
||||
describe("in JSX / TSX", () => {
|
||||
const tsx = (text: string) => makeWith([javascript({ jsx: true, typescript: true }), linkedTags, history()], text);
|
||||
|
||||
it("renames the closing tag while the opening one is typed, and back", () => {
|
||||
const v = tsx('const a = <div| className="x">hi</div>;');
|
||||
type(v, "s");
|
||||
expect(show(v)).toBe('const a = <divs| className="x">hi</divs>;');
|
||||
const w = tsx("const a = <Foo>hi</Fo|o>;");
|
||||
type(w, "x");
|
||||
expect(show(w)).toBe("const a = <Foxo>hi</Fox|o>;");
|
||||
});
|
||||
|
||||
it("renames member and namespaced names as a whole", () => {
|
||||
const v = tsx("const a = <Foo.Bar|>x</Foo.Bar>;");
|
||||
type(v, "z");
|
||||
expect(v.state.doc.toString()).toBe("const a = <Foo.Barz>x</Foo.Barz>;");
|
||||
const w = tsx("const a = <|Foo.Bar>x</Foo.Bar>;");
|
||||
type(w, "My");
|
||||
expect(w.state.doc.toString()).toBe("const a = <MyFoo.Bar>x</MyFoo.Bar>;");
|
||||
});
|
||||
|
||||
it("follows the element's own closing tag through nested same-name elements", () => {
|
||||
const v = tsx("const a = <div|><div></div></div>;");
|
||||
type(v, "x");
|
||||
expect(v.state.doc.toString()).toBe("const a = <divx><div></div></divx>;");
|
||||
});
|
||||
|
||||
it("leaves fragments, self-closing tags and attributes alone", () => {
|
||||
const v = tsx("const a = <Foo| />;");
|
||||
type(v, "x");
|
||||
expect(v.state.doc.toString()).toBe("const a = <Foox />;");
|
||||
const w = tsx("const a = <div |>x</div>;");
|
||||
type(w, "a");
|
||||
expect(w.state.doc.toString()).toBe("const a = <div a>x</div>;");
|
||||
const f = tsx("const a = <|>x</>;");
|
||||
type(f, "p");
|
||||
expect(f.state.doc.toString()).toBe("const a = <p>x</>;");
|
||||
});
|
||||
|
||||
it("undoes both tags in one step", () => {
|
||||
const v = tsx("const a = <div|></div>;");
|
||||
type(v, "x");
|
||||
expect(undo(v)).toBe(true);
|
||||
expect(v.state.doc.toString()).toBe("const a = <div></div>;");
|
||||
});
|
||||
});
|
||||
|
||||
describe("the smart key gates the filter", () => {
|
||||
/** The real wiring: prefsExtension attaches the filter for the document's language. */
|
||||
const prefs = (language: string | undefined, smartKeys: Record<string, unknown> = {}) =>
|
||||
@@ -256,6 +304,28 @@ describe("linked html tags", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("links tags for JSX / TSX", () => {
|
||||
for (const language of ["typescriptreact", "javascriptreact"]) {
|
||||
const v = makeWith(
|
||||
[
|
||||
javascript({ jsx: true, typescript: language === "typescriptreact" }),
|
||||
prefsExtension({
|
||||
prefs: validateEditorExtras({ smartKeys: {} }),
|
||||
path: "",
|
||||
softWrap: false,
|
||||
showWhitespace: false,
|
||||
hardWrapAt: 120,
|
||||
readOnly: false,
|
||||
language,
|
||||
}),
|
||||
],
|
||||
"const a = <div|></div>;",
|
||||
);
|
||||
type(v, "s");
|
||||
expect(v.state.doc.toString()).toBe("const a = <divs></divs>;");
|
||||
}
|
||||
});
|
||||
|
||||
it("stays off when the option is off", () => {
|
||||
const v = prefs("html", { simultaneousTagEditing: false });
|
||||
type(v, "s");
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
/**
|
||||
* Linked editing for matching HTML tags, as in IDEA's Simultaneous
|
||||
* Linked editing for matching HTML and JSX tags, as in IDEA's Simultaneous
|
||||
* `<tag></tag>` editing (on by default) and VS Code's Linked Editing: editing
|
||||
* the name in an opening (or closing) tag renames the matching tag of the same
|
||||
* element as you type. Done from the syntax tree — `@lezer/html`'s
|
||||
* `OpenTag`/`CloseTag` elements, shared by every HTML-based mode — so it works
|
||||
* without a language server.
|
||||
* `OpenTag`/`CloseTag` elements, shared by every HTML-based mode, and
|
||||
* `@lezer/javascript`'s `JSXOpenTag`/`JSXCloseTag` — so it works without a
|
||||
* language server.
|
||||
*
|
||||
* A transaction whose change lies inside one tag's `TagName` is extended with
|
||||
* A transaction whose change lies inside one tag's name is extended with
|
||||
* the same edit at the same offset in the counterpart's name — one
|
||||
* transaction, so undo takes both back together. Without a matching tag (void
|
||||
* and self-closing tags, unclosed elements, a stray close tag) or with the two
|
||||
@@ -18,18 +19,37 @@ import { syntaxTree } from "@codemirror/language";
|
||||
import type { SyntaxNode, Tree } from "@lezer/common";
|
||||
import { isExternalChange } from "@/editor/api";
|
||||
|
||||
/** The `TagName` a changed range edits — an insertion at either edge extends the name. */
|
||||
/** A JSX tag's whole name — `div`, `Foo`, `Foo.Bar`, `svg:rect` — as a direct child of its tag. */
|
||||
const JSX_NAMES = new Set(["JSXIdentifier", "JSXBuiltin", "JSXMemberExpression", "JSXNamespacedName"]);
|
||||
const JSX_TAGS = new Set(["JSXOpenTag", "JSXCloseTag"]);
|
||||
|
||||
/** The JSX tag name `n` lies in, or null outside one. */
|
||||
function jsxNameOf(n: SyntaxNode | null): SyntaxNode | null {
|
||||
while (n?.parent && !JSX_TAGS.has(n.parent.name)) n = n.parent;
|
||||
return n?.parent && JSX_NAMES.has(n.name) ? n : null;
|
||||
}
|
||||
|
||||
/** The tag name a changed range edits — an insertion at either edge extends the name. */
|
||||
function tagNameAround(tree: Tree, from: number, to: number): SyntaxNode | null {
|
||||
let n = tree.resolveInner(from, -1);
|
||||
if (n.name !== "TagName") n = tree.resolveInner(from, 1);
|
||||
return n.name === "TagName" && n.from <= from && to <= n.to ? n : null;
|
||||
for (const side of [-1, 1] as const) {
|
||||
const inner = tree.resolveInner(from, side);
|
||||
const n = inner.name === "TagName" ? inner : jsxNameOf(inner);
|
||||
if (n && n.from <= from && to <= n.to) return n;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The matching tag's name of the same element, or null without one. */
|
||||
function counterpartName(name: SyntaxNode): SyntaxNode | null {
|
||||
const tag = name.parent;
|
||||
const element = tag?.parent;
|
||||
if (!tag || element?.name !== "Element") return null;
|
||||
if (!tag || !element) return null;
|
||||
if (element.name === "JSXElement") {
|
||||
const other = element.getChild(tag.name === "JSXOpenTag" ? "JSXCloseTag" : "JSXOpenTag");
|
||||
for (let c = other?.firstChild; c; c = c.nextSibling) if (JSX_NAMES.has(c.name)) return c;
|
||||
return null;
|
||||
}
|
||||
if (element.name !== "Element") return null;
|
||||
const other = element.getChild(
|
||||
/^Open/.test(tag.name) ? tag.name.replace("Open", "Close") : tag.name.replace("Close", "Open"),
|
||||
);
|
||||
@@ -37,10 +57,10 @@ function counterpartName(name: SyntaxNode): SyntaxNode | null {
|
||||
}
|
||||
|
||||
/** Insertions at a name's edge must extend the name; structural characters end it. */
|
||||
const NOT_NAME_CHARS = /[\s/>"'<=]/;
|
||||
const NOT_NAME_CHARS = /[\s/>"'<={}]/;
|
||||
|
||||
/**
|
||||
* Editing the name of an opening (or closing) HTML tag renames its matching
|
||||
* Editing the name of an opening (or closing) HTML or JSX tag renames its matching
|
||||
* tag, from the syntax tree — no language server. Installed while Smart Keys ›
|
||||
* Simultaneous `<tag></tag>` editing is on (the default).
|
||||
*/
|
||||
|
||||
@@ -518,12 +518,20 @@ export const GUTTER_ICON_GROUPS = [
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Languages whose outer parser is `@lezer/html`, where simultaneous
|
||||
* `<tag></tag>` editing works from the syntax tree. Angular templates carry
|
||||
* the `html` backend id (the Angular mode is picked per project), `erb` is a
|
||||
* token-based mode without a syntax tree and stays out.
|
||||
* Languages whose outer parser is `@lezer/html`, plus JSX / TSX, where
|
||||
* simultaneous `<tag></tag>` editing works from the syntax tree. Angular
|
||||
* templates carry the `html` backend id (the Angular mode is picked per
|
||||
* project), `erb` is a token-based mode without a syntax tree and stays out.
|
||||
*/
|
||||
const LINKED_TAG_LANGUAGES = new Set(["html", "vue", "jsp", "django-html", "astro"]);
|
||||
const LINKED_TAG_LANGUAGES = new Set([
|
||||
"html",
|
||||
"vue",
|
||||
"jsp",
|
||||
"django-html",
|
||||
"astro",
|
||||
"typescriptreact",
|
||||
"javascriptreact",
|
||||
]);
|
||||
|
||||
export interface PrefsOptions {
|
||||
prefs: EditorExtras;
|
||||
@@ -652,8 +660,8 @@ export function prefsExtension(o: PrefsOptions): Extension {
|
||||
if (k.tabOutOfPair) out.push(tabOut);
|
||||
// Simultaneous `<tag></tag>` editing, from the syntax tree: every mode whose outer
|
||||
// parser is `@lezer/html` — plain HTML plus the HTML-based modes (Vue SFCs, Angular
|
||||
// templates, JSP, Django and Astro; Angular templates carry the `html` backend id).
|
||||
// ERB is token-based (no syntax tree), so it stays out.
|
||||
// templates, JSP, Django and Astro; Angular templates carry the `html` backend id),
|
||||
// and JSX / TSX. ERB is token-based (no syntax tree), so it stays out.
|
||||
if (!o.readOnly && k.simultaneousTagEditing && LINKED_TAG_LANGUAGES.has(o.language ?? "")) out.push(linkedTags);
|
||||
if (o.commentStyle) out.push(lineCommentStyle.of(o.commentStyle));
|
||||
|
||||
|
||||
@@ -571,7 +571,10 @@ describe("DocumentManager + slots", () => {
|
||||
if (id === a.doc) throw new Error("disk full");
|
||||
await save(id);
|
||||
});
|
||||
const logged = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
await expect(manager.saveAll("explicit")).rejects.toThrow("disk full");
|
||||
expect(logged).toHaveBeenCalledWith("saving /p/a.txt failed", expect.objectContaining({ message: "disk full" }));
|
||||
logged.mockRestore();
|
||||
expect(backend.files.get("/p/a.txt")).toBe("a\n");
|
||||
expect(backend.files.get("/p/b.txt")).toBe("changed b\n");
|
||||
expect(a.getMeta().dirty).toBe(true);
|
||||
|
||||
@@ -927,7 +927,7 @@ export class DocumentManager {
|
||||
try {
|
||||
await model.save("auto");
|
||||
} catch (e) {
|
||||
console.warn(`autosave of ${model.path} failed`, e);
|
||||
logError(`autosave of ${model.path} failed`, e);
|
||||
}
|
||||
}
|
||||
// As in IDEA, a file whose changes are not saved (autosave off, or a failed save) stays
|
||||
@@ -985,6 +985,8 @@ export class DocumentManager {
|
||||
.filter((m) => !(skipUntitled && isUntitledUri(m.path)))
|
||||
.map((m) =>
|
||||
m.save(reason).catch((e) => {
|
||||
// The notification shows the message only; the log keeps the stack for reports.
|
||||
logError(`saving ${m.path} failed`, e);
|
||||
errors.push(e);
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -6,6 +6,14 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.compactListPopup {
|
||||
min-width: 0;
|
||||
}
|
||||
.listDivider {
|
||||
width: 100%;
|
||||
height: 1px;
|
||||
background: var(--border-popup);
|
||||
}
|
||||
.listHeader {
|
||||
height: 28px;
|
||||
flex: none;
|
||||
@@ -116,7 +124,7 @@
|
||||
.listBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 24px;
|
||||
min-height: var(--h-list-row);
|
||||
padding: 0 0 4px;
|
||||
box-sizing: content-box;
|
||||
}
|
||||
@@ -374,52 +382,79 @@
|
||||
text-decoration: underline;
|
||||
}
|
||||
.defPopup {
|
||||
width: min(640px, 90vw);
|
||||
max-height: 460px;
|
||||
width: 600px;
|
||||
height: 400px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
.defHeader {
|
||||
height: 28px;
|
||||
min-height: var(--h-field);
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
padding: 0 6px 0 12px;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-1) var(--space-2);
|
||||
background: var(--bg-popup-inline, var(--bg-elev));
|
||||
border-bottom: 1px solid var(--border-popup);
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.defFile {
|
||||
.defTarget {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
min-width: 0;
|
||||
color: var(--fg-emphasis);
|
||||
}
|
||||
.defTarget > svg {
|
||||
flex: none;
|
||||
}
|
||||
.defName,
|
||||
.defPath {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.defPath {
|
||||
max-width: 45%;
|
||||
min-width: 0;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.defFrame {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
outline: none;
|
||||
}
|
||||
.defCount {
|
||||
.defActions {
|
||||
margin-inline-start: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: none;
|
||||
gap: var(--space-0-5);
|
||||
}
|
||||
.defCount {
|
||||
font-size: var(--fs-small);
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.defBody {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
padding: 4px 12px;
|
||||
padding: var(--space-3) var(--space-2);
|
||||
color: var(--fg-emphasis);
|
||||
}
|
||||
.defBody pre {
|
||||
.defCode {
|
||||
margin: 0;
|
||||
font: inherit;
|
||||
white-space: pre;
|
||||
}
|
||||
.defCode code {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.previewDialog [data-dialog-body] {
|
||||
display: flex;
|
||||
|
||||
@@ -340,6 +340,7 @@ describe("quick definition popup", () => {
|
||||
],
|
||||
index: 0,
|
||||
themeClasses: "",
|
||||
codeStyle: { fontSize: "16px", lineHeight: "24px" },
|
||||
});
|
||||
render(<LspPopups />);
|
||||
const frame = () => screen.getByRole("dialog", { name: "Definition" }).firstElementChild as HTMLElement;
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
Spinner,
|
||||
SymbolBadge,
|
||||
fileIconName,
|
||||
firstSelectable,
|
||||
fuzzyMatch,
|
||||
selectableText,
|
||||
T,
|
||||
@@ -26,6 +27,7 @@ import {
|
||||
closePopup,
|
||||
updatePopup,
|
||||
useLspPopup,
|
||||
type DefinitionTarget,
|
||||
type ListPopupItem,
|
||||
type ListPreview,
|
||||
type LspPopup,
|
||||
@@ -39,6 +41,7 @@ import styles from "./Popups.module.css";
|
||||
import fieldsetStyles from "@/ui/DialogFieldset.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useRowHeight } from "@/ui/density";
|
||||
|
||||
export function BulbIcon({ fix }: { fix?: boolean }) {
|
||||
return <Icon name={fix ? "bulb-fix" : "bulb"} size={16} className={styles.bulb} />;
|
||||
@@ -81,19 +84,44 @@ function ListPreviewPanel({
|
||||
const LIST_PREVIEW_WIDTH = 420;
|
||||
const MIN_SIDE_BY_SIDE_WIDTH = 660;
|
||||
|
||||
type ListPopupRow =
|
||||
| { kind: "action"; item: ListPopupItem; match: number[] | null }
|
||||
| { kind: "section"; key: string; label?: string };
|
||||
|
||||
const isListSection = (row: ListPopupRow) => row.kind === "section";
|
||||
const dividerHeight = (row: ListPopupRow) => (row.kind === "section" && !row.label ? 9 : undefined);
|
||||
|
||||
function listPopupRows(items: ListPopupItem[], query: string): ListPopupRow[] {
|
||||
const rows: ListPopupRow[] = [];
|
||||
let previous: string | undefined;
|
||||
for (const item of items) {
|
||||
const match = query ? fuzzyMatch(item.label, query) : null;
|
||||
if (query && match === null) continue;
|
||||
const { section } = item;
|
||||
if (section?.id !== previous && (section?.label || rows.length)) {
|
||||
rows.push({ kind: "section", key: `section:${rows.length}`, label: section?.label });
|
||||
}
|
||||
rows.push({ kind: "action", item, match });
|
||||
previous = section?.id;
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
const [query, setQuery] = useState("");
|
||||
const filtered = useMemo(() => {
|
||||
if (!query) return popup.items.map((item) => ({ item, match: null as number[] | null }));
|
||||
return popup.items.map((item) => ({ item, match: fuzzyMatch(item.label, query) })).filter((r) => r.match !== null);
|
||||
}, [popup.items, query]);
|
||||
const firstEnabled = Math.max(
|
||||
0,
|
||||
filtered.findIndex((r) => !r.item.disabled),
|
||||
);
|
||||
const rows = useMemo(() => listPopupRows(popup.items, query), [popup.items, query]);
|
||||
const firstEnabled = rows.findIndex((row) => row.kind === "action" && !row.item.disabled);
|
||||
const [active, setActive] = useState(firstEnabled);
|
||||
const activeIndex = Math.min(active, Math.max(0, filtered.length - 1));
|
||||
const activeItem = filtered[activeIndex]?.item;
|
||||
const clamped = Math.min(active, rows.length - 1);
|
||||
const activeIndex =
|
||||
rows[clamped]?.kind === "action"
|
||||
? clamped
|
||||
: firstEnabled >= 0
|
||||
? firstEnabled
|
||||
: firstSelectable(rows, isListSection);
|
||||
const activeRow = rows[activeIndex];
|
||||
const activeItem = activeRow?.kind === "action" ? activeRow.item : undefined;
|
||||
const showIcons = !popup.compact || popup.items.some((item) => item.icon || item.symbol);
|
||||
|
||||
// Choosers highlight what the selected row would act on.
|
||||
useEffect(() => {
|
||||
@@ -155,16 +183,20 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
if (item) activate(item);
|
||||
} else if (e.key === "Backspace" && query) {
|
||||
setQuery(query.slice(0, -1));
|
||||
setActive(0);
|
||||
setActive(-1);
|
||||
e.preventDefault();
|
||||
} else if (e.key.length === 1 && !(e.key === " " && !query)) {
|
||||
setQuery(query + e.key);
|
||||
setActive(0);
|
||||
setActive(-1);
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
const height = Math.min(12, Math.max(1, filtered.length)) * 24;
|
||||
const rowHeight = useRowHeight();
|
||||
const height = Math.min(
|
||||
12 * rowHeight,
|
||||
rows.reduce((sum, row) => sum + (dividerHeight(row) ?? rowHeight), 0) || rowHeight,
|
||||
);
|
||||
// Rows are virtualized (absolutely positioned), so size the popup from the content.
|
||||
const width = useMemo(() => {
|
||||
const chars = Math.max(
|
||||
@@ -173,8 +205,9 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
(i) => i.label.length + (i.preview?.length ?? 0) + (i.detail?.length ?? 0) + (i.shortcut?.length ?? 0),
|
||||
),
|
||||
);
|
||||
return Math.min(720, Math.max(320, chars * 7 + 90 + (popup.numbered ? 16 : 0)));
|
||||
}, [popup]);
|
||||
const padding = popup.compact ? 44 + (showIcons ? 20 : 0) : 90;
|
||||
return Math.min(720, Math.max(popup.compact ? 272 : 320, chars * 7 + padding + (popup.numbered ? 16 : 0)));
|
||||
}, [popup, showIcons]);
|
||||
const shownPreview = popup.preview
|
||||
? preview && preview.id === activeItem?.id
|
||||
? preview.data
|
||||
@@ -215,6 +248,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
aria-label={popup.title}
|
||||
className={clsx(
|
||||
styles.listPopup,
|
||||
popup.compact && styles.compactListPopup,
|
||||
hasPreview && styles.withPreview,
|
||||
previewBelow && styles.previewBelow,
|
||||
previewLeft && styles.previewLeft,
|
||||
@@ -241,14 +275,19 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
</div>
|
||||
<div ref={bodyRef} onKeyDown={onKeyDown} className={styles.listBody} style={{ height }}>
|
||||
<List
|
||||
items={filtered}
|
||||
getKey={(r) => r.item.id}
|
||||
items={rows}
|
||||
getKey={(row) => (row.kind === "section" ? row.key : row.item.id)}
|
||||
isSection={isListSection}
|
||||
sectionHeightOf={dividerHeight}
|
||||
renderSection={(row) =>
|
||||
row.kind === "section" && row.label ? <T>{row.label}</T> : <span className={styles.listDivider} />
|
||||
}
|
||||
activeIndex={activeIndex}
|
||||
onActiveChange={setActive}
|
||||
hoverSelects
|
||||
autoFocus
|
||||
aria-label={popup.title}
|
||||
onActivate={(r) => activate(r.item)}
|
||||
onActivate={(row) => row.kind === "action" && activate(row.item)}
|
||||
empty={
|
||||
popup.busy ? (
|
||||
<span className={styles.empty}>
|
||||
@@ -260,7 +299,9 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
</span>
|
||||
)
|
||||
}
|
||||
renderItem={({ item, match }) => {
|
||||
renderItem={(row) => {
|
||||
if (row.kind !== "action") return null;
|
||||
const { item, match } = row;
|
||||
const n = popup.numbered && !query ? indexOf(item) + 1 : 0;
|
||||
return (
|
||||
<div
|
||||
@@ -271,7 +312,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
data-line={item.location?.line}
|
||||
>
|
||||
{popup.numbered && <span className={styles.mnemonic}>{n > 0 && n <= 9 ? n : ""}</span>}
|
||||
<ItemIcon item={item} />
|
||||
{showIcons && <ItemIcon item={item} />}
|
||||
<HighlightedText className={styles.label} text={item.label} indices={match} tone="accent" />
|
||||
{item.preview && (
|
||||
<span className={styles.preview} title={item.preview}>
|
||||
@@ -504,6 +545,8 @@ function DefinitionPopup({ popup }: { popup: Extract<LspPopup, { kind: "definiti
|
||||
const target = popup.targets[popup.index]!;
|
||||
const { location } = target;
|
||||
const many = popup.targets.length > 1;
|
||||
const source = (loc: DefinitionTarget["location"]) => `${relativePath(root, loc.path)}:${loc.range.start.line + 1}`;
|
||||
const targetIcon = (path: string) => fileIconName(basename(path), path);
|
||||
const open = () => {
|
||||
closePopup();
|
||||
void editorService().openFile(location.path, {
|
||||
@@ -524,41 +567,76 @@ function DefinitionPopup({ popup }: { popup: Extract<LspPopup, { kind: "definiti
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Popup open anchor={popup.anchor} onClose={closePopup} aria-label="Definition" className={styles.defPopup}>
|
||||
<Popup
|
||||
open
|
||||
anchor={popup.anchor}
|
||||
onClose={closePopup}
|
||||
aria-label={tx("Definition")}
|
||||
className={styles.defPopup}
|
||||
resizable="both"
|
||||
>
|
||||
<div className={styles.defFrame} tabIndex={-1} data-autofocus onKeyDown={onKeyDown}>
|
||||
<div className={styles.defHeader}>
|
||||
<Icon name={fileIconName(basename(location.path), location.path)} size={14} />
|
||||
{many ? (
|
||||
<Select
|
||||
variant="ghost"
|
||||
className={styles.defTarget}
|
||||
aria-label="Definition"
|
||||
value={String(popup.index)}
|
||||
options={popup.targets.map((t, i) => ({
|
||||
value: String(i),
|
||||
label: t.name,
|
||||
detail: `${basename(t.location.path)}:${t.location.range.start.line + 1}`,
|
||||
verbatim: true,
|
||||
icon: targetIcon(t.location.path),
|
||||
detail: source(t.location),
|
||||
}))}
|
||||
onChange={(v) => select(Number(v))}
|
||||
/>
|
||||
) : (
|
||||
<span className={styles.defFile}>{basename(location.path)}</span>
|
||||
<div className={styles.defTarget}>
|
||||
<Icon name={targetIcon(location.path)} size={14} />
|
||||
<span className={styles.defName} title={target.name}>
|
||||
{target.name}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<span className={styles.defPath}>
|
||||
{relativePath(root, location.path)}:{location.range.start.line + 1}
|
||||
<span className={styles.defPath} title={source(location)}>
|
||||
{source(location)}
|
||||
</span>
|
||||
<span className={styles.spacer} />
|
||||
{many && (
|
||||
<span className={styles.defCount}>
|
||||
{popup.index + 1}/{popup.targets.length}
|
||||
</span>
|
||||
)}
|
||||
<IconButton icon="edit" size="small" title="Edit Source" shortcut="F4" onClick={open} />
|
||||
<div className={styles.defActions}>
|
||||
{many && (
|
||||
<>
|
||||
<IconButton
|
||||
icon="chevron-left"
|
||||
size="small"
|
||||
title="Previous Definition"
|
||||
onClick={() => select(popup.index - 1)}
|
||||
/>
|
||||
<span className={styles.defCount} aria-live="polite">
|
||||
{popup.index + 1}/{popup.targets.length}
|
||||
</span>
|
||||
<IconButton
|
||||
icon="chevron-right"
|
||||
size="small"
|
||||
title="Next Definition"
|
||||
onClick={() => select(popup.index + 1)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<IconButton icon="edit" size="small" title="Edit Source" shortcut="F4" onClick={open} />
|
||||
</div>
|
||||
</div>
|
||||
<div className={clsx(popup.themeClasses, styles.docScope)}>
|
||||
<div
|
||||
className={clsx(popup.themeClasses, styles.defBody)}
|
||||
style={popup.codeStyle}
|
||||
tabIndex={0}
|
||||
role="region"
|
||||
aria-label={tx("Preview")}
|
||||
>
|
||||
<DomContent
|
||||
key={popup.index}
|
||||
className={clsx(styles.defBody, selectableText)}
|
||||
build={() => renderCode(target.text, target.language, "cm-lsp-code")}
|
||||
className={selectableText}
|
||||
build={() => renderCode(target.text, target.language, styles.defCode)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -323,6 +323,22 @@ describe("applying completions", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("puts the caret inside the parentheses of a server-inserted call that takes arguments", async () => {
|
||||
setInvokeRoute(() => Promise.resolve(null));
|
||||
try {
|
||||
const { view, req } = setup("x.rea|\n", "", [completionExtension()]);
|
||||
view.dispatch({ effects: StateEffect.appendConfig.of(lspDoc.of({ doc: 1 } as EditorDocContext)) });
|
||||
const command = { title: "Apply Completion", command: "jetbrains.kotlin.completion.apply", arguments: ["1"] };
|
||||
const kotlin = item({ label: "read", kind: "method", labelDetail: "(name: String)", insertText: "", command });
|
||||
applyLspCompletion(view, makeCompletion(kotlin, req), 5, 5, "insert");
|
||||
view.dispatch({ changes: { from: 5, insert: "d()" }, annotations: remoteChange.of(true) });
|
||||
expect(view.state.doc.toString()).toBe("x.read()\n");
|
||||
expect(view.state.selection.main.head).toBe(7);
|
||||
} finally {
|
||||
setInvokeRoute(null);
|
||||
}
|
||||
});
|
||||
|
||||
it("completes at every caret whose typed prefix matches the main caret's", () => {
|
||||
const { view, req } = setup("a.cr|\nb.cr\nc.xy", "", [EditorState.allowMultipleSelections.of(true)]);
|
||||
// Carets after both `cr`s (the main one first) and after `xy`.
|
||||
|
||||
@@ -462,6 +462,8 @@ async function applyLateEdits(view: EditorView, c: LspCompletion, insertedAt: nu
|
||||
interface ServerInsert {
|
||||
at: number;
|
||||
others: readonly number[];
|
||||
/** The item is a call that takes arguments: the caret goes inside an inserted `()`. */
|
||||
inside?: boolean;
|
||||
}
|
||||
const awaitServerInsert = StateEffect.define<ServerInsert | null>();
|
||||
const serverInsertAt = StateField.define<ServerInsert | null>({
|
||||
@@ -470,7 +472,11 @@ const serverInsertAt = StateField.define<ServerInsert | null>({
|
||||
for (const e of tr.effects) if (e.is(awaitServerInsert)) return e.value;
|
||||
// The edit landed, or the caret moved on before it did.
|
||||
if (value === null || tr.annotation(remoteChange) || tr.selection) return null;
|
||||
return { at: tr.changes.mapPos(value.at, -1), others: value.others.map((p) => tr.changes.mapPos(p, -1)) };
|
||||
return {
|
||||
at: tr.changes.mapPos(value.at, -1),
|
||||
others: value.others.map((p) => tr.changes.mapPos(p, -1)),
|
||||
inside: value.inside,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -541,7 +547,9 @@ const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
|
||||
if (tr.changes.touchesRange(from, to)) continue;
|
||||
others.push({ from: tr.changes.mapPos(from, 1), to: tr.changes.mapPos(to, -1) });
|
||||
}
|
||||
const selection = EditorSelection.cursor(mainAfter);
|
||||
const inside =
|
||||
pending.inside && /\(\)$/.test(landed.insert) && tr.newDoc.sliceString(mainAfter - 2, mainAfter) === "()";
|
||||
const selection = EditorSelection.cursor(inside ? mainAfter - 1 : mainAfter);
|
||||
if (!others.length) return [tr, { selection, sequential: true }];
|
||||
// Not part of this transaction: a remote one is not sent back to the document model.
|
||||
const changes = others
|
||||
@@ -553,6 +561,12 @@ const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
|
||||
/** Client-side commands handled by the editor itself (VS Code ids servers commonly send). */
|
||||
const CLIENT_COMMANDS = new Set(["editor.action.triggerParameterHints", "editor.action.triggerSuggest"]);
|
||||
|
||||
/** A function or method whose signature lists parameters (`(name: String)`), as far as the item tells. */
|
||||
function takesArguments(item: Pick<CompletionItem, "kind" | "labelDetail" | "detail">): boolean {
|
||||
if (item.kind && !CALLABLE.has(item.kind)) return false;
|
||||
return /^\s*\(\s*[^)\s]/.test(item.labelDetail ?? item.detail ?? "");
|
||||
}
|
||||
|
||||
/** kotlin-lsp inserts the item itself (`jetbrains.kotlin.completion.apply`): nothing goes in here. */
|
||||
function serverInserts(item: CompletionItem): boolean {
|
||||
const cmd = item.command?.command;
|
||||
@@ -564,7 +578,10 @@ function runCommand(view: EditorView, item: CompletionItem, others: readonly num
|
||||
if (!command?.command) return;
|
||||
const cmd = command.command;
|
||||
const serverInserted = serverInserts(item);
|
||||
if (serverInserted) view.dispatch({ effects: awaitServerInsert.of({ at: view.state.selection.main.head, others }) });
|
||||
if (serverInserted)
|
||||
view.dispatch({
|
||||
effects: awaitServerInsert.of({ at: view.state.selection.main.head, others, inside: takesArguments(item) }),
|
||||
});
|
||||
if (cmd === "editor.action.triggerParameterHints") setTimeout(() => triggerSignatureHelp(view), 0);
|
||||
else if (cmd === "editor.action.triggerSuggest") setTimeout(() => startCompletion(view), 0);
|
||||
else if (!CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.")) {
|
||||
|
||||
@@ -413,12 +413,14 @@ export async function quickDefinition(view: EditorView, kind: "definition" | "ty
|
||||
showHint(view, "Cannot read the definition's file");
|
||||
return;
|
||||
}
|
||||
const { fontFamily, fontSize, fontWeight, lineHeight, tabSize } = getComputedStyle(view.contentDOM);
|
||||
openPopup({
|
||||
kind: "definition",
|
||||
anchor: caretAnchor(view, pos),
|
||||
targets,
|
||||
index: 0,
|
||||
themeClasses: view.themeClasses,
|
||||
codeStyle: { fontFamily, fontSize, fontWeight, lineHeight, tabSize },
|
||||
});
|
||||
} catch (e) {
|
||||
if (!stale()) reportLspError(view, e, true);
|
||||
|
||||
@@ -28,6 +28,7 @@ import { inlineCompletionExtension, registerInlineCompletionActions } from "./in
|
||||
import { semanticExtension } from "./semantic";
|
||||
import { usagesLensExtension } from "./codeLens";
|
||||
import { autoImportExtension } from "./autoImport";
|
||||
import { jsxAttrValueExtension } from "./jsxAttrValue";
|
||||
import { importsOnPasteExtension, registerImportsOnPasteActions } from "./importsOnPaste";
|
||||
import { installConfigurationNavigationEvents } from "./configurationNavigation";
|
||||
import { installAvailabilityEvents } from "./availability";
|
||||
@@ -69,6 +70,7 @@ export function lspExtensions(ctx: EditorDocContext): Extension[] {
|
||||
semanticExtension(),
|
||||
usagesLensExtension(),
|
||||
autoImportExtension(),
|
||||
jsxAttrValueExtension(ctx.language),
|
||||
importsOnPasteExtension(),
|
||||
unresolvedReferences(),
|
||||
syntaxErrorsExtension(),
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { history, undo } from "@codemirror/commands";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
lspHover: vi.fn(),
|
||||
cancelRequest: vi.fn<(id: number) => Promise<void>>(async () => {}),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const real = await orig<typeof import("@/platform/ipc")>();
|
||||
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
|
||||
});
|
||||
|
||||
const { attrValueKind, isStringLikeType, jsxAttrValueExtension } = await import("./jsxAttrValue");
|
||||
const { lspDoc } = await import("./lsp");
|
||||
|
||||
const ctx = { doc: 3, path: "/p/a.tsx", language: "typescriptreact", uiMode: "TSX", readOnly: false };
|
||||
const views: EditorView[] = [];
|
||||
const hover = (sig: string) => ({
|
||||
status: "ok" as const,
|
||||
data: { contents: { kind: "markdown", value: "```typescript\n" + sig + "\n```" }, range: null },
|
||||
});
|
||||
|
||||
function editor(text: string, language = "typescriptreact") {
|
||||
const at = text.indexOf("|");
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: text.replace("|", ""),
|
||||
selection: EditorSelection.cursor(at),
|
||||
extensions: [
|
||||
javascript({ jsx: true, typescript: true }),
|
||||
history(),
|
||||
lspDoc.of({ ...ctx, language }),
|
||||
jsxAttrValueExtension(language),
|
||||
],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
return view;
|
||||
}
|
||||
|
||||
function show(view: EditorView): string {
|
||||
const doc = view.state.doc.toString();
|
||||
const head = view.state.selection.main.head;
|
||||
return doc.slice(0, head) + "|" + doc.slice(head);
|
||||
}
|
||||
|
||||
/** Types `ch` through the real input handlers. */
|
||||
function type(v: EditorView, ch: string) {
|
||||
const r = v.state.selection.main;
|
||||
const insert = () => v.state.update(v.state.replaceSelection(ch), { userEvent: "input.type" });
|
||||
if (!v.state.facet(EditorView.inputHandler).some((h) => h(v, r.from, r.to, ch, insert))) v.dispatch(insert());
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
ipc.lspHover.mockReset();
|
||||
ipc.cancelRequest.mockClear();
|
||||
});
|
||||
afterEach(() => {
|
||||
views.splice(0).forEach((v) => v.destroy());
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("isStringLikeType", () => {
|
||||
it("accepts strings, string literals and template literal types", () => {
|
||||
expect(isStringLikeType("string")).toBe(true);
|
||||
expect(isStringLikeType("string | undefined")).toBe(true);
|
||||
expect(isStringLikeType('"primary" | "secondary" | undefined')).toBe(true);
|
||||
expect(isStringLikeType("'a|b' | 'c'")).toBe(true);
|
||||
expect(isStringLikeType("`btn-${string}`")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects everything else", () => {
|
||||
expect(isStringLikeType("number")).toBe(false);
|
||||
expect(isStringLikeType("string | number")).toBe(false);
|
||||
expect(isStringLikeType("() => void")).toBe(false);
|
||||
expect(isStringLikeType("ReactNode")).toBe(false);
|
||||
expect(isStringLikeType("any")).toBe(false);
|
||||
expect(isStringLikeType("undefined")).toBe(false);
|
||||
expect(isStringLikeType("Record<string, string | number>")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("attrValueKind", () => {
|
||||
const md = (sig: string) => hover(sig).data.contents;
|
||||
|
||||
it("reads DOM and component prop signatures", () => {
|
||||
expect(
|
||||
attrValueKind(md("(property) React.HTMLAttributes<HTMLDivElement>.className?: string | undefined"), "className"),
|
||||
).toBe("quotes");
|
||||
expect(attrValueKind(md("(property) label: string"), "label")).toBe("quotes");
|
||||
expect(attrValueKind(md('(property) "aria-label"?: string | undefined'), "aria-label")).toBe("quotes");
|
||||
expect(
|
||||
attrValueKind(
|
||||
md('(property) React.HTMLAttributes<HTMLDivElement>["aria-label"]?: string | undefined'),
|
||||
"aria-label",
|
||||
),
|
||||
).toBe("quotes");
|
||||
expect(attrValueKind(md('(property) variant?: "ghost" | "primary" | undefined'), "variant")).toBe("quotes");
|
||||
expect(
|
||||
attrValueKind(md("(property) React.HTMLAttributes<HTMLDivElement>.tabIndex?: number | undefined"), "tabIndex"),
|
||||
).toBe("braces");
|
||||
expect(attrValueKind(md("(property) count: number"), "count")).toBe("braces");
|
||||
expect(
|
||||
attrValueKind(
|
||||
md(
|
||||
"(property) React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | undefined",
|
||||
),
|
||||
"onClick",
|
||||
),
|
||||
).toBe("braces");
|
||||
});
|
||||
|
||||
it("falls back to braces without a type", () => {
|
||||
expect(attrValueKind(null, "x")).toBe("braces");
|
||||
expect(attrValueKind({ kind: "markdown", value: "any" }, "x")).toBe("braces");
|
||||
});
|
||||
});
|
||||
|
||||
describe("= after a JSX attribute name", () => {
|
||||
it("inserts quotes for a string prop, caret inside", async () => {
|
||||
ipc.lspHover.mockResolvedValue(hover("(property) label: string"));
|
||||
const v = editor("const a = <Btn label| />;");
|
||||
type(v, "=");
|
||||
expect(show(v)).toBe("const a = <Btn label=| />;");
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(show(v)).toBe('const a = <Btn label="|" />;');
|
||||
expect(ipc.lspHover).toHaveBeenCalledWith(expect.any(Number), 3, { line: 0, col: 15 });
|
||||
});
|
||||
|
||||
it("inserts braces for other props, and undo takes the pair back first", async () => {
|
||||
ipc.lspHover.mockResolvedValue(hover("(property) count: number"));
|
||||
const v = editor("const a = <Btn count|>x</Btn>;");
|
||||
type(v, "=");
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(show(v)).toBe("const a = <Btn count={|}>x</Btn>;");
|
||||
undo(v);
|
||||
expect(v.state.doc.toString()).toBe("const a = <Btn count=>x</Btn>;");
|
||||
});
|
||||
|
||||
it("falls back to braces when the server is unavailable or slow", async () => {
|
||||
ipc.lspHover.mockRejectedValue({ kind: "unavailable", message: "none" });
|
||||
const v = editor("const a = <Btn count| />;");
|
||||
type(v, "=");
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(show(v)).toBe("const a = <Btn count={|} />;");
|
||||
|
||||
ipc.lspHover.mockReturnValue(new Promise(() => {}));
|
||||
const w = editor("const a = <Btn label| />;");
|
||||
type(w, "=");
|
||||
await vi.advanceTimersByTimeAsync(600);
|
||||
expect(show(w)).toBe("const a = <Btn label={|} />;");
|
||||
expect(ipc.cancelRequest).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("drops the pair once something else was typed", async () => {
|
||||
let answer!: (v: unknown) => void;
|
||||
ipc.lspHover.mockReturnValue(new Promise((r) => (answer = r)));
|
||||
const v = editor("const a = <Btn label| />;");
|
||||
type(v, "=");
|
||||
type(v, "x");
|
||||
answer(hover("(property) label: string"));
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(show(v)).toBe("const a = <Btn label=x| />;");
|
||||
});
|
||||
|
||||
it("stays out where there is no value-less attribute name before the caret", () => {
|
||||
for (const text of [
|
||||
'const a = <Btn label|"x" />;',
|
||||
"const a = <Btn label|{x} />;",
|
||||
"const a = |;",
|
||||
'const a = <Btn label="x|" />;',
|
||||
"const a = <Btn {...p}| />;",
|
||||
]) {
|
||||
const v = editor(text);
|
||||
type(v, "=");
|
||||
expect(ipc.lspHover).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
|
||||
it("is only installed for JSX languages", () => {
|
||||
const v = editor("const a = <Btn label| />;", "typescript");
|
||||
type(v, "=");
|
||||
expect(ipc.lspHover).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* JSX attribute values on `=`, as in WebStorm's "Add for JSX attribute: Based
|
||||
* on type": typing `=` after an attribute name that has no value yet inserts
|
||||
* `""` when the prop's type is string-like and `{}` otherwise, with the caret
|
||||
* between them. The type comes from the language server's hover on the name;
|
||||
* without an answer in time (no server, still starting) it falls back to `{}`.
|
||||
*
|
||||
* The `=` goes in at once and the pair follows as its own `input.complete`
|
||||
* step — undo removes the pair first and Tab steps out of it. Anything typed
|
||||
* meanwhile wins: the pair is dropped.
|
||||
*/
|
||||
import { EditorSelection, type EditorState, type Extension } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { syntaxTree } from "@codemirror/language";
|
||||
import type { SyntaxNode } from "@lezer/common";
|
||||
import type { Markup } from "@/bindings";
|
||||
import { commands, nextRequestId } from "@/platform/ipc";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { docOf, lspRequest } from "./lsp";
|
||||
import { offsetToPos } from "./positions";
|
||||
|
||||
/** Languages whose editors parse JSX. */
|
||||
const JSX_LANGUAGES = new Set(["typescriptreact", "javascriptreact"]);
|
||||
|
||||
/** How long the pair waits for the prop's type before falling back to `{}`. */
|
||||
const WAIT_MS = 500;
|
||||
|
||||
type ValueKind = "quotes" | "braces";
|
||||
|
||||
/** The name of the value-less JSX attribute ending at `pos`, or null. */
|
||||
function attributeNameBefore(state: EditorState, pos: number): SyntaxNode | null {
|
||||
let n: SyntaxNode | null = syntaxTree(state).resolveInner(pos, -1);
|
||||
while (n?.parent && n.parent.name !== "JSXAttribute") n = n.parent;
|
||||
const attr = n?.parent;
|
||||
if (!n || !attr || attr.firstChild?.from !== n.from || n.to !== pos || attr.to !== pos) return null;
|
||||
return n;
|
||||
}
|
||||
|
||||
/** Splits a type at its top-level `|`s: unions inside parentheses, generics, objects or strings stay whole. */
|
||||
function unionMembers(type: string): string[] {
|
||||
const out: string[] = [];
|
||||
let depth = 0;
|
||||
let quote: string | null = null;
|
||||
let start = 0;
|
||||
for (let i = 0; i < type.length; i++) {
|
||||
const ch = type[i]!;
|
||||
if (quote) {
|
||||
if (ch === "\\") i++;
|
||||
else if (ch === quote) quote = null;
|
||||
} else if (ch === '"' || ch === "'" || ch === "`") quote = ch;
|
||||
else if ("([{<".includes(ch)) depth++;
|
||||
else if (")]}>".includes(ch) && !(ch === ">" && type[i - 1] === "=")) depth--;
|
||||
else if (ch === "|" && depth === 0) {
|
||||
out.push(type.slice(start, i).trim());
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
out.push(type.slice(start).trim());
|
||||
return out.filter(Boolean);
|
||||
}
|
||||
|
||||
const STRING_MEMBER = /^(?:string|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`)$/;
|
||||
|
||||
/** `string`, string literals and template literal types, optionally with `undefined` / `null`. */
|
||||
export function isStringLikeType(type: string): boolean {
|
||||
const members = unionMembers(type).filter((m) => m !== "undefined" && m !== "null");
|
||||
return members.length > 0 && members.every((m) => STRING_MEMBER.test(m));
|
||||
}
|
||||
|
||||
const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
|
||||
/**
|
||||
* The delimiters for `attr`'s value from its hover: TypeScript shows
|
||||
* `(property) label: string` for a component prop and
|
||||
* `(property) React.HTMLAttributes<T>.className?: string | undefined` for a DOM one
|
||||
* (`HTMLAttributes<T>["aria-label"]?:` for a name that is not an identifier).
|
||||
*/
|
||||
export function attrValueKind(markup: Markup | null | undefined, attr: string): ValueKind {
|
||||
if (!markup) return "braces";
|
||||
const code = /```[^\n]*\n([\s\S]*?)```/.exec(markup.value)?.[1] ?? markup.value;
|
||||
const sig = code.replace(/\s+/g, " ").trim();
|
||||
const name = escape(attr);
|
||||
const typed = new RegExp(`(?:^|[\\s.)>])(?:${name}|\\[?"${name}"\\]?|'${name}')\\??\\s*:\\s*([\\s\\S]+)$`).exec(sig);
|
||||
return typed && isStringLikeType(typed[1]!) ? "quotes" : "braces";
|
||||
}
|
||||
|
||||
async function valueKind(view: EditorView, nameFrom: number, attr: string): Promise<ValueKind> {
|
||||
const doc = docOf(view);
|
||||
if (!doc) return "braces";
|
||||
const state = view.state;
|
||||
const id = nextRequestId();
|
||||
const wanted = () => view.state.doc === state.doc;
|
||||
const hover = lspRequest(() => commands.lspHover(id, doc.doc, offsetToPos(state.doc, nameFrom)), wanted)
|
||||
.then((h) => attrValueKind(h?.contents, attr))
|
||||
.catch((): ValueKind => "braces");
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeout = new Promise<null>((resolve) => (timer = setTimeout(() => resolve(null), WAIT_MS)));
|
||||
const kind = await Promise.race([hover, timeout]);
|
||||
clearTimeout(timer);
|
||||
if (kind) return kind;
|
||||
void commands.cancelRequest(id).catch(() => {});
|
||||
return "braces";
|
||||
}
|
||||
|
||||
async function insertValue(view: EditorView, nameFrom: number, attr: string) {
|
||||
const state = view.state;
|
||||
const after = state.selection.main.head;
|
||||
const kind = await valueKind(view, nameFrom, attr);
|
||||
if (!view.dom.isConnected || view.state.doc !== state.doc || view.state.selection.main.head !== after) return;
|
||||
const { pairQuotes, pairBrackets } = editorPrefs().smartKeys;
|
||||
if (kind === "quotes" ? !pairQuotes : !pairBrackets) return;
|
||||
view.dispatch({
|
||||
changes: { from: after, insert: kind === "quotes" ? '""' : "{}" },
|
||||
selection: EditorSelection.cursor(after + 1),
|
||||
userEvent: "input.complete",
|
||||
});
|
||||
}
|
||||
|
||||
const attrValueInput = EditorView.inputHandler.of((view, from, to, text, insert) => {
|
||||
const { state } = view;
|
||||
if (text !== "=" || from !== to || state.readOnly || state.selection.ranges.length > 1) return false;
|
||||
const name = attributeNameBefore(state, from);
|
||||
if (!name || /["'{]/.test(state.sliceDoc(from, from + 1))) return false;
|
||||
const { pairQuotes, pairBrackets } = editorPrefs().smartKeys;
|
||||
if (!pairQuotes && !pairBrackets) return false;
|
||||
view.dispatch(insert());
|
||||
void insertValue(view, name.from, state.sliceDoc(name.from, name.to));
|
||||
return true;
|
||||
});
|
||||
|
||||
/** `=` after a JSX attribute name fills in `""` or `{}` by the prop's type, in JSX / TSX editors. */
|
||||
export function jsxAttrValueExtension(language: string): Extension {
|
||||
return JSX_LANGUAGES.has(language) ? attrValueInput : [];
|
||||
}
|
||||
@@ -37,6 +37,17 @@ describe("markdown LaTeX math", () => {
|
||||
expect(root.querySelector("p")?.textContent?.startsWith("Prices $5 and $10, with ")).toBe(true);
|
||||
});
|
||||
|
||||
it("leaves separate code spans inside dollar signs as code", () => {
|
||||
const root = parseSafe("($`x` `y`$)");
|
||||
expect(root.querySelector("p")?.innerHTML).toBe("($<code>x</code> <code>y</code>$)");
|
||||
});
|
||||
|
||||
it("matches a longer backtick delimiter around math inside emphasis", () => {
|
||||
const root = parseSafe("**($``x` + y``$)**");
|
||||
expect(root.querySelector("strong .katex annotation")?.textContent).toBe("x` + y");
|
||||
expect(root.querySelector("code")).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps an unfinished protected delimiter from swallowing a later formula", () => {
|
||||
const root = parseSafe("Unfinished $`x` and $y$.");
|
||||
expect(root.querySelector("p > code")?.textContent).toBe("x");
|
||||
|
||||
@@ -39,9 +39,10 @@ function findClosingDelimiter(src: string, from: number, delim: string): number
|
||||
return -1;
|
||||
}
|
||||
|
||||
const PROTECTED_INLINE_DOLLAR = /^\$`([^`\r\n]+)`\$/;
|
||||
// The first backtick run of the opening length ends the code span.
|
||||
const PROTECTED_INLINE_DOLLAR = /^\$(?<ticks>`+)(?!`)(?<tex>(?:[^`\r\n]|(?!\k<ticks>(?!`))`+(?!`))+)\k<ticks>\$/;
|
||||
// Marked masks code spans as `[aaa]` before calling emStrongMask
|
||||
const MASKED_PROTECTED_INLINE_DOLLAR = /^\$\[(a+)\]\$/;
|
||||
const MASKED_PROTECTED_INLINE_DOLLAR = /^\$\[(?<tex>a+)\]\$/;
|
||||
|
||||
/**
|
||||
* Matches inline `$...$` from index 0 using Pandoc-style guards so currency
|
||||
@@ -87,7 +88,7 @@ function matchInlineMath(
|
||||
if (src[0] === "$") {
|
||||
const match = protectedDollar.exec(src);
|
||||
if (match) {
|
||||
const text = match[1]!;
|
||||
const text = match.groups!.tex!;
|
||||
return text.trim() ? { raw: match[0], text, display: false } : null;
|
||||
}
|
||||
if (src[1] === "`") return null;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/** State of the React popups the LSP editor features open (rendered by `Popups.tsx`). */
|
||||
import { create } from "zustand";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import type { CSSProperties } from "react";
|
||||
import type { Location, Markup } from "@/bindings";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import type { WorkspaceEditSummary } from "./workspaceEdit";
|
||||
@@ -13,6 +14,8 @@ export interface PopupPoint {
|
||||
export interface ListPopupItem {
|
||||
id: string;
|
||||
label: string;
|
||||
/** Adjacent actions with the same section id share a caption or divider. */
|
||||
section?: { id: string; label?: string };
|
||||
/** Muted trailing text (file:line, kind…). */
|
||||
detail?: string;
|
||||
/** Second line / muted text after the label (code preview). */
|
||||
@@ -90,6 +93,7 @@ export type LspPopup =
|
||||
targets: DefinitionTarget[];
|
||||
index: number;
|
||||
themeClasses: string;
|
||||
codeStyle: Pick<CSSProperties, "fontFamily" | "fontSize" | "fontWeight" | "lineHeight" | "tabSize">;
|
||||
}
|
||||
| {
|
||||
kind: "list";
|
||||
@@ -98,6 +102,8 @@ export type LspPopup =
|
||||
items: ListPopupItem[];
|
||||
/** Rows 1-9 get a number; typing it runs the row (IDEA's numbered popups). */
|
||||
numbered?: boolean;
|
||||
/** Compact action list, with room for icons only when a row has one. */
|
||||
compact?: boolean;
|
||||
/** More rows are still being looked for (`aria-busy`). */
|
||||
busy?: boolean;
|
||||
/** Header pin button (e.g. "Open in Find Tool Window"). */
|
||||
|
||||
@@ -28,6 +28,7 @@ export interface Refactoring {
|
||||
/** Action id (keymaps, menu). */
|
||||
action: string;
|
||||
label: string;
|
||||
section?: { id: string; label?: string };
|
||||
/** LSP kind prefix that can produce it; null for client-side refactorings. */
|
||||
kind: string | null;
|
||||
/** IDEA's reason when nothing applies at the caret / selection. */
|
||||
@@ -35,6 +36,9 @@ export interface Refactoring {
|
||||
}
|
||||
|
||||
const AT_NAME = "Caret should be positioned at the name of the element to be refactored";
|
||||
const EXTRACT = { id: "extract", label: "Extract/Introduce" };
|
||||
const MOVE = { id: "move" };
|
||||
const HIERARCHY = { id: "hierarchy" };
|
||||
|
||||
/** IDEA's Refactor This order. */
|
||||
export const REFACTORINGS: readonly Refactoring[] = [
|
||||
@@ -52,26 +56,11 @@ export const REFACTORINGS: readonly Refactoring[] = [
|
||||
kind: "refactor.rewrite",
|
||||
reason: () => "Caret should be positioned at the name of the function or method to be refactored",
|
||||
},
|
||||
{ id: "move", action: "refactor.move", label: "Move…", kind: "refactor.move", reason: () => AT_NAME },
|
||||
{
|
||||
id: "safeDelete",
|
||||
action: "refactor.safeDelete",
|
||||
label: "Safe Delete…",
|
||||
kind: null,
|
||||
reason: () => "Caret should be on a symbol",
|
||||
},
|
||||
{
|
||||
id: "extractMethod",
|
||||
action: "refactor.extractMethod",
|
||||
label: "Extract Method…",
|
||||
kind: "refactor.extract",
|
||||
reason: (sel) =>
|
||||
sel ? "Selected block should represent a set of statements or an expression" : "Select the code to extract",
|
||||
},
|
||||
{
|
||||
id: "extractVariable",
|
||||
action: "refactor.extractVariable",
|
||||
label: "Introduce Variable…",
|
||||
section: EXTRACT,
|
||||
kind: "refactor.extract",
|
||||
reason: (sel) => (sel ? "Selected block should represent an expression" : "Caret should be inside an expression"),
|
||||
},
|
||||
@@ -79,6 +68,7 @@ export const REFACTORINGS: readonly Refactoring[] = [
|
||||
id: "extractConstant",
|
||||
action: "refactor.extractConstant",
|
||||
label: "Introduce Constant…",
|
||||
section: EXTRACT,
|
||||
kind: "refactor.extract",
|
||||
reason: (sel) => (sel ? "Selected block should represent an expression" : "Caret should be inside an expression"),
|
||||
},
|
||||
@@ -86,6 +76,7 @@ export const REFACTORINGS: readonly Refactoring[] = [
|
||||
id: "extractField",
|
||||
action: "refactor.extractField",
|
||||
label: "Introduce Field…",
|
||||
section: EXTRACT,
|
||||
kind: "refactor.extract",
|
||||
reason: (sel) =>
|
||||
sel ? "Selected block should represent an expression" : "Caret should be inside an expression in a class",
|
||||
@@ -94,22 +85,50 @@ export const REFACTORINGS: readonly Refactoring[] = [
|
||||
id: "extractParameter",
|
||||
action: "refactor.extractParameter",
|
||||
label: "Introduce Parameter…",
|
||||
section: EXTRACT,
|
||||
kind: "refactor.extract",
|
||||
reason: (sel) =>
|
||||
sel ? "Selected block should represent an expression" : "Caret should be inside an expression in a function",
|
||||
},
|
||||
{
|
||||
id: "extractMethod",
|
||||
action: "refactor.extractMethod",
|
||||
label: "Extract Method…",
|
||||
section: EXTRACT,
|
||||
kind: "refactor.extract",
|
||||
reason: (sel) =>
|
||||
sel ? "Selected block should represent a set of statements or an expression" : "Select the code to extract",
|
||||
},
|
||||
{
|
||||
id: "extractInterface",
|
||||
action: "refactor.extractInterface",
|
||||
label: "Extract Interface…",
|
||||
section: EXTRACT,
|
||||
kind: null,
|
||||
reason: () => "Caret should be inside a class",
|
||||
},
|
||||
{ id: "inline", action: "refactor.inline", label: "Inline…", kind: "refactor.inline", reason: () => AT_NAME },
|
||||
{
|
||||
id: "inline",
|
||||
action: "refactor.inline",
|
||||
label: "Inline…",
|
||||
section: { id: "inline" },
|
||||
kind: "refactor.inline",
|
||||
reason: () => AT_NAME,
|
||||
},
|
||||
{ id: "move", action: "refactor.move", label: "Move…", section: MOVE, kind: "refactor.move", reason: () => AT_NAME },
|
||||
{
|
||||
id: "safeDelete",
|
||||
action: "refactor.safeDelete",
|
||||
label: "Safe Delete…",
|
||||
section: MOVE,
|
||||
kind: null,
|
||||
reason: () => "Caret should be on a symbol",
|
||||
},
|
||||
{
|
||||
id: "pullMembersUp",
|
||||
action: "refactor.pullMembersUp",
|
||||
label: "Pull Members Up…",
|
||||
section: HIERARCHY,
|
||||
kind: null,
|
||||
reason: () => "Caret should be inside a class that has members to pull up",
|
||||
},
|
||||
@@ -117,6 +136,7 @@ export const REFACTORINGS: readonly Refactoring[] = [
|
||||
id: "pushMembersDown",
|
||||
action: "refactor.pushMembersDown",
|
||||
label: "Push Members Down…",
|
||||
section: HIERARCHY,
|
||||
kind: null,
|
||||
reason: () => "Caret should be inside a class that has members to push down",
|
||||
},
|
||||
|
||||
@@ -181,7 +181,7 @@ describe("catalog", () => {
|
||||
});
|
||||
|
||||
describe("Refactor This", () => {
|
||||
it("lists only the refactorings applicable at the caret, in IDEA order", async () => {
|
||||
it("lists applicable refactorings in menu order and groups extraction actions", async () => {
|
||||
prepare = ok({ start: { line: 0, col: 0 }, end: { line: 0, col: 1 } });
|
||||
query = answer([
|
||||
action("Inline variable", "refactor.inline"),
|
||||
@@ -190,7 +190,9 @@ describe("Refactor This", () => {
|
||||
action("Extract into function", "refactor.extract", "Can't extract here"),
|
||||
]);
|
||||
await refactorThis(editor(), vi.fn());
|
||||
expect(labels()).toEqual(["Rename…", "Safe Delete…", "Introduce Variable…", "Inline…", "Convert to raw string"]);
|
||||
expect(labels()).toEqual(["Rename…", "Introduce Variable…", "Inline…", "Safe Delete…", "Convert to raw string"]);
|
||||
const popup = useLspPopup.getState().popup;
|
||||
expect(popup?.kind === "list" && popup.items[1]?.section?.label).toBe("Extract/Introduce");
|
||||
// IDEA's numbered list: 1-9 run a row directly.
|
||||
expect((useLspPopup.getState().popup as { numbered?: boolean }).numbered).toBe(true);
|
||||
expect(lspCodeActionQuery).toHaveBeenCalledOnce();
|
||||
|
||||
@@ -263,7 +263,13 @@ export function refactorThisItems(
|
||||
go = () => introduceFallback(view, INTRODUCE[r.id]!, answer.status === "notReady" ? "notReady" : "error");
|
||||
if (!go) continue;
|
||||
const exec = go;
|
||||
items.push({ id: r.id, label: r.label, shortcut: shortcutLabel(r.action), run: () => void exec() });
|
||||
items.push({
|
||||
id: r.id,
|
||||
label: r.label,
|
||||
section: r.section,
|
||||
shortcut: shortcutLabel(r.action),
|
||||
run: () => void exec(),
|
||||
});
|
||||
}
|
||||
other.forEach((a, i) =>
|
||||
items.push({
|
||||
@@ -326,6 +332,7 @@ export async function refactorThis(view: EditorView, rename: (view: EditorView)
|
||||
anchor: caretAnchor(view, state.selection.main.head),
|
||||
title: "Refactor This",
|
||||
items,
|
||||
compact: true,
|
||||
numbered: true,
|
||||
});
|
||||
}
|
||||
@@ -338,6 +345,7 @@ export function showNothingHere(
|
||||
kind: "list",
|
||||
anchor,
|
||||
title: "Refactor This",
|
||||
compact: true,
|
||||
items: [{ id: "nothing", label: "Nothing here", disabled: "No refactoring applies here", run: () => {} }],
|
||||
});
|
||||
}
|
||||
@@ -202,7 +202,8 @@ it("refreshes an existing chat's searchable model choices and switches through i
|
||||
const modelButton = screen.getByRole("button", { name: "Model" });
|
||||
fireEvent.click(modelButton);
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("discovery offline");
|
||||
expect(screen.getByRole("option", { name: "session-only" })).toBeVisible();
|
||||
expect(screen.queryByRole("option", { name: "session-only" })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("option", { name: /^old/ })).toBeVisible();
|
||||
expect(screen.getByRole("option", { name: "second-cached" })).toBeVisible();
|
||||
expect(backend.refresh.mock.calls).toEqual([["second", false, null]]);
|
||||
expect(screen.queryByRole("option", { name: "big" })).not.toBeInTheDocument();
|
||||
@@ -219,7 +220,8 @@ it("refreshes an existing chat's searchable model choices and switches through i
|
||||
await act(async () => pending.resolve(ok(fresh)));
|
||||
|
||||
expect(modelButton).toHaveTextContent("old");
|
||||
expect(screen.getByRole("option", { name: "session-only" })).toBeVisible();
|
||||
expect(screen.queryByRole("option", { name: "session-only" })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("option", { name: "fresh" })).toBeVisible();
|
||||
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("low");
|
||||
expect(screen.getByRole("button", { name: "Mode" })).toHaveTextContent("plan");
|
||||
expect(screen.getByText("Earlier message")).toBeVisible();
|
||||
|
||||
@@ -3,7 +3,7 @@ import { commitFileDiffData, openDiff, withChain, type DiffData } from "@/featur
|
||||
import { repositoryPath } from "@/features/vcs/repositoryPaths";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands, onIdeEvent } from "@/platform/ipc";
|
||||
import { basename, relativeDir } from "@/platform/project";
|
||||
import { basename, dirname, relativeDir } from "@/platform/project";
|
||||
import { fileIconName, Icon, IconButton, showContextMenu, Spinner, T, Tree } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
@@ -97,7 +97,7 @@ export function useChangesOpen(
|
||||
|
||||
const NO_SELECTION: ReadonlySet<string> = new Set();
|
||||
|
||||
/** A row of the Changes pane: a group, a commit, or a file. */
|
||||
/** A row of the Changes pane: a group, a commit, a repository, or a file. */
|
||||
type ChangeRow =
|
||||
| {
|
||||
key: string;
|
||||
@@ -109,8 +109,33 @@ type ChangeRow =
|
||||
children: ChangeRow[];
|
||||
}
|
||||
| { key: string; type: "commit"; commit: AgentCommit; children: ChangeRow[] }
|
||||
| { key: string; type: "repo"; root: string; children: ChangeRow[] }
|
||||
| { key: string; type: "file"; change: AgentChange; commit?: AgentCommit };
|
||||
|
||||
/** `files` under a row per repository, when the task changed files in several. */
|
||||
function byRepository(files: ChangeRow[], prefix: string): ChangeRow[] {
|
||||
const roots = new Map<string, ChangeRow[]>();
|
||||
for (const f of files) {
|
||||
const root = f.type === "file" ? f.change.repo : null;
|
||||
if (!root) return files;
|
||||
roots.set(root, [...(roots.get(root) ?? []), f]);
|
||||
}
|
||||
if (roots.size < 2) return files;
|
||||
return [...roots].map(([root, children]) => ({
|
||||
key: `${prefix}repo:${root}`,
|
||||
type: "repo" as const,
|
||||
root,
|
||||
children,
|
||||
}));
|
||||
}
|
||||
|
||||
/** The keys of the repository rows, at the top or in a group: shown open. */
|
||||
function repositoryKeys(rows: readonly ChangeRow[]): string[] {
|
||||
return rows
|
||||
.flatMap((r) => (r.type === "group" ? r.children : [r]))
|
||||
.flatMap((r) => (r.type === "repo" ? [r.key] : []));
|
||||
}
|
||||
|
||||
function statsOf(changes: readonly AgentChange[]) {
|
||||
return changes.reduce((n, c) => ({ added: n.added + c.added, removed: n.removed + c.removed }), {
|
||||
added: 0,
|
||||
@@ -124,11 +149,10 @@ function changeRows(
|
||||
grouped: boolean,
|
||||
): ChangeRow[] {
|
||||
if (!grouped)
|
||||
return uncommitted.map((change) => ({
|
||||
key: change.path,
|
||||
type: "file" as const,
|
||||
change,
|
||||
}));
|
||||
return byRepository(
|
||||
uncommitted.map((change) => ({ key: change.path, type: "file" as const, change })),
|
||||
"",
|
||||
);
|
||||
const roots: ChangeRow[] = [];
|
||||
if (uncommitted.length) {
|
||||
roots.push({
|
||||
@@ -137,11 +161,10 @@ function changeRows(
|
||||
label: "Uncommitted",
|
||||
count: uncommitted.length,
|
||||
...statsOf(uncommitted),
|
||||
children: uncommitted.map((change) => ({
|
||||
key: `uncommitted:${change.path}`,
|
||||
type: "file",
|
||||
change,
|
||||
})),
|
||||
children: byRepository(
|
||||
uncommitted.map((change) => ({ key: `uncommitted:${change.path}`, type: "file" as const, change })),
|
||||
"uncommitted:",
|
||||
),
|
||||
});
|
||||
}
|
||||
if (commits.length) {
|
||||
@@ -202,15 +225,12 @@ export function ChangesPane({
|
||||
// Only the working files roll back; a commit's files are history.
|
||||
const rollbackable = useMemo(() => {
|
||||
const out = new Map<string, AgentChange>();
|
||||
for (const root of rows) {
|
||||
if (root.type === "file") {
|
||||
if (!root.commit) out.set(root.key, root.change);
|
||||
continue;
|
||||
}
|
||||
for (const child of root.children) {
|
||||
if (child.type === "file" && !child.commit) out.set(child.key, child.change);
|
||||
}
|
||||
}
|
||||
const walk = (row: ChangeRow) => {
|
||||
if (row.type === "file") {
|
||||
if (!row.commit) out.set(row.key, row.change);
|
||||
} else if (row.type !== "commit") row.children.forEach(walk);
|
||||
};
|
||||
rows.forEach(walk);
|
||||
return out;
|
||||
}, [rows]);
|
||||
// Selection keys that no longer name a working file (a commit's file, a stale row) don't count.
|
||||
@@ -407,11 +427,17 @@ export function ChangesPane({
|
||||
roots={rows}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) =>
|
||||
n.type === "file" ? basename(n.change.path) : n.type === "commit" ? n.commit.summary : n.label
|
||||
n.type === "file"
|
||||
? basename(n.change.path)
|
||||
: n.type === "commit"
|
||||
? n.commit.summary
|
||||
: n.type === "repo"
|
||||
? basename(n.root)
|
||||
: n.label
|
||||
}
|
||||
getChildren={(n) => (n.type === "file" ? undefined : n.children)}
|
||||
isExpandable={(n) => n.type !== "file" && n.children.length > 0}
|
||||
defaultExpanded={grouped ? ["group:uncommitted", "group:committed"] : undefined}
|
||||
defaultExpanded={[...(grouped ? ["group:uncommitted", "group:committed"] : []), ...repositoryKeys(rows)]}
|
||||
activateExpandable={(n) => n.type === "commit"}
|
||||
selected={selected}
|
||||
onSelectionChange={(sel, lead) => {
|
||||
@@ -445,6 +471,23 @@ export function ChangesPane({
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (n.type === "repo") {
|
||||
const files = n.children.flatMap((c) => (c.type === "file" ? [c.change] : []));
|
||||
const stats = statsOf(files);
|
||||
return (
|
||||
<span className={styles.changeGroup} title={n.root}>
|
||||
<Icon name="folder" size={14} />
|
||||
<span className={styles.changeGroupName}>{basename(n.root)}</span>
|
||||
<span
|
||||
className={styles.muted}
|
||||
>{`${files.length} ${tx(files.length === 1 ? "file" : "files")}`}</span>
|
||||
<span className={styles.changeStat}>
|
||||
{stats.added > 0 && <span className={styles.added}>+{stats.added}</span>}{" "}
|
||||
{stats.removed > 0 && <span className={styles.removed}>−{stats.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (n.type === "commit") {
|
||||
const stats = statsOf(n.commit.files);
|
||||
return (
|
||||
@@ -468,7 +511,13 @@ export function ChangesPane({
|
||||
<span className={styles.changeName} style={{ color: KIND_COLOR[n.change.kind] }}>
|
||||
{basename(n.change.path)}
|
||||
</span>
|
||||
<span className={styles.changeDir}>{relativeDir(task.cwd, n.change.path)}</span>
|
||||
<span className={styles.changeDir}>
|
||||
{n.change.repo
|
||||
? n.change.relPath.includes("/")
|
||||
? dirname(n.change.relPath)
|
||||
: ""
|
||||
: relativeDir(task.cwd, n.change.path)}
|
||||
</span>
|
||||
<span className={styles.changeStat}>
|
||||
{n.change.added > 0 && <span className={styles.added}>+{n.change.added}</span>}{" "}
|
||||
{n.change.removed > 0 && <span className={styles.removed}>−{n.change.removed}</span>}
|
||||
|
||||
@@ -187,14 +187,15 @@ export function SessionComposer({
|
||||
: { ...catalogModel, current: task.model ?? catalogModel.current };
|
||||
return [...task.config, recovered];
|
||||
}
|
||||
const candidateModels = catalogModel?.values;
|
||||
if (!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]);
|
||||
// The agent's current catalog is what a chat can switch to. The session's own list only
|
||||
// keeps the model it runs selectable when the catalog no longer offers it.
|
||||
const offered = catalogModel?.values;
|
||||
if (!offered?.length) return task.config;
|
||||
const kept = model.values.filter(
|
||||
(v) => (v.value === model.current || v.value === task.model) && !offered.some((o) => o.value === v.value),
|
||||
);
|
||||
return task.config.map((o) => (o === model ? { ...model, values: [...offered, ...kept] } : o));
|
||||
}, [task.config, task.model, model, model?.current, catalogModel, canRefreshModels]);
|
||||
const [sending, setSending] = useState(false);
|
||||
const configChange = useRef<{ loadingModel: boolean } | null>(null);
|
||||
const [configuring, setConfiguring] = useState<typeof configChange.current>(null);
|
||||
|
||||
@@ -1935,6 +1935,7 @@ describe("session state across tasks and hosts", () => {
|
||||
added: 8,
|
||||
removed: 2,
|
||||
oldPath: null,
|
||||
repo: null,
|
||||
},
|
||||
];
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
@@ -2056,7 +2057,9 @@ describe("session state across tasks and hosts", () => {
|
||||
entries.set(id, [{ type: "agent", text: `Reply ${id}` }]);
|
||||
entries.set(`${id}/sub`, [{ type: "agent", text: `Sub ${id}` }]);
|
||||
entryLoads.set(id, { error: "err" });
|
||||
changes.set(id, [{ path: "a.ts", relPath: "a.ts", oldPath: null, kind: "modified", added: 1, removed: 0 }]);
|
||||
changes.set(id, [
|
||||
{ path: "a.ts", relPath: "a.ts", oldPath: null, repo: null, kind: "modified", added: 1, removed: 0 },
|
||||
]);
|
||||
scrollPositions.set(id, { top: 10, stick: false });
|
||||
}
|
||||
entries.set("gone", [{ type: "agent", text: "Deleted reply" }]);
|
||||
@@ -2090,6 +2093,7 @@ describe("session state across tasks and hosts", () => {
|
||||
added: 1,
|
||||
removed: 0,
|
||||
oldPath: null,
|
||||
repo: null,
|
||||
},
|
||||
];
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
@@ -2868,6 +2872,7 @@ describe("accept changes", () => {
|
||||
added: 8,
|
||||
removed: 2,
|
||||
oldPath: null,
|
||||
repo: null,
|
||||
},
|
||||
];
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
@@ -2904,6 +2909,7 @@ describe("accept changes", () => {
|
||||
added: 8,
|
||||
removed: 2,
|
||||
oldPath: null,
|
||||
repo: null,
|
||||
},
|
||||
];
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
@@ -2922,6 +2928,7 @@ describe("last turn changes", () => {
|
||||
added: 1,
|
||||
removed: 0,
|
||||
oldPath: null,
|
||||
repo: null,
|
||||
});
|
||||
|
||||
it("lists and rolls back only what the last turn changed, the session still counting the whole task", async () => {
|
||||
@@ -2969,6 +2976,7 @@ describe("grouped changes", () => {
|
||||
added: 1,
|
||||
removed: 1,
|
||||
oldPath: null,
|
||||
repo: null,
|
||||
});
|
||||
const worktreeTask = () => {
|
||||
useChangesOptions.setState({ groupByCommit: true });
|
||||
@@ -3018,6 +3026,44 @@ describe("grouped changes", () => {
|
||||
expect(screen.getByRole("button", { name: /1 commit/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("puts the files of a task across nested repositories under a row per repository", async () => {
|
||||
const inRepo = (repo: string, rel: string): AgentChange => ({
|
||||
...change(rel),
|
||||
path: `/${repo}/${rel.slice(rel.indexOf("/") + 1)}`,
|
||||
repo: `/${repo}`,
|
||||
});
|
||||
backend.changes = [inRepo("api", "api/src/a.ts"), inRepo("api", "api/b.ts"), inRepo("web", "web/c.ts")];
|
||||
useAgents.setState({ tasks: new Map([["A", task("A")]]) });
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
const pane = await screen.findByRole("complementary", { name: "Changes" });
|
||||
|
||||
await within(pane).findByText("a.ts");
|
||||
// Open from the start, each repository leads its files, which show their folder as the agent names it.
|
||||
const rows = [...pane.querySelectorAll("[data-row]")].map((r) => r.textContent);
|
||||
expect(rows).toEqual(["api2 files+2 −2", "a.tsapi/src+1 −1", "b.tsapi+1 −1", "web1 file+1 −1", "c.tsweb+1 −1"]);
|
||||
expect(within(pane).getByTitle("/api")).toBeInTheDocument();
|
||||
|
||||
fireEvent.mouseDown(within(pane).getByText("c.ts"));
|
||||
fireEvent.click(within(pane).getByRole("button", { name: "Rollback Selected Changes…" }));
|
||||
await waitFor(() => expect(backend.rolledBack).toEqual([["A", ["web/c.ts"], "sinceStart"]]));
|
||||
});
|
||||
|
||||
it("lists a task's files without repository rows when they are all in one", async () => {
|
||||
backend.changes = [
|
||||
{ ...change("a.ts"), repo: "/project" },
|
||||
{ ...change("b.ts"), repo: "/project" },
|
||||
];
|
||||
useAgents.setState({ tasks: new Map([["A", task("A")]]) });
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
const pane = await screen.findByRole("complementary", { name: "Changes" });
|
||||
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
|
||||
expect(within(pane).queryByText("project")).toBeNull();
|
||||
// A file at the top of the project names no folder.
|
||||
expect([...pane.querySelectorAll("[data-row]")].map((r) => r.textContent)).toEqual(["a.ts+1 −1", "b.ts+1 −1"]);
|
||||
});
|
||||
|
||||
it("accepts the task's committed work too, not only the uncommitted files", async () => {
|
||||
backend.grouped = {
|
||||
uncommitted: [],
|
||||
|
||||
@@ -287,8 +287,12 @@ describe("agent unread activity", () => {
|
||||
.set("two", [{ type: "agent", text: "Answer two" }])
|
||||
.set("open", [{ type: "agent", text: "Answer open" }]),
|
||||
changes: new Map(s.changes)
|
||||
.set("one", [{ path: "a.ts", relPath: "a.ts", oldPath: null, kind: "modified", added: 1, removed: 0 }])
|
||||
.set("two", [{ path: "b.ts", relPath: "b.ts", oldPath: null, kind: "modified", added: 1, removed: 0 }]),
|
||||
.set("one", [
|
||||
{ path: "a.ts", relPath: "a.ts", oldPath: null, repo: null, kind: "modified", added: 1, removed: 0 },
|
||||
])
|
||||
.set("two", [
|
||||
{ path: "b.ts", relPath: "b.ts", oldPath: null, repo: null, kind: "modified", added: 1, removed: 0 },
|
||||
]),
|
||||
groupedChanges: new Map(s.groupedChanges)
|
||||
.set("one", { uncommitted: [], commits: [] })
|
||||
.set("two", { uncommitted: [], commits: [] }),
|
||||
@@ -513,6 +517,7 @@ describe("the diff of an agent change", () => {
|
||||
added: 1,
|
||||
removed: 1,
|
||||
oldPath: null,
|
||||
repo: null,
|
||||
});
|
||||
|
||||
it("lists the task's other changed files, so F7 moves on to the next one", async () => {
|
||||
|
||||
@@ -140,13 +140,17 @@ describe("menu state from the frontend", () => {
|
||||
registerToolWindow({ id: "zeta", title: "Terminal", icon: "terminal", anchor: "bottom", component: () => null }),
|
||||
registerToolWindow({ id: "alpha", title: "Problems", icon: "problems", anchor: "bottom", component: () => null }),
|
||||
];
|
||||
saveLayout("Focus");
|
||||
saveLayout("Review");
|
||||
const dyn = dynamicMenuItems();
|
||||
expect(dyn.toolWindows!.map((i) => [i.action, i.label])).toEqual([
|
||||
["toolwindow.alpha", "Problems"],
|
||||
["toolwindow.zeta", "Terminal"],
|
||||
]);
|
||||
expect(dyn.toolWindowLayouts).toEqual([{ action: "layout.restore", arg: "Review", label: "Review" }]);
|
||||
expect(dyn.toolWindowLayouts).toEqual([
|
||||
{ action: "layout.restore", arg: "Focus", label: "Focus", checked: false },
|
||||
{ action: "layout.restore", arg: "Review", label: "Review", checked: true },
|
||||
]);
|
||||
expect(buildMenuConfig("macos").dynamic).toEqual(dyn);
|
||||
offs.forEach((d) => d());
|
||||
localStorage.clear();
|
||||
|
||||
@@ -2,10 +2,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import * as ipc from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import * as services from "@/workbench/contributions";
|
||||
import { installCloseGuard, type CloseDeps } from "../closeGuard";
|
||||
import type { MessageRequest as PromptRequest } from "@/workbench/messages";
|
||||
import { installCloseGuard, quitApp, type CloseDeps } from "../closeGuard";
|
||||
|
||||
const native = vi.hoisted(() => ({
|
||||
close: undefined as ((event: { preventDefault: () => void }) => Promise<void>) | undefined,
|
||||
order: [] as string[],
|
||||
}));
|
||||
vi.mock("@tauri-apps/api/window", () => ({
|
||||
getAllWindows: async () => [],
|
||||
@@ -16,6 +18,9 @@ vi.mock("@tauri-apps/api/window", () => ({
|
||||
native.close = callback;
|
||||
return () => {};
|
||||
},
|
||||
unminimize: async () => void native.order.push("unminimize"),
|
||||
show: async () => void native.order.push("show"),
|
||||
setFocus: async () => void native.order.push("setFocus"),
|
||||
}),
|
||||
}));
|
||||
|
||||
@@ -141,3 +146,82 @@ describe("native window close", () => {
|
||||
expect(deps.onSaveFailed).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
// A quit can start outside the window (Dock, logout, another window): its prompts are drawn
|
||||
// inside the window, so it has to come forward before asking.
|
||||
describe("quitting from outside the window", () => {
|
||||
function recordingDeps(button: string) {
|
||||
const asked: PromptRequest[] = [];
|
||||
const d: CloseDeps = {
|
||||
...deps,
|
||||
ask: async (r: PromptRequest) => {
|
||||
native.order.push("ask");
|
||||
asked.push(r);
|
||||
return { button, checked: false };
|
||||
},
|
||||
};
|
||||
return { d, asked };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
native.order = [];
|
||||
vi.spyOn(ipc.commands, "appQuit").mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("raises the window before asking to confirm the quit", async () => {
|
||||
useProject.setState({
|
||||
project: { root: "/project", name: "project" },
|
||||
lightEdit: false,
|
||||
settings: { general: { confirmExit: true } },
|
||||
} as never);
|
||||
const { d, asked } = recordingDeps("exit");
|
||||
await quitApp(d);
|
||||
expect(asked).toHaveLength(1);
|
||||
expect(native.order).toEqual(["unminimize", "show", "setFocus", "ask"]);
|
||||
expect(ipc.commands.appQuit).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("does not touch the window when the confirmation is off", async () => {
|
||||
useProject.setState({
|
||||
project: { root: "/project", name: "project" },
|
||||
lightEdit: false,
|
||||
settings: { general: { confirmExit: false } },
|
||||
} as never);
|
||||
const { d } = recordingDeps("exit");
|
||||
await quitApp(d);
|
||||
expect(native.order).toEqual([]);
|
||||
expect(ipc.commands.appQuit).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("leaves a window with nothing to ask where it is while the app quits", async () => {
|
||||
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: true, windows: 2 });
|
||||
deps.runningProcesses = async () => [];
|
||||
const { d, asked } = recordingDeps("cancel");
|
||||
useProject.setState({
|
||||
project: { root: "/project", name: "project" },
|
||||
lightEdit: false,
|
||||
settings: { general: {} },
|
||||
} as never);
|
||||
uninstall = installCloseGuard(d);
|
||||
await vi.waitFor(() => expect(native.close).toBeDefined());
|
||||
await native.close!({ preventDefault: vi.fn() });
|
||||
expect(asked).toEqual([]);
|
||||
expect(native.order).toEqual([]);
|
||||
});
|
||||
|
||||
it("raises each window before the prompts a quit makes it show", async () => {
|
||||
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: true, windows: 2 });
|
||||
deps.runningProcesses = async () => ["server.js"];
|
||||
const { d } = recordingDeps("cancel");
|
||||
useProject.setState({
|
||||
project: { root: "/project", name: "project" },
|
||||
lightEdit: false,
|
||||
settings: { general: {} },
|
||||
} as never);
|
||||
uninstall = installCloseGuard(d);
|
||||
await vi.waitFor(() => expect(native.close).toBeDefined());
|
||||
await native.close!({ preventDefault: vi.fn() });
|
||||
expect(native.order.slice(0, 4)).toEqual(["unminimize", "show", "setFocus", "ask"]);
|
||||
expect(ipc.commands.appCancelQuit).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -200,6 +200,33 @@ async function processNames(deps: CloseDeps): Promise<string[]> {
|
||||
|
||||
let closing = false;
|
||||
|
||||
/**
|
||||
* A quit can start outside this window: the Dock or a logout on macOS, another window's action, a
|
||||
* remote client. Every prompt of that flow is drawn inside the window, so a minimized or covered
|
||||
* one asks without showing anything and the app looks stuck. Bring the window up before asking.
|
||||
*/
|
||||
async function raiseWindowForPrompts(): Promise<void> {
|
||||
if (!isTauri()) return;
|
||||
try {
|
||||
const { getCurrentWindow } = await import("@tauri-apps/api/window");
|
||||
const window = getCurrentWindow();
|
||||
await Promise.allSettled([window.unminimize(), window.show(), window.setFocus()]);
|
||||
} catch {
|
||||
// A window that cannot be raised still asks; the prompts must not be lost to this.
|
||||
}
|
||||
}
|
||||
|
||||
/** `deps` whose prompts bring the window up first; a window with nothing to ask stays where it is. */
|
||||
function raisingBeforeAsk(deps: CloseDeps): CloseDeps {
|
||||
return {
|
||||
...deps,
|
||||
ask: async (request) => {
|
||||
await raiseWindowForPrompts();
|
||||
return deps.ask(request);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Drops saved tabs when that setting is on. The result says whether a cancelled close should put them back. */
|
||||
function forgetTabs(): boolean {
|
||||
if (!closeTabsWithWindowEnabled(useProject.getState().settings)) return false;
|
||||
@@ -218,6 +245,8 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
|
||||
};
|
||||
try {
|
||||
const ctx = await commands.windowCloseContext();
|
||||
// Each window of a quit asks about its own processes and unsaved changes, if it has any.
|
||||
if (ctx.quitting) deps = raisingBeforeAsk(deps);
|
||||
if (!(await closeDocumentWindows())) {
|
||||
await (ctx.quitting ? commands.appCancelQuit() : commands.windowGroupCancelClose());
|
||||
return false;
|
||||
@@ -331,7 +360,7 @@ export async function quitApp(deps: CloseDeps = defaultDeps): Promise<void> {
|
||||
dirty: 0,
|
||||
project: null,
|
||||
},
|
||||
{ ...deps, prepareClose: undefined },
|
||||
{ ...raisingBeforeAsk(deps), prepareClose: undefined },
|
||||
);
|
||||
if (!ok) return;
|
||||
}
|
||||
|
||||
@@ -107,6 +107,11 @@ export function buildMenuConfig(os: HostOs): MenuConfig {
|
||||
toolWindows: toolWindowsRestorable() ? "hidden" : "shown",
|
||||
};
|
||||
for (const key of keysWithPrefix("menu.")) labels[key] = t(key, params);
|
||||
labels["menu.layout.applyNamed"] = tx("Apply");
|
||||
labels["menu.layout.restoreNamed"] = tx("Restore");
|
||||
labels["menu.layout.saveNamed"] = tx("Save Changes");
|
||||
labels["menu.layout.renameNamed"] = tx("Rename…");
|
||||
labels["menu.layout.deleteNamed"] = tx("Delete…");
|
||||
const accelerators: Record<string, string> = {};
|
||||
const seen = new Set<string>();
|
||||
for (const [, id] of effectiveBindings()) {
|
||||
@@ -154,9 +159,13 @@ export function dynamicMenuItems(): Record<string, DynamicItem[]> {
|
||||
const toolWindows = [...useContributions.getState().toolWindows.values()]
|
||||
.map((tw) => ({ action: `toolwindow.${tw.id}`, arg: null, label: tw.verbatim ? tw.title : tx(tw.title) }))
|
||||
.sort((a, b) => a.label.localeCompare(b.label));
|
||||
const layouts = useToolWindowLayouts
|
||||
.getState()
|
||||
.layouts.map((l) => ({ action: "layout.restore", arg: l.name, label: l.name }));
|
||||
const { layouts, active } = useToolWindowLayouts.getState();
|
||||
const namedLayouts = layouts.map(({ name }) => ({
|
||||
action: "layout.restore",
|
||||
arg: name,
|
||||
label: name,
|
||||
checked: name === active,
|
||||
}));
|
||||
const slots = Object.fromEntries(
|
||||
Object.entries(useMenuSlotItems.getState().slots).map(([slot, items]) => [
|
||||
slot,
|
||||
@@ -165,7 +174,7 @@ export function dynamicMenuItems(): Record<string, DynamicItem[]> {
|
||||
.sort((a, b) => a.label.localeCompare(b.label)),
|
||||
]),
|
||||
);
|
||||
return { ...slots, toolWindows, toolWindowLayouts: layouts, statusBarWidgets: statusBarWidgetItems() };
|
||||
return { ...slots, toolWindows, toolWindowLayouts: namedLayouts, statusBarWidgets: statusBarWidgetItems() };
|
||||
}
|
||||
|
||||
/** Action ids of every IDE item in a menu model. */
|
||||
|
||||
@@ -119,9 +119,24 @@ export function selectInProjectView(path?: string | null, focus = true) {
|
||||
* menu groups), the navigation bar, Finder / Explorer and the terminal.
|
||||
*/
|
||||
export function selectInTargets(path: string): MenuItem[] {
|
||||
const { unity } = useProjectTree.getState();
|
||||
const views = VIEW_MODES.filter(([mode]) => mode !== "unity" || unity).map(([mode, label]) => ({
|
||||
label,
|
||||
disabled: !modeShows(path, mode),
|
||||
run: () => {
|
||||
setViewMode(mode);
|
||||
selectInProjectView(path);
|
||||
},
|
||||
}));
|
||||
return [
|
||||
{ kind: "header", label: "Select In" },
|
||||
{ label: "Project View", icon: "toolwindow-project", run: () => void selectInProjectView(path) },
|
||||
{ kind: "header", label: "Select In", asTitle: true },
|
||||
{
|
||||
label: "Project View",
|
||||
icon: "toolwindow-project",
|
||||
run: () => void selectInProjectView(path),
|
||||
submenu: views,
|
||||
performOnSelect: true,
|
||||
},
|
||||
...menuGroupItems("selectIn", { paths: [path] }),
|
||||
...(getAction("navigate.navigationBar") && maybeEditorService()?.activePath() === path
|
||||
? [{ kind: "action" as const, action: "navigate.navigationBar", label: "Navigation Bar" }]
|
||||
@@ -153,7 +168,6 @@ export function showNewPopupForEditor(orRoot = false): boolean {
|
||||
}
|
||||
|
||||
function showSelectIn(path: string) {
|
||||
// At the caret, like IDEA's popup; centred near the top otherwise.
|
||||
const view = activeEditor()?.view;
|
||||
const coords = view && activeEditor()?.ctx.path === path ? view.coordsAtPos(view.state.selection.main.head) : null;
|
||||
const at = coords ? { x: coords.left, y: coords.bottom + 2 } : { x: window.innerWidth / 2 - 100, y: 80 };
|
||||
|
||||
@@ -46,7 +46,7 @@ import {
|
||||
type ProjectViewLead,
|
||||
type ProjectViewRootContribution,
|
||||
} from "@/workbench/contributions";
|
||||
import { ancestorsWithin, isSameOrInside, nameOf, type PackageKind } from "./paths";
|
||||
import { ancestorsWithin, isInside, isSameOrInside, nameOf, type PackageKind } from "./paths";
|
||||
|
||||
export interface ViewOptions extends TreeOptions {
|
||||
/** Select the active editor's file in the tree (IDEA: Always Select Opened File). */
|
||||
@@ -730,23 +730,29 @@ export function extraRootOf(path: string): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Whether the current pane can show `path` (Select In switches to "Project" otherwise). */
|
||||
export function modeShows(path: string): boolean {
|
||||
const { mode, root } = get();
|
||||
if (!root) return false;
|
||||
/** Whether a pane can show `path`. */
|
||||
export function modeShows(path: string, mode = get().mode): boolean {
|
||||
const state = get();
|
||||
if (!state.root) return false;
|
||||
switch (mode) {
|
||||
case "unity":
|
||||
return unityPathVisible(path, treeOptions(get()));
|
||||
return !!state.unity && unityPathVisible(path, treeOptions({ ...state, mode }));
|
||||
case "project":
|
||||
return true;
|
||||
case "projectFiles":
|
||||
return memberRootOf(path) !== null || (!get().members && isSameOrInside(path, root));
|
||||
return memberRootOf(path) !== null || (!state.members && isSameOrInside(path, state.root));
|
||||
case "scratches":
|
||||
return projectViewRoots(useProjectViewRoots.getState().roots).some(
|
||||
(r) => r.scope === "scratches" && r.path !== undefined && isSameOrInside(path, r.path),
|
||||
);
|
||||
default:
|
||||
return currentModel().keyOfPath.has(path);
|
||||
default: {
|
||||
if (mode === state.mode) return currentModel().keyOfPath.has(path);
|
||||
const pane = { ...state, mode };
|
||||
const files = filesOf(pane);
|
||||
if (files?.includes(path)) return true;
|
||||
// Only a folder that contains a listed file needs a tree lookup.
|
||||
return !!files?.some((file) => isInside(file, path)) && selectModel(pane).keyOfPath.has(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -51,6 +51,10 @@ type Row =
|
||||
const ROW = 24;
|
||||
const SEPARATOR = 9;
|
||||
const CURRENT_FILE_LABEL = "Current File";
|
||||
const MIN_WIDTH = 310;
|
||||
const MAX_WIDTH = 500;
|
||||
// Space beside a name for the icon, metadata, inline actions and list insets.
|
||||
const ROW_CHROME_WIDTH = 160;
|
||||
|
||||
export function buildRows(
|
||||
configs: readonly RunConfig[],
|
||||
@@ -112,6 +116,21 @@ function anchorElement(): Element | { x: number; y: number } {
|
||||
return document.querySelector("[data-run-chooser]") ?? { x: Math.round(window.innerWidth / 2) - 150, y: 40 };
|
||||
}
|
||||
|
||||
function chooserWidth(configs: readonly RunConfig[], anchor: ReturnType<typeof anchorElement>): number {
|
||||
const ownerWidth = anchor instanceof Element ? Math.ceil(anchor.getBoundingClientRect().width) : 0;
|
||||
const context = document.createElement("canvas").getContext("2d");
|
||||
let nameWidth = 0;
|
||||
if (context) {
|
||||
const { fontSize, fontFamily } = getComputedStyle(document.body);
|
||||
context.font = `500 ${fontSize} ${fontFamily}`;
|
||||
nameWidth = configs.reduce((widest, config) => Math.max(widest, context.measureText(config.name).width), 0);
|
||||
}
|
||||
return Math.min(
|
||||
Math.max(MAX_WIDTH, ownerWidth),
|
||||
Math.max(MIN_WIDTH, ownerWidth, Math.ceil(nameWidth) + ROW_CHROME_WIDTH),
|
||||
);
|
||||
}
|
||||
|
||||
/** Run/Debug configuration chooser popup (⌃⌥R), anchored to the title bar widget. */
|
||||
/** Deletes a configuration from the chooser once the user confirms, as IDEA's popup asks first. */
|
||||
async function askDeleteConfig(config: RunConfig) {
|
||||
@@ -180,6 +199,7 @@ function ConfigChooser() {
|
||||
// The configuration whose actions menu (⋮) is open.
|
||||
const [menu, setMenu] = useState<{ name: string; anchor: Element; items: MenuItem[] } | null>(null);
|
||||
const [anchor] = useState(anchorElement);
|
||||
const width = useMemo(() => chooserWidth(configs, anchor), [configs, anchor]);
|
||||
const close = () => {
|
||||
closedAt = Date.now();
|
||||
useRun.setState({ chooserOpen: false });
|
||||
@@ -328,6 +348,7 @@ function ConfigChooser() {
|
||||
placement="bottom-start"
|
||||
aria-label="Run/Debug Configurations"
|
||||
className={styles.chooser}
|
||||
style={{ width }}
|
||||
trapFocus
|
||||
>
|
||||
{mode !== "select" && (
|
||||
@@ -349,7 +370,7 @@ function ConfigChooser() {
|
||||
variant="bare"
|
||||
/>
|
||||
</div>
|
||||
<div style={{ height }}>
|
||||
<div className={styles.chooserViewport} style={{ height }}>
|
||||
<List<Row>
|
||||
aria-label="Configurations"
|
||||
className={styles.chooserList}
|
||||
@@ -417,6 +438,7 @@ function ConfigChooser() {
|
||||
}
|
||||
if (r.type !== "config") return null;
|
||||
const c = r.config;
|
||||
const target = c.target ? targetName(c, runTargets) : null;
|
||||
const running = selectedTarget(c.id, sessions, debugSessions);
|
||||
return (
|
||||
<span className={styles.chooserRow} title={commandLine(c)}>
|
||||
@@ -428,10 +450,17 @@ function ConfigChooser() {
|
||||
/>
|
||||
</span>
|
||||
{numbers.size > 0 && <span className={styles.chooserMnemonic}>{numbers.get(r.key) ?? ""}</span>}
|
||||
<span className={clsx(styles.chooserName, c.id === selectedId && styles.chooserSelected)}>
|
||||
<span
|
||||
className={clsx(styles.chooserName, c.id === selectedId && styles.chooserSelected)}
|
||||
title={c.name}
|
||||
>
|
||||
{r.indices ? <HighlightedText text={c.name} indices={r.indices} /> : c.name}
|
||||
</span>
|
||||
{c.target && <span className={styles.chooserMuted}>@ {targetName(c, runTargets)}</span>}
|
||||
{target && (
|
||||
<span className={styles.chooserMuted} title={target}>
|
||||
@ {target}
|
||||
</span>
|
||||
)}
|
||||
{c.isTest && (
|
||||
<span className={styles.badge}>
|
||||
<T>test</T>
|
||||
|
||||
@@ -444,20 +444,27 @@
|
||||
/* Configuration chooser */
|
||||
|
||||
.chooser {
|
||||
width: 340px;
|
||||
padding: 0 0 4px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
padding-block-end: var(--space-1);
|
||||
}
|
||||
.chooserSearch {
|
||||
flex: none;
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid var(--border-popup);
|
||||
}
|
||||
.chooserViewport {
|
||||
min-height: 0;
|
||||
}
|
||||
.chooserList {
|
||||
height: 100%;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
.chooserRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
gap: var(--space-1-5);
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
@@ -494,7 +501,10 @@
|
||||
font-weight: 500;
|
||||
}
|
||||
.chooserMuted {
|
||||
flex: none;
|
||||
min-width: 0;
|
||||
max-width: 35%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--fg-faint);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
@@ -512,6 +522,7 @@
|
||||
opacity: 0.55;
|
||||
}
|
||||
.chooserCaption {
|
||||
flex: none;
|
||||
padding: 6px 10px 0;
|
||||
color: var(--fg-secondary);
|
||||
font-weight: 500;
|
||||
@@ -525,6 +536,7 @@
|
||||
}
|
||||
/* IDEA's popup ad text. */
|
||||
.chooserHint {
|
||||
flex: none;
|
||||
padding: 4px 10px 0;
|
||||
border-top: 1px solid var(--border-popup);
|
||||
color: var(--fg-faint);
|
||||
@@ -532,6 +544,7 @@
|
||||
}
|
||||
.chooserActions {
|
||||
display: flex;
|
||||
flex: none;
|
||||
margin-right: -4px;
|
||||
}
|
||||
.chooserSeparator {
|
||||
|
||||
@@ -148,6 +148,26 @@
|
||||
}
|
||||
}
|
||||
|
||||
@container settings-content (max-width: 440px) {
|
||||
.stackFields > .row:not(.toggleRow) {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
row-gap: var(--space-1-5);
|
||||
}
|
||||
|
||||
.stackFields > .row:not(.toggleRow) > .label {
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.stackFields > .row:not(.toggleRow) > .label::after {
|
||||
content: none;
|
||||
}
|
||||
|
||||
.stackFields > .row:not(.toggleRow) > .hint {
|
||||
grid-column: 1;
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.swatches {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -203,11 +223,13 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
max-width: 480px;
|
||||
border-radius: var(--radius-small);
|
||||
box-shadow: inset 0 0 0 1px var(--border-strong);
|
||||
overflow: hidden;
|
||||
}
|
||||
.globCompact {
|
||||
max-width: 480px;
|
||||
}
|
||||
.listToolbar {
|
||||
display: flex;
|
||||
gap: var(--space-0-5);
|
||||
@@ -230,9 +252,11 @@
|
||||
align-items: center;
|
||||
height: var(--h-row);
|
||||
padding: 0 8px;
|
||||
font-family: var(--font-mono);
|
||||
color: var(--fg);
|
||||
}
|
||||
.globMono {
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
.globSelected {
|
||||
background: var(--bg-selected);
|
||||
color: var(--fg-strong);
|
||||
|
||||
@@ -43,7 +43,17 @@ export function SearchLabel({ text: source, className }: { text: string; classNa
|
||||
return <span className={className}>{parts}</span>;
|
||||
}
|
||||
|
||||
export function Section({ title, children, className }: { title?: string; children: ReactNode; className?: string }) {
|
||||
export function Section({
|
||||
title,
|
||||
children,
|
||||
className,
|
||||
stackFields,
|
||||
}: {
|
||||
title?: string;
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
stackFields?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<section className={clsx(styles.section, className)} aria-label={tx(title)}>
|
||||
{title && (
|
||||
@@ -52,7 +62,7 @@ export function Section({ title, children, className }: { title?: string; childr
|
||||
<span className={styles.sectionRule} aria-hidden />
|
||||
</div>
|
||||
)}
|
||||
<FormGroup className={styles.sectionBody}>{children}</FormGroup>
|
||||
<FormGroup className={clsx(styles.sectionBody, stackFields && styles.stackFields)}>{children}</FormGroup>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -307,12 +317,15 @@ export function ColorSwatches({ value, presets, onChange, allowCustom = true, ..
|
||||
export interface GlobListEditorProps {
|
||||
value: readonly string[];
|
||||
onChange: (value: string[]) => void;
|
||||
className?: string;
|
||||
mono?: boolean;
|
||||
placeholder?: string;
|
||||
"aria-label"?: string;
|
||||
/** Shown for an empty list. */
|
||||
emptyText?: string;
|
||||
/** Accessible name of the inline editor. */
|
||||
itemLabel?: string;
|
||||
fullWidth?: boolean;
|
||||
/** Entries are paths: + opens this chooser (Edit still takes typing). */
|
||||
browse?: { directory: boolean; title: string };
|
||||
}
|
||||
@@ -321,9 +334,12 @@ export interface GlobListEditorProps {
|
||||
export function GlobListEditor({
|
||||
value,
|
||||
onChange,
|
||||
className,
|
||||
mono = true,
|
||||
placeholder = "**/pattern",
|
||||
emptyText = "No patterns",
|
||||
itemLabel = "Pattern",
|
||||
fullWidth,
|
||||
browse,
|
||||
...aria
|
||||
}: GlobListEditorProps) {
|
||||
@@ -404,7 +420,7 @@ export function GlobListEditor({
|
||||
|
||||
const rows = editing && editing.index >= value.length ? [...value, ""] : value;
|
||||
return (
|
||||
<div className={styles.globEditor}>
|
||||
<div className={clsx(styles.globEditor, !fullWidth && styles.globCompact, className)}>
|
||||
<div className={styles.listToolbar} role="toolbar" aria-controls={listId}>
|
||||
<IconButton icon="plus" title="Add" size="small" onClick={() => void add()} />
|
||||
<IconButton icon="minus" title="Remove" size="small" disabled={selected === null} onClick={remove} />
|
||||
@@ -437,14 +453,14 @@ export function GlobListEditor({
|
||||
id={`${listId}-${i}`}
|
||||
role="option"
|
||||
aria-selected={selected === i}
|
||||
className={clsx(styles.globRow, selected === i && styles.globSelected)}
|
||||
className={clsx(styles.globRow, mono && styles.globMono, selected === i && styles.globSelected)}
|
||||
onMouseDown={() => setSelected(i)}
|
||||
onDoubleClick={() => setEditing({ index: i, text: glob })}
|
||||
>
|
||||
{editing?.index === i ? (
|
||||
<Input
|
||||
autoFocus
|
||||
mono
|
||||
mono={mono}
|
||||
variant="bare"
|
||||
className={styles.globInput}
|
||||
value={editing.text}
|
||||
|
||||
@@ -17,45 +17,51 @@ import { SdkField, tildify, useDetected, useJdtlsJdk } from "./components";
|
||||
import { isMavenThreadCount } from "./mavenThreads";
|
||||
import styles from "./Sdk.module.css";
|
||||
|
||||
function PathInput({
|
||||
k,
|
||||
label,
|
||||
placeholder,
|
||||
hint,
|
||||
title,
|
||||
file,
|
||||
}: {
|
||||
interface PathFieldProps {
|
||||
k: string;
|
||||
label: string;
|
||||
placeholder: string;
|
||||
hint?: string;
|
||||
title: string;
|
||||
id?: string;
|
||||
"aria-label"?: string;
|
||||
/** Browse for a file instead of a directory. */
|
||||
file?: boolean;
|
||||
}) {
|
||||
}
|
||||
|
||||
function PathField({ k, placeholder, title, id, file, ...aria }: PathFieldProps) {
|
||||
const [value, set] = useSetting<string>(k);
|
||||
return (
|
||||
<span className={styles.pathRow}>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
className={styles.pathInput}
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => set(e.target.value.trim())}
|
||||
aria-label={aria["aria-label"]}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
onClick={async () => {
|
||||
const p = await choosePath({ directory: !file, title, defaultPath: value || undefined });
|
||||
if (p) set(p);
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function PathInput({
|
||||
label,
|
||||
hint,
|
||||
...field
|
||||
}: Omit<PathFieldProps, "id" | "aria-label"> & { label: string; hint?: string }) {
|
||||
const id = useId();
|
||||
return (
|
||||
<Row label={label} htmlFor={id} hint={hint}>
|
||||
<span className={styles.pathRow}>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
className={styles.pathInput}
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => set(e.target.value.trim())}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
onClick={async () => {
|
||||
const p = await choosePath({ directory: !file, title, defaultPath: value || undefined });
|
||||
if (p) set(p);
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
<PathField {...field} id={id} />
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -499,9 +505,19 @@ export function JavaPage() {
|
||||
export function GradlePage() {
|
||||
const [distribution, setDistribution] = useSetting<string>("languages.java.gradle.distribution");
|
||||
const [runUsing, setRunUsing] = useSetting<string>("languages.java.gradle.runUsing");
|
||||
const local = distribution === "local";
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<div className={styles.gradleSettings}>
|
||||
<Section>
|
||||
<PathInput
|
||||
k="languages.java.gradle.userHome"
|
||||
label="Gradle user home"
|
||||
placeholder="~/.gradle"
|
||||
title="Select Gradle User Home Directory"
|
||||
hint="Sets GRADLE_USER_HOME. Empty uses Gradle's default."
|
||||
/>
|
||||
</Section>
|
||||
<Section title="Build and Run">
|
||||
<Row
|
||||
label="Build and run using"
|
||||
hint="Gradle runs a main class as a JavaExec task on its source set's runtime classpath (Gradle's resource processing included). OpenIDEA launches it on the Java language server's classpath."
|
||||
@@ -516,6 +532,36 @@ export function GradlePage() {
|
||||
]}
|
||||
/>
|
||||
</Row>
|
||||
</Section>
|
||||
<Section title="Gradle runtime">
|
||||
<Row
|
||||
label="Distribution"
|
||||
hint={
|
||||
local
|
||||
? "Uses bin/gradle (bin/gradle.bat on Windows) instead of the wrapper or pinned toolchain."
|
||||
: "Uses the Gradle wrapper when present, otherwise the project-pinned mise/asdf Gradle, then Gradle on PATH."
|
||||
}
|
||||
>
|
||||
<div className={styles.gradleDistribution}>
|
||||
<Select
|
||||
value={distribution}
|
||||
onChange={setDistribution}
|
||||
aria-label="Distribution"
|
||||
options={[
|
||||
{ value: "wrapper", label: "Gradle wrapper" },
|
||||
{ value: "local", label: "Local installation" },
|
||||
]}
|
||||
/>
|
||||
{local && (
|
||||
<PathField
|
||||
k="languages.java.gradle.home"
|
||||
aria-label="Gradle home"
|
||||
placeholder="Gradle installation directory"
|
||||
title="Select Gradle Home Directory"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</Row>
|
||||
<SdkRow
|
||||
k="languages.java.gradle.jvm"
|
||||
label="Gradle JVM"
|
||||
@@ -526,36 +572,6 @@ export function GradlePage() {
|
||||
aria-label="Gradle JVM"
|
||||
hint="JDK used for Gradle sync, tasks, run configurations and tests. An explicit JAVA_HOME in a run configuration takes precedence."
|
||||
/>
|
||||
<Row
|
||||
label="Distribution"
|
||||
hint="Uses the Gradle wrapper when present, otherwise the project-pinned mise/asdf Gradle, then Gradle on PATH."
|
||||
>
|
||||
<Select
|
||||
value={distribution}
|
||||
onChange={setDistribution}
|
||||
aria-label="Distribution"
|
||||
options={[
|
||||
{ value: "wrapper", label: "Gradle wrapper" },
|
||||
{ value: "local", label: "Local installation" },
|
||||
]}
|
||||
/>
|
||||
</Row>
|
||||
{distribution === "local" && (
|
||||
<PathInput
|
||||
k="languages.java.gradle.home"
|
||||
label="Gradle home"
|
||||
placeholder="Gradle installation directory"
|
||||
title="Select Gradle Home Directory"
|
||||
hint="Uses bin/gradle (bin/gradle.bat on Windows) instead of the wrapper or pinned toolchain."
|
||||
/>
|
||||
)}
|
||||
<PathInput
|
||||
k="languages.java.gradle.userHome"
|
||||
label="Gradle user home"
|
||||
placeholder="~/.gradle"
|
||||
title="Select Gradle User Home Directory"
|
||||
hint="Sets GRADLE_USER_HOME. Empty uses Gradle's default."
|
||||
/>
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
@@ -571,36 +587,43 @@ export function MavenPage() {
|
||||
const [activeProfiles, setActiveProfiles] = useSetting<string>("languages.java.maven.activeProfiles");
|
||||
const id = useId();
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<div className={styles.mavenSettings}>
|
||||
<Section>
|
||||
<Toggle
|
||||
label="Delegate IDE build/run actions to Maven"
|
||||
checked={delegateBuild}
|
||||
onChange={setDelegateBuild}
|
||||
hint="Run and Debug build Maven modules with Maven (the project's javac) instead of the Java language server. Editor problems still come from the language server."
|
||||
/>
|
||||
<Toggle
|
||||
label="Automatically download sources"
|
||||
checked={downloadSources}
|
||||
onChange={setDownloadSources}
|
||||
hint="The Java language server downloads the sources of all dependencies when it imports the project. When off, a library class opens decompiled and its Download Sources banner fetches the sources of that library only."
|
||||
/>
|
||||
<Toggle
|
||||
label="Always update snapshots"
|
||||
checked={updateSnapshots}
|
||||
onChange={setUpdateSnapshots}
|
||||
hint="Checks remote repositories for newer SNAPSHOT dependencies on every sync, build and run (-U)."
|
||||
/>
|
||||
<SdkRow
|
||||
k="languages.java.maven.runnerJre"
|
||||
label="JRE"
|
||||
kind="jdk"
|
||||
emptyLabel="Use Project JDK"
|
||||
directory
|
||||
browseTitle="Select JDK Home Directory"
|
||||
aria-label="JRE"
|
||||
hint="JDK used for Maven sync, builds, goals and tests. An explicit JAVA_HOME in a run configuration takes precedence."
|
||||
/>
|
||||
<Row
|
||||
label="Thread count"
|
||||
htmlFor={id}
|
||||
hint={
|
||||
threadsInvalid ? (
|
||||
<span className={styles.error} role="alert">
|
||||
<T>
|
||||
Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C,
|
||||
2.5C).
|
||||
</T>
|
||||
</span>
|
||||
) : (
|
||||
"Passed as -T to Maven builds and run configurations: a thread count (4) or a core multiplier (2C, 2.5C) for parallel builds of multi-module projects. Empty runs Maven serially."
|
||||
)
|
||||
}
|
||||
>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
invalid={threadsInvalid}
|
||||
className={styles.mavenThreads}
|
||||
value={threads}
|
||||
placeholder="4, 2C"
|
||||
onChange={(e) => setThreads(e.target.value.trim())}
|
||||
aria-label="Thread count"
|
||||
/>
|
||||
</Row>
|
||||
</Section>
|
||||
<Section title="Environment" stackFields>
|
||||
<SdkRow
|
||||
k="languages.java.maven.home"
|
||||
label="Maven home path"
|
||||
@@ -620,6 +643,13 @@ export function MavenPage() {
|
||||
file
|
||||
hint="Passed as -s (mirrors, servers, proxies)."
|
||||
/>
|
||||
<PathInput
|
||||
k="languages.java.maven.localRepository"
|
||||
label="Local repository"
|
||||
placeholder="From settings.xml, else ~/.m2/repository"
|
||||
title="Select Local Repository"
|
||||
hint="Passed as -Dmaven.repo.local."
|
||||
/>
|
||||
<PathInput
|
||||
k="languages.java.maven.toolchains"
|
||||
label="Toolchains file"
|
||||
@@ -628,12 +658,31 @@ export function MavenPage() {
|
||||
file
|
||||
hint="Passed as -t; selects the JDKs Maven compiles with."
|
||||
/>
|
||||
<PathInput
|
||||
k="languages.java.maven.localRepository"
|
||||
label="Local repository"
|
||||
placeholder="From settings.xml, else ~/.m2/repository"
|
||||
title="Select Local Repository"
|
||||
hint="Passed as -Dmaven.repo.local."
|
||||
</Section>
|
||||
<Section title="Importing">
|
||||
<Toggle
|
||||
label="Automatically download sources"
|
||||
checked={downloadSources}
|
||||
onChange={setDownloadSources}
|
||||
hint="The Java language server downloads the sources of all dependencies when it imports the project. When off, a library class opens decompiled and its Download Sources banner fetches the sources of that library only."
|
||||
/>
|
||||
</Section>
|
||||
<Section title="Runner" stackFields>
|
||||
<Toggle
|
||||
label="Delegate IDE build/run actions to Maven"
|
||||
checked={delegateBuild}
|
||||
onChange={setDelegateBuild}
|
||||
hint="Run and Debug build Maven modules with Maven (the project's javac) instead of the Java language server. Editor problems still come from the language server."
|
||||
/>
|
||||
<SdkRow
|
||||
k="languages.java.maven.runnerJre"
|
||||
label="JRE"
|
||||
kind="jdk"
|
||||
emptyLabel="Use Project JDK"
|
||||
directory
|
||||
browseTitle="Select JDK Home Directory"
|
||||
aria-label="JRE"
|
||||
hint="JDK used for Maven sync, builds, goals and tests. An explicit JAVA_HOME in a run configuration takes precedence."
|
||||
/>
|
||||
<Row
|
||||
label="Active profiles"
|
||||
@@ -650,35 +699,8 @@ export function MavenPage() {
|
||||
aria-label="Active profiles"
|
||||
/>
|
||||
</Row>
|
||||
<Row
|
||||
label="Thread count"
|
||||
htmlFor={id}
|
||||
hint={
|
||||
threadsInvalid ? (
|
||||
<span className={styles.error} role="alert">
|
||||
<T>
|
||||
Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C,
|
||||
2.5C).
|
||||
</T>
|
||||
</span>
|
||||
) : (
|
||||
"Passed as -T to Maven builds and run configurations: a thread count (4) or a core multiplier (2C, 2.5C) for parallel builds of multi-module projects. Empty runs Maven serially."
|
||||
)
|
||||
}
|
||||
>
|
||||
<span className={styles.pathRow}>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
invalid={threadsInvalid}
|
||||
className={styles.pathInput}
|
||||
value={threads}
|
||||
placeholder="4, 2C"
|
||||
onChange={(e) => setThreads(e.target.value.trim())}
|
||||
aria-label="Thread count"
|
||||
/>
|
||||
</span>
|
||||
</Row>
|
||||
</Section>
|
||||
<Section>
|
||||
<Toggle
|
||||
label="Use Maven Daemon (mvnd)"
|
||||
checked={daemon}
|
||||
|
||||
@@ -18,6 +18,15 @@
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.mavenSettings .sdkField {
|
||||
min-width: 0;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.mavenThreads {
|
||||
width: 100px;
|
||||
}
|
||||
|
||||
.interpreterRow {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
@@ -268,6 +277,30 @@
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.gradleSettings .pathRow {
|
||||
max-width: 560px;
|
||||
}
|
||||
|
||||
.gradleSettings .sdkField {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.gradleDistribution {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
width: 560px;
|
||||
}
|
||||
|
||||
.gradleDistribution > :first-child {
|
||||
flex: 0 1 180px;
|
||||
}
|
||||
|
||||
.gradleDistribution > .pathRow {
|
||||
flex: 1 1 230px;
|
||||
}
|
||||
|
||||
/* Project Structure */
|
||||
.structure {
|
||||
display: grid;
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
.inline {
|
||||
.themeSync {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
margin-left: 8px;
|
||||
padding: 0 4px;
|
||||
border-radius: var(--radius-row);
|
||||
}
|
||||
.themeSelect {
|
||||
flex: 1 1 120px;
|
||||
flex: 1 1 140px;
|
||||
min-width: min(120px, 100%);
|
||||
max-width: 180px;
|
||||
}
|
||||
@@ -30,10 +28,16 @@
|
||||
color: var(--fg-subtle);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.popupBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 8px 14px;
|
||||
.preferredThemes {
|
||||
width: min(440px, calc(100vw - var(--space-4)));
|
||||
padding: var(--space-2) var(--space-3);
|
||||
}
|
||||
.preferredThemes label {
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.preferredThemes button {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* Inline option groups, with custom font controls wrapping together. */
|
||||
@@ -47,33 +51,45 @@
|
||||
margin: 0 -6px;
|
||||
border-radius: var(--radius-row);
|
||||
}
|
||||
/* Custom font block (IDEA Appearance): labels share one column, so the UI font,
|
||||
fallback and Size controls all start at the same x. */
|
||||
.idleDuration {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
.fileSynchronization {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
padding-top: var(--space-2);
|
||||
}
|
||||
.customFontRow {
|
||||
display: grid;
|
||||
grid-template-columns: max-content minmax(0, 1fr);
|
||||
grid-template-columns: fit-content(42%) minmax(0, 280px) max-content;
|
||||
align-items: start;
|
||||
column-gap: var(--space-2);
|
||||
row-gap: var(--space-1);
|
||||
min-height: 28px;
|
||||
min-height: var(--h-field);
|
||||
padding: 2px 6px;
|
||||
margin: 0 -6px;
|
||||
border-radius: var(--radius-row);
|
||||
}
|
||||
.customFontRow > .fontLabel {
|
||||
padding-top: 3px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.customFontRow > .fontCheck {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.fontControl {
|
||||
.fontLabel,
|
||||
.fontCheck,
|
||||
.fontSize {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: var(--h-field);
|
||||
min-width: 0;
|
||||
}
|
||||
.sizeInput {
|
||||
width: 64px;
|
||||
.fontSize {
|
||||
gap: var(--space-2);
|
||||
}
|
||||
@container settings-content (max-width: 580px) {
|
||||
.customFontRow {
|
||||
grid-template-columns: fit-content(42%) minmax(0, 280px);
|
||||
}
|
||||
.fontSize {
|
||||
grid-column: 2;
|
||||
}
|
||||
}
|
||||
.disabled {
|
||||
color: var(--fg-subtle);
|
||||
@@ -81,6 +97,15 @@
|
||||
.pathInput {
|
||||
width: 320px;
|
||||
}
|
||||
.directoryBrowse {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
.directoryBrowse > button {
|
||||
flex: none;
|
||||
}
|
||||
.backgroundPreview {
|
||||
height: var(--h-control);
|
||||
max-width: 64px;
|
||||
@@ -91,8 +116,14 @@
|
||||
.patternInput {
|
||||
width: 160px;
|
||||
}
|
||||
.patternHint,
|
||||
.preview {
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
line-height: 1.4;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.preview {
|
||||
color: var(--fg-muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
@@ -118,7 +149,7 @@
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
gap: var(--space-1) var(--space-4);
|
||||
}
|
||||
.radio {
|
||||
display: inline-flex;
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
.hover {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 320px) minmax(0, max-content);
|
||||
column-gap: var(--space-4);
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.hover > :first-child {
|
||||
padding-block-start: var(--space-2);
|
||||
}
|
||||
|
||||
@container settings-content (max-width: 540px) {
|
||||
.hover {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.hover > :first-child {
|
||||
padding-block-start: 2px;
|
||||
}
|
||||
|
||||
.hover > :last-child {
|
||||
margin-inline-start: calc(16px + var(--space-2) - 6px);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
.executableControls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.executableControls > input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.testResult {
|
||||
display: block;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.branchPatterns {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.updateMethods {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1) var(--space-4);
|
||||
}
|
||||
|
||||
@container settings-content (max-width: 440px) {
|
||||
.executable > div {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
row-gap: var(--space-1);
|
||||
}
|
||||
|
||||
.executable > div > div {
|
||||
grid-column: 1;
|
||||
}
|
||||
}
|
||||
@@ -7,45 +7,30 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.radio {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
min-height: 28px;
|
||||
}
|
||||
.radio input {
|
||||
margin: 0;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
.disabled {
|
||||
color: var(--fg-subtle);
|
||||
.radioRow {
|
||||
min-height: var(--h-field);
|
||||
}
|
||||
.hint {
|
||||
padding-left: 20px;
|
||||
padding-inline-start: calc(16px + var(--space-2));
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
/* Manual configuration, indented under its radio button. */
|
||||
.manual {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding-left: 20px;
|
||||
padding-inline-start: calc(16px + var(--space-2));
|
||||
}
|
||||
.kinds {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
.hostRow {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 24px;
|
||||
}
|
||||
.host {
|
||||
width: 220px;
|
||||
}
|
||||
.port {
|
||||
width: 64px;
|
||||
.field {
|
||||
width: 100%;
|
||||
}
|
||||
.wide {
|
||||
width: 360px;
|
||||
@@ -55,11 +40,6 @@
|
||||
align-items: center;
|
||||
min-height: 28px;
|
||||
}
|
||||
.auth {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding-left: 20px;
|
||||
}
|
||||
.error {
|
||||
color: var(--danger);
|
||||
}
|
||||
@@ -82,6 +62,10 @@
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
.urlRow > input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.result {
|
||||
min-height: 1lh;
|
||||
overflow-wrap: anywhere;
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
.field,
|
||||
.shellControls {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.shellControls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.shellControls > input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.families {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(265px, 100%), 1fr));
|
||||
column-gap: var(--space-4);
|
||||
}
|
||||
|
||||
.fontPicker {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.metrics {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
column-gap: var(--space-4);
|
||||
}
|
||||
|
||||
.metrics > div {
|
||||
margin-inline: 0;
|
||||
padding-inline: 0;
|
||||
}
|
||||
|
||||
.options > div:first-child {
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(245px, 100%), 1fr));
|
||||
}
|
||||
|
||||
@container settings-content (max-width: 440px) {
|
||||
section .textRow[class] {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.textRow > label {
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.textRow > :last-child {
|
||||
grid-column: 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
.checkRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-3);
|
||||
padding-block: var(--space-2);
|
||||
border-radius: var(--radius-row);
|
||||
}
|
||||
|
||||
.checkStatus {
|
||||
min-width: 0;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.checkedLabel::after {
|
||||
content: ":";
|
||||
}
|
||||
|
||||
:lang(fr) .checkedLabel::after {
|
||||
content: "\00a0:";
|
||||
}
|
||||
@@ -1,16 +1,42 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { executeAction, useActions } from "@/platform/actions";
|
||||
import { formatClock, formatDay } from "@/platform/dateFormat";
|
||||
import { call, commands, onIdeEvent, type UpdateStatus } from "@/platform/ipc";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { Button, T } from "@/ui";
|
||||
import { Row } from "../components/Form";
|
||||
import { Button } from "@/ui";
|
||||
import { Row, SearchLabel } from "../components/Form";
|
||||
import { useLabelMatch } from "../components/context";
|
||||
import formStyles from "../components/Form.module.css";
|
||||
import styles from "./Updates.module.css";
|
||||
|
||||
export function UpdateStatusRows() {
|
||||
export function UpdateVersionRow() {
|
||||
const tx = useTx();
|
||||
const [version, setVersion] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
void commands
|
||||
.appBuildInfo()
|
||||
.then((info) => live && setVersion(info.version))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, []);
|
||||
return (
|
||||
<Row label="Current version">
|
||||
<span>{version ?? tx("Loading…")}</span>
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
|
||||
export function UpdateCheckRow() {
|
||||
const tx = useTx();
|
||||
const [status, setStatus] = useState<UpdateStatus | null>(null);
|
||||
const canCheck = useActions((s) => s.actions.has("app.checkForUpdates"));
|
||||
const checkedMatch = useLabelMatch("Last checked");
|
||||
const checkMatch = useLabelMatch("Check Now");
|
||||
const matched = checkedMatch || checkMatch;
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
let received = false;
|
||||
@@ -18,10 +44,6 @@ export function UpdateStatusRows() {
|
||||
received = true;
|
||||
if (live) setStatus(status);
|
||||
});
|
||||
void commands
|
||||
.appBuildInfo()
|
||||
.then((info) => live && setVersion(info.version))
|
||||
.catch(() => {});
|
||||
void call(commands.appUpdateStatus())
|
||||
.then((status) => live && !received && setStatus(status))
|
||||
.catch(() => {});
|
||||
@@ -31,20 +53,18 @@ export function UpdateStatusRows() {
|
||||
};
|
||||
}, []);
|
||||
const date = status?.lastChecked == null ? null : new Date(status.lastChecked);
|
||||
const lastChecked = !status ? tx("Loading…") : date ? `${formatDay(date)} ${formatClock(date)}` : tx("Never");
|
||||
return (
|
||||
<>
|
||||
<Row label="Current version">
|
||||
<span>{version ?? tx("Loading…")}</span>
|
||||
</Row>
|
||||
<Row label="Last checked">
|
||||
<span>{!status ? tx("Loading…") : date ? `${formatDay(date)} ${formatClock(date)}` : tx("Never")}</span>
|
||||
<Button
|
||||
disabled={!canCheck || !status || status.checking}
|
||||
onClick={() => void executeAction("app.checkForUpdates")}
|
||||
>
|
||||
<T>{status?.checking ? "Checking for updates…" : "Check Now"}</T>
|
||||
</Button>
|
||||
</Row>
|
||||
</>
|
||||
<div className={clsx(styles.checkRow, matched && formStyles.matched)} data-search-match={matched || undefined}>
|
||||
<Button
|
||||
disabled={!canCheck || !status || status.checking}
|
||||
onClick={() => void executeAction("app.checkForUpdates")}
|
||||
>
|
||||
<SearchLabel text={status?.checking ? "Checking for updates…" : "Check Now"} />
|
||||
</Button>
|
||||
<div className={styles.checkStatus} role="status">
|
||||
<SearchLabel text="Last checked" className={styles.checkedLabel} /> <span>{lastChecked}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -180,6 +180,8 @@
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
scroll-padding-top: var(--h-list-row);
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
}
|
||||
.mappingRows th {
|
||||
position: sticky;
|
||||
@@ -192,6 +194,14 @@
|
||||
.mappingVcsColumn {
|
||||
width: 112px;
|
||||
}
|
||||
.unregisteredMappings {
|
||||
color: var(--fg-subtle);
|
||||
background: var(--bg-control-hover);
|
||||
}
|
||||
.unregisteredMappings .mappingGroupHeader {
|
||||
color: var(--fg-muted);
|
||||
font-weight: 600;
|
||||
}
|
||||
.mappingRows .mappingSelect {
|
||||
width: 100%;
|
||||
padding-inline-start: 0;
|
||||
@@ -275,10 +285,45 @@
|
||||
color: var(--fg-subtle);
|
||||
margin-left: auto;
|
||||
}
|
||||
.macroField {
|
||||
.toolIdentity {
|
||||
display: grid;
|
||||
grid-template-columns: max-content minmax(0, 1fr) max-content minmax(0, 1fr);
|
||||
column-gap: var(--space-2);
|
||||
padding-inline-start: 18px;
|
||||
}
|
||||
.toolIdentity > * {
|
||||
grid-column: span 2;
|
||||
grid-template-columns: subgrid;
|
||||
}
|
||||
.toolIdentity > .toolDescription {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.toolDescription > div {
|
||||
grid-column: 2 / -1;
|
||||
}
|
||||
@container settings-content (max-width: 560px) {
|
||||
.toolIdentity {
|
||||
grid-template-columns: fit-content(45%) minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
.toolField {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1-5);
|
||||
width: 100%;
|
||||
}
|
||||
.toolField > input {
|
||||
flex: 1 1 104px;
|
||||
min-width: min(104px, 100%);
|
||||
}
|
||||
.toolOptions > summary {
|
||||
width: fit-content;
|
||||
padding-block: var(--space-1);
|
||||
cursor: pointer;
|
||||
}
|
||||
.toolOptions > div {
|
||||
padding-top: var(--space-1);
|
||||
}
|
||||
.macroList {
|
||||
display: flex;
|
||||
|
||||
@@ -98,7 +98,14 @@ function ThemeRow() {
|
||||
showPicked(shown);
|
||||
};
|
||||
return (
|
||||
<Row label="Theme">
|
||||
<Row
|
||||
label="Theme"
|
||||
hint={
|
||||
<button type="button" className={styles.link} onClick={() => selectPage("plugins#themes")}>
|
||||
<T>Get more themes</T>
|
||||
</button>
|
||||
}
|
||||
>
|
||||
<Select<ConcreteTheme>
|
||||
value={shown}
|
||||
options={themeSelectOptions(choices, shown)}
|
||||
@@ -108,11 +115,7 @@ function ThemeRow() {
|
||||
className={styles.themeSelect}
|
||||
disabled={sync}
|
||||
/>
|
||||
{/* As in IntelliJ IDEA: most themes are plugins, so point at the marketplace's. */}
|
||||
<button type="button" className={styles.link} onClick={() => selectPage("plugins#themes")}>
|
||||
<T>Get more themes</T>
|
||||
</button>
|
||||
<span className={clsx(styles.inline, matched && styles.matched)}>
|
||||
<span className={clsx(styles.themeSync, matched && styles.matched)}>
|
||||
<Checkbox
|
||||
checked={sync}
|
||||
onChange={(on) => {
|
||||
@@ -141,7 +144,7 @@ function ThemeRow() {
|
||||
offset={4}
|
||||
aria-label="Preferred themes"
|
||||
>
|
||||
<div className={styles.popupBody}>
|
||||
<FormGroup className={styles.preferredThemes}>
|
||||
<Row label="Preferred theme for light OS mode">
|
||||
<Select<ConcreteTheme>
|
||||
value={light}
|
||||
@@ -158,7 +161,7 @@ function ThemeRow() {
|
||||
aria-label="Preferred dark theme"
|
||||
/>
|
||||
</Row>
|
||||
</div>
|
||||
</FormGroup>
|
||||
</Popup>
|
||||
</Row>
|
||||
);
|
||||
@@ -260,53 +263,37 @@ function CustomFontRow() {
|
||||
const [size, setSize] = useSetting<number>("appearance.uiFontSize");
|
||||
const id = useId();
|
||||
const matched = useLabelMatch("Use custom font");
|
||||
// Labels share one column (IDEA Appearance): the UI font, fallback and Size
|
||||
// controls all start at the same x instead of drifting with flex wrapping.
|
||||
return (
|
||||
<div className={clsx(styles.customFontRow, matched && styles.matched)}>
|
||||
<span className={styles.fontCheck}>
|
||||
<Checkbox checked={on} onChange={setOn} label={<SearchLabel text="Use custom font:" />} />
|
||||
</span>
|
||||
<span className={styles.fontControl}>
|
||||
<FontPicker label="UI font" disabled={!on} value={family} onChange={setFamily} />
|
||||
</span>
|
||||
<FontPicker label="UI font" disabled={!on} value={family} onChange={setFamily} />
|
||||
<div className={clsx(styles.fontSize, !on && styles.disabled)}>
|
||||
<label htmlFor={`${id}-size`}>
|
||||
<SearchLabel text="Size:" />
|
||||
</label>
|
||||
<NumberInput
|
||||
id={`${id}-size`}
|
||||
value={size}
|
||||
onChange={setSize}
|
||||
{...LIMITS.uiFontSize}
|
||||
integer
|
||||
disabled={!on}
|
||||
aria-label="UI font size"
|
||||
/>
|
||||
</div>
|
||||
<label className={clsx(styles.fontLabel, !on && styles.disabled)} htmlFor={`${id}-fallback`}>
|
||||
<SearchLabel text="Fallback font:" />
|
||||
</label>
|
||||
<span className={styles.fontControl}>
|
||||
<FontPicker
|
||||
id={`${id}-fallback`}
|
||||
label="UI fallback font"
|
||||
disabled={!on}
|
||||
value={fallback}
|
||||
onChange={setFallback}
|
||||
allowEmpty
|
||||
/>
|
||||
</span>
|
||||
<label className={clsx(styles.fontLabel, !on && styles.disabled)} htmlFor={`${id}-size`}>
|
||||
<SearchLabel text="Size:" />
|
||||
</label>
|
||||
<span className={styles.fontControl}>
|
||||
{on ? (
|
||||
<NumberInput
|
||||
id={`${id}-size`}
|
||||
value={size}
|
||||
onChange={setSize}
|
||||
{...LIMITS.uiFontSize}
|
||||
integer
|
||||
aria-label="UI font size"
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
id={`${id}-size`}
|
||||
className={styles.sizeInput}
|
||||
value={String(size)}
|
||||
disabled
|
||||
aria-label="UI font size"
|
||||
readOnly
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
<FontPicker
|
||||
id={`${id}-fallback`}
|
||||
label="UI fallback font"
|
||||
disabled={!on}
|
||||
value={fallback}
|
||||
onChange={setFallback}
|
||||
allowEmpty
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -617,21 +604,23 @@ function DefaultDirectoryRow() {
|
||||
htmlFor={id}
|
||||
hint={'This directory is preselected in "Open…" and "New Window" dialogs.'}
|
||||
>
|
||||
<Input
|
||||
id={id}
|
||||
className={styles.pathInput}
|
||||
value={dir}
|
||||
placeholder="System default"
|
||||
onChange={(e) => setDir(e.target.value)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
aria-label="Browse"
|
||||
disabled={!isTauri()}
|
||||
onClick={() => void browse()}
|
||||
/>
|
||||
<div className={styles.directoryBrowse}>
|
||||
<Input
|
||||
id={id}
|
||||
className={styles.pathInput}
|
||||
value={dir}
|
||||
placeholder="System default"
|
||||
onChange={(e) => setDir(e.target.value)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
aria-label="Browse"
|
||||
disabled={!isTauri()}
|
||||
onClick={() => void browse()}
|
||||
/>
|
||||
</div>
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -759,16 +748,32 @@ function IdleSaveRow() {
|
||||
const [seconds, setSeconds] = useSetting<number>("general.idleSeconds");
|
||||
const matched = useLabelMatch("Save files if the IDE is idle for");
|
||||
return (
|
||||
<div className={clsx(styles.fontRow, matched && styles.matched)}>
|
||||
<div className={clsx(styles.fontRow, matched && styles.matched)} data-search-match={matched || undefined}>
|
||||
<Checkbox checked={on} onChange={setOn} label={<SearchLabel text="Save files if the IDE is idle for" />} />
|
||||
<NumberInput value={seconds} onChange={setSeconds} {...IDLE_LIMITS} integer aria-label="Idle seconds" />
|
||||
<span className={clsx(!on && styles.disabled)}>
|
||||
<T>seconds</T>
|
||||
<span className={styles.idleDuration}>
|
||||
<NumberInput value={seconds} onChange={setSeconds} {...IDLE_LIMITS} integer aria-label="Idle seconds" />
|
||||
<span className={clsx(!on && styles.disabled)}>
|
||||
<T>seconds</T>
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FileSynchronizationRow() {
|
||||
const labelId = useId();
|
||||
return (
|
||||
<div className={styles.fileSynchronization} role="group" aria-labelledby={labelId}>
|
||||
<div id={labelId}>
|
||||
<SearchLabel text="Synchronization" />
|
||||
</div>
|
||||
<Indented>
|
||||
<BoundToggle k="files.syncOnFocus" label="Synchronize external changes when switching to the IDE window" />
|
||||
</Indented>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Date Formats
|
||||
|
||||
@@ -785,15 +790,19 @@ function DateFormatRows() {
|
||||
onChange={(v) => set({ overrideSystem: v })}
|
||||
/>
|
||||
<Indented>
|
||||
<Row label="Date format" htmlFor={id} hint="Placeholders: yyyy, yy, MMMM, MMM, MM, M, dd, d">
|
||||
<Row label="Date format" htmlFor={id} disabled={!f.overrideSystem}>
|
||||
<Input
|
||||
id={id}
|
||||
className={styles.patternInput}
|
||||
aria-describedby={`${id}-help`}
|
||||
mono
|
||||
disabled={!f.overrideSystem}
|
||||
value={f.pattern}
|
||||
onChange={(e) => e.target.value.trim() && set({ pattern: e.target.value })}
|
||||
/>
|
||||
<span id={`${id}-help`} className={styles.patternHint}>
|
||||
<T>Placeholders: yyyy, yy, MMMM, MMM, MM, M, dd, d</T>
|
||||
</span>
|
||||
</Row>
|
||||
<Toggle
|
||||
label="Use 24-hour time format"
|
||||
@@ -801,6 +810,11 @@ function DateFormatRows() {
|
||||
disabled={!f.overrideSystem}
|
||||
onChange={(v) => set({ use24Hour: v })}
|
||||
/>
|
||||
<Row label="Preview" htmlFor={`${id}-preview`}>
|
||||
<output id={`${id}-preview`} className={styles.preview}>
|
||||
{formatTimestamp(now - 2 * 3_600_000, now, f)} · {formatTimestamp(now - 3 * 86_400_000, now, f)}
|
||||
</output>
|
||||
</Row>
|
||||
</Indented>
|
||||
<Toggle
|
||||
label="Use pretty formatting"
|
||||
@@ -808,11 +822,6 @@ function DateFormatRows() {
|
||||
checked={f.pretty}
|
||||
onChange={(v) => set({ pretty: v })}
|
||||
/>
|
||||
<Row label="Preview">
|
||||
<span className={styles.preview}>
|
||||
{formatTimestamp(now - 2 * 3_600_000, now, f)} · {formatTimestamp(now - 3 * 86_400_000, now, f)}
|
||||
</span>
|
||||
</Row>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -919,6 +928,12 @@ export const BEHAVIOR_PAGES: PageSpec[] = [
|
||||
},
|
||||
{ kind: "custom", label: "Accent color", keywords: ["accent colour", "highlight"], component: AccentRow },
|
||||
{ kind: "custom", label: "Different tool window background", component: ToolWindowBackgroundRow },
|
||||
{
|
||||
kind: "custom",
|
||||
label: "Use custom font",
|
||||
keywords: ["UI font size", "Size", "font family", "fallback font"],
|
||||
component: CustomFontRow,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -936,12 +951,6 @@ export const BEHAVIOR_PAGES: PageSpec[] = [
|
||||
title: "Accessibility",
|
||||
options: [
|
||||
{ kind: "custom", label: "Zoom", keywords: ["scale", "zoom ide"], component: ZoomRow },
|
||||
{
|
||||
kind: "custom",
|
||||
label: "Use custom font",
|
||||
keywords: ["UI font size", "Size", "font family", "fallback font"],
|
||||
component: CustomFontRow,
|
||||
},
|
||||
{ kind: "toggle", key: "appearance.contrastScrollbars", label: "Use contrast scrollbars" },
|
||||
{
|
||||
kind: "toggle",
|
||||
@@ -1064,8 +1073,11 @@ export const BEHAVIOR_PAGES: PageSpec[] = [
|
||||
title: "System Settings",
|
||||
group: APPEARANCE_GROUP,
|
||||
order: 1,
|
||||
keywords: ["general", "startup", "exit", "quit", "autosave", "save", "local history", "welcome", "editor tabs"],
|
||||
keywords: ["general", "startup", "exit", "quit", "save", "local history", "welcome", "editor tabs"],
|
||||
sections: [
|
||||
{
|
||||
options: [{ kind: "toggle", key: "general.confirmExit", label: "Confirm before exiting the IDE" }],
|
||||
},
|
||||
{
|
||||
title: "Project",
|
||||
options: [
|
||||
@@ -1080,23 +1092,12 @@ export const BEHAVIOR_PAGES: PageSpec[] = [
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Caches",
|
||||
options: [
|
||||
{
|
||||
kind: "custom",
|
||||
label: "Local data directory",
|
||||
keywords: ["cache", "local data", "data directory", "C盘", "缓存", "目录"],
|
||||
component: LocalDataDirRow,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Autosave",
|
||||
title: "Files",
|
||||
options: [
|
||||
{
|
||||
kind: "custom",
|
||||
label: "Save files if the IDE is idle for",
|
||||
keywords: ["idle", "seconds"],
|
||||
keywords: ["Autosave", "idle", "seconds"],
|
||||
component: IdleSaveRow,
|
||||
},
|
||||
{
|
||||
@@ -1105,9 +1106,21 @@ export const BEHAVIOR_PAGES: PageSpec[] = [
|
||||
label: "Save files when switching to a different application or a built-in terminal",
|
||||
},
|
||||
{
|
||||
kind: "toggle",
|
||||
key: "files.syncOnFocus",
|
||||
label: "Synchronize external changes when switching to the IDE window",
|
||||
kind: "custom",
|
||||
label: "Synchronization",
|
||||
keywords: ["Synchronize external changes when switching to the IDE window"],
|
||||
component: FileSynchronizationRow,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Caches",
|
||||
options: [
|
||||
{
|
||||
kind: "custom",
|
||||
label: "Local data directory",
|
||||
keywords: ["cache", "local data", "data directory", "C盘", "缓存", "目录"],
|
||||
component: LocalDataDirRow,
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -1137,7 +1150,6 @@ export const BEHAVIOR_PAGES: PageSpec[] = [
|
||||
{
|
||||
title: "Exit",
|
||||
options: [
|
||||
{ kind: "toggle", key: "general.confirmExit", label: "Confirm before exiting the IDE" },
|
||||
{
|
||||
kind: "toggle",
|
||||
key: "general.closeWithoutWelcome",
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
.spelling .list {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.wordPanel:not([hidden]) {
|
||||
display: grid;
|
||||
gap: var(--space-1-5);
|
||||
padding-top: var(--space-1);
|
||||
}
|
||||
|
||||
.note {
|
||||
margin: 0;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
line-height: 1.4;
|
||||
}
|
||||
@@ -4,13 +4,15 @@
|
||||
* dictionaries, also filled by the "Save to dictionary" quick fix) and custom
|
||||
* dictionary files.
|
||||
*/
|
||||
import { useId, useState } from "react";
|
||||
import { useSettingsDialog } from "../../model/staging";
|
||||
import { useSetting } from "../../components/context";
|
||||
import { GlobListEditor, Row, Section } from "../../components/Form";
|
||||
import { GlobListEditor, Row, SearchLabel, Section } from "../../components/Form";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { T } from "@/ui";
|
||||
import { T, Tabs } from "@/ui";
|
||||
import type { PageSpec } from "../spec";
|
||||
import styles from "../../components/Form.module.css";
|
||||
import formStyles from "../../components/Form.module.css";
|
||||
import styles from "./Spelling.module.css";
|
||||
|
||||
function NaturalLanguagesPage() {
|
||||
return (
|
||||
@@ -19,7 +21,7 @@ function NaturalLanguagesPage() {
|
||||
label="English (USA, UK)"
|
||||
hint="Bundled Hunspell dictionaries (SCOWL en_US and en_GB) and common programming terms."
|
||||
>
|
||||
<span className={styles.hint}>
|
||||
<span className={formStyles.hint}>
|
||||
<T>Used by Proofreading › Typo</T>
|
||||
</span>
|
||||
</Row>
|
||||
@@ -29,38 +31,78 @@ function NaturalLanguagesPage() {
|
||||
|
||||
const words = (list: readonly string[]) => [...new Set(list.map((w) => w.trim()).filter(Boolean))];
|
||||
|
||||
function SpellingPage() {
|
||||
const wordDictionaries = [
|
||||
{ id: "project", label: "Project dictionary", hint: "Stored with the project." },
|
||||
{ id: "application", label: "Application dictionary", hint: "Accepted in every project." },
|
||||
];
|
||||
|
||||
function AcceptedWords() {
|
||||
const hasProject = useProject((s) => !!s.project);
|
||||
const newProjects = useSettingsDialog((s) => s.newProjects);
|
||||
const [projectWords, setProjectWords] = useSetting<string[]>("spelling.projectWords", "project");
|
||||
const [ideWords, setIdeWords] = useSetting<string[]>("spelling.ideWords", "global");
|
||||
const [dictionaries, setDictionaries] = useSetting<string[]>("spelling.customDictionaries", "global");
|
||||
const [scope, setScope] = useState("project");
|
||||
const id = useId();
|
||||
const showProject = hasProject && !newProjects;
|
||||
const scopes = showProject ? wordDictionaries : wordDictionaries.slice(1);
|
||||
const activeScope = showProject ? scope : "application";
|
||||
|
||||
return (
|
||||
<>
|
||||
<Section title="Accepted words">
|
||||
{hasProject && !newProjects && (
|
||||
<Row label="Project dictionary" stacked hint="Stored with the project.">
|
||||
<GlobListEditor
|
||||
aria-label="Project dictionary"
|
||||
value={projectWords ?? []}
|
||||
onChange={(v) => setProjectWords(words(v))}
|
||||
placeholder="word"
|
||||
emptyText="No words"
|
||||
itemLabel="Word"
|
||||
/>
|
||||
</Row>
|
||||
)}
|
||||
<Row label="Application dictionary" stacked hint="Accepted in every project.">
|
||||
<GlobListEditor
|
||||
aria-label="Application dictionary"
|
||||
value={ideWords ?? []}
|
||||
onChange={(v) => setIdeWords(words(v))}
|
||||
placeholder="word"
|
||||
emptyText="No words"
|
||||
itemLabel="Word"
|
||||
/>
|
||||
</Row>
|
||||
</Section>
|
||||
{showProject && (
|
||||
<Tabs
|
||||
items={wordDictionaries}
|
||||
activeId={activeScope}
|
||||
onSelect={setScope}
|
||||
variant="compact"
|
||||
layout="wrap"
|
||||
panelIdPrefix={id}
|
||||
aria-label="Accepted words"
|
||||
/>
|
||||
)}
|
||||
{scopes.map(({ id: scopeId, label, hint }) => {
|
||||
const isProject = scopeId === "project";
|
||||
const active = activeScope === scopeId;
|
||||
const value = isProject ? projectWords : ideWords;
|
||||
const setValue = isProject ? setProjectWords : setIdeWords;
|
||||
return (
|
||||
<div
|
||||
key={scopeId}
|
||||
id={`${id}-panel-${scopeId}`}
|
||||
role={showProject ? "tabpanel" : undefined}
|
||||
aria-labelledby={showProject ? `${id}-tab-${scopeId}` : undefined}
|
||||
hidden={!active}
|
||||
className={styles.wordPanel}
|
||||
>
|
||||
{active && (
|
||||
<>
|
||||
{!showProject && <SearchLabel text={label} />}
|
||||
<GlobListEditor
|
||||
className={styles.list}
|
||||
aria-label={label}
|
||||
value={value ?? []}
|
||||
onChange={(v) => setValue(words(v))}
|
||||
placeholder="word"
|
||||
emptyText="No words"
|
||||
itemLabel="Word"
|
||||
mono={false}
|
||||
/>
|
||||
<p className={styles.note}>
|
||||
<T>{hint}</T>
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SpellingPage() {
|
||||
const [dictionaries, setDictionaries] = useSetting<string[]>("spelling.customDictionaries", "global");
|
||||
return (
|
||||
<div className={styles.spelling}>
|
||||
<Section title="Custom dictionaries">
|
||||
<Row
|
||||
label="Dictionary files"
|
||||
@@ -68,6 +110,7 @@ function SpellingPage() {
|
||||
hint="Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder."
|
||||
>
|
||||
<GlobListEditor
|
||||
className={styles.list}
|
||||
aria-label="Custom dictionaries"
|
||||
value={dictionaries ?? []}
|
||||
onChange={(v) => setDictionaries(words(v))}
|
||||
@@ -77,7 +120,10 @@ function SpellingPage() {
|
||||
/>
|
||||
</Row>
|
||||
</Section>
|
||||
</>
|
||||
<Section title="Accepted words">
|
||||
<AcceptedWords />
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,14 +9,13 @@ import { useSettingsPageFocus } from "@/workbench/contributions";
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import type { SelectOption } from "@/ui";
|
||||
import { ColorSwatches, FormGroup, GlobListEditor, NumberInput, Row, Toggle } from "../components/Form";
|
||||
import { ColorSwatches, FormGroup, GlobListEditor, Row, SettingNumber, Toggle } from "../components/Form";
|
||||
import { usePageContext, useSetting } from "../components/context";
|
||||
import { useSettingsDialog } from "../model/staging";
|
||||
import { lazyPage } from "./lazyPage";
|
||||
import type { PageSpec } from "./spec";
|
||||
import { Indented, ToggleNumber } from "./workflowControls";
|
||||
import styles from "./Workflow.module.css";
|
||||
import { T } from "@/ui";
|
||||
import { ToggleNumber } from "./workflowControls";
|
||||
import dataViewStyles from "./DebuggerDataViews.module.css";
|
||||
|
||||
const CMakeProfiles = lazyPage("build.cmake", () => import("./cmake").then((m) => m.CMakeProfiles));
|
||||
const GradlePage = lazyPage("build.gradle", () => import("../languages/LanguagePages").then((m) => m.GradlePage));
|
||||
@@ -50,6 +49,7 @@ function BufferRow() {
|
||||
numberKey="console.bufferKb"
|
||||
label="Override console cycle buffer size"
|
||||
unit="KB"
|
||||
disableWhenOff
|
||||
hint="Older output is discarded"
|
||||
{...L.bufferKb}
|
||||
/>
|
||||
@@ -81,6 +81,7 @@ function FoldPatterns() {
|
||||
onChange={set}
|
||||
placeholder="at org.example."
|
||||
aria-label="Fold console lines that contain"
|
||||
fullWidth
|
||||
/>
|
||||
</Row>
|
||||
);
|
||||
@@ -134,27 +135,22 @@ function LogLevelRow({ level, label }: { level: (typeof LOG_LEVELS)[number]["lev
|
||||
);
|
||||
}
|
||||
|
||||
function TooltipDelayRow() {
|
||||
const [enabled] = useSetting<boolean>("debugger.valueTooltip");
|
||||
const [delay, setDelay] = useSetting<number>("debugger.valueTooltipDelay");
|
||||
const tooltipHint = "Hovering a variable while suspended evaluates it in the selected frame.";
|
||||
|
||||
function ValueTooltipRow() {
|
||||
const [enabled, setEnabled] = useSetting<boolean>("debugger.valueTooltip");
|
||||
return (
|
||||
<Indented>
|
||||
<Row label="Value tooltip delay (ms)">
|
||||
<NumberInput
|
||||
value={delay}
|
||||
onChange={setDelay}
|
||||
{...L.tooltipDelay}
|
||||
integer
|
||||
step={100}
|
||||
aria-label="Value tooltip delay (ms)"
|
||||
/>
|
||||
{!enabled && (
|
||||
<span className={styles.note}>
|
||||
<T>Value tooltips are off</T>
|
||||
</span>
|
||||
)}
|
||||
</Row>
|
||||
</Indented>
|
||||
<div className={dataViewStyles.hover}>
|
||||
<Toggle label="Show value tooltip on mouse hover" checked={enabled} onChange={setEnabled} hint={tooltipHint} />
|
||||
<SettingNumber
|
||||
k="debugger.valueTooltipDelay"
|
||||
label="Value tooltip delay (ms)"
|
||||
{...L.tooltipDelay}
|
||||
integer
|
||||
step={100}
|
||||
disabled={!enabled}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -275,6 +271,8 @@ export const EXECUTION_PAGES: PageSpec[] = [
|
||||
"Always update snapshots",
|
||||
"SNAPSHOT",
|
||||
"-U",
|
||||
"Importing",
|
||||
"Automatically download sources",
|
||||
],
|
||||
component: MavenPage,
|
||||
},
|
||||
@@ -288,8 +286,8 @@ export const EXECUTION_PAGES: PageSpec[] = [
|
||||
sections: [
|
||||
{
|
||||
options: [
|
||||
{ kind: "custom", label: "Override console cycle buffer size", keywords: ["KB"], component: BufferRow },
|
||||
{ kind: "toggle", key: "console.softWrap", label: "Use soft wraps in console" },
|
||||
{ kind: "custom", label: "Override console cycle buffer size", keywords: ["KB"], component: BufferRow },
|
||||
{
|
||||
kind: "select",
|
||||
key: "console.encoding",
|
||||
@@ -297,6 +295,11 @@ export const EXECUTION_PAGES: PageSpec[] = [
|
||||
options: CONSOLE_ENCODINGS,
|
||||
hint: "Encoding of the output of processes started from Run configurations.",
|
||||
},
|
||||
],
|
||||
},
|
||||
{ options: [{ kind: "custom", label: "Fold console lines that contain", component: FoldPatterns }] },
|
||||
{
|
||||
options: [
|
||||
{
|
||||
kind: "custom",
|
||||
label: "Colour log lines by level",
|
||||
@@ -305,7 +308,6 @@ export const EXECUTION_PAGES: PageSpec[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{ options: [{ kind: "custom", label: "Fold console lines that contain", component: FoldPatterns }] },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -372,12 +374,6 @@ export const EXECUTION_PAGES: PageSpec[] = [
|
||||
sections: [
|
||||
{
|
||||
options: [
|
||||
{
|
||||
kind: "toggle",
|
||||
key: "debugger.inlineValues",
|
||||
label: "Show values inline",
|
||||
hint: "Values of local variables are shown after the lines that use them while suspended.",
|
||||
},
|
||||
{ kind: "toggle", key: "debugger.sortValues", label: "Sort values alphabetically" },
|
||||
{
|
||||
kind: "toggle",
|
||||
@@ -385,14 +381,24 @@ export const EXECUTION_PAGES: PageSpec[] = [
|
||||
label: "Evaluate watches while the program runs",
|
||||
hint: "Where the debugger can do it without suspending (JavaScript). A watch with side effects runs again on each refresh.",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Editor",
|
||||
options: [
|
||||
{
|
||||
kind: "toggle",
|
||||
key: "debugger.valueTooltip",
|
||||
key: "debugger.inlineValues",
|
||||
label: "Show values inline",
|
||||
hint: "Values of local variables are shown after the lines that use them while suspended.",
|
||||
},
|
||||
{
|
||||
kind: "custom",
|
||||
label: "Show value tooltip on mouse hover",
|
||||
hint: "Hovering a variable while suspended evaluates it in the selected frame.",
|
||||
keywords: ["Value tooltip delay (ms)", tooltipHint],
|
||||
component: ValueTooltipRow,
|
||||
},
|
||||
{ kind: "toggle", key: "debugger.valueTooltipOnSelection", label: "Show value tooltip on code selection" },
|
||||
{ kind: "custom", label: "Value tooltip delay (ms)", component: TooltipDelayRow },
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
@@ -15,8 +15,8 @@ import {
|
||||
type ProxyModeValid,
|
||||
type ProxySettingsValid,
|
||||
} from "@/platform/proxySettings";
|
||||
import { Button, Checkbox, Input, Popup, T } from "@/ui";
|
||||
import { NumberInput, Row, SearchLabel } from "../components/Form";
|
||||
import { Button, Checkbox, Input, Popup, Radio, T } from "@/ui";
|
||||
import { FormGroup, NumberInput, Row, SearchLabel } from "../components/Form";
|
||||
import { usePageContext, useSetting } from "../components/context";
|
||||
import { stage } from "../model/staging";
|
||||
import type { PageSpec } from "./spec";
|
||||
@@ -47,27 +47,6 @@ function useProxy(): [ProxySettingsValid, (patch: Partial<ProxySettingsValid>) =
|
||||
return [proxy, update];
|
||||
}
|
||||
|
||||
function Radio({
|
||||
name,
|
||||
checked,
|
||||
onSelect,
|
||||
label,
|
||||
disabled,
|
||||
}: {
|
||||
name: string;
|
||||
checked: boolean;
|
||||
onSelect: () => void;
|
||||
label: string;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<label className={clsx(styles.radio, disabled && styles.disabled)}>
|
||||
<input type="radio" name={name} checked={checked} disabled={disabled} onChange={onSelect} />
|
||||
<SearchLabel text={label} />
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function ProxyOptions() {
|
||||
const [proxy, update] = useProxy();
|
||||
const name = useId();
|
||||
@@ -88,10 +67,11 @@ function ProxyOptions() {
|
||||
{MODES.map((m) => (
|
||||
<div key={m.value}>
|
||||
<Radio
|
||||
className={styles.radioRow}
|
||||
name={name}
|
||||
checked={proxy.mode === m.value}
|
||||
onSelect={() => update({ mode: m.value })}
|
||||
label={m.label}
|
||||
onChange={() => update({ mode: m.value })}
|
||||
label={<SearchLabel text={m.label} />}
|
||||
/>
|
||||
{m.hint && (
|
||||
<div className={styles.hint}>
|
||||
@@ -106,52 +86,50 @@ function ProxyOptions() {
|
||||
{KINDS.map((k) => (
|
||||
<Radio
|
||||
key={k.value}
|
||||
className={styles.radioRow}
|
||||
name={kindName}
|
||||
checked={proxy.kind === k.value}
|
||||
disabled={!manual}
|
||||
onSelect={() => update(withProxyKind(proxy, k.value))}
|
||||
label={k.label}
|
||||
onChange={() => update(withProxyKind(proxy, k.value))}
|
||||
label={<SearchLabel text={k.label} />}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className={styles.hostRow}>
|
||||
<FormGroup>
|
||||
<Row label="Host name" htmlFor={ids.host}>
|
||||
<Input
|
||||
id={ids.host}
|
||||
className={styles.host}
|
||||
className={styles.field}
|
||||
disabled={!manual}
|
||||
value={proxy.host}
|
||||
onChange={(e) => update({ host: e.target.value })}
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Port number" htmlFor={ids.port}>
|
||||
{manual ? (
|
||||
<NumberInput
|
||||
id={ids.port}
|
||||
value={proxy.port}
|
||||
onChange={(port) => update({ port })}
|
||||
{...PROXY_PORT_LIMITS}
|
||||
integer
|
||||
aria-label="Port number"
|
||||
/>
|
||||
) : (
|
||||
<Input id={ids.port} className={styles.port} value={String(proxy.port)} disabled readOnly />
|
||||
)}
|
||||
<NumberInput
|
||||
id={ids.port}
|
||||
value={proxy.port}
|
||||
onChange={(port) => update({ port })}
|
||||
{...PROXY_PORT_LIMITS}
|
||||
integer
|
||||
disabled={!manual}
|
||||
aria-label="Port number"
|
||||
/>
|
||||
</Row>
|
||||
</div>
|
||||
<Row
|
||||
label="No proxy for"
|
||||
htmlFor={ids.noProxy}
|
||||
hint="Comma-separated host names; * matches any characters, e.g. *.example.com, 192.168.*"
|
||||
>
|
||||
<Input
|
||||
id={ids.noProxy}
|
||||
className={styles.wide}
|
||||
disabled={!manual}
|
||||
value={proxy.noProxy}
|
||||
onChange={(e) => update({ noProxy: e.target.value })}
|
||||
/>
|
||||
</Row>
|
||||
<Row
|
||||
label="No proxy for"
|
||||
htmlFor={ids.noProxy}
|
||||
hint="Comma-separated host names; * matches any characters, e.g. *.example.com, 192.168.*"
|
||||
>
|
||||
<Input
|
||||
id={ids.noProxy}
|
||||
className={styles.field}
|
||||
disabled={!manual}
|
||||
value={proxy.noProxy}
|
||||
onChange={(e) => update({ noProxy: e.target.value })}
|
||||
/>
|
||||
</Row>
|
||||
</FormGroup>
|
||||
<div className={styles.toggle}>
|
||||
<Checkbox
|
||||
checked={proxy.authenticate}
|
||||
@@ -160,11 +138,11 @@ function ProxyOptions() {
|
||||
label={<SearchLabel text="Proxy authentication" />}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.auth}>
|
||||
<FormGroup indented>
|
||||
<Row label="Login" htmlFor={ids.login}>
|
||||
<Input
|
||||
id={ids.login}
|
||||
className={styles.host}
|
||||
className={styles.field}
|
||||
disabled={!auth}
|
||||
value={proxy.login}
|
||||
onChange={(e) => update({ login: e.target.value })}
|
||||
@@ -174,19 +152,19 @@ function ProxyOptions() {
|
||||
<Input
|
||||
id={ids.password}
|
||||
type="password"
|
||||
className={styles.host}
|
||||
className={styles.field}
|
||||
disabled={!auth}
|
||||
value={proxy.password}
|
||||
onChange={(e) => update({ password: e.target.value })}
|
||||
/>
|
||||
</Row>
|
||||
</div>
|
||||
{problem && (
|
||||
<div className={styles.error} role="alert">
|
||||
<T>{problem}</T>
|
||||
</div>
|
||||
)}
|
||||
</FormGroup>
|
||||
</div>
|
||||
{problem && (
|
||||
<div className={styles.error} role="alert">
|
||||
<T>{problem}</T>
|
||||
</div>
|
||||
)}
|
||||
<CheckConnection proxy={proxy} />
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -16,14 +16,15 @@ import {
|
||||
type ExternalToolValid,
|
||||
} from "@/platform/workflowSettings";
|
||||
import { Button, Checkbox, IconButton, Input, Menu, type SelectOption, T } from "@/ui";
|
||||
import { NumberInput, Row, SearchLabel, Section, Select, SettingSelect, Toggle } from "../components/Form";
|
||||
import { FormGroup, NumberInput, Row, SearchLabel, Section, Select, SettingSelect, Toggle } from "../components/Form";
|
||||
import { useLabelMatch, useSetting } from "../components/context";
|
||||
import { selectPage, setQuery } from "../model/staging";
|
||||
import { MirrorPrefixRow } from "./DownloadSources";
|
||||
import { MCP_SERVER_PAGE } from "./mcpServer";
|
||||
import type { PageSpec } from "./spec";
|
||||
import { BoundToggle, Grid, Indented, PageLink, TableEditor } from "./workflowControls";
|
||||
import { BoundToggle, Grid, PageLink, TableEditor } from "./workflowControls";
|
||||
import styles from "./Workflow.module.css";
|
||||
import terminalStyles from "./TerminalSettings.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { TERMINAL_MAX_FPS_OPTIONS } from "@/platform/workflowSettings";
|
||||
|
||||
@@ -62,29 +63,27 @@ const isMac = typeof navigator !== "undefined" && /Mac/i.test(navigator.platform
|
||||
// ---------------------------------------------------------------------------
|
||||
// Terminal
|
||||
|
||||
function TextSetting({
|
||||
function TerminalTextSetting({
|
||||
k,
|
||||
label,
|
||||
placeholder,
|
||||
hint,
|
||||
width = "wide",
|
||||
mono,
|
||||
}: {
|
||||
k: string;
|
||||
label: string;
|
||||
placeholder?: string;
|
||||
hint?: ReactNode;
|
||||
width?: "wide" | "medium";
|
||||
mono?: boolean;
|
||||
}) {
|
||||
const [value, set] = useSetting<string>(k);
|
||||
const id = useId();
|
||||
return (
|
||||
<Row label={label} htmlFor={id} hint={hint}>
|
||||
<Row label={label} htmlFor={id} hint={hint} className={terminalStyles.textRow}>
|
||||
<Input
|
||||
id={id}
|
||||
mono={mono}
|
||||
className={styles[width]}
|
||||
className={terminalStyles.field}
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => set(e.target.value)}
|
||||
@@ -95,7 +94,7 @@ function TextSetting({
|
||||
|
||||
function StartDirectoryRow() {
|
||||
return (
|
||||
<TextSetting
|
||||
<TerminalTextSetting
|
||||
k="terminal.startDirectory"
|
||||
label="Start directory"
|
||||
placeholder="Project root"
|
||||
@@ -148,25 +147,35 @@ function ShellPathRow() {
|
||||
label="Shell path"
|
||||
htmlFor={id}
|
||||
hint="A command line, e.g. /bin/zsh --login. Leave empty to use the login shell."
|
||||
className={terminalStyles.textRow}
|
||||
>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
className={styles.wide}
|
||||
value={value}
|
||||
placeholder={detected ?? "Login shell"}
|
||||
onChange={(e) => set(e.target.value)}
|
||||
/>
|
||||
<IconButton
|
||||
ref={menuRef}
|
||||
icon="chevron-down"
|
||||
size="small"
|
||||
title="Installed Shells"
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
disabled={shells.length === 0}
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
/>
|
||||
<div className={terminalStyles.shellControls}>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
value={value}
|
||||
placeholder={detected ?? "Login shell"}
|
||||
onChange={(e) => set(e.target.value)}
|
||||
/>
|
||||
<IconButton
|
||||
ref={menuRef}
|
||||
icon="chevron-down"
|
||||
size="small"
|
||||
title="Installed Shells"
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
disabled={shells.length === 0}
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
aria-label="Browse"
|
||||
disabled={!isTauri()}
|
||||
onClick={() => void browse()}
|
||||
/>
|
||||
</div>
|
||||
<Menu
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
@@ -175,14 +184,6 @@ function ShellPathRow() {
|
||||
aria-label="Installed shells"
|
||||
items={shells.map((p) => ({ id: p, label: p, checked: quotePath(p) === value, run: () => set(quotePath(p)) }))}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
aria-label="Browse"
|
||||
disabled={!isTauri()}
|
||||
onClick={() => void browse()}
|
||||
/>
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -225,41 +226,45 @@ function TerminalKeybindingsLink() {
|
||||
|
||||
function TerminalOptions() {
|
||||
return (
|
||||
<Grid
|
||||
left={
|
||||
<>
|
||||
<BoundToggle k="terminal.audibleBell" label="Audible bell" />
|
||||
<BoundToggle k="terminal.closeOnExit" label="Close session when it ends" />
|
||||
<BoundToggle k="terminal.mouseReporting" label="Mouse reporting" />
|
||||
<BoundToggle k="terminal.copyOnSelection" label="Copy to clipboard on selection" />
|
||||
<BoundToggle k="terminal.pasteOnMiddleClick" label="Paste on middle mouse button click" />
|
||||
<BoundToggle
|
||||
k="terminal.escapeToEditor"
|
||||
label="Move focus to the Editor with Escape"
|
||||
hint="Otherwise Escape goes to the shell."
|
||||
/>
|
||||
</>
|
||||
}
|
||||
right={
|
||||
<>
|
||||
<BoundToggle
|
||||
k="terminal.overrideIdeShortcuts"
|
||||
label="Override IDE shortcuts"
|
||||
hint={<TerminalKeybindingsLink />}
|
||||
/>
|
||||
<BoundToggle k="terminal.shellIntegration" label="Shell integration" />
|
||||
<BoundToggle k="terminal.highlightHyperlinks" label="Highlight hyperlinks" />
|
||||
<BoundToggle k="terminal.highlightSelection" label="Highlight occurrences of selected text" />
|
||||
{isMac && <BoundToggle k="terminal.optionAsMeta" label="Use Option as Meta key" />}
|
||||
<SettingSelect
|
||||
k="terminal.maxFps"
|
||||
label="Maximum refresh rate"
|
||||
hint="Caps how often fast terminal output is painted. Hidden windows always paint more slowly."
|
||||
options={TERMINAL_MAX_FPS_OPTIONS}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<>
|
||||
<div className={terminalStyles.options}>
|
||||
<Grid
|
||||
left={
|
||||
<>
|
||||
<BoundToggle k="terminal.audibleBell" label="Audible bell" />
|
||||
<BoundToggle k="terminal.closeOnExit" label="Close session when it ends" />
|
||||
<BoundToggle k="terminal.mouseReporting" label="Mouse reporting" />
|
||||
<BoundToggle k="terminal.copyOnSelection" label="Copy to clipboard on selection" />
|
||||
<BoundToggle k="terminal.pasteOnMiddleClick" label="Paste on middle mouse button click" />
|
||||
<BoundToggle
|
||||
k="terminal.escapeToEditor"
|
||||
label="Move focus to the Editor with Escape"
|
||||
hint="Otherwise Escape goes to the shell."
|
||||
/>
|
||||
</>
|
||||
}
|
||||
right={
|
||||
<>
|
||||
<BoundToggle
|
||||
k="terminal.overrideIdeShortcuts"
|
||||
label="Override IDE shortcuts"
|
||||
hint={<TerminalKeybindingsLink />}
|
||||
/>
|
||||
<BoundToggle k="terminal.shellIntegration" label="Shell integration" />
|
||||
<BoundToggle k="terminal.highlightHyperlinks" label="Highlight hyperlinks" />
|
||||
<BoundToggle k="terminal.highlightSelection" label="Highlight occurrences of selected text" />
|
||||
{isMac && <BoundToggle k="terminal.optionAsMeta" label="Use Option as Meta key" />}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<SettingSelect
|
||||
k="terminal.maxFps"
|
||||
label="Maximum refresh rate"
|
||||
hint="Caps how often fast terminal output is painted. Hidden windows always paint more slowly."
|
||||
options={TERMINAL_MAX_FPS_OPTIONS}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -285,9 +290,9 @@ function TerminalFont() {
|
||||
</PageLink>
|
||||
</span>
|
||||
</div>
|
||||
<Indented>
|
||||
<Row label="Font">
|
||||
<span className={styles.fontFamily}>
|
||||
<div className={terminalStyles.families}>
|
||||
<Row label="Font" stacked>
|
||||
<span className={terminalStyles.fontPicker}>
|
||||
<FontPicker
|
||||
value={family}
|
||||
onChange={setFamily}
|
||||
@@ -305,6 +310,11 @@ function TerminalFont() {
|
||||
</span>
|
||||
</span>
|
||||
</Row>
|
||||
<Row label="Fallback font" stacked hint="Used for characters the main font lacks.">
|
||||
<FontPicker value={fallback} onChange={setFallback} allowEmpty label="Terminal fallback font" />
|
||||
</Row>
|
||||
</div>
|
||||
<div className={terminalStyles.metrics}>
|
||||
<Row label="Size">
|
||||
<NumberInput
|
||||
value={size}
|
||||
@@ -315,28 +325,25 @@ function TerminalFont() {
|
||||
aria-label="Terminal font size"
|
||||
/>
|
||||
</Row>
|
||||
</Indented>
|
||||
<Row label="Line height">
|
||||
<NumberInput
|
||||
value={lineHeight}
|
||||
onChange={setLineHeight}
|
||||
{...L.terminalLineHeight}
|
||||
step={0.1}
|
||||
aria-label="Terminal line height"
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Fallback font" hint="Used for characters the main font lacks.">
|
||||
<FontPicker value={fallback} onChange={setFallback} allowEmpty label="Terminal fallback font" />
|
||||
</Row>
|
||||
<Row label="Column width">
|
||||
<NumberInput
|
||||
value={columnWidth}
|
||||
onChange={setColumnWidth}
|
||||
{...L.terminalColumnWidth}
|
||||
step={0.1}
|
||||
aria-label="Terminal column width"
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Line height">
|
||||
<NumberInput
|
||||
value={lineHeight}
|
||||
onChange={setLineHeight}
|
||||
{...L.terminalLineHeight}
|
||||
step={0.1}
|
||||
aria-label="Terminal line height"
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Column width">
|
||||
<NumberInput
|
||||
value={columnWidth}
|
||||
onChange={setColumnWidth}
|
||||
{...L.terminalColumnWidth}
|
||||
step={0.1}
|
||||
aria-label="Terminal column width"
|
||||
/>
|
||||
</Row>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -451,21 +458,22 @@ function ToolField({
|
||||
onChange,
|
||||
macros,
|
||||
placeholder,
|
||||
className,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
macros?: boolean;
|
||||
placeholder?: string;
|
||||
className?: string;
|
||||
}) {
|
||||
const id = useId();
|
||||
return (
|
||||
<Row label={label} htmlFor={id} className={styles.alignedRow}>
|
||||
<span className={styles.macroField}>
|
||||
<Row label={label} htmlFor={id} className={className}>
|
||||
<span className={styles.toolField}>
|
||||
<Input
|
||||
id={id}
|
||||
mono={macros}
|
||||
className={styles.wide}
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
@@ -486,6 +494,9 @@ function ExternalToolsEditor() {
|
||||
const [selected, setSelected] = useState<string | null>(tools[0]?.id ?? null);
|
||||
const current = tools.find((t) => t.id === selected) ?? null;
|
||||
const index = current ? tools.indexOf(current) : -1;
|
||||
const advancedMatch = useLabelMatch("Advanced options");
|
||||
const synchronizeMatch = useLabelMatch("Synchronize files after execution");
|
||||
const consoleMatch = useLabelMatch("Open console for tool output");
|
||||
|
||||
const update = (patch: Partial<ExternalToolValid>) => {
|
||||
if (!current) return;
|
||||
@@ -564,50 +575,62 @@ function ExternalToolsEditor() {
|
||||
</div>
|
||||
</div>
|
||||
{current && (
|
||||
<Section title="Tool Settings">
|
||||
<ToolField label="Name" value={current.name} onChange={(name) => update({ name })} />
|
||||
<ToolField
|
||||
label="Group"
|
||||
value={current.group}
|
||||
onChange={(group) => update({ group })}
|
||||
placeholder="External Tools"
|
||||
/>
|
||||
<ToolField
|
||||
label="Description"
|
||||
value={current.description}
|
||||
onChange={(description) => update({ description })}
|
||||
/>
|
||||
<ToolField
|
||||
label="Program"
|
||||
value={current.program}
|
||||
onChange={(program) => update({ program })}
|
||||
macros
|
||||
placeholder="e.g. /usr/bin/env"
|
||||
/>
|
||||
<ToolField
|
||||
label="Arguments"
|
||||
value={current.arguments}
|
||||
onChange={(args) => update({ arguments: args })}
|
||||
macros
|
||||
/>
|
||||
<ToolField
|
||||
label="Working directory"
|
||||
value={current.workingDirectory}
|
||||
onChange={(workingDirectory) => update({ workingDirectory })}
|
||||
macros
|
||||
placeholder="$ProjectFileDir$"
|
||||
/>
|
||||
<Checkbox
|
||||
checked={current.synchronizeAfter}
|
||||
onChange={(synchronizeAfter) => update({ synchronizeAfter })}
|
||||
label="Synchronize files after execution"
|
||||
/>
|
||||
<Checkbox
|
||||
checked={current.openConsole}
|
||||
onChange={(openConsole) => update({ openConsole })}
|
||||
label="Open console for tool output"
|
||||
/>
|
||||
</Section>
|
||||
<>
|
||||
<div className={styles.toolIdentity}>
|
||||
<ToolField label="Name" value={current.name} onChange={(name) => update({ name })} />
|
||||
<ToolField
|
||||
label="Group"
|
||||
value={current.group}
|
||||
onChange={(group) => update({ group })}
|
||||
placeholder="External Tools"
|
||||
/>
|
||||
<ToolField
|
||||
label="Description"
|
||||
value={current.description}
|
||||
onChange={(description) => update({ description })}
|
||||
className={styles.toolDescription}
|
||||
/>
|
||||
</div>
|
||||
<Section title="Tool Settings">
|
||||
<ToolField
|
||||
label="Program"
|
||||
value={current.program}
|
||||
onChange={(program) => update({ program })}
|
||||
macros
|
||||
placeholder="e.g. /usr/bin/env"
|
||||
/>
|
||||
<ToolField
|
||||
label="Arguments"
|
||||
value={current.arguments}
|
||||
onChange={(args) => update({ arguments: args })}
|
||||
macros
|
||||
/>
|
||||
<ToolField
|
||||
label="Working directory"
|
||||
value={current.workingDirectory}
|
||||
onChange={(workingDirectory) => update({ workingDirectory })}
|
||||
macros
|
||||
placeholder="$ProjectFileDir$"
|
||||
/>
|
||||
</Section>
|
||||
<details className={styles.toolOptions} open={advancedMatch || synchronizeMatch || consoleMatch || undefined}>
|
||||
<summary>
|
||||
<SearchLabel text="Advanced options" />
|
||||
</summary>
|
||||
<FormGroup indented>
|
||||
<Toggle
|
||||
checked={current.synchronizeAfter}
|
||||
onChange={(synchronizeAfter) => update({ synchronizeAfter })}
|
||||
label="Synchronize files after execution"
|
||||
/>
|
||||
<Toggle
|
||||
checked={current.openConsole}
|
||||
onChange={(openConsole) => update({ openConsole })}
|
||||
label="Open console for tool output"
|
||||
/>
|
||||
</FormGroup>
|
||||
</details>
|
||||
</>
|
||||
)}
|
||||
<div className={styles.note}>
|
||||
<T>
|
||||
@@ -636,11 +659,26 @@ export const TOOLS_PAGES: PageSpec[] = [
|
||||
{ kind: "custom", label: "Environment variables", keywords: ["env"], component: EnvRow },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Font",
|
||||
options: [
|
||||
{
|
||||
kind: "custom",
|
||||
label: "Use editor font",
|
||||
keywords: ["Font", "Show only monospaced fonts", "Size", "Line height", "Fallback font", "Column width"],
|
||||
component: TerminalFont,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Application Settings",
|
||||
options: [
|
||||
{ kind: "custom", label: "Shell path", component: ShellPathRow },
|
||||
{ kind: "text", key: "terminal.tabName", label: "Default Tab name", placeholder: "Local" },
|
||||
{
|
||||
kind: "custom",
|
||||
label: "Default Tab name",
|
||||
component: () => <TerminalTextSetting k="terminal.tabName" label="Default Tab name" placeholder="Local" />,
|
||||
},
|
||||
{
|
||||
kind: "select",
|
||||
key: "terminal.appTitleAsTabName",
|
||||
@@ -673,17 +711,6 @@ export const TOOLS_PAGES: PageSpec[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Font",
|
||||
options: [
|
||||
{
|
||||
kind: "custom",
|
||||
label: "Use editor font",
|
||||
keywords: ["Font", "Show only monospaced fonts", "Size", "Line height", "Fallback font", "Column width"],
|
||||
component: TerminalFont,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -850,7 +877,9 @@ export const TOOLS_PAGES: PageSpec[] = [
|
||||
"Arguments",
|
||||
"Working directory",
|
||||
"Insert Macro",
|
||||
"Advanced options",
|
||||
"Synchronize files after execution",
|
||||
"Open console for tool output",
|
||||
],
|
||||
component: ExternalToolsEditor,
|
||||
},
|
||||
|
||||
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача