mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-23 08:49:33 -10:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7540ef29b7 | ||
|
|
706ce87cb7 | ||
|
|
4e5dbc8e0c | ||
|
|
79accd1311 | ||
|
|
85d02e03f9 | ||
|
|
e689c95e93 | ||
|
|
bb243909bf | ||
|
|
64544a4edd | ||
|
|
4fd1e4356e | ||
|
|
1794cd4fbb |
No files matched your search
+436
-49
@@ -399,163 +399,429 @@ pub fn apply_save_json(
|
||||
Ok(saved_names)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
|
||||
".github/plugin/plugin.json",
|
||||
".plugin/plugin.json",
|
||||
".claude-plugin/plugin.json",
|
||||
".cursor-plugin/plugin.json",
|
||||
"plugin.json",
|
||||
];
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
enum SourceFormat {
|
||||
Jsonc,
|
||||
CodexToml,
|
||||
CopilotPlugin { root: PathBuf },
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct SourceSpec {
|
||||
id: &'static str,
|
||||
label: &'static str,
|
||||
id: String,
|
||||
label: String,
|
||||
path: PathBuf,
|
||||
format: SourceFormat,
|
||||
suggested_scope: McpScope,
|
||||
native_provider: Option<&'static str>,
|
||||
claude_project_lookup: bool,
|
||||
disabled_servers: std::sync::Arc<BTreeSet<String>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct CopilotSettings {
|
||||
disabled_mcp_servers: std::sync::Arc<BTreeSet<String>>,
|
||||
disabled_plugins: BTreeSet<String>,
|
||||
}
|
||||
|
||||
fn external_source_specs(home_dir: Option<&Path>, workspace_root: Option<&Path>) -> Vec<SourceSpec> {
|
||||
let mut specs = Vec::new();
|
||||
let no_disabled: std::sync::Arc<BTreeSet<String>> = std::sync::Arc::new(BTreeSet::new());
|
||||
if let Some(root) = workspace_root {
|
||||
specs.push(SourceSpec {
|
||||
id: "workspace-mcp",
|
||||
label: "Project (.mcp.json)",
|
||||
id: "workspace-mcp".into(),
|
||||
label: "Project (.mcp.json)".into(),
|
||||
path: root.join(".mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("claude"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "vscode-mcp",
|
||||
label: "VS Code (.vscode/mcp.json)",
|
||||
id: "vscode-mcp".into(),
|
||||
label: "VS Code (.vscode/mcp.json)".into(),
|
||||
path: root.join(".vscode").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: None,
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "cursor-project",
|
||||
label: "Cursor Project (.cursor/mcp.json)",
|
||||
id: "cursor-project".into(),
|
||||
label: "Cursor Project (.cursor/mcp.json)".into(),
|
||||
path: root.join(".cursor").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("cursor"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "codex-project",
|
||||
label: "Codex Project (.codex/config.toml)",
|
||||
id: "codex-project".into(),
|
||||
label: "Codex Project (.codex/config.toml)".into(),
|
||||
path: root.join(".codex").join("config.toml"),
|
||||
format: SourceFormat::CodexToml,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("codex"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "gemini-project",
|
||||
label: "Gemini Project (.gemini/settings.json)",
|
||||
id: "gemini-project".into(),
|
||||
label: "Gemini Project (.gemini/settings.json)".into(),
|
||||
path: root.join(".gemini").join("settings.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("gemini"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
}
|
||||
if let Some(home) = home_dir {
|
||||
let copilot_dir = home.join(".copilot");
|
||||
let copilot_settings = read_copilot_settings(&copilot_dir);
|
||||
specs.push(SourceSpec {
|
||||
id: "copilot-cli",
|
||||
label: "GitHub Copilot CLI",
|
||||
path: home.join(".copilot").join("mcp-config.json"),
|
||||
id: "copilot-cli".into(),
|
||||
label: "GitHub Copilot CLI".into(),
|
||||
path: copilot_dir.join("mcp-config.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("copilot"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: copilot_settings.disabled_mcp_servers.clone(),
|
||||
});
|
||||
specs.extend(copilot_plugin_source_specs(&copilot_dir, &copilot_settings));
|
||||
specs.push(SourceSpec {
|
||||
id: "claude-code",
|
||||
label: "Claude Code",
|
||||
id: "claude-code".into(),
|
||||
label: "Claude Code".into(),
|
||||
path: home.join(".claude.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("claude"),
|
||||
claude_project_lookup: true,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "codex",
|
||||
label: "Codex",
|
||||
id: "codex".into(),
|
||||
label: "Codex".into(),
|
||||
path: home.join(".codex").join("config.toml"),
|
||||
format: SourceFormat::CodexToml,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("codex"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "cursor",
|
||||
label: "Cursor",
|
||||
id: "cursor".into(),
|
||||
label: "Cursor".into(),
|
||||
path: home.join(".cursor").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("cursor"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "gemini",
|
||||
label: "Gemini CLI",
|
||||
id: "gemini".into(),
|
||||
label: "Gemini CLI".into(),
|
||||
path: home.join(".gemini").join("settings.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("gemini"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "jetbrains-air",
|
||||
label: "JetBrains Air",
|
||||
id: "jetbrains-air".into(),
|
||||
label: "JetBrains Air".into(),
|
||||
path: home.join(".jetbrains").join("mcp").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: None,
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "copilot-intellij",
|
||||
label: "GitHub Copilot (JetBrains)",
|
||||
id: "copilot-intellij".into(),
|
||||
label: "GitHub Copilot (JetBrains)".into(),
|
||||
path: home.join(".config").join("github-copilot").join("intellij").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: None,
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled,
|
||||
});
|
||||
}
|
||||
specs
|
||||
}
|
||||
|
||||
fn read_source_servers(spec: &SourceSpec, workspace_root: Option<&Path>) -> BTreeMap<String, AgentMcpServer> {
|
||||
let Ok(text) = std::fs::read_to_string(&spec.path) else {
|
||||
return BTreeMap::new();
|
||||
fn read_copilot_settings(copilot_dir: &Path) -> CopilotSettings {
|
||||
let Ok(text) = std::fs::read_to_string(copilot_dir.join("settings.json")) else {
|
||||
return CopilotSettings::default();
|
||||
};
|
||||
if spec.format == SourceFormat::CodexToml {
|
||||
return parse_codex_toml_servers(&text);
|
||||
}
|
||||
let Ok(root) = parse_jsonc_value(&text) else {
|
||||
return BTreeMap::new();
|
||||
return CopilotSettings::default();
|
||||
};
|
||||
let mut servers = extract_servers_from_root(&root, None);
|
||||
if spec.claude_project_lookup
|
||||
&& let Some(ws) = workspace_root
|
||||
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
|
||||
{
|
||||
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
|
||||
for (proj_key, proj_val) in projects {
|
||||
let matches = Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
|
||||
if matches {
|
||||
for (name, srv) in extract_servers_from_root(proj_val, None) {
|
||||
servers.insert(name, srv);
|
||||
let disabled_mcp_servers = root
|
||||
.get("disabledMcpServers")
|
||||
.and_then(Value::as_array)
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|v| v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned))
|
||||
.collect::<BTreeSet<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let disabled_plugins = root
|
||||
.get("enabledPlugins")
|
||||
.and_then(Value::as_object)
|
||||
.map(|obj| {
|
||||
obj.iter()
|
||||
.filter(|(_, v)| v.as_bool() == Some(false))
|
||||
.map(|(k, _)| k.trim().to_owned())
|
||||
.filter(|k| !k.is_empty())
|
||||
.collect::<BTreeSet<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
CopilotSettings { disabled_mcp_servers: std::sync::Arc::new(disabled_mcp_servers), disabled_plugins }
|
||||
}
|
||||
|
||||
fn copilot_plugin_source_specs(copilot_dir: &Path, settings: &CopilotSettings) -> Vec<SourceSpec> {
|
||||
let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json")) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(root) = parse_jsonc_value(&text) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(installed) = root.get("installedPlugins").and_then(Value::as_array) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut seen_ids = HashSet::new();
|
||||
let mut specs = Vec::new();
|
||||
for entry in installed {
|
||||
let Some(obj) = entry.as_object() else { continue };
|
||||
if obj.get("enabled").and_then(Value::as_bool) == Some(false) {
|
||||
continue;
|
||||
}
|
||||
let Some(name) = obj.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
let marketplace = obj.get("marketplace").and_then(Value::as_str).map(str::trim).unwrap_or_default();
|
||||
if settings.disabled_plugins.contains(name)
|
||||
|| (!marketplace.is_empty()
|
||||
&& (settings.disabled_plugins.contains(&format!("{name}@{marketplace}"))
|
||||
|| settings.disabled_plugins.contains(&format!("{marketplace}/{name}"))))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(raw_cache) = obj.get("cache_path").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let plugin_root =
|
||||
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
|
||||
if !plugin_root.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let Some((manifest_path, _)) = read_copilot_plugin_servers(&plugin_root) else {
|
||||
continue;
|
||||
};
|
||||
let base_id = if marketplace.is_empty() {
|
||||
format!("copilot-plugin:{name}")
|
||||
} else {
|
||||
format!("copilot-plugin:{marketplace}/{name}")
|
||||
};
|
||||
let mut id = base_id.clone();
|
||||
let mut suffix = 2usize;
|
||||
while !seen_ids.insert(id.clone()) {
|
||||
id = format!("{base_id}#{suffix}");
|
||||
suffix += 1;
|
||||
}
|
||||
let label = if marketplace.is_empty() {
|
||||
format!("GitHub Copilot Plugin ({name})")
|
||||
} else {
|
||||
format!("GitHub Copilot Plugin ({name} · {marketplace})")
|
||||
};
|
||||
specs.push(SourceSpec {
|
||||
id,
|
||||
label,
|
||||
path: manifest_path,
|
||||
format: SourceFormat::CopilotPlugin { root: plugin_root },
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("copilot"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: settings.disabled_mcp_servers.clone(),
|
||||
});
|
||||
}
|
||||
specs
|
||||
}
|
||||
|
||||
fn resolve_within_dir(base_dir: &Path, candidate: &Path) -> Option<PathBuf> {
|
||||
if candidate.as_os_str().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let base_canon = dunce::canonicalize(base_dir).ok()?;
|
||||
let clean = candidate.strip_prefix(".").unwrap_or(candidate);
|
||||
let joined = if clean.is_relative() { base_dir.join(clean) } else { clean.to_path_buf() };
|
||||
let meta = std::fs::metadata(&joined).ok()?;
|
||||
if !meta.is_file() {
|
||||
return None;
|
||||
}
|
||||
let target_canon = dunce::canonicalize(&joined).ok()?;
|
||||
target_canon.starts_with(&base_canon).then_some(joined)
|
||||
}
|
||||
|
||||
fn expand_plugin_root_vars(value: &str, root: &str) -> String {
|
||||
value.replace("${COPILOT_PLUGIN_ROOT}", root).replace("${CLAUDE_PLUGIN_ROOT}", root).replace("${PLUGIN_ROOT}", root)
|
||||
}
|
||||
|
||||
fn expand_plugin_servers(servers: &mut BTreeMap<String, AgentMcpServer>, plugin_root: &Path) {
|
||||
let root = plugin_root.to_string_lossy();
|
||||
for srv in servers.values_mut() {
|
||||
if let Some(cmd) = srv.command.as_mut() {
|
||||
*cmd = expand_plugin_root_vars(cmd, &root);
|
||||
}
|
||||
for arg in &mut srv.args {
|
||||
*arg = expand_plugin_root_vars(arg, &root);
|
||||
}
|
||||
if let Some(url) = srv.url.as_mut() {
|
||||
*url = expand_plugin_root_vars(url, &root);
|
||||
}
|
||||
for val in srv.env.values_mut() {
|
||||
*val = expand_plugin_root_vars(val, &root);
|
||||
}
|
||||
for val in srv.headers.values_mut() {
|
||||
*val = expand_plugin_root_vars(val, &root);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_plugin_manifest_servers(
|
||||
plugin_root: &Path,
|
||||
manifest_path: &Path,
|
||||
mcp_val: &Value,
|
||||
) -> (PathBuf, BTreeMap<String, AgentMcpServer>) {
|
||||
match mcp_val {
|
||||
Value::String(rel) => {
|
||||
if let Some(path) = resolve_within_dir(plugin_root, Path::new(rel.trim())) {
|
||||
let map = read_external_file(&path);
|
||||
return (path, map);
|
||||
}
|
||||
(manifest_path.to_path_buf(), BTreeMap::new())
|
||||
}
|
||||
Value::Object(_) => {
|
||||
let wrapper = json!({ "mcpServers": mcp_val });
|
||||
(manifest_path.to_path_buf(), extract_servers_from_root(&wrapper, None))
|
||||
}
|
||||
Value::Array(items) => {
|
||||
let mut merged = BTreeMap::new();
|
||||
let mut first_path: Option<PathBuf> = None;
|
||||
for item in items {
|
||||
match item {
|
||||
Value::String(rel) => {
|
||||
if let Some(path) = resolve_within_dir(plugin_root, Path::new(rel.trim())) {
|
||||
let map = read_external_file(&path);
|
||||
if !map.is_empty() && first_path.is_none() {
|
||||
first_path = Some(path);
|
||||
}
|
||||
merged.extend(map);
|
||||
}
|
||||
}
|
||||
Value::Object(_) => {
|
||||
let map = extract_servers_from_root(item, None);
|
||||
if !map.is_empty() && first_path.is_none() {
|
||||
first_path = Some(manifest_path.to_path_buf());
|
||||
}
|
||||
merged.extend(map);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(first_path.unwrap_or_else(|| manifest_path.to_path_buf()), merged)
|
||||
}
|
||||
_ => (manifest_path.to_path_buf(), BTreeMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_copilot_plugin_servers(plugin_root: &Path) -> Option<(PathBuf, BTreeMap<String, AgentMcpServer>)> {
|
||||
if let Some(dot_mcp) = resolve_within_dir(plugin_root, Path::new(".mcp.json")) {
|
||||
let mut servers = read_external_file(&dot_mcp);
|
||||
if !servers.is_empty() {
|
||||
expand_plugin_servers(&mut servers, plugin_root);
|
||||
return Some((dot_mcp, servers));
|
||||
}
|
||||
}
|
||||
for rel in COPILOT_PLUGIN_MANIFESTS {
|
||||
let Some(manifest_path) = resolve_within_dir(plugin_root, Path::new(rel)) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(text) = std::fs::read_to_string(&manifest_path) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(manifest) = parse_jsonc_value(&text) else {
|
||||
continue;
|
||||
};
|
||||
let Some(mcp_val) = manifest.get("mcpServers") else {
|
||||
continue;
|
||||
};
|
||||
let (source_path, mut servers) = extract_plugin_manifest_servers(plugin_root, &manifest_path, mcp_val);
|
||||
if !servers.is_empty() {
|
||||
expand_plugin_servers(&mut servers, plugin_root);
|
||||
return Some((source_path, servers));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn read_source_servers(spec: &SourceSpec, workspace_root: Option<&Path>) -> BTreeMap<String, AgentMcpServer> {
|
||||
let mut servers = match &spec.format {
|
||||
SourceFormat::CopilotPlugin { root } => {
|
||||
read_copilot_plugin_servers(root).map(|(_, map)| map).unwrap_or_default()
|
||||
}
|
||||
SourceFormat::CodexToml => {
|
||||
let Ok(text) = std::fs::read_to_string(&spec.path) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
parse_codex_toml_servers(&text)
|
||||
}
|
||||
SourceFormat::Jsonc => {
|
||||
let Ok(text) = std::fs::read_to_string(&spec.path) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let Ok(root) = parse_jsonc_value(&text) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let mut map = extract_servers_from_root(&root, None);
|
||||
if spec.claude_project_lookup
|
||||
&& let Some(ws) = workspace_root
|
||||
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
|
||||
{
|
||||
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
|
||||
for (proj_key, proj_val) in projects {
|
||||
let matches =
|
||||
Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
|
||||
if matches {
|
||||
for (name, srv) in extract_servers_from_root(proj_val, None) {
|
||||
map.insert(name, srv);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
map
|
||||
}
|
||||
};
|
||||
for name in spec.disabled_servers.iter() {
|
||||
if let Some(srv) = servers.get_mut(name) {
|
||||
srv.enabled = false;
|
||||
}
|
||||
}
|
||||
servers
|
||||
@@ -612,8 +878,8 @@ pub fn discover_external_sources(home_dir: Option<&Path>, workspace_root: Option
|
||||
})
|
||||
.collect();
|
||||
out.push(McpExternalSource {
|
||||
id: spec.id.to_owned(),
|
||||
label: spec.label.to_owned(),
|
||||
id: spec.id,
|
||||
label: spec.label,
|
||||
path: IpcPath(spec.path),
|
||||
suggested_scope: spec.suggested_scope,
|
||||
native_provider: spec.native_provider.map(str::to_owned),
|
||||
@@ -641,7 +907,7 @@ pub fn apply_import_selected(
|
||||
let mut by_source: BTreeMap<&str, BTreeMap<String, AgentMcpServer>> = BTreeMap::new();
|
||||
for spec in &specs {
|
||||
if selections.iter().any(|s| s.source_id == spec.id) {
|
||||
by_source.insert(spec.id, read_source_servers(spec, workspace_root));
|
||||
by_source.insert(spec.id.as_str(), read_source_servers(spec, workspace_root));
|
||||
}
|
||||
}
|
||||
let target = match scope {
|
||||
@@ -1370,4 +1636,125 @@ mod tests {
|
||||
assert_eq!(workspace["events-sse"].transport, McpTransport::Sse);
|
||||
assert_eq!(workspace["events-sse"].url.as_deref(), Some("https://sse.example.com/events"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovers_and_imports_copilot_installed_plugin_mcp_servers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("home");
|
||||
let copilot = home.join(".copilot");
|
||||
let azure_root = copilot.join("installed-plugins/_direct/azure-skills");
|
||||
let inline_root = copilot.join("installed-plugins/awesome-copilot/inline-tools");
|
||||
let disabled_root = copilot.join("installed-plugins/_direct/disabled-plug");
|
||||
let outside_root = tmp.path().join("outside");
|
||||
|
||||
std::fs::create_dir_all(azure_root.join(".plugin")).unwrap();
|
||||
std::fs::create_dir_all(inline_root.join(".claude-plugin")).unwrap();
|
||||
std::fs::create_dir_all(&disabled_root).unwrap();
|
||||
std::fs::create_dir_all(&outside_root).unwrap();
|
||||
|
||||
std::fs::write(
|
||||
azure_root.join(".plugin/plugin.json"),
|
||||
r#"{"name":"azure","version":"1.2.106","mcpServers":"./.mcp.json"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
azure_root.join(".mcp.json"),
|
||||
r#"{"mcpServers":{"azure":{"command":"npx","args":["-y","@azure/mcp@latest","${COPILOT_PLUGIN_ROOT}/cfg"],"env":{"PLUG_DIR":"${CLAUDE_PLUGIN_ROOT}"}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
std::fs::write(
|
||||
inline_root.join(".claude-plugin/plugin.json"),
|
||||
r#"{"name":"inline-tools","version":"0.1.0","mcpServers":{"inline-srv":{"command":"${PLUGIN_ROOT}/bin/run","args":["--stdio"]},"muted-srv":{"command":"echo","args":["off"]}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
std::fs::write(
|
||||
disabled_root.join(".mcp.json"),
|
||||
r#"{"mcpServers":{"never":{"command":"npx","args":["never"]}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
std::fs::write(outside_root.join("secret.json"), r#"{"mcpServers":{"escaped":{"command":"sh"}}}"#).unwrap();
|
||||
let escape_root = copilot.join("installed-plugins/_direct/escape-plug");
|
||||
std::fs::create_dir_all(escape_root.join(".plugin")).unwrap();
|
||||
std::fs::write(
|
||||
escape_root.join(".plugin/plugin.json"),
|
||||
r#"{"name":"escape-plug","mcpServers":"../../../../outside/secret.json"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// `~/.copilot/config.json` includes leading `//` comments in Copilot CLI.
|
||||
let config_json = format!(
|
||||
"// Managed automatically.\n{}",
|
||||
serde_json::json!({
|
||||
"installedPlugins": [
|
||||
{
|
||||
"name": "azure",
|
||||
"marketplace": "",
|
||||
"enabled": true,
|
||||
"cache_path": azure_root,
|
||||
},
|
||||
{
|
||||
"name": "inline-tools",
|
||||
"marketplace": "awesome-copilot",
|
||||
"enabled": true,
|
||||
"cache_path": inline_root,
|
||||
},
|
||||
{
|
||||
"name": "disabled-plug",
|
||||
"marketplace": "",
|
||||
"enabled": false,
|
||||
"cache_path": disabled_root,
|
||||
},
|
||||
{
|
||||
"name": "escape-plug",
|
||||
"marketplace": "",
|
||||
"enabled": true,
|
||||
"cache_path": escape_root,
|
||||
}
|
||||
]
|
||||
})
|
||||
);
|
||||
std::fs::write(copilot.join("config.json"), config_json).unwrap();
|
||||
std::fs::write(copilot.join("settings.json"), r#"{"disabledMcpServers":["muted-srv"]}"#).unwrap();
|
||||
|
||||
let sources = discover_external_sources(Some(&home), None);
|
||||
assert_eq!(sources.len(), 2);
|
||||
|
||||
let azure_src = sources.iter().find(|s| s.id == "copilot-plugin:azure").unwrap();
|
||||
assert_eq!(azure_src.label, "GitHub Copilot Plugin (azure)");
|
||||
assert_eq!(azure_src.native_provider.as_deref(), Some("copilot"));
|
||||
assert_eq!(azure_src.path.0, azure_root.join(".mcp.json"));
|
||||
assert_eq!(azure_src.servers.len(), 1);
|
||||
assert!(azure_src.servers[0].enabled);
|
||||
assert_eq!(
|
||||
azure_src.servers[0].args,
|
||||
vec!["-y", "@azure/mcp@latest", &format!("{}/cfg", azure_root.display())]
|
||||
);
|
||||
|
||||
let inline_src = sources.iter().find(|s| s.id == "copilot-plugin:awesome-copilot/inline-tools").unwrap();
|
||||
assert_eq!(inline_src.label, "GitHub Copilot Plugin (inline-tools · awesome-copilot)");
|
||||
assert_eq!(inline_src.path.0, inline_root.join(".claude-plugin/plugin.json"));
|
||||
let active = inline_src.servers.iter().find(|s| s.name == "inline-srv").unwrap();
|
||||
assert!(active.enabled);
|
||||
assert_eq!(active.command.as_deref(), Some(format!("{}/bin/run", inline_root.display()).as_str()));
|
||||
let muted = inline_src.servers.iter().find(|s| s.name == "muted-srv").unwrap();
|
||||
assert!(!muted.enabled);
|
||||
|
||||
let mut user = BTreeMap::new();
|
||||
let mut workspace = BTreeMap::new();
|
||||
let imported = apply_import_selected(
|
||||
&mut user,
|
||||
&mut workspace,
|
||||
Some(&home),
|
||||
None,
|
||||
McpScope::User,
|
||||
&[McpImportSelection { source_id: "copilot-plugin:azure".into(), name: "azure".into() }],
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(imported, vec!["azure".to_string()]);
|
||||
assert_eq!(user["azure"].env.get("PLUG_DIR").map(String::as_str), Some(azure_root.to_str().unwrap()));
|
||||
}
|
||||
}
|
||||
@@ -916,6 +916,37 @@ impl DbManager {
|
||||
self.tunnels.lock().remove(id);
|
||||
}
|
||||
|
||||
/// Creates a database on the server of data source `id` by running `statement` on the data
|
||||
/// source's own database, after closing the IDE's connections to `template`, the database
|
||||
/// the server copies (PostgreSQL and SQL Server refuse to copy one that has sessions).
|
||||
pub async fn create_database(&self, id: &str, template: &str, statement: &str) -> IdeResult<()> {
|
||||
let id = split_target(id).0;
|
||||
if self.source(id)?.read_only {
|
||||
return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only"));
|
||||
}
|
||||
self.disconnect(&format!("{id}:{template}")).await;
|
||||
self.pool(id).await?.execute(statement, 0, &CancellationToken::new()).await?;
|
||||
self.remember_statement(id, statement);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops `database` of the server of data source `id` by running `statement` on the data
|
||||
/// source's own database, after closing the IDE's connections to `database`.
|
||||
/// Refuses the database the data source connects to and read-only data sources.
|
||||
pub async fn drop_database(&self, id: &str, database: &str, statement: &str) -> IdeResult<()> {
|
||||
let id = split_target(id).0;
|
||||
if self.source(id)?.read_only {
|
||||
return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only"));
|
||||
}
|
||||
if self.databases(id).await?.current == database {
|
||||
return Err(IdeError::invalid(format!("the data source connects to {database}; it cannot drop it")));
|
||||
}
|
||||
self.disconnect(&format!("{id}:{database}")).await;
|
||||
self.pool(id).await?.execute(statement, 0, &CancellationToken::new()).await?;
|
||||
self.remember_statement(id, statement);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The databases of the server of data source `id` (PostgreSQL), the connected one first.
|
||||
pub async fn databases(&self, id: &str) -> IdeResult<Databases> {
|
||||
let id = split_target(id).0;
|
||||
|
||||
@@ -230,6 +230,44 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
|
||||
}
|
||||
|
||||
/// Runs `job` with the newest installed copy of its tool, the way the dialogs do.
|
||||
#[tokio::test]
|
||||
async fn drops_a_database_the_ide_holds_connections_to() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
db.execute("p", "DROP DATABASE IF EXISTS oi_drop_me", 0, &c).await?;
|
||||
db.execute("p", "CREATE DATABASE oi_drop_me TEMPLATE template0", 0, &c).await?;
|
||||
|
||||
// What the tree and a manual-commit console leave open on the database.
|
||||
db.schemas("p:oi_drop_me").await?;
|
||||
db.set_manual_commit("p:oi_drop_me", true).await?;
|
||||
db.execute("p:oi_drop_me", "SELECT 1", 1, &c).await?;
|
||||
|
||||
db.drop_database("p", "oi_drop_me", "drop database oi_drop_me").await?;
|
||||
assert!(!db.is_connected("p:oi_drop_me"));
|
||||
assert!(!db.databases("p").await?.names.iter().any(|n| n == "oi_drop_me"));
|
||||
|
||||
let current = db.databases("p").await?.current;
|
||||
let refused = db.drop_database("p", ¤t, &format!("drop database \"{current}\"")).await;
|
||||
assert!(refused.is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn creates_a_database_from_a_template_the_ide_holds_connections_to() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
db.execute("p", "DROP DATABASE IF EXISTS oi_from_template", 0, &c).await?;
|
||||
db.schemas("p:template1").await?;
|
||||
|
||||
db.create_database("p", "template1", "create database oi_from_template").await?;
|
||||
assert!(!db.is_connected("p:template1"));
|
||||
assert!(db.databases("p").await?.names.iter().any(|n| n == "oi_from_template"));
|
||||
db.execute("p", "DROP DATABASE oi_from_template", 0, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_tool(db: &DbManager, target: &str, job: ide_db::tools::DbToolJob) -> IdeResult<()> {
|
||||
let install = ide_db::tools::find_installs(job.tool()).into_iter().next().expect("installed");
|
||||
let mut lines = Vec::new();
|
||||
|
||||
@@ -95,3 +95,44 @@ async fn sqlserver_values_paging_transactions_and_cancellation() {
|
||||
task.await.unwrap();
|
||||
assert_eq!(pool.rows("SELECT 1", 1).await.unwrap()[0][0].as_deref(), Some("1"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlserver_creates_from_a_held_model_and_force_drops_a_held_database() {
|
||||
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
|
||||
let mut parts = server.splitn(4, ':');
|
||||
let (host, port, user, password) = (
|
||||
parts.next().unwrap(),
|
||||
parts.next().unwrap().parse().unwrap(),
|
||||
parts.next().unwrap(),
|
||||
parts.next().unwrap_or(""),
|
||||
);
|
||||
let source = |database: &str| DataSource {
|
||||
id: "s".into(),
|
||||
name: "sqlserver".into(),
|
||||
driver: DbDriver::SqlServer,
|
||||
host: host.into(),
|
||||
port: Some(port),
|
||||
user: user.into(),
|
||||
database: database.into(),
|
||||
ssl: DbSslMode::Disable,
|
||||
..Default::default()
|
||||
};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().to_path_buf();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = ide_db::DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
db.save_sources(vec![source("master")]).await.unwrap();
|
||||
db.set_password("s", Some(password.into()), false).await.unwrap();
|
||||
let name = format!("oi_force_drop_{}", std::process::id());
|
||||
// The tree's connection to `model` would keep SQL Server from copying it.
|
||||
db.schemas("s:model").await.unwrap();
|
||||
db.create_database("s", "model", &format!("create database {name};")).await.unwrap();
|
||||
assert!(!db.is_connected("s:model"));
|
||||
|
||||
let other = Pool::connect(&source(&name), Some(password), None).await.unwrap();
|
||||
let held = Held::acquire(&other).await.unwrap();
|
||||
let force = format!("alter database {name} set single_user with rollback immediate;\ndrop database {name};");
|
||||
db.drop_database("s", &name, &force).await.unwrap();
|
||||
assert!(!db.databases("s").await.unwrap().names.contains(&name));
|
||||
drop(held);
|
||||
}
|
||||
@@ -139,6 +139,32 @@ pub async fn db_disconnect(host: &Host, window: &str, id: String) -> IdeResult<(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_create_database(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
template: String,
|
||||
statement: String,
|
||||
) -> IdeResult<()> {
|
||||
// Creates a database on the server of data source `id` with `statement`, copied from `template` (New › Database).
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.create_database(&id, &template, &statement).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_drop_database(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
database: String,
|
||||
statement: String,
|
||||
) -> IdeResult<()> {
|
||||
// Drops `database` of the server of data source `id` with `statement` (Drop… on a database node).
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.drop_database(&id, &database, &statement).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_databases(host: &Host, window: &str, id: String) -> IdeResult<Databases> {
|
||||
// Databases of the server of data source `id` (PostgreSQL); connect to one as `<id>:<database>`.
|
||||
@@ -478,10 +504,12 @@ ide_command::domain!(
|
||||
db_connected,
|
||||
db_console_path,
|
||||
db_consoles,
|
||||
db_create_database,
|
||||
db_database_catalog,
|
||||
db_databases,
|
||||
db_ddl,
|
||||
db_disconnect,
|
||||
db_drop_database,
|
||||
db_execute,
|
||||
db_explain,
|
||||
db_finish_transaction,
|
||||
|
||||
@@ -286,6 +286,8 @@ impl Host {
|
||||
effective.languages.java.gradle.linked_projects.as_deref(),
|
||||
build_files.as_deref(),
|
||||
);
|
||||
// After the import settings: they extend the workspace folder's name.
|
||||
ide_sdk::jdtls_workspaces::use_own_temp(cfg, &data_dir);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -879,16 +879,15 @@ fn background_tasks_scale_and_renew_cpu_fuel_budget() {
|
||||
// Room for activation (about 3_100 on macOS, more on Windows). A background task gets ten
|
||||
// times it (5 s / 500 ms): enough for each step of `patient` with its CPU work (32_000 to
|
||||
// 80_000), not for the whole run without the refill on each report.
|
||||
let f = fixture(Limits {
|
||||
let limits = Limits {
|
||||
fuel: 40_000,
|
||||
timeout: Duration::from_millis(500),
|
||||
background: Duration::from_millis(5_000),
|
||||
..Limits::default()
|
||||
});
|
||||
};
|
||||
let f = fixture(limits);
|
||||
f.install(&misbehave_pkg());
|
||||
if f.host.set_capability("misbehave", "process:git", true).is_err() {
|
||||
return;
|
||||
}
|
||||
f.host.set_capability("misbehave", "process:git", true).expect("grant Git capability");
|
||||
// Warm up activation in its own call so `patient` starts with a fresh budget.
|
||||
assert_eq!(f.run("misbehave", "echo", Some("warm")).unwrap().as_deref(), Some("warm"));
|
||||
|
||||
@@ -897,6 +896,13 @@ fn background_tasks_scale_and_renew_cpu_fuel_budget() {
|
||||
|
||||
let err = f.run("misbehave", "spin", None).unwrap_err();
|
||||
assert!(err.contains("exceeded its CPU budget (40000 fuel per call)"), "{err}");
|
||||
|
||||
// Beginning a task alone must not renew its scaled budget.
|
||||
let quiet = fixture(limits);
|
||||
quiet.install(&misbehave_pkg());
|
||||
quiet.host.set_capability("misbehave", "process:git", true).expect("grant Git capability");
|
||||
let err = quiet.run("misbehave", "patient", Some("quiet:4000")).unwrap_err();
|
||||
assert!(err.contains("exceeded its CPU budget (400000 fuel per call)"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
1056d650117bc2216ac518aa26b27cf898f58db62369ae285b9d8925ada74dff
|
||||
b24fb8d5161006104698fb07a43432601b4f16fdc4a34cc70058cbef7e973066
|
||||
+9
-3
@@ -181,9 +181,13 @@ impl commands::Guest for Misbehave {
|
||||
};
|
||||
let child = process::start(&cmd, None)?;
|
||||
// CPU work per step (loop iterations), for fuel budget tests.
|
||||
let work: u64 = arg.as_deref().and_then(|a| a.parse().ok()).unwrap_or(0);
|
||||
let arg = arg.as_deref().unwrap_or("");
|
||||
let report = !arg.starts_with("quiet:");
|
||||
let work: u64 = arg.strip_prefix("quiet:").unwrap_or(arg).parse().unwrap_or(0);
|
||||
for step in 0..25 {
|
||||
task.report(step, Some(25), Some("waiting"));
|
||||
if report {
|
||||
task.report(step, Some(25), Some("waiting"));
|
||||
}
|
||||
let mut x: u64 = 0;
|
||||
for _ in 0..work {
|
||||
x = std::hint::black_box(x.wrapping_add(1));
|
||||
@@ -195,7 +199,9 @@ impl commands::Guest for Misbehave {
|
||||
// Let it finish on its own: no kill, no slow teardown.
|
||||
child.close_stdin()?;
|
||||
let _ = child.wait(5_000);
|
||||
task.report(25, Some(25), Some("done"));
|
||||
if report {
|
||||
task.report(25, Some(25), Some("done"));
|
||||
}
|
||||
Ok(Some("still here".into()))
|
||||
}
|
||||
// `editor.write` is not granted: an error, not a trap.
|
||||
|
||||
@@ -21,10 +21,63 @@ fn root(data_dir: &Path) -> PathBuf {
|
||||
data_dir.join("lsp").join("jdtls")
|
||||
}
|
||||
|
||||
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder).
|
||||
/// jdtls' temporary folder, inside its workspace.
|
||||
const TEMP_DIR: &str = ".tmp";
|
||||
|
||||
fn workspace(cfg: &LanguageServerConfig) -> Option<&Path> {
|
||||
cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)).map(Path::new)
|
||||
}
|
||||
|
||||
fn temp_arg(workspace: &Path) -> String {
|
||||
format!("-Djava.io.tmpdir={}", workspace.join(TEMP_DIR).to_string_lossy())
|
||||
}
|
||||
|
||||
/// Gives jdtls a temporary folder inside a workspace of ours (`<workspace>/.tmp`) unless the
|
||||
/// user's JVM arguments choose one. JDT APT copies a project's annotation processor jars into a
|
||||
/// new `jdt-apt-*` folder for each processor class loader and deletes it only when the JVM exits
|
||||
/// normally — never on Windows, where the jars are still open then — so in the system temp
|
||||
/// folder they pile up with every start; [`mark_used`] empties this one before each start.
|
||||
pub fn use_own_temp(cfg: &mut LanguageServerConfig, data_dir: &Path) {
|
||||
if cfg.name != "jdtls" || cfg.args.iter().any(|a| a.contains("-Djava.io.tmpdir=")) {
|
||||
return;
|
||||
}
|
||||
let Some(arg) = workspace(cfg).filter(|w| w.starts_with(root(data_dir))).map(temp_arg) else { return };
|
||||
// Launched directly, JVM options go before `-jar`; through the script, as `--jvm-arg=`.
|
||||
match cfg.args.iter().position(|a| a == "-jar") {
|
||||
Some(jar) => cfg.args.insert(jar, arg),
|
||||
None => cfg.args.push(format!("--jvm-arg={arg}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Empties the temporary folder [`use_own_temp`] gave the workspace. Best effort: files a server
|
||||
/// still has open on Windows stay until a later start.
|
||||
fn clear_temp(cfg: &LanguageServerConfig, workspace: &Path) {
|
||||
let arg = temp_arg(workspace);
|
||||
if !cfg.args.iter().any(|a| a.strip_prefix("--jvm-arg=").unwrap_or(a) == arg) {
|
||||
return;
|
||||
}
|
||||
let temp = workspace.join(TEMP_DIR);
|
||||
for entry in std::fs::read_dir(&temp).into_iter().flatten().flatten() {
|
||||
let path = entry.path();
|
||||
let removed = if entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
std::fs::remove_dir_all(&path)
|
||||
} else {
|
||||
std::fs::remove_file(&path)
|
||||
};
|
||||
if let Err(e) = removed {
|
||||
tracing::debug!("jdtls: cannot remove temporary {}: {e}", path.display());
|
||||
}
|
||||
}
|
||||
if let Err(e) = std::fs::create_dir_all(&temp) {
|
||||
tracing::warn!("jdtls: cannot create its temporary folder {}: {e}", temp.display());
|
||||
}
|
||||
}
|
||||
|
||||
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder), and empties
|
||||
/// the workspace's temporary folder.
|
||||
pub fn mark_used(cfg: &LanguageServerConfig) {
|
||||
let Some(dir) = cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)) else { return };
|
||||
let dir = Path::new(dir);
|
||||
let Some(dir) = workspace(cfg) else { return };
|
||||
clear_temp(cfg, dir);
|
||||
if let Err(e) = std::fs::create_dir_all(dir).and_then(|()| {
|
||||
let marker = std::fs::File::create(dir.join(USED_MARKER))?;
|
||||
marker.set_modified(SystemTime::now())
|
||||
@@ -142,6 +195,43 @@ mod tests {
|
||||
assert!(ws.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdtls_keeps_its_temporary_files_in_its_workspace_and_starts_with_none() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = root(tmp.path()).join("p");
|
||||
let temp = format!("-Djava.io.tmpdir={}", ws.join(TEMP_DIR).to_string_lossy());
|
||||
|
||||
// Through the launcher script.
|
||||
let mut script = cfg(&ws);
|
||||
use_own_temp(&mut script, tmp.path());
|
||||
assert_eq!(script.args.last(), Some(&format!("--jvm-arg={temp}")));
|
||||
// Launched directly: a JVM option, before `-jar`.
|
||||
let mut direct = cfg(&ws);
|
||||
direct.args.splice(0..0, ["-Xmx2G".to_owned(), "-jar".to_owned(), "launcher.jar".to_owned()]);
|
||||
use_own_temp(&mut direct, tmp.path());
|
||||
assert_eq!(direct.args[..3], ["-Xmx2G".to_owned(), temp.clone(), "-jar".to_owned()]);
|
||||
|
||||
let stale = ws.join(TEMP_DIR).join("jdt-apt-1");
|
||||
std::fs::create_dir_all(&stale).unwrap();
|
||||
std::fs::write(stale.join("0_processor.jar"), "").unwrap();
|
||||
std::fs::write(ws.join(TEMP_DIR).join("file.tmp"), "").unwrap();
|
||||
mark_used(&direct);
|
||||
assert!(ws.join(TEMP_DIR).is_dir());
|
||||
assert_eq!(std::fs::read_dir(ws.join(TEMP_DIR)).unwrap().count(), 0);
|
||||
|
||||
// The user's own choice, and a workspace that is not ours, are left alone.
|
||||
let mut own = cfg(&ws);
|
||||
own.args.push("--jvm-arg=-Djava.io.tmpdir=/elsewhere".into());
|
||||
use_own_temp(&mut own, tmp.path());
|
||||
assert_eq!(own.args.iter().filter(|a| a.contains("java.io.tmpdir")).count(), 1);
|
||||
let mut theirs = cfg(&tmp.path().join("their-workspace"));
|
||||
use_own_temp(&mut theirs, tmp.path());
|
||||
assert!(!theirs.args.iter().any(|a| a.contains("java.io.tmpdir")));
|
||||
std::fs::create_dir_all(ws.join(TEMP_DIR).join("kept")).unwrap();
|
||||
mark_used(&cfg(&ws));
|
||||
assert!(ws.join(TEMP_DIR).join("kept").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_workspace_from_before_markers_is_judged_by_its_folders_and_log() {
|
||||
|
||||
@@ -131,7 +131,7 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
|
||||
|
||||
- **Global (`User`)**: saved in `settings.toml` with environment variable and HTTP header values stored in the OS credential store, shared across projects and agents (or scoped to selected agents).
|
||||
- **Project (`Workspace`)**: saved in `.openidea/settings.toml`; entries with the same name override Global servers, and servers added outside OpenIDEA stay off until approved.
|
||||
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json`, `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
|
||||
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json` (and installed Copilot CLI plugins), `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
|
||||
- **Per-session (`MCP` / `/mcp`)**: in both **New Agent Task** and active task conversations, open **MCP** in the composer toolbar (or run `/mcp`) to enable or disable individual servers—including the built-in `openidea` server—for that task only, or click **Reset** to return to the inherited defaults.
|
||||
|
||||
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply. **Settings › Agents › Working Status** can show playful words for what it does there instead; they are off by default. Once turned on, they take turns from the moment the work changes, or only after the agent reports nothing new for a number of seconds (0 to 600, 0 by default); screen readers still hear what the agent is doing. Each word stays eight seconds while the agent keeps at the same work, and at least three when it moves on, so the line doesn't flicker. The same page replaces the words: pick what the status says (**Reading…**, **Running a command…**…) and add or remove its words. **Restore Built-in Words** brings back OpenIDEA's; an activity left without words keeps its plain status.
|
||||
|
||||
@@ -131,7 +131,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
|
||||
- **全局(`用户`)**:保存在 `settings.toml` 中,环境变量与 HTTP 请求头的值保存在系统凭据存储里,跨项目与各智能体共享(也可限定给选定的智能体)。
|
||||
- **项目(`工作区`)**:保存在 `.openidea/settings.toml` 中,同名服务器覆盖全局配置;在 OpenIDEA 外部写入的项目服务器在批准启用前保持关闭。
|
||||
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
|
||||
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`(及已安装的 Copilot CLI 插件)、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
|
||||
- **按会话覆盖(`MCP` / `/mcp`)**:在 **新建 Agent 任务** 和进行中的任务对话中,单击输入框工具栏的 **MCP**(或输入 `/mcp`),即可仅针对当前任务开启或关闭任意服务器(包括内置的 `openidea` 服务器),或点击 **重置** 恢复继承的默认状态。
|
||||
|
||||
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。在 **设置 › 智能体 › 工作状态** 中可以让这里改为显示与当前工作相关的趣味文字,默认关闭。开启后,工作一变化就轮换显示,也可以设置在 agent 无新进展多少秒后才显示(0 到 600,默认 0);屏幕阅读器读出的仍是 agent 实际在做的事。agent 持续做同一类工作时,每条文字停留八秒;转向其他工作时也至少停留三秒,状态行不会频繁跳动。同一页面还可以替换这些文字:选择状态(**正在读取…**、**正在运行命令…**…),再添加或移除对应的文字。**恢复内置文字** 会换回 OpenIDEA 自带的文字;没有任何文字的状态只显示实际进展。
|
||||
|
||||
@@ -416,6 +416,7 @@ test("dragging the Changes pane's edge resizes it for the next session too", asy
|
||||
|
||||
// The next session starts with the dragged width.
|
||||
await page.reload();
|
||||
await expect(page.getByRole("tree", { name: "Project" })).toBeVisible();
|
||||
await seedTasks(page, "editor");
|
||||
await seedChanges(page);
|
||||
await expect.poll(async () => Math.round((await changes.boundingBox())!.width)).toBe(Math.round(widened));
|
||||
|
||||
@@ -1024,3 +1024,37 @@ test("aligns Mermaid diagrams in replies to their container align attribute", as
|
||||
expect(Math.abs(offsets[2]!.rightGap)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(offsets[3]!.leftGap - offsets[3]!.rightGap)).toBeLessThanOrEqual(1.5);
|
||||
});
|
||||
|
||||
test("renders LaTeX math formulas with KaTeX and keeps wide equations scrollable", async ({ page }) => {
|
||||
const reply = await openReply(
|
||||
page,
|
||||
[
|
||||
"Inline $E = mc^2$ and \\(a^2 + b^2 = c^2\\), prices $5 and $10 stay plain.",
|
||||
"",
|
||||
"$$",
|
||||
"\\int_{-\\infty}^{\\infty} e^{-x^2} \\, dx = \\sqrt{\\pi}",
|
||||
"$$",
|
||||
"",
|
||||
"```math",
|
||||
"\\sum_{k=1}^{n} k = \\frac{n(n+1)}{2} + a_1 + a_2 + a_3 + a_4 + a_5 + a_6 + a_7 + a_8 + a_9 + a_{10}",
|
||||
"```",
|
||||
].join("\n"),
|
||||
);
|
||||
await expect(reply.locator(".katex")).toHaveCount(4);
|
||||
await expect(reply.locator(".katex-display")).toHaveCount(2);
|
||||
await expect(reply).toContainText("prices $5 and $10 stay plain.");
|
||||
|
||||
const layout = await reply.evaluate((el) => {
|
||||
const firstKatex = el.querySelector<HTMLElement>(".katex")!;
|
||||
const display = el.querySelectorAll<HTMLElement>(".katex-display");
|
||||
const font = getComputedStyle(firstKatex).fontFamily;
|
||||
return {
|
||||
font,
|
||||
height: firstKatex.getBoundingClientRect().height,
|
||||
overflowX: getComputedStyle(display[1]!).overflowX,
|
||||
};
|
||||
});
|
||||
expect(layout.font).toContain("KaTeX_Main");
|
||||
expect(layout.height).toBeGreaterThan(10);
|
||||
expect(layout.overflowX).toBe("auto");
|
||||
});
|
||||
@@ -102,7 +102,7 @@ test("stripe themes inherit base tooltip tokens and keep shortcut text readable"
|
||||
delete root.dataset.colorTheme;
|
||||
root.dataset.theme = kind;
|
||||
root.dataset.pluginTheme = "test/base-tooltip";
|
||||
const path = "/src/features/plugins/bridge.ts";
|
||||
const path = "/src/features/plugins/themeRuntime.ts";
|
||||
const { pluginThemeCss } = await import(/* @vite-ignore */ path);
|
||||
const style = document.createElement("style");
|
||||
style.id = "test-plugin-theme";
|
||||
|
||||
@@ -80,6 +80,7 @@
|
||||
"dompurify": "^3.4.17",
|
||||
"emmet": "2.4.11",
|
||||
"immer": "^11.1.21",
|
||||
"katex": "^0.19.1",
|
||||
"marked": "^18.1.1",
|
||||
"mermaid": "12.1.0",
|
||||
"react": "^19.1.0",
|
||||
|
||||
Generated
+11
@@ -119,6 +119,9 @@ importers:
|
||||
immer:
|
||||
specifier: ^11.1.21
|
||||
version: 11.1.21
|
||||
katex:
|
||||
specifier: ^0.19.1
|
||||
version: 0.19.1
|
||||
marked:
|
||||
specifier: ^18.1.1
|
||||
version: 18.1.1
|
||||
@@ -1799,6 +1802,10 @@ packages:
|
||||
resolution: {integrity: sha512-/B6p9eY9DX7aHBfpkHdpirDTZ5QH9xTwL9y837PWuzuv41O5jFdqNQwVQEQsimY0/iVNkwBY4+4hMfhQ7d4Dbw==}
|
||||
hasBin: true
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-jG8uKntjSEcm2EpQOh0XturpPuuC9r3Sq5HLHdsFdWZT27E672SF19QEi+of0/YeOy15lDgRhKvr5614uRrEfA==}
|
||||
hasBin: true
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==}
|
||||
|
||||
@@ -3792,6 +3799,10 @@ snapshots:
|
||||
dependencies:
|
||||
commander: 15.1.0
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
commander: 15.1.0
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
|
||||
@@ -93,10 +93,12 @@ db_connect trusted project_host bin
|
||||
db_connected trusted project_host bindings sync
|
||||
db_console_path always project_host bindings sync
|
||||
db_consoles always project_host bindings sync
|
||||
db_create_database trusted project_host bindings async
|
||||
db_database_catalog trusted project_host bindings async
|
||||
db_databases trusted project_host bindings async
|
||||
db_ddl trusted project_host bindings async
|
||||
db_disconnect trusted project_host bindings async
|
||||
db_drop_database trusted project_host bindings async
|
||||
db_dump_info trusted desktop bindings async
|
||||
db_execute trusted project_host bindings async
|
||||
db_explain trusted project_host bindings async
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { AuxKind } from "./platform/auxWindow";
|
||||
import { mountWindowRoot } from "./windowBoot";
|
||||
import { activateSecondaryWindow } from "./workbench/activateSecondary";
|
||||
|
||||
export async function bootAuxiliaryWindow(aux: { kind: AuxKind; parent: string }): Promise<void> {
|
||||
activateSecondaryWindow();
|
||||
switch (aux.kind) {
|
||||
case "settings": {
|
||||
const { bootSettingsWindow } = await import("./settingsWindowBoot");
|
||||
mountWindowRoot(bootSettingsWindow(aux.parent));
|
||||
return;
|
||||
}
|
||||
case "comparison": {
|
||||
const { bootComparisonWindow } = await import("./comparisonWindowBoot");
|
||||
mountWindowRoot(bootComparisonWindow(aux.parent));
|
||||
return;
|
||||
}
|
||||
case "diff": {
|
||||
const { bootDiffWindow } = await import("./diffWindowBoot");
|
||||
mountWindowRoot(bootDiffWindow(aux.parent));
|
||||
return;
|
||||
}
|
||||
case "deployment": {
|
||||
const { bootDeploymentWindow } = await import("./deploymentWindowBoot");
|
||||
mountWindowRoot(bootDeploymentWindow(aux.parent));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -272,10 +272,12 @@ export const commands = {
|
||||
dbConsolePath: (id: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("db_console_path", { id })),
|
||||
/** The query consoles of data source `id`; `create` adds the next one first. */
|
||||
dbConsoles: (id: string, create: boolean) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("db_consoles", { id, create })),
|
||||
dbCreateDatabase: (id: string, template: string, statement: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_create_database", { id, template, statement })),
|
||||
dbDatabaseCatalog: (id: string, database: string) => typedError<DbCatalogSchema[], IdeError>(__TAURI_INVOKE("db_database_catalog", { id, database })),
|
||||
dbDatabases: (id: string) => typedError<DbDatabases, IdeError>(__TAURI_INVOKE("db_databases", { id })),
|
||||
dbDdl: (id: string, schema: string, table: string) => typedError<string, IdeError>(__TAURI_INVOKE("db_ddl", { id, schema, table })),
|
||||
dbDisconnect: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_disconnect", { id })),
|
||||
dbDropDatabase: (id: string, database: string, statement: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_drop_database", { id, database, statement })),
|
||||
/** What made the dump at `path` and whether it creates its own database (from its first bytes). */
|
||||
dbDumpInfo: (path: string) => typedError<DbDumpInfo, IdeError>(__TAURI_INVOKE("db_dump_info", { path })),
|
||||
dbExecute: (request: RequestId, id: string, statements: SqlStatement[], skip: number, maxRows: number, schema: string | null) => typedError<DbStatementOutcome[], IdeError>(__TAURI_INVOKE("db_execute", { request, id, statements, skip, maxRows, schema })),
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { ComponentType } from "react";
|
||||
import { activate as editor } from "./editor/core";
|
||||
import { confirmLeave } from "./features/app/closeGuard";
|
||||
import { installLocaleSync } from "./features/app/locale";
|
||||
import { installMenuBridge } from "./features/app/menuBridge";
|
||||
import { trackRuntimeSettings } from "./features/settings/runtime";
|
||||
import { activate as vcs } from "./features/vcs";
|
||||
import { activateComparisonWindow, ComparisonWindow } from "./features/vcs/ComparisonWindow";
|
||||
import { installKeyboardDispatcher } from "./platform/keymap";
|
||||
import { activateList } from "./windowBoot";
|
||||
|
||||
/**
|
||||
* Comparison window of project window `parent`: changed files between two
|
||||
* revisions and their diffs, with the editor and Git but no workbench.
|
||||
*/
|
||||
export function bootComparisonWindow(parent: string): ComponentType {
|
||||
activateList("comparison window", [
|
||||
["locale", installLocaleSync],
|
||||
["settings", trackRuntimeSettings],
|
||||
["menu", installMenuBridge],
|
||||
["editor", editor],
|
||||
["vcs", vcs],
|
||||
["comparison", () => activateComparisonWindow(parent, (project) => confirmLeave(undefined, project))],
|
||||
]);
|
||||
installKeyboardDispatcher();
|
||||
return ComparisonWindow;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { ComponentType } from "react";
|
||||
import { installLocaleSync } from "./features/app/locale";
|
||||
import { activateDeploymentWindow, DeploymentWindow } from "./features/deployment/window";
|
||||
import { trackRuntimeSettings } from "./features/settings/runtime";
|
||||
import { activateDiffViewer } from "./features/vcs/diffViewer";
|
||||
import { activateList } from "./windowBoot";
|
||||
|
||||
/**
|
||||
* Sync with Deployed window of project window `parent`: local files next to
|
||||
* their copies on a deployment server, with the diff viewer but no workbench.
|
||||
*/
|
||||
export function bootDeploymentWindow(parent: string): ComponentType {
|
||||
activateList("deployment window", [
|
||||
["locale", installLocaleSync],
|
||||
["settings", trackRuntimeSettings],
|
||||
["diff", activateDiffViewer],
|
||||
["deployment", () => activateDeploymentWindow(parent)],
|
||||
]);
|
||||
return DeploymentWindow;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { ComponentType } from "react";
|
||||
import { installLocaleSync } from "./features/app/locale";
|
||||
import { installMenuBridge } from "./features/app/menuBridge";
|
||||
import { trackRuntimeSettings } from "./features/settings/runtime";
|
||||
import { activate as vcs } from "./features/vcs";
|
||||
import { activateDiffWindow, DiffWindow } from "./features/vcs/DiffWindow";
|
||||
import { installKeyboardDispatcher } from "./platform/keymap";
|
||||
import { activateList } from "./windowBoot";
|
||||
|
||||
/**
|
||||
* Diff window of project window `parent`: one file's diff, with Git and its own
|
||||
* documents but no workbench.
|
||||
*/
|
||||
export function bootDiffWindow(parent: string): ComponentType {
|
||||
activateList("diff window", [
|
||||
["locale", installLocaleSync],
|
||||
["settings", trackRuntimeSettings],
|
||||
["menu", installMenuBridge],
|
||||
["vcs", vcs],
|
||||
["diff", () => activateDiffWindow(parent)],
|
||||
]);
|
||||
installKeyboardDispatcher();
|
||||
return DiffWindow;
|
||||
}
|
||||
@@ -69,6 +69,14 @@ describe("markdown rendering", () => {
|
||||
expect(md.markupToHtml({ kind: "markdown", value: "`x`" })).toBe("<p><code>x</code></p>\n");
|
||||
expect(md.markupToHtml({ kind: "plaintext", value: "<b>" })).toBe('<p class="cm-lsp-plain"><b></p>');
|
||||
});
|
||||
|
||||
it("renders LaTeX math in LSP / documentation markdown", async () => {
|
||||
const md = await freshMarkdown();
|
||||
await md.loadMarkdown();
|
||||
const root = document.createElement("div");
|
||||
root.innerHTML = md.markupToHtml({ kind: "markdown", value: "Complexity $O(n \\log n)$" });
|
||||
expect(root.querySelector(".katex")).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// On Windows, opening `//server/share` signs in to that server with the user's credentials.
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
.katex {
|
||||
overflow-wrap: normal;
|
||||
}
|
||||
|
||||
.katex-display {
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
padding: 2px 0;
|
||||
}
|
||||
|
||||
.katex-error {
|
||||
color: var(--danger) !important;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Marked } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { mathExtension, renderMath } from "./markdownMath";
|
||||
|
||||
const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension());
|
||||
|
||||
function parseSafe(md: string): HTMLElement {
|
||||
const html = marked.parse(md, { async: false }) as string;
|
||||
const root = DOMPurify.sanitize(html, {
|
||||
USE_PROFILES: { html: true },
|
||||
ADD_ATTR: ["data-math"],
|
||||
FORBID_TAGS: ["style", "form"],
|
||||
FORBID_ATTR: ["style"],
|
||||
RETURN_DOM: true,
|
||||
}) as HTMLElement;
|
||||
renderMath(root);
|
||||
return root;
|
||||
}
|
||||
|
||||
describe("markdown LaTeX math", () => {
|
||||
it("renders inline $...$ and avoids currency false positives", () => {
|
||||
const root = parseSafe(
|
||||
"Energy $E = mc^2$ and CJK 设$x=1$时.\n\nPrices: $5 and $10, or $5-$10, or $ 5 $, or \\$x\\$.",
|
||||
);
|
||||
expect(root.querySelectorAll(".katex")).toHaveLength(2);
|
||||
expect(root.querySelectorAll(".katex-display")).toHaveLength(0);
|
||||
const paras = [...root.querySelectorAll("p")];
|
||||
expect(paras[1]!.textContent).toBe("Prices: $5 and $10, or $5-$10, or $ 5 $, or $x$.");
|
||||
});
|
||||
|
||||
it("prevents * and _ inside math from triggering emphasis while allowing emphasis around math", () => {
|
||||
const root = parseSafe("Formula $(a)_1 + (b)_2$ and $a * b$ and $c * d$, plus **$x^2$**.");
|
||||
expect(root.querySelector("em")).toBeNull();
|
||||
expect(root.querySelectorAll(".katex")).toHaveLength(4);
|
||||
expect(root.querySelector("strong .katex")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("renders multi-line, single-line, inline, and adjacent $$...$$ blocks", () => {
|
||||
const root = parseSafe(
|
||||
"Para\n$$\n\\begin{aligned}\na &= b \\\\\nc &= d\n\\end{aligned}\n$$\n\n$$E = mc^2$$\n\n$$a$$ and $$b$$",
|
||||
);
|
||||
expect(root.querySelectorAll(".katex-display")).toHaveLength(4);
|
||||
expect(root.querySelector("p")?.textContent).toBe("Para");
|
||||
const lastP = [...root.querySelectorAll("p")].at(-1)!;
|
||||
expect(lastP.querySelectorAll(".katex-display")).toHaveLength(2);
|
||||
expect(lastP.textContent).toContain("and");
|
||||
});
|
||||
|
||||
it("renders \\(...\\) and \\[...\\] without breaking escaped links", () => {
|
||||
const root = parseSafe("Inline \\(x + y\\).\n\n\\[\nx^2 + y^2 = z^2\n\\]\n\n\\[text\\](https://example.com)");
|
||||
expect(root.querySelectorAll(".katex")).toHaveLength(2);
|
||||
expect(root.querySelectorAll(".katex-display")).toHaveLength(1);
|
||||
const lastP = [...root.querySelectorAll("p")].at(-1)!;
|
||||
expect(lastP.textContent).toBe("[text](https://example.com)");
|
||||
});
|
||||
|
||||
it("renders ```math code blocks while keeping ```latex and inline code literal", () => {
|
||||
const root = parseSafe("```math\n\\int_0^1 x^2 dx\n```\n\n```latex\n$x$\n```\n\nInline `$y$`.");
|
||||
expect(root.querySelectorAll(".katex-display")).toHaveLength(1);
|
||||
expect(root.querySelector("pre > code.language-latex")?.textContent).toBe("$x$\n");
|
||||
expect(root.querySelector("p > code")?.textContent).toBe("$y$");
|
||||
});
|
||||
|
||||
it("renders invalid LaTeX as an error node instead of throwing", () => {
|
||||
const root = parseSafe("Bad $\\unknowncommand{x}$ and $$\\frac{1$$");
|
||||
expect(root.querySelectorAll(".katex")).toHaveLength(1);
|
||||
expect(root.querySelector(".katex-error")).not.toBeNull();
|
||||
expect(root.textContent).toContain("\\unknowncommand");
|
||||
});
|
||||
|
||||
it("blocks unsafe LaTeX trust commands and raw HTML style/script injection", () => {
|
||||
const root = parseSafe(
|
||||
[
|
||||
"$\\href{javascript:alert(1)}{click}$",
|
||||
'<div style="position:fixed">x</div>',
|
||||
'<span data-math="inline"><img src=x onerror=alert(1)>a</span>',
|
||||
].join("\n\n"),
|
||||
);
|
||||
expect(root.querySelector("a")).toBeNull();
|
||||
expect(root.querySelector("img")).toBeNull();
|
||||
expect(root.querySelector("div[style]")).toBeNull();
|
||||
expect(root.querySelectorAll(".katex")).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* LaTeX math support for Markdown (`marked` + `DOMPurify` + KaTeX).
|
||||
*
|
||||
* `mathExtension()` tokenizes `$$...$$`, `$...$`, `\[...\]`, `\(...\)`, and
|
||||
* ```` ```math ```` blocks into sanitized-safe `<div|span data-math="display|inline">`
|
||||
* placeholders, which survive `DOMPurify` (with `data-math` allowed) and are
|
||||
* rendered synchronously into KaTeX DOM by `renderMath()` right after sanitization.
|
||||
*/
|
||||
import katex from "katex";
|
||||
import "katex/dist/katex.min.css";
|
||||
import "./markdownMath.css";
|
||||
import type { MarkedExtension, Tokens } from "marked";
|
||||
|
||||
interface MathToken extends Tokens.Generic {
|
||||
type: "blockMath" | "inlineMath";
|
||||
raw: string;
|
||||
text: string;
|
||||
display: boolean;
|
||||
}
|
||||
|
||||
const escapeHtml = (s: string) =>
|
||||
s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
export function mathPlaceholder(tex: string, display: boolean, block = display): string {
|
||||
const tag = block ? "div" : "span";
|
||||
const mode = display ? "display" : "inline";
|
||||
return `<${tag} data-math="${mode}">${escapeHtml(tex)}</${tag}>`;
|
||||
}
|
||||
|
||||
/** Finds the closing `delim` (`$$`, `\)`, or `\]`) skipping `\` escapes. Returns content end index or -1. */
|
||||
function findClosingDelimiter(src: string, from: number, delim: string): number {
|
||||
for (let i = from; i < src.length; i++) {
|
||||
if (src.startsWith(delim, i)) return i;
|
||||
if (src[i] === "\\") {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches inline `$...$` from index 0 using Pandoc-style guards so currency
|
||||
* like `$5 and $10` or `$5-$10` stays plain text while `$x$`, `设$x=1$`, etc. match.
|
||||
*/
|
||||
function matchInlineDollar(src: string): { end: number; text: string } | null {
|
||||
if (src[0] !== "$" || src[1] === "$" || !src[1] || /\s/.test(src[1])) return null;
|
||||
for (let i = 1; i < src.length; i++) {
|
||||
const ch = src[i]!;
|
||||
if (ch === "\\") {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === "\n" && (src[i + 1] === "\n" || (src[i + 1] === "\r" && src[i + 2] === "\n"))) {
|
||||
return null;
|
||||
}
|
||||
if (ch === "$") {
|
||||
if (i <= 1 || /\s/.test(src[i - 1]!)) continue;
|
||||
const next = src[i + 1] ?? "";
|
||||
if (next === "$" || /\d/.test(next)) return null;
|
||||
const text = src.slice(1, i);
|
||||
if (!text.trim()) return null;
|
||||
return { end: i + 1, text };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Matches inline `$$...$$`, `$...$`, `\(...\)`, or `\[...\]` starting at index 0 of `src`. */
|
||||
function matchInlineMath(src: string): { raw: string; text: string; display: boolean } | null {
|
||||
if (src.startsWith("$$")) {
|
||||
const close = findClosingDelimiter(src, 2, "$$");
|
||||
if (close > 2) {
|
||||
const text = src.slice(2, close);
|
||||
if (text.trim()) return { raw: src.slice(0, close + 2), text, display: true };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (src[0] === "$") {
|
||||
const m = matchInlineDollar(src);
|
||||
return m ? { raw: src.slice(0, m.end), text: m.text, display: false } : null;
|
||||
}
|
||||
if (src.startsWith("\\(")) {
|
||||
const close = findClosingDelimiter(src, 2, "\\)");
|
||||
if (close > 2) {
|
||||
const text = src.slice(2, close);
|
||||
if (text.trim()) return { raw: src.slice(0, close + 2), text, display: false };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (src.startsWith("\\[")) {
|
||||
const close = findClosingDelimiter(src, 2, "\\]");
|
||||
if (close > 2 && src[close + 2] !== "(") {
|
||||
const text = src.slice(2, close);
|
||||
if (text.trim()) return { raw: src.slice(0, close + 2), text, display: true };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const BLOCK_DOLLAR_MULTI = /^ {0,3}\$\$[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*\$\$[ \t]*(?:\r?\n+|$)/;
|
||||
const BLOCK_DOLLAR_SINGLE = /^ {0,3}\$\$((?:\\[\s\S]|[^$\n]|\$(?!\$))+?)\$\$[ \t]*(?:\r?\n+|$)/;
|
||||
const BLOCK_BRACKET_MULTI = /^ {0,3}\\\[[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*\\\][ \t]*(?:\r?\n+|$)/;
|
||||
const BLOCK_BRACKET_SINGLE = /^ {0,3}\\\[((?:\\[\s\S]|[^\\\n]|\\(?!\]))+?)\\\][ \t]*(?:\r?\n+|$)/;
|
||||
|
||||
function matchBlockMath(src: string): { raw: string; text: string } | null {
|
||||
for (const re of [BLOCK_DOLLAR_MULTI, BLOCK_DOLLAR_SINGLE, BLOCK_BRACKET_MULTI, BLOCK_BRACKET_SINGLE]) {
|
||||
const m = re.exec(src);
|
||||
if (m && m[1]!.trim()) return { raw: m[0], text: m[1]! };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Masks math spans with `a`s (preserving newlines) so `*` and `_` inside math never trigger emphasis. */
|
||||
function maskInlineMath(src: string): string {
|
||||
let out = "";
|
||||
let i = 0;
|
||||
while (i < src.length) {
|
||||
if (src[i] === "\\" && src[i + 1] !== "(" && src[i + 1] !== "[") {
|
||||
out += src.slice(i, i + 2);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (src[i] === "$" || (src[i] === "\\" && (src[i + 1] === "(" || src[i + 1] === "["))) {
|
||||
const m = matchInlineMath(src.slice(i));
|
||||
if (m) {
|
||||
out += m.raw.replace(/[^\r\n]/g, "a");
|
||||
i += m.raw.length;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out += src[i]!;
|
||||
i++;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function mathExtension(): MarkedExtension {
|
||||
return {
|
||||
hooks: {
|
||||
emStrongMask(src) {
|
||||
return maskInlineMath(src);
|
||||
},
|
||||
},
|
||||
renderer: {
|
||||
code({ text, lang }) {
|
||||
if (lang?.trim().split(/\s+/)[0]?.toLowerCase() !== "math") return false;
|
||||
return `${mathPlaceholder(text, true, true)}\n`;
|
||||
},
|
||||
},
|
||||
extensions: [
|
||||
{
|
||||
name: "blockMath",
|
||||
level: "block",
|
||||
start(src) {
|
||||
const m = /\n {0,3}(?:\$\$|\\\[)/.exec(src);
|
||||
return m ? m.index : undefined;
|
||||
},
|
||||
tokenizer(src): MathToken | undefined {
|
||||
const m = matchBlockMath(src);
|
||||
if (!m) return undefined;
|
||||
return { type: "blockMath", raw: m.raw, text: m.text, display: true };
|
||||
},
|
||||
renderer(token) {
|
||||
const t = token as MathToken;
|
||||
return `${mathPlaceholder(t.text, true, true)}\n`;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "inlineMath",
|
||||
level: "inline",
|
||||
start(src) {
|
||||
for (let i = 0; i < src.length; i++) {
|
||||
const ch = src[i]!;
|
||||
if (ch === "\\") {
|
||||
const next = src[i + 1];
|
||||
if (next === "(" || next === "[") return i;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$") return i;
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
tokenizer(src): MathToken | undefined {
|
||||
const m = matchInlineMath(src);
|
||||
if (!m) return undefined;
|
||||
return { type: "inlineMath", raw: m.raw, text: m.text, display: m.display };
|
||||
},
|
||||
renderer(token) {
|
||||
const t = token as MathToken;
|
||||
return mathPlaceholder(t.text, t.display, false);
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** Renders every `[data-math]` placeholder inside `root` synchronously using KaTeX. */
|
||||
export function renderMath(root: ParentNode): void {
|
||||
root.querySelectorAll<HTMLElement>("[data-math]").forEach((el) => {
|
||||
const mode = el.getAttribute("data-math");
|
||||
el.removeAttribute("data-math");
|
||||
if (mode !== "inline" && mode !== "display") return;
|
||||
const tex = (el.textContent ?? "").trim();
|
||||
if (!tex) return;
|
||||
katex.render(tex, el, {
|
||||
displayMode: mode === "display",
|
||||
throwOnError: false,
|
||||
strict: false,
|
||||
trust: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,19 +1,24 @@
|
||||
/** Markdown → sanitized HTML (marked + DOMPurify); loaded on demand by `markdown.ts`. */
|
||||
import { Marked } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { mathExtension, renderMath } from "./markdownMath";
|
||||
|
||||
/** DOMPurify's default link schemes plus `file:` and jdtls' `jdt:` (library classes). */
|
||||
const ALLOWED_URI = /^(?:(?:(?:f|ht)tps?|mailto|tel|file|jdt):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i;
|
||||
|
||||
const marked = new Marked({ gfm: true, breaks: false });
|
||||
const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension());
|
||||
|
||||
export function markdownToSafeHtml(markdown: string): string {
|
||||
const html = marked.parse(markdown, { async: false }) as string;
|
||||
// Comments and docs come from anyone; a `<style>` here would restyle the whole IDE.
|
||||
return DOMPurify.sanitize(html, {
|
||||
const root = DOMPurify.sanitize(html, {
|
||||
USE_PROFILES: { html: true },
|
||||
ALLOWED_URI_REGEXP: ALLOWED_URI,
|
||||
ADD_ATTR: ["data-math"],
|
||||
FORBID_TAGS: ["style", "form"],
|
||||
FORBID_ATTR: ["style"],
|
||||
});
|
||||
RETURN_DOM: true,
|
||||
}) as HTMLElement;
|
||||
renderMath(root);
|
||||
return root.innerHTML;
|
||||
}
|
||||
@@ -369,6 +369,17 @@ describe("streamed replies", () => {
|
||||
expect(container.querySelector("details p")?.textContent).toBe("text");
|
||||
});
|
||||
|
||||
it("renders LaTeX math across streamed blocks", () => {
|
||||
const text = "Inline $a + b$.\n\n$$\n\\frac{1}{2}\n$$\n\nTail";
|
||||
const blocks = markdownBlocks(text);
|
||||
expect(blocks).toHaveLength(3);
|
||||
expect(blocks.join("")).toBe(text);
|
||||
const { container } = render(<Markdown text={text} cwd="/repo" />);
|
||||
expect(container.querySelectorAll(".katex")).toHaveLength(2);
|
||||
expect(container.querySelector(".katex-display")).not.toBeNull();
|
||||
expect(screen.queryByRole("button", { name: "Copy Code" })).toBeNull();
|
||||
});
|
||||
|
||||
it("cuts only what streamed on after the blocks that ended", () => {
|
||||
const before = markdownBlocks("One.\n\nTwo.\n\nThr");
|
||||
const after = markdownBlocks("One.\n\nTwo.\n\nThree.\n\n- a", before);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { useEffect, useLayoutEffect, useRef, useSyncExternalStore } from "react"
|
||||
import { Marked } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { highlightInto } from "@/editor/lsp/markdown";
|
||||
import { mathExtension, renderMath } from "@/editor/lsp/markdownMath";
|
||||
import { iconNode } from "@/ui/iconNode";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { openExternalUrl } from "@/platform/openUrl";
|
||||
@@ -37,7 +38,7 @@ const marked = new Marked({
|
||||
return `<div data-mermaid=""><pre><code class="language-mermaid">${escapeHtml(text)}</code></pre></div>\n`;
|
||||
},
|
||||
},
|
||||
});
|
||||
}).use(mathExtension());
|
||||
|
||||
/** Rendered messages by text, least recently used first: reopening a conversation renders it again. */
|
||||
const rendered = new Map<string, string>();
|
||||
@@ -133,10 +134,11 @@ function renderHtml(text: string): string {
|
||||
FORBID_TAGS: ["style", "form", "source"],
|
||||
FORBID_ATTR: ["style", "srcset"],
|
||||
ALLOW_DATA_ATTR: false,
|
||||
// Only the mermaid placeholder written by the renderer above; data attributes
|
||||
// Only the mermaid and math placeholders written by the renderer above; data attributes
|
||||
// quoted in a reply stay out.
|
||||
ADD_ATTR: ["data-mermaid"],
|
||||
ADD_ATTR: ["data-mermaid", "data-math"],
|
||||
}) as HTMLElement;
|
||||
renderMath(root);
|
||||
root.querySelectorAll("li").forEach(wrapLooseText);
|
||||
// WebKit cuts controls inside <pre> out of a text selection, even when transparent.
|
||||
root.querySelectorAll("pre").forEach((pre) => {
|
||||
|
||||
@@ -17,24 +17,13 @@ import {
|
||||
registerMenuGroup,
|
||||
registerMenuSlotItem,
|
||||
registerOverlay,
|
||||
registerSettingsPages,
|
||||
registerStatusItem,
|
||||
registerToolWindow,
|
||||
toolWindowService,
|
||||
} from "@/workbench/contributions";
|
||||
import { AgentsStatus } from "./AgentsStatus";
|
||||
import {
|
||||
AGENTS_GROUP,
|
||||
HOME_KIND,
|
||||
MCP_PAGE,
|
||||
POLICY_PAGE,
|
||||
REGISTRY_PAGE,
|
||||
SESSION_KIND,
|
||||
TASK_DRAG,
|
||||
TOOL_WINDOW,
|
||||
WORKING_STATUS_PAGE,
|
||||
providerIcon,
|
||||
} from "./model";
|
||||
import { activateSettingsPages } from "./settingsPages";
|
||||
import { HOME_KIND, MCP_PAGE, REGISTRY_PAGE, SESSION_KIND, TASK_DRAG, TOOL_WINDOW, providerIcon } from "./model";
|
||||
import { sendPaths, sendSelection, trackEditorCopies } from "./references";
|
||||
import { focusedSession, inputSession } from "./sessionFocus";
|
||||
import { cycleFocusedEffort } from "./effortFocus";
|
||||
@@ -54,45 +43,7 @@ import { TaskStatusMark } from "./TaskStatusMark";
|
||||
import { taskActions, useAgentsHeaderMenu } from "./taskActions";
|
||||
import { replyActions } from "./replyActions";
|
||||
|
||||
/** Settings › Agents › Coding Agents and Settings › Agents › External MCP Servers (also used by the Settings window). */
|
||||
export function activateSettingsPages(): () => void {
|
||||
return registerSettingsPages([
|
||||
{
|
||||
id: REGISTRY_PAGE,
|
||||
title: "Coding Agents",
|
||||
group: AGENTS_GROUP,
|
||||
// First in Agents, which sits after Languages & Frameworks and before Tools.
|
||||
order: 450,
|
||||
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
|
||||
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
|
||||
},
|
||||
{
|
||||
id: WORKING_STATUS_PAGE,
|
||||
title: "Working Status",
|
||||
group: AGENTS_GROUP,
|
||||
// After Chat.
|
||||
order: 465,
|
||||
keywords: ["agent", "status", "playful", "words", "working", "spinner", "fun", "delay", "seconds"],
|
||||
component: lazyComponent(() => import("./WorkingStatusPage").then((m) => m.WorkingStatusPage)),
|
||||
},
|
||||
{
|
||||
id: MCP_PAGE,
|
||||
title: "External MCP Servers",
|
||||
group: AGENTS_GROUP,
|
||||
order: 475,
|
||||
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
|
||||
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
|
||||
},
|
||||
{
|
||||
id: POLICY_PAGE,
|
||||
title: "Command Permissions",
|
||||
group: AGENTS_GROUP,
|
||||
order: 490,
|
||||
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "permission", "command", "exec"],
|
||||
component: lazyComponent(() => import("./AgentPolicyPage").then((m) => m.AgentPolicyPage)),
|
||||
},
|
||||
]);
|
||||
}
|
||||
export { activateSettingsPages } from "./settingsPages";
|
||||
|
||||
export function activate(): () => void {
|
||||
const sync = (root: string | null | undefined) => {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { registerSettingsPages } from "@/workbench/contributions";
|
||||
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE, WORKING_STATUS_PAGE } from "./model";
|
||||
|
||||
/** Settings › Agents › Coding Agents and Settings › Agents › External MCP Servers (also used by the Settings window). */
|
||||
export function activateSettingsPages(): () => void {
|
||||
return registerSettingsPages([
|
||||
{
|
||||
id: REGISTRY_PAGE,
|
||||
title: "Coding Agents",
|
||||
group: AGENTS_GROUP,
|
||||
// First in Agents, which sits after Languages & Frameworks and before Tools.
|
||||
order: 450,
|
||||
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
|
||||
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
|
||||
},
|
||||
{
|
||||
id: WORKING_STATUS_PAGE,
|
||||
title: "Working Status",
|
||||
group: AGENTS_GROUP,
|
||||
// After Chat.
|
||||
order: 465,
|
||||
keywords: ["agent", "status", "playful", "words", "working", "spinner", "fun", "delay", "seconds"],
|
||||
component: lazyComponent(() => import("./WorkingStatusPage").then((m) => m.WorkingStatusPage)),
|
||||
},
|
||||
{
|
||||
id: MCP_PAGE,
|
||||
title: "External MCP Servers",
|
||||
group: AGENTS_GROUP,
|
||||
order: 475,
|
||||
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
|
||||
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
|
||||
},
|
||||
{
|
||||
id: POLICY_PAGE,
|
||||
title: "Command Permissions",
|
||||
group: AGENTS_GROUP,
|
||||
order: 490,
|
||||
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "permission", "command", "exec"],
|
||||
component: lazyComponent(() => import("./AgentPolicyPage").then((m) => m.AgentPolicyPage)),
|
||||
},
|
||||
]);
|
||||
}
|
||||
@@ -22,12 +22,6 @@ import { installLaunchHandling, installLightEditAutoClose, windowActions } from
|
||||
import { WorkspaceDialogHost } from "./WorkspaceDialog";
|
||||
import { installWindowGroups } from "@/platform/windowGroups";
|
||||
|
||||
/** The UI locale of a secondary (Settings, comparison) window. */
|
||||
export const activateLocale = installLocaleSync;
|
||||
/** Native menu items of a secondary window that runs actions itself (comparison). */
|
||||
export const activateMenuBridge = installMenuBridge;
|
||||
export { confirmLeave } from "./closeGuard";
|
||||
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
installLocaleSync(),
|
||||
|
||||
@@ -370,6 +370,9 @@
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.formFull {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.paramInput {
|
||||
font-family: var(--openidea-editor-font, var(--font-mono));
|
||||
font-weight: var(--fw-code);
|
||||
|
||||
@@ -454,7 +454,7 @@ export function DatabaseView() {
|
||||
case "source":
|
||||
return sourceIcon(n.source);
|
||||
case "database":
|
||||
return "database";
|
||||
return "db-database";
|
||||
case "schema":
|
||||
return "db-schema";
|
||||
case "folder":
|
||||
|
||||
@@ -1,34 +1,42 @@
|
||||
/**
|
||||
* Dialogs of the Database tree's object actions, after IDEA's: Rename, Confirm
|
||||
* Drop, Truncate, Modify Table / New Table (with a Preview of the SQL they
|
||||
* run), Remove Data Source, Data Source from URL, and the Quick Documentation popup.
|
||||
* Drop, Truncate, Modify Table / New Table, New Database / New Schema (with a
|
||||
* Preview of the SQL they run), Remove Data Source, Data Source from URL, and the Quick Documentation popup.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { call, commands, type DbColumnInfo, type DbDriver } from "@/platform/ipc";
|
||||
import { highlightInto } from "@/editor/lsp/markdown";
|
||||
import { Button, Checkbox, Dialog, IconButton, Input, Popup, Icon, T } from "@/ui";
|
||||
import { Button, Checkbox, Dialog, IconButton, Input, Popup, Icon, Select, T, type SelectOption } from "@/ui";
|
||||
import { parseSourceUrl, sourceLabel, splitTarget } from "./model";
|
||||
import { nodeTarget, schemaObjectOf, tableOf, type DbNode } from "./nodes";
|
||||
import {
|
||||
alterTableSql,
|
||||
canAlterColumn,
|
||||
createDatabaseSql,
|
||||
createSchemaSql,
|
||||
createTableSql,
|
||||
draftOf,
|
||||
dropDatabaseSql,
|
||||
dropSql,
|
||||
ident,
|
||||
reference,
|
||||
renameSql,
|
||||
truncateSql,
|
||||
type ColumnDraft,
|
||||
templateOf,
|
||||
type CreateOptions,
|
||||
type DbObjectRef,
|
||||
} from "./objects";
|
||||
import {
|
||||
closeDialog,
|
||||
detailsKey,
|
||||
connectedTargets,
|
||||
createDatabase,
|
||||
dropDatabase,
|
||||
loadDetails,
|
||||
openSourceDialog,
|
||||
readableDdl,
|
||||
refresh,
|
||||
renameSource,
|
||||
runSql,
|
||||
sourceById,
|
||||
@@ -80,14 +88,15 @@ function objectName(o: DbObjectRef): string {
|
||||
function useRunner() {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const running = useRef(false);
|
||||
const runAndClose = async (id: string, statements: string[]) => {
|
||||
if (running.current) return;
|
||||
const runAndClose = async (id: string, statements: string[]): Promise<boolean> => {
|
||||
if (running.current) return false;
|
||||
running.current = true;
|
||||
setBusy(true);
|
||||
const ok = await runSql(id, statements);
|
||||
running.current = false;
|
||||
setBusy(false);
|
||||
if (ok) closeDialog();
|
||||
return ok;
|
||||
};
|
||||
return { busy, runAndClose };
|
||||
}
|
||||
@@ -116,7 +125,7 @@ function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }
|
||||
width={480}
|
||||
buttons={[
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{ label: "Refactor", role: "default", disabled: busy || !name.trim(), onClick: submit },
|
||||
{ label: "Refactor", role: "default", disabled: busy || !name.trim(), onClick: () => void submit() },
|
||||
]}
|
||||
>
|
||||
<div className={styles.dialogBody}>
|
||||
@@ -213,6 +222,169 @@ function TruncateDialog({ id, schema, table }: { id: string; schema: string; tab
|
||||
);
|
||||
}
|
||||
|
||||
// ---- New Database / New Schema / Drop database ---------------------------------
|
||||
|
||||
const TEMPLATES: SelectOption[] = [
|
||||
{ value: "", label: "Server default" },
|
||||
...["template0", "template1"].map((name) => ({ value: name, label: name, verbatim: true })),
|
||||
];
|
||||
|
||||
/** An optional text field of the create dialogs: empty leaves it to the server. */
|
||||
function OptionField({
|
||||
id,
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
id: string;
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<label className={styles.formLabel} htmlFor={id}>
|
||||
{tx(label)}
|
||||
</label>
|
||||
<Input id={id} placeholder="Server default" value={value} onChange={(e) => onChange(e.target.value)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** New › Database (`database`) or New › Schema (`schema`) in target `id`. */
|
||||
function CreateDialog({ id, what }: { id: string; what: "database" | "schema" }) {
|
||||
const driver = driverOf(id);
|
||||
const [name, setName] = useState("");
|
||||
const [opts, setOpts] = useState<CreateOptions>({});
|
||||
const { busy: running, runAndClose } = useRunner();
|
||||
const [creating, setCreating] = useState(false);
|
||||
const busy = running || creating;
|
||||
const sql = (what === "database" ? createDatabaseSql : createSchemaSql)(driver, name.trim() || "<name>", opts);
|
||||
const submit = async () => {
|
||||
if (what === "schema") {
|
||||
if (await runAndClose(id, [sql])) void refresh(id);
|
||||
return;
|
||||
}
|
||||
setCreating(true);
|
||||
if (await createDatabase(id, templateOf(driver, opts), sql)) closeDialog();
|
||||
else setCreating(false);
|
||||
};
|
||||
const field = (key: keyof CreateOptions, label: string) => (
|
||||
<OptionField
|
||||
id={`db-new-${key}`}
|
||||
label={label}
|
||||
value={opts[key] ?? ""}
|
||||
onChange={(value) => setOpts((o) => ({ ...o, [key]: value }))}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={closeDialog}
|
||||
title={what === "database" ? "New Database" : "New Schema"}
|
||||
width={560}
|
||||
buttons={[
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{ label: "OK", role: "default", disabled: busy || !name.trim(), onClick: submit },
|
||||
]}
|
||||
>
|
||||
<div className={styles.form}>
|
||||
<label className={styles.formLabel} htmlFor="db-new-name">
|
||||
<T>Name:</T>
|
||||
</label>
|
||||
<Input id="db-new-name" autoFocus value={name} onChange={(e) => setName(e.target.value)} />
|
||||
{what === "database" && driver === "postgres" && (
|
||||
<>
|
||||
{field("owner", "Owner:")}
|
||||
<label className={styles.formLabel} htmlFor="db-new-template">
|
||||
<T>Template:</T>
|
||||
</label>
|
||||
<Select
|
||||
id="db-new-template"
|
||||
value={opts.template ?? ""}
|
||||
options={TEMPLATES}
|
||||
onChange={(template) => setOpts((o) => ({ ...o, template }))}
|
||||
/>
|
||||
<span />
|
||||
<span className={styles.formHint}>
|
||||
<T>Restoring a dump needs template0: template1 can already hold extensions and schemas.</T>
|
||||
</span>
|
||||
{field("encoding", "Encoding:")}
|
||||
{field("tablespace", "Tablespace:")}
|
||||
</>
|
||||
)}
|
||||
{what === "database" && driver === "sqlServer" && field("collation", "Collation:")}
|
||||
{what === "schema" && driver === "mysql" && (
|
||||
<>
|
||||
{field("charset", "Character set:")}
|
||||
{field("collation", "Collation:")}
|
||||
</>
|
||||
)}
|
||||
{what === "schema" && driver !== "mysql" && field("owner", "Owner:")}
|
||||
<div className={styles.formFull}>
|
||||
<SqlPreview sql={sql} />
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/** PostgreSQL 13 added `drop database … with (force)`. */
|
||||
const PG_FORCE_DROP = 130000;
|
||||
|
||||
function DropDatabaseDialog({ id, database }: { id: string; database: string }) {
|
||||
const driver = driverOf(id);
|
||||
const [force, setForce] = useState(false);
|
||||
const [version, setVersion] = useState<number | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
if (driver !== "postgres") return;
|
||||
let live = true;
|
||||
void withConnection(id, () => call(commands.dbServerVersion(id)))
|
||||
.then((v) => live && setVersion(v))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [id, driver]);
|
||||
const canForce = driver === "sqlServer" || (version ?? 0) >= PG_FORCE_DROP;
|
||||
const sql = dropDatabaseSql(driver, database, force && canForce);
|
||||
const submit = async () => {
|
||||
setBusy(true);
|
||||
if (await dropDatabase(id, database, sql)) closeDialog();
|
||||
else setBusy(false);
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={closeDialog}
|
||||
title="Confirm Drop"
|
||||
width={520}
|
||||
buttons={[
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{ label: "OK", role: "default", disabled: busy, onClick: () => void submit() },
|
||||
]}
|
||||
>
|
||||
<div className={styles.dialogBody}>
|
||||
<div className={styles.dialogLead}>
|
||||
{tx`Drop database`} <strong>{database}</strong>
|
||||
{tx`? This cannot be undone.`}
|
||||
</div>
|
||||
<span className={styles.formHint}>
|
||||
<T>The IDE closes its own connections to the database first.</T>
|
||||
</span>
|
||||
<Checkbox
|
||||
checked={force && canForce}
|
||||
onChange={setForce}
|
||||
disabled={!canForce}
|
||||
label="Close the sessions of other clients"
|
||||
/>
|
||||
<SqlPreview sql={sql} />
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Modify Table / New Table -----------------------------------------------
|
||||
|
||||
const TYPES: Record<DbDriver, string[]> = {
|
||||
@@ -726,6 +898,12 @@ export function ObjectDialogs() {
|
||||
return <DropDialog id={dialog.id} object={dialog.object} />;
|
||||
case "truncate":
|
||||
return <TruncateDialog id={dialog.id} schema={dialog.schema} table={dialog.table} />;
|
||||
case "createDatabase":
|
||||
return <CreateDialog id={dialog.id} what="database" />;
|
||||
case "createSchema":
|
||||
return <CreateDialog id={dialog.id} what="schema" />;
|
||||
case "dropDatabase":
|
||||
return <DropDatabaseDialog id={dialog.id} database={dialog.database} />;
|
||||
case "modifyTable":
|
||||
return (
|
||||
<ModifyTableDialog
|
||||
|
||||
@@ -39,13 +39,41 @@ const PAGE_SIZES = ["100", "500", "1000", "5000"];
|
||||
|
||||
export { tableTitle } from "./tableInput";
|
||||
|
||||
/** WHERE, ORDER BY and page of a table tab, kept when a tab that is no longer kept alive mounts again. */
|
||||
interface TableViewState {
|
||||
offset: number;
|
||||
limit: number;
|
||||
sort: DbSortKey[];
|
||||
filterText: string;
|
||||
filter: string;
|
||||
}
|
||||
|
||||
const MAX_VIEW_STATES = 100;
|
||||
const viewStates = new Map<string, TableViewState>();
|
||||
|
||||
function rememberViewState(key: string, state: TableViewState) {
|
||||
viewStates.delete(key);
|
||||
viewStates.set(key, state);
|
||||
if (viewStates.size > MAX_VIEW_STATES) viewStates.delete(viewStates.keys().next().value!);
|
||||
}
|
||||
|
||||
/** Test hook: forget the remembered table view states. */
|
||||
export function _resetTableViewStates() {
|
||||
viewStates.clear();
|
||||
}
|
||||
|
||||
export function TableEditor({ input }: { input: EditorInput }) {
|
||||
const ref = input.data as TableRef;
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [limit, setLimit] = useState(500);
|
||||
const [sort, setSort] = useState<DbSortKey[]>([]);
|
||||
const [filterText, setFilterText] = useState("");
|
||||
const [filter, setFilter] = useState("");
|
||||
const [initial] = useState(() => viewStates.get(input.key));
|
||||
const [offset, setOffset] = useState(initial?.offset ?? 0);
|
||||
const [limit, setLimit] = useState(initial?.limit ?? 500);
|
||||
const [sort, setSort] = useState<DbSortKey[]>(initial?.sort ?? []);
|
||||
const [filterText, setFilterText] = useState(initial?.filterText ?? "");
|
||||
const [filter, setFilter] = useState(initial?.filter ?? "");
|
||||
useEffect(
|
||||
() => rememberViewState(input.key, { offset, limit, sort, filterText, filter }),
|
||||
[input.key, offset, limit, sort, filterText, filter],
|
||||
);
|
||||
const [nonce, setNonce] = useState(0);
|
||||
const [edits, setEdits] = useState<PendingEdits>(emptyEdits);
|
||||
const [panel, setPanel] = useState<DataPanel | null>(null);
|
||||
|
||||
@@ -81,8 +81,6 @@ function tableTarget(arg: unknown): TableCommandTarget {
|
||||
return { rows: activeCellGrid()?.selectedRows() ?? [], editor: null };
|
||||
}
|
||||
|
||||
export { activateSettingsPages } from "./settingsPages";
|
||||
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
onIdeEvent("dbSourcesChanged", () => {
|
||||
@@ -111,6 +109,8 @@ export function activate(): () => void {
|
||||
component: lazyComponent(() => import("./TableEditor").then((m) => m.TableEditor)),
|
||||
title: tableTitle,
|
||||
icon: () => "database",
|
||||
// Switching tabs keeps the rows, filters, page and unsubmitted edits without querying again.
|
||||
keepAlive: true,
|
||||
}),
|
||||
registerOverlay({
|
||||
id: "database.dialogs",
|
||||
|
||||
@@ -4,8 +4,12 @@ import {
|
||||
alterTableSql,
|
||||
canDrop,
|
||||
canModifyTable,
|
||||
createDatabaseSql,
|
||||
createSchemaSql,
|
||||
createTableSql,
|
||||
draftOf,
|
||||
dropDatabaseSql,
|
||||
templateOf,
|
||||
dropSql,
|
||||
ident,
|
||||
reference,
|
||||
@@ -341,3 +345,49 @@ describe("snowflake object SQL", () => {
|
||||
expect(alterTableSql("snowflake", "HR", "EMP", "EMP", dropped)).toEqual(["alter table HR.EMP drop column NAME;"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("database and schema SQL", () => {
|
||||
it("creates a PostgreSQL database with only the options given", () => {
|
||||
expect(createDatabaseSql("postgres", "shop", {})).toBe("create database shop;");
|
||||
expect(
|
||||
createDatabaseSql("postgres", "Shop Copy", {
|
||||
owner: "app",
|
||||
template: "template0",
|
||||
encoding: "UTF8",
|
||||
tablespace: " ",
|
||||
}),
|
||||
).toBe(`create database "Shop Copy" owner app template template0 encoding 'UTF8';`);
|
||||
expect(createDatabaseSql("postgres", "shop", { encoding: "it's" })).toBe("create database shop encoding 'it''s';");
|
||||
});
|
||||
|
||||
it("names the database the server copies for a new one", () => {
|
||||
expect(templateOf("postgres", {})).toBe("template1");
|
||||
expect(templateOf("postgres", { template: "template0" })).toBe("template0");
|
||||
expect(templateOf("sqlServer", { template: "ignored" })).toBe("model");
|
||||
});
|
||||
|
||||
it("creates a SQL Server database with a collation", () => {
|
||||
expect(createDatabaseSql("sqlServer", "shop", { collation: "Latin1_General_CI_AS", owner: "ignored" })).toBe(
|
||||
"create database shop collate Latin1_General_CI_AS;",
|
||||
);
|
||||
});
|
||||
|
||||
it("creates a schema with an owner, and a MySQL schema as a database", () => {
|
||||
expect(createSchemaSql("postgres", "sales", {})).toBe("create schema sales;");
|
||||
expect(createSchemaSql("postgres", "sales", { owner: "app" })).toBe("create schema sales authorization app;");
|
||||
expect(createSchemaSql("sqlServer", "sales", { owner: "dbo" })).toBe("create schema sales authorization dbo;");
|
||||
expect(createSchemaSql("mysql", "shop", { charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci" })).toBe(
|
||||
"create database shop character set utf8mb4 collate utf8mb4_0900_ai_ci;",
|
||||
);
|
||||
expect(createSchemaSql("mysql", "shop", {})).toBe("create database shop;");
|
||||
});
|
||||
|
||||
it("drops a database, forcing out other sessions when asked", () => {
|
||||
expect(dropDatabaseSql("postgres", "shop", false)).toBe("drop database shop;");
|
||||
expect(dropDatabaseSql("postgres", "shop", true)).toBe("drop database shop with (force);");
|
||||
expect(dropDatabaseSql("sqlServer", "shop", false)).toBe("drop database shop;");
|
||||
expect(dropDatabaseSql("sqlServer", "shop", true)).toBe(
|
||||
"alter database shop set single_user with rollback immediate;\ndrop database shop;",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -180,6 +180,63 @@ export function truncateSql(
|
||||
return `truncate table ${q}${opts.restartIdentity ? " restart identity" : ""}${opts.cascade ? " cascade" : ""};`;
|
||||
}
|
||||
|
||||
const literal = (value: string) => `'${value.replace(/'/g, "''")}'`;
|
||||
|
||||
/** Options of New › Database / New › Schema; an empty or absent one is left to the server. */
|
||||
export interface CreateOptions {
|
||||
owner?: string;
|
||||
template?: string;
|
||||
encoding?: string;
|
||||
tablespace?: string;
|
||||
charset?: string;
|
||||
collation?: string;
|
||||
}
|
||||
|
||||
/** New › Database (PostgreSQL, SQL Server). */
|
||||
export function createDatabaseSql(driver: DbDriver, name: string, opts: CreateOptions): string {
|
||||
const clauses: string[] = [];
|
||||
const add = (keyword: string, value: string | undefined, quote = (v: string) => ident(driver, v)) => {
|
||||
if (value?.trim()) clauses.push(`${keyword} ${quote(value.trim())}`);
|
||||
};
|
||||
if (driver === "postgres") {
|
||||
add("owner", opts.owner);
|
||||
add("template", opts.template);
|
||||
add("encoding", opts.encoding, literal);
|
||||
add("tablespace", opts.tablespace);
|
||||
} else if (driver === "sqlServer") {
|
||||
add("collate", opts.collation, (v) => v);
|
||||
}
|
||||
return `create database ${ident(driver, name)}${clauses.map((c) => ` ${c}`).join("")};`;
|
||||
}
|
||||
|
||||
/** The database the server copies for New › Database: the chosen template on PostgreSQL, `model` on SQL Server. */
|
||||
export function templateOf(driver: DbDriver, opts: CreateOptions): string {
|
||||
return driver === "sqlServer" ? "model" : opts.template?.trim() || "template1";
|
||||
}
|
||||
|
||||
/** New › Schema; on MySQL a schema is a database, with a character set and collation instead of an owner. */
|
||||
export function createSchemaSql(driver: DbDriver, name: string, opts: CreateOptions): string {
|
||||
if (driver === "mysql") {
|
||||
const charset = opts.charset?.trim() ? ` character set ${opts.charset.trim()}` : "";
|
||||
const collation = opts.collation?.trim() ? ` collate ${opts.collation.trim()}` : "";
|
||||
return `create database ${ident(driver, name)}${charset}${collation};`;
|
||||
}
|
||||
const owner = opts.owner?.trim() ? ` authorization ${ident(driver, opts.owner.trim())}` : "";
|
||||
return `create schema ${ident(driver, name)}${owner};`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop on a database node. `force` ends the sessions of other clients first:
|
||||
* `with (force)` on PostgreSQL 13+, single-user mode on SQL Server.
|
||||
*/
|
||||
export function dropDatabaseSql(driver: DbDriver, name: string, force: boolean): string {
|
||||
const db = ident(driver, name);
|
||||
// One batch: the session that sets single-user mode is the single user, so it must drop too.
|
||||
if (driver === "sqlServer" && force)
|
||||
return `alter database ${db} set single_user with rollback immediate;\ndrop database ${db};`;
|
||||
return `drop database ${db}${force && driver === "postgres" ? " with (force)" : ""};`;
|
||||
}
|
||||
|
||||
export type ScriptKind = "selectAll" | "selectFirst" | "insert" | "update" | "delete";
|
||||
|
||||
export const SCRIPT_LABELS: Record<ScriptKind, string> = {
|
||||
|
||||
@@ -417,6 +417,16 @@ describe("connection and metadata continuations", () => {
|
||||
});
|
||||
}
|
||||
|
||||
it("does not list sources after the project is closed", async () => {
|
||||
// Closing the project resets `loaded`; a still-mounted SQL console then asks for sources again.
|
||||
useProject.setState({ project: null });
|
||||
backend.sources.mockRejectedValue(new Error("no project is open in this window"));
|
||||
backend.connected.mockRejectedValue(new Error("no project is open in this window"));
|
||||
await loadSources();
|
||||
expect(ui.notify).not.toHaveBeenCalled();
|
||||
expect(backend.sources).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("can load metadata again after a disconnect fails", async () => {
|
||||
backend.disconnect.mockRejectedValueOnce(new Error("disconnect failed"));
|
||||
await expect(disconnect("pg")).rejects.toThrow("disconnect failed");
|
||||
|
||||
@@ -130,6 +130,11 @@ export type DialogState =
|
||||
/** Confirm Drop / Truncate, with a preview of the statement. */
|
||||
| { kind: "drop"; id: string; object: DbObjectRef }
|
||||
| { kind: "truncate"; id: string; schema: string; table: string }
|
||||
/** New › Database of data source `id`; New › Schema in target `id`. */
|
||||
| { kind: "createDatabase"; id: string }
|
||||
| { kind: "createSchema"; id: string }
|
||||
/** Drop on database `database` of data source `id`. */
|
||||
| { kind: "dropDatabase"; id: string; database: string }
|
||||
/** Modify Table (`table` null: New › Table); `focusColumn` selects a column, `addColumn` starts a new one. */
|
||||
| { kind: "modifyTable"; id: string; schema: string; table: string | null; focusColumn?: string; addColumn?: boolean }
|
||||
/** Quick Documentation of a tree node, shown at `anchor` (client coordinates). */
|
||||
@@ -325,6 +330,8 @@ function sourceMutation(id: string): () => boolean {
|
||||
}
|
||||
|
||||
export async function loadSources(): Promise<void> {
|
||||
// Closing the project resets `loaded` while its SQL consoles are still mounted.
|
||||
if (!useProject.getState().project) return;
|
||||
const request = ++sourcesRequest;
|
||||
const current = projectRequest();
|
||||
const intents = new Map(connectionIntents);
|
||||
@@ -614,6 +621,20 @@ export function listsDatabases(source: DataSource | undefined): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/** New › Database and Drop on database nodes: PostgreSQL and SQL Server data sources that show their databases. */
|
||||
export function createsDatabases(source: DataSource | undefined): boolean {
|
||||
return listsDatabases(source) && source?.driver !== "snowflake";
|
||||
}
|
||||
|
||||
/** The target New › Schema creates a schema in: a database node, or a data source that shows schemas directly. */
|
||||
export function newSchemaTarget(n: DbNode): string | null {
|
||||
if (n.kind === "database") return createsDatabases(sourceById(n.id)) ? n.id : null;
|
||||
if (n.kind !== "source" || !n.source.id) return null;
|
||||
const driver = n.source.driver;
|
||||
if (driver !== "postgres" && driver !== "sqlServer" && driver !== "mysql") return null;
|
||||
return listsDatabases(n.source) ? null : n.source.id;
|
||||
}
|
||||
|
||||
interface LoadedLevels {
|
||||
schemas: string[];
|
||||
tables: [string, string][];
|
||||
@@ -1091,6 +1112,38 @@ export async function runSql(id: string, texts: string[]): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a database on data source `id` with `sql` after disconnecting `template`, then refreshes
|
||||
* the data source, reloading what the tree had shown of `template` too.
|
||||
*/
|
||||
export async function createDatabase(id: string, template: string, sql: string): Promise<boolean> {
|
||||
const levels = loadedLevels(id);
|
||||
await disconnect(`${id}:${template}`);
|
||||
try {
|
||||
// Asks for a password the data source does not save, like any statement it runs.
|
||||
await withConnection(id, () => call(commands.dbCreateDatabase(id, template, sql)));
|
||||
} catch (e) {
|
||||
notifications().notify({ level: "error", title: tx`Cannot create database`, body: message(e) });
|
||||
void refresh(id, levels);
|
||||
return false;
|
||||
}
|
||||
void refresh(id, levels);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Drops `database` of data source `id` with `sql` after disconnecting it, then refreshes the data source. */
|
||||
export async function dropDatabase(id: string, database: string, sql: string): Promise<boolean> {
|
||||
await disconnect(`${id}:${database}`);
|
||||
try {
|
||||
await withConnection(id, () => call(commands.dbDropDatabase(id, database, sql)));
|
||||
} catch (e) {
|
||||
notifications().notify({ level: "error", title: tx`Cannot drop database ${database}`, body: message(e) });
|
||||
return false;
|
||||
}
|
||||
void refresh(id);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Opens the query console of `id` with `text` appended and selected (SQL Scripts › …). */
|
||||
export async function openConsoleWith(id: string, text: string): Promise<void> {
|
||||
let path: string;
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { DbDriver, DbTablePage } from "@/platform/ipc";
|
||||
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
|
||||
import { activeCellGrid, installCellActions } from "./cellActions";
|
||||
import { getContext } from "@/platform/context";
|
||||
import { TableEditor } from "./TableEditor";
|
||||
import { TableEditor, _resetTableViewStates } from "./TableEditor";
|
||||
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
|
||||
import { tableInput } from "./tableInput";
|
||||
|
||||
@@ -59,6 +59,7 @@ const page: DbTablePage = {
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
_resetTableViewStates();
|
||||
backend.driver = "clickhouse";
|
||||
backend.page.mockResolvedValue({ status: "ok", data: page });
|
||||
backend.applyEdits.mockClear();
|
||||
@@ -211,3 +212,25 @@ it("omits a reset inserted cell from Submit instead of writing SQL NULL", async
|
||||
disposeActions();
|
||||
}
|
||||
});
|
||||
|
||||
describe("table editor view state", () => {
|
||||
it("queries with the sort it had when its tab mounts again", async () => {
|
||||
const input = tableInput("source", "default", "users");
|
||||
let view!: ReturnType<typeof render>;
|
||||
await act(async () => {
|
||||
view = render(<TableEditor input={input} />);
|
||||
});
|
||||
await screen.findByRole("gridcell", { name: "Ann" });
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole("columnheader", { name: /name/ }));
|
||||
});
|
||||
const sorted = backend.page.mock.calls.at(-1)!;
|
||||
expect(sorted[5]).toEqual([{ column: "name", descending: false }]);
|
||||
view.unmount();
|
||||
backend.page.mockClear();
|
||||
await act(async () => {
|
||||
render(<TableEditor input={input} />);
|
||||
});
|
||||
expect(backend.page.mock.calls[0]![5]).toEqual(sorted[5]);
|
||||
});
|
||||
});
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
DB_TOOL_WINDOW,
|
||||
OUTPUT_TAB,
|
||||
connect,
|
||||
createsDatabases,
|
||||
RESULTS_VIEW,
|
||||
detailsKey,
|
||||
disconnect,
|
||||
@@ -24,6 +25,7 @@ import {
|
||||
loadSources,
|
||||
loadTables,
|
||||
consoleFiles,
|
||||
newSchemaTarget,
|
||||
newConsole,
|
||||
openConsole,
|
||||
openConsoleFile,
|
||||
@@ -358,6 +360,9 @@ export function registerDatabaseTreeActions(): () => void {
|
||||
if (!n) return;
|
||||
const id = nodeTarget(n);
|
||||
if (n.kind === "source") return void removeSource(n.source);
|
||||
const source = sourceById(id);
|
||||
if (n.kind === "database" && !n.current && !source?.readOnly && createsDatabases(source))
|
||||
return openDialog({ kind: "dropDatabase", id: splitTarget(n.id).id, database: n.name });
|
||||
const o = objectOf(n);
|
||||
if (id && o && canDrop(driverOf(id), o)) openDialog({ kind: "drop", id, object: o });
|
||||
},
|
||||
@@ -390,6 +395,28 @@ export function registerDatabaseTreeActions(): () => void {
|
||||
});
|
||||
},
|
||||
}),
|
||||
tree({
|
||||
id: "db.newDatabase",
|
||||
title: "Database…",
|
||||
icon: "db-database",
|
||||
keywords: ["create database", "new database"],
|
||||
run: ({ arg }) => {
|
||||
const source = sourceOf(nodeFrom(arg));
|
||||
if (source?.id && !source.readOnly && createsDatabases(source))
|
||||
openDialog({ kind: "createDatabase", id: source.id });
|
||||
},
|
||||
}),
|
||||
tree({
|
||||
id: "db.newSchema",
|
||||
title: "Schema…",
|
||||
icon: "db-schema",
|
||||
keywords: ["create schema", "new schema"],
|
||||
run: ({ arg }) => {
|
||||
const n = nodeFrom(arg);
|
||||
const id = n && newSchemaTarget(n);
|
||||
if (id && !sourceById(id)?.readOnly) openDialog({ kind: "createSchema", id });
|
||||
},
|
||||
}),
|
||||
tree({
|
||||
id: "db.newTable",
|
||||
title: "Table",
|
||||
|
||||
@@ -5,7 +5,15 @@ import { fileSourceName, parseSourceUrl } from "./model";
|
||||
import { VENDORS, vendorPreset } from "./vendors";
|
||||
import { nodeTarget, objectOf, tableOf, type DbNode } from "./nodes";
|
||||
import { SCRIPT_LABELS, canDrop, canModifyTable, canRename, type ScriptKind } from "./objects";
|
||||
import { connectedTargets, openDialog, openSourceDialog, sourceById, useDatabase } from "./store";
|
||||
import {
|
||||
connectedTargets,
|
||||
createsDatabases,
|
||||
newSchemaTarget,
|
||||
openDialog,
|
||||
openSourceDialog,
|
||||
sourceById,
|
||||
useDatabase,
|
||||
} from "./store";
|
||||
import { readClipboardPlainText } from "@/platform/clipboard";
|
||||
import { useRemote } from "@/platform/remote";
|
||||
import { dumpScope, mysqlDumpScope } from "./dumpTools";
|
||||
@@ -113,6 +121,8 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
|
||||
const rename = act("db.rename", n, { disabled: !(n.kind === "source" || (o && canRename(driver, o))) });
|
||||
const drop = act("db.drop", n, { disabled: !o || !canDrop(driver, o) });
|
||||
const copyRef = act("db.copyReference", n);
|
||||
const readOnly = !!sourceById(id)?.readOnly;
|
||||
const newSchema = newSchemaTarget(n) ? [act("db.newSchema", n, { disabled: readOnly })] : [];
|
||||
const navigation = (extra: MenuItem[] = []): MenuItem => ({
|
||||
label: "Navigation",
|
||||
submenu: [...extra, act("db.jumpToConsole", n)],
|
||||
@@ -124,7 +134,18 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
|
||||
return [
|
||||
act("db.properties", n, { label: "Properties" }),
|
||||
sep,
|
||||
{ label: "New", icon: "plus", submenu: [newConsole, sep, ...dataSourceItems()] },
|
||||
{
|
||||
label: "New",
|
||||
icon: "plus",
|
||||
submenu: [
|
||||
newConsole,
|
||||
sep,
|
||||
...(createsDatabases(n.source) ? [act("db.newDatabase", n, { disabled: readOnly })] : []),
|
||||
...newSchema,
|
||||
...(createsDatabases(n.source) || newSchema.length ? [sep] : []),
|
||||
...dataSourceItems(),
|
||||
],
|
||||
},
|
||||
{ label: "Copy/Paste", submenu: [copyRef, act("db.duplicateSource", n)] },
|
||||
refresh,
|
||||
...(n.source.driver === "snowflake" ? [act("db.introspect", n)] : []),
|
||||
@@ -144,7 +165,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
|
||||
}
|
||||
case "database":
|
||||
return [
|
||||
{ label: "New", icon: "plus", submenu: [newConsole] },
|
||||
{ label: "New", icon: "plus", submenu: [newConsole, ...(newSchema.length ? [sep, ...newSchema] : [])] },
|
||||
{ label: "Copy/Paste", submenu: [copyRef] },
|
||||
refresh,
|
||||
act("db.disconnect", n, { disabled: !useDatabase.getState().connected.has(id) || n.current }),
|
||||
@@ -152,6 +173,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
|
||||
navigation(),
|
||||
sqlScripts(n, false),
|
||||
...importExport(dumpItems(n, true)),
|
||||
...(createsDatabases(sourceById(id)) ? [sep, act("db.drop", n, { disabled: n.current || readOnly })] : []),
|
||||
];
|
||||
case "schema":
|
||||
case "folder":
|
||||
|
||||
@@ -17,8 +17,6 @@ import { transferMenuEntries } from "./model";
|
||||
import { REMOTE_HOST_WINDOW, useDeployment } from "./store";
|
||||
import { installDeploymentEditorHost } from "./windowBridge";
|
||||
|
||||
export { activateDeploymentWindow, DeploymentWindow } from "./window";
|
||||
|
||||
/** Deployed URL of the path the last menu was prepared for. */
|
||||
let webUrlFor: { path: string; url: string | null } | null = null;
|
||||
|
||||
|
||||
@@ -24,8 +24,6 @@ import { githubHandler, handlerContextKey } from "./toolwindow/handlers";
|
||||
import { GithubDialogHost } from "./ui/dialogs";
|
||||
import { activateSettingsPages } from "./settingsPages";
|
||||
|
||||
export { activateSettingsPages } from "./settingsPages";
|
||||
|
||||
const WINDOW = "pullRequests";
|
||||
const TIMELINE_KIND = "github.timeline";
|
||||
const WHEN = "projectOpen";
|
||||
|
||||
+12
-86
@@ -13,13 +13,7 @@ import { activate as projectTree } from "./project-tree";
|
||||
import { activate as search } from "./search";
|
||||
import { activate as dependencies } from "./dependencies";
|
||||
import { activate as codeInsight } from "./code-insight";
|
||||
import {
|
||||
activate as vcs,
|
||||
activateComparisonWindow,
|
||||
activateDiffViewer,
|
||||
activateDiffWindow,
|
||||
activateSettingsPages as vcsPages,
|
||||
} from "./vcs";
|
||||
import { activate as vcs } from "./vcs";
|
||||
import { activate as terminal } from "./terminal";
|
||||
import { activate as run } from "./run";
|
||||
import { activate as dotnet } from "./dotnet";
|
||||
@@ -32,13 +26,13 @@ import { activate as profiler } from "./profiler";
|
||||
import { activate as logcat } from "./logcat";
|
||||
import { activate as buildTools } from "./build-tools";
|
||||
import { activate as build } from "./build";
|
||||
import { activate as templates, activateSettingsPages as templatesPages } from "./templates";
|
||||
import { activate as todo, activateSettingsPages as todoPages } from "./todo";
|
||||
import { activate as settings, activateRuntimeSettings, activateSettingsWindow } from "./settings";
|
||||
import { activate as app, activateLocale as appLocale, activateMenuBridge, confirmLeave } from "./app";
|
||||
import { activate as templates } from "./templates";
|
||||
import { activate as todo } from "./todo";
|
||||
import { activate as settings } from "./settings";
|
||||
import { activate as app } from "./app";
|
||||
import { activate as perf } from "./perf";
|
||||
import { activate as plugins, activateSettingsPages as pluginsPages } from "./plugins";
|
||||
import { activate as tools, activateSettingsPages as toolsPages } from "./tools";
|
||||
import { activate as plugins } from "./plugins";
|
||||
import { activate as tools } from "./tools";
|
||||
import { activate as scratch } from "./scratch";
|
||||
import { activate as libraries } from "./libraries";
|
||||
import { activate as viewers } from "./viewers";
|
||||
@@ -46,16 +40,16 @@ import { activate as notebook } from "./notebook";
|
||||
import { activate as web } from "./web";
|
||||
import { activate as analysis } from "./analysis";
|
||||
import { activate as services } from "./services";
|
||||
import { activate as github, activateSettingsPages as githubPages } from "./github";
|
||||
import { activate as github } from "./github";
|
||||
import { activate as httpClient } from "./http-client";
|
||||
import { activate as cucumber } from "./cucumber";
|
||||
import { activate as rails } from "./rails";
|
||||
import { activate as thymeleaf } from "./thymeleaf";
|
||||
import { activate as database, activateSettingsPages as databasePages } from "./database";
|
||||
import { activate as database } from "./database";
|
||||
import { activate as graphql } from "./graphql";
|
||||
import { activate as deployment, activateDeploymentWindow } from "./deployment";
|
||||
import { activate as agents, activateSettingsPages as agentsPages } from "./agents";
|
||||
import { activate as vim, activateSettingsPages as vimPages } from "./vim";
|
||||
import { activate as deployment } from "./deployment";
|
||||
import { activate as agents } from "./agents";
|
||||
import { activate as vim } from "./vim";
|
||||
import { activate as ssh } from "./ssh";
|
||||
import { activate as lspMessages } from "./lsp-messages";
|
||||
import { activate as remoteDev } from "./remote-dev";
|
||||
@@ -132,71 +126,3 @@ function activateAll(what: string, list: Array<[string, Activate]>): () => void
|
||||
export function activateFeatures(): () => void {
|
||||
return activateAll("feature", features);
|
||||
}
|
||||
|
||||
export { SettingsWindow } from "./settings";
|
||||
export { ComparisonWindow, DiffWindow } from "./vcs";
|
||||
export { DeploymentWindow } from "./deployment";
|
||||
|
||||
/**
|
||||
* A comparison window of project window `parent`: the changed files between two revisions and
|
||||
* their diffs, with the editor and Git but no workbench.
|
||||
*/
|
||||
export function activateComparisonWindowFeatures(parent: string): () => void {
|
||||
return activateAll("comparison window", [
|
||||
["locale", appLocale],
|
||||
["settings", activateRuntimeSettings],
|
||||
["menu", activateMenuBridge],
|
||||
["editor", editor],
|
||||
["vcs", vcs],
|
||||
["comparison", () => activateComparisonWindow(parent, (project) => confirmLeave(undefined, project))],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The diff window of project window `parent`: one file's diff, with Git and its own documents but
|
||||
* no workbench.
|
||||
*/
|
||||
export function activateDiffWindowFeatures(parent: string): () => void {
|
||||
return activateAll("diff window", [
|
||||
["locale", appLocale],
|
||||
["settings", activateRuntimeSettings],
|
||||
["menu", activateMenuBridge],
|
||||
["vcs", vcs],
|
||||
["diff", () => activateDiffWindow(parent)],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Sync with Deployed window of project window `parent`: local files next to their copies on a
|
||||
* deployment server, with the diff viewer but no workbench.
|
||||
*/
|
||||
export function activateDeploymentWindowFeatures(parent: string): () => void {
|
||||
return activateAll("deployment window", [
|
||||
["locale", appLocale],
|
||||
["settings", activateRuntimeSettings],
|
||||
["diff", activateDiffViewer],
|
||||
["deployment", () => activateDeploymentWindow(parent)],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The native Settings window of project window `parent`: only the settings
|
||||
* pages (no workbench, project, editors or background services).
|
||||
*/
|
||||
export function activateSettingsWindowFeatures(parent: string): () => void {
|
||||
const pages: Array<[string, Activate]> = [
|
||||
["project-trust", projectTrust],
|
||||
["locale", appLocale],
|
||||
["settings", () => activateSettingsWindow(parent)],
|
||||
["templates", templatesPages],
|
||||
["todo", todoPages],
|
||||
["plugins", pluginsPages],
|
||||
["tools", toolsPages],
|
||||
["agents", agentsPages],
|
||||
["vim", vimPages],
|
||||
["vcs", vcsPages],
|
||||
["github", githubPages],
|
||||
["database", databasePages],
|
||||
];
|
||||
return activateAll("settings pages", pages);
|
||||
}
|
||||
@@ -104,6 +104,19 @@ describe("notebook Markdown preview", () => {
|
||||
rerender(<MarkdownCell source="plain" attachments={{}} path="/p/a.ipynb" />);
|
||||
expect(container.querySelector("p")).toBe(paragraph);
|
||||
});
|
||||
|
||||
it("renders LaTeX math in Markdown cells while blocking unsafe styles", () => {
|
||||
const { container } = render(
|
||||
<MarkdownCell
|
||||
source={'Inline $x^2$ and <div style="position:fixed">hi</div>\n\n$$\n\\sum_{i=1}^n i\n$$'}
|
||||
attachments={{}}
|
||||
path="/p/a.ipynb"
|
||||
/>,
|
||||
);
|
||||
expect(container.querySelectorAll(".katex")).toHaveLength(2);
|
||||
expect(container.querySelector(".katex-display")).not.toBeNull();
|
||||
expect(container.querySelector("div[style]")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("notebook image outputs", () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import DOMPurify from "dompurify";
|
||||
import { Marked } from "marked";
|
||||
import { mathExtension, renderMath } from "@/editor/lsp/markdownMath";
|
||||
import { mimeText, object, own } from "./outputs";
|
||||
|
||||
export const OUTPUT_CSP =
|
||||
@@ -194,7 +195,7 @@ function htmlRoot(html: string, markdown = false): HTMLElement {
|
||||
"rowspan",
|
||||
"scope",
|
||||
"align",
|
||||
...(markdown ? ["href"] : ["style"]),
|
||||
...(markdown ? ["href", "data-math"] : ["style"]),
|
||||
],
|
||||
// Attachment references are resolved by us after sanitization. No arbitrary
|
||||
// URI survives the explicit src allowlist below.
|
||||
@@ -221,13 +222,14 @@ export function staticOutputDocument(html: string): string {
|
||||
return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${OUTPUT_CSP}"><style>body{margin:8px;font:13px system-ui,sans-serif;color:#222;background:white;overflow-wrap:anywhere}table{border-collapse:collapse;max-width:100%}th,td{padding:4px 8px;border:1px solid #ddd;text-align:left}pre{white-space:pre-wrap}img{max-width:100%;height:auto}</style></head><body>${root.innerHTML}</body></html>`;
|
||||
}
|
||||
|
||||
const markdown = new Marked({ gfm: true });
|
||||
const markdown = new Marked({ gfm: true }).use(mathExtension());
|
||||
/**
|
||||
* Sanitized Markdown with inert links; link clicks are handled by the editor and
|
||||
* `attachment:` images are left for `resolveMarkdownAttachments`.
|
||||
*/
|
||||
export function markdownRoot(source: string): HTMLElement {
|
||||
const root = htmlRoot(markdown.parse(source, { async: false }) as string, true);
|
||||
renderMath(root);
|
||||
for (const link of root.querySelectorAll("a[href]")) {
|
||||
const href = link.getAttribute("href")!;
|
||||
link.removeAttribute("href");
|
||||
|
||||
+13
-253
@@ -6,262 +6,35 @@
|
||||
* variables, notifications become balloons, consent requests open the
|
||||
* permission dialog, and opened files fire `on-language` / `on-file`.
|
||||
*/
|
||||
import type { ActiveTheme, PluginEvent, PluginUpdate } from "@/bindings";
|
||||
import type { PluginEvent, PluginUpdate } from "@/bindings";
|
||||
import { useEditorRegistry } from "@/editor/api";
|
||||
import { refreshLanguageInfos } from "@/editor/core/cm/languages";
|
||||
import { clearBackoffs } from "@/editor/lsp/availability";
|
||||
import { endpointsChanged, notifications } from "@/workbench/contributions";
|
||||
import { useI18n } from "@/platform/i18n";
|
||||
import { useProducerNames } from "@/platform/inspections";
|
||||
import { languageListChanged } from "@/platform/languageList";
|
||||
import {
|
||||
isThemeAvailable,
|
||||
parsePluginThemeRef,
|
||||
providePluginThemePreview,
|
||||
useContributedThemes,
|
||||
} from "@/platform/themes";
|
||||
import {
|
||||
applyThemeAttributes,
|
||||
currentThemeChoice,
|
||||
currentThemeId,
|
||||
subscribeScheme,
|
||||
syncWindowBackground,
|
||||
useThemeOverride,
|
||||
windowBackgroundHex,
|
||||
} from "@/workbench/theme";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { pluginsBackend } from "./backend";
|
||||
import { trackIconTheme } from "./iconThemes";
|
||||
import { defineBuiltinUiPoints } from "./points";
|
||||
import { localizeContributions, loadPluginCatalogs, usePluginCatalogs } from "./pluginText";
|
||||
import { clearUiContributions, syncUiContributions } from "./projection";
|
||||
import { handleRuntimeEvent, refreshEventKinds, startRuntimeUi } from "./runtimeUi";
|
||||
import { refreshRunTargets } from "./runTargets";
|
||||
import {
|
||||
grantPlugin,
|
||||
runPluginCommand,
|
||||
refreshPlugins,
|
||||
selectPluginTheme,
|
||||
updateAllPlugins,
|
||||
usePlugins,
|
||||
} from "./store";
|
||||
import { grantPlugin, runPluginCommand, refreshPlugins, updateAllPlugins, usePlugins } from "./store";
|
||||
import { followThemeSetting, syncPluginProjection, trackPluginTheme } from "./themeRuntime";
|
||||
|
||||
export { pluginActionId } from "./points";
|
||||
export {
|
||||
applyPluginTheme,
|
||||
followThemeSetting,
|
||||
PLUGIN_THEME_CACHE_KEY,
|
||||
PLUGIN_THEME_STYLE_ID,
|
||||
providePluginThemePreviews,
|
||||
trackPluginTheme,
|
||||
type CachedPluginTheme,
|
||||
} from "./themeRuntime";
|
||||
|
||||
/** Keeps the projected UI contributions in line with the plugin list. */
|
||||
export function syncProjection(): () => void {
|
||||
const apply = () => {
|
||||
const s = usePlugins.getState();
|
||||
syncUiContributions(localizeContributions(s.ui, usePluginCatalogs.getState().catalogs), s.plugins);
|
||||
// Their problems are listed by name in Settings › Inspections.
|
||||
useProducerNames.setState({
|
||||
names: new Map(
|
||||
s.plugins.flatMap((p): [string, string][] => [
|
||||
[`plugin:${p.id}`, p.name],
|
||||
[`plugin-provider:${p.id}`, p.name],
|
||||
]),
|
||||
),
|
||||
});
|
||||
};
|
||||
const loadCatalogs = () => void loadPluginCatalogs(usePlugins.getState().ui, useI18n.getState().locale);
|
||||
apply();
|
||||
loadCatalogs();
|
||||
const unsubscribe = [
|
||||
usePlugins.subscribe((s, prev) => {
|
||||
if (s.ui !== prev.ui) loadCatalogs();
|
||||
if (s.ui !== prev.ui || s.plugins !== prev.plugins) {
|
||||
clearBackoffs();
|
||||
apply();
|
||||
}
|
||||
}),
|
||||
usePluginCatalogs.subscribe((s, prev) => s.catalogs !== prev.catalogs && apply()),
|
||||
useI18n.subscribe((s, prev) => s.locale !== prev.locale && loadCatalogs()),
|
||||
];
|
||||
return () => {
|
||||
unsubscribe.forEach((u) => u());
|
||||
clearUiContributions();
|
||||
};
|
||||
}
|
||||
|
||||
// --- theme ------------------------------------------------------------------
|
||||
|
||||
export const PLUGIN_THEME_STYLE_ID = "openidea-plugin-theme";
|
||||
|
||||
/** Stylesheet for a plugin theme. Its selector outranks every built-in theme block. */
|
||||
export function pluginThemeCss(theme: ActiveTheme["theme"]): string {
|
||||
const kind = theme.kind === "light" ? "light" : "dark";
|
||||
const decls = [` color-scheme: ${kind};`];
|
||||
for (const [name, value] of Object.entries(theme.tokens)) {
|
||||
// Backend validates; keep the guard so a malformed payload can't inject declarations.
|
||||
if (!/^--[a-z0-9-]+$/.test(name) || value == null || /[;{}<>\\]/.test(value)) continue;
|
||||
decls.push(` ${name}: ${value};`);
|
||||
}
|
||||
return `:root[data-plugin-theme]:not([data-plugin-theme=""]) {\n${decls.join("\n")}\n}\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a plugin theme (null restores the built-in one): its tokens as a
|
||||
* stylesheet over the built-in light or dark base named by its `kind`. A
|
||||
* stylesheet rather than inline styles, so the accent picked in Settings ›
|
||||
* Appearance and the editor colour scheme still layer on top.
|
||||
*/
|
||||
export function applyPluginTheme(theme: ActiveTheme | null, root: HTMLElement = document.documentElement) {
|
||||
const doc = root.ownerDocument;
|
||||
const current = doc.getElementById(PLUGIN_THEME_STYLE_ID);
|
||||
const id = theme && `${theme.pluginId}/${theme.theme.id}`;
|
||||
const css = theme && pluginThemeCss(theme.theme);
|
||||
// The same theme again (each window hears every selection): replacing its stylesheet restyles the page.
|
||||
if (theme && current?.textContent === css && root.dataset.pluginTheme === id) return;
|
||||
current?.remove();
|
||||
const had = root.dataset.pluginTheme !== undefined;
|
||||
if (!theme) {
|
||||
delete root.dataset.pluginTheme;
|
||||
delete root.dataset.pluginThemeKind;
|
||||
if (had) applyThemeAttributes(currentThemeId(), root);
|
||||
} else {
|
||||
const style = doc.createElement("style");
|
||||
style.id = PLUGIN_THEME_STYLE_ID;
|
||||
style.textContent = css;
|
||||
doc.head.appendChild(style);
|
||||
root.dataset.pluginTheme = id!;
|
||||
root.dataset.pluginThemeKind = theme.theme.kind === "light" ? "light" : "dark";
|
||||
applyThemeAttributes(currentThemeId(), root);
|
||||
}
|
||||
if (had || theme) syncWindowBackground();
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick Switch's theme preview of plugin themes: a live plugin's theme as it
|
||||
* contributes it, shown in this window only; nothing is selected or saved.
|
||||
*/
|
||||
export function providePluginThemePreviews(): () => void {
|
||||
return providePluginThemePreview((ref) => {
|
||||
const state = usePlugins.getState();
|
||||
if (ref === "selected") return applyPluginTheme(state.activeTheme);
|
||||
const want = ref ? parsePluginThemeRef(ref) : null;
|
||||
const item = want
|
||||
? state.ui.find((c) => c.point === "themes" && c.pluginId === want.pluginId && c.key === want.themeId)
|
||||
: undefined;
|
||||
applyPluginTheme(item ? { pluginId: item.pluginId, theme: item.decl as ActiveTheme["theme"] } : null);
|
||||
});
|
||||
}
|
||||
|
||||
/** localStorage key read by public/boot.js: the selected theme's stylesheet, applied before the app loads. */
|
||||
export const PLUGIN_THEME_CACHE_KEY = "openidea.pluginTheme";
|
||||
|
||||
export interface CachedPluginTheme {
|
||||
/** `data-plugin-theme`: `<pluginId>/<themeId>`. */
|
||||
id: string;
|
||||
kind: "light" | "dark";
|
||||
css: string;
|
||||
}
|
||||
|
||||
function cachePluginTheme(theme: ActiveTheme | null) {
|
||||
try {
|
||||
if (!theme) {
|
||||
localStorage.removeItem(PLUGIN_THEME_CACHE_KEY);
|
||||
return;
|
||||
}
|
||||
const cached: CachedPluginTheme = {
|
||||
id: `${theme.pluginId}/${theme.theme.id}`,
|
||||
kind: theme.theme.kind === "light" ? "light" : "dark",
|
||||
css: pluginThemeCss(theme.theme),
|
||||
};
|
||||
localStorage.setItem(PLUGIN_THEME_CACHE_KEY, JSON.stringify(cached));
|
||||
} catch {
|
||||
/* storage unavailable */
|
||||
}
|
||||
}
|
||||
|
||||
let reportedFrame: string | undefined;
|
||||
|
||||
/**
|
||||
* Tells the backend the theme's resolved frame colour, which new windows open
|
||||
* in. Selecting a theme clears it there, so it is sent once per selection.
|
||||
*/
|
||||
function reportThemeFrame(theme: ActiveTheme | null) {
|
||||
const frame = theme ? windowBackgroundHex() : null;
|
||||
if (!theme || !frame) {
|
||||
reportedFrame = undefined;
|
||||
return;
|
||||
}
|
||||
const key = `${theme.pluginId}/${theme.theme.id}|${frame}`;
|
||||
if (key === reportedFrame) return;
|
||||
reportedFrame = key;
|
||||
void pluginsBackend()
|
||||
.setThemeFrame(frame)
|
||||
.catch(() => (reportedFrame = undefined));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the selected plugin theme and keeps it for the next start-up. Until
|
||||
* the first plugin list arrives, the theme public/boot.js restored stays.
|
||||
*/
|
||||
export function trackPluginTheme(): () => void {
|
||||
const sync = (s: ReturnType<typeof usePlugins.getState>) => {
|
||||
if (!s.activeTheme && (!s.loaded || s.error)) return;
|
||||
applyPluginTheme(s.activeTheme);
|
||||
cachePluginTheme(s.activeTheme);
|
||||
reportThemeFrame(s.activeTheme);
|
||||
};
|
||||
sync(usePlugins.getState());
|
||||
const unsubscribe = usePlugins.subscribe((s, prev) => {
|
||||
if (s.activeTheme !== prev.activeTheme || s.loaded !== prev.loaded) sync(s);
|
||||
});
|
||||
return () => {
|
||||
unsubscribe();
|
||||
applyPluginTheme(null);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes the plugin host's theme the one the Appearance settings select: a
|
||||
* plugin theme (`plugin:<id>/<theme>`, from any theme picker, the OS mode with
|
||||
* "Sync with OS", or the plugin's details page) is selected there once its
|
||||
* plugin is live; a built-in one clears it. While the selected plugin is off,
|
||||
* its built-in base shows and the selection is kept for when it is back.
|
||||
*/
|
||||
export function followThemeSetting(): () => void {
|
||||
let requested: string | undefined;
|
||||
const reconcile = () => {
|
||||
const plugins = usePlugins.getState();
|
||||
if (!plugins.loaded || plugins.error || !useProject.getState().settings?.appearance) return;
|
||||
const choice = currentThemeChoice();
|
||||
const want = parsePluginThemeRef(choice);
|
||||
const target = want && isThemeAvailable(choice) ? choice : null;
|
||||
const active = plugins.activeTheme;
|
||||
const current = active ? `plugin:${active.pluginId}/${active.theme.id}` : null;
|
||||
if (target === current || (want && !target && !current)) {
|
||||
requested = undefined;
|
||||
return;
|
||||
}
|
||||
// A selected plugin that is off: leave the host's selection for when it is back.
|
||||
if (want && !target) {
|
||||
if (requested === "") return;
|
||||
requested = "";
|
||||
void selectPluginTheme(null, null);
|
||||
return;
|
||||
}
|
||||
if (requested === (target ?? "")) return;
|
||||
requested = target ?? "";
|
||||
void selectPluginTheme(want && target ? want.pluginId : null, want && target ? want.themeId : null);
|
||||
};
|
||||
reconcile();
|
||||
const disposers = [
|
||||
// Not on the host's theme changing: another window selects it before this one's settings
|
||||
// say so, and selecting this window's choice back would flip it until they agree.
|
||||
usePlugins.subscribe((s, prev) => {
|
||||
if (s.loaded !== prev.loaded) reconcile();
|
||||
}),
|
||||
useProject.subscribe((s, prev) => {
|
||||
if (s.settings?.appearance !== prev.settings?.appearance) reconcile();
|
||||
}),
|
||||
useThemeOverride.subscribe(reconcile),
|
||||
useContributedThemes.subscribe(reconcile),
|
||||
subscribeScheme(reconcile),
|
||||
];
|
||||
return () => disposers.forEach((d) => d());
|
||||
return syncPluginProjection(clearBackoffs);
|
||||
}
|
||||
|
||||
/** Reports the focused editor's file to the backend (`editor-focused` events). */
|
||||
@@ -335,19 +108,6 @@ export function handlePluginEvent(e: PluginEvent) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* For windows that only show plugins (Settings): stays in line with what
|
||||
* changes elsewhere — installs, enable / disable, the theme, languages —
|
||||
* while notifications and permission prompts stay with the project windows.
|
||||
*/
|
||||
export function followPluginChanges(): () => void {
|
||||
return pluginsBackend().onEvent((e) => {
|
||||
if (e.type === "runTargetsChanged") void refreshRunTargets(false).catch(() => {});
|
||||
if (e.type === "commandsChanged" || e.type === "themeChanged" || e.type === "languagesChanged")
|
||||
handlePluginEvent(e);
|
||||
});
|
||||
}
|
||||
|
||||
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function scheduleRefresh() {
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* Editor-free first-party plugin UI points (commands, themes, icon themes,
|
||||
* secrets, endpoints), shared by the workbench and the Settings window without
|
||||
* pulling in CodeMirror-backed plugin editors.
|
||||
*/
|
||||
import { registerEndpointProvider, type EndpointEntry } from "@/workbench/contributions";
|
||||
import type { PluginInfo, ThemeDef } from "@/bindings";
|
||||
import { pluginIconName } from "./pluginIcon";
|
||||
import { registerAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { addContributedTheme, pluginThemeRef } from "@/platform/themes";
|
||||
import { currentThemeChoice, setTheme, useThemeOverride } from "@/workbench/theme";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { Button, Kbd, T } from "@/ui";
|
||||
import { addIconTheme, iconThemeKey, selectIconTheme, useSelectedIconTheme } from "./iconThemes";
|
||||
import { defineUiPoint, type UiItem } from "./projection";
|
||||
import { SecretsDetails, type SecretDecl } from "./secrets";
|
||||
import { pluginSettingsPageId } from "./settings";
|
||||
import { pluginsBackend } from "./backend";
|
||||
import { isLive, runPluginCommand } from "./store";
|
||||
import styles from "./PluginsPage.module.css";
|
||||
|
||||
/** Unpacks an action argument: a bare path, or a menu's `{ path, paths }`. */
|
||||
export function commandArgs(arg: unknown): [string | null, string[]] {
|
||||
if (typeof arg === "string") return [arg, []];
|
||||
const { path, paths, line, column } = (arg ?? {}) as {
|
||||
path?: unknown;
|
||||
paths?: unknown;
|
||||
line?: unknown;
|
||||
column?: unknown;
|
||||
};
|
||||
if (typeof path !== "string" || !Array.isArray(paths)) return [null, []];
|
||||
if (typeof line === "number" && typeof column === "number")
|
||||
return [JSON.stringify({ path, line, column }), paths.filter((p): p is string => typeof p === "string")];
|
||||
return [path, paths.filter((p): p is string => typeof p === "string")];
|
||||
}
|
||||
|
||||
export const pluginActionId = (pluginId: string, commandId: string) => `plugin.${pluginId}.${commandId}`;
|
||||
|
||||
interface CommandDecl {
|
||||
id: string;
|
||||
title: string;
|
||||
icon?: string | null;
|
||||
category?: string | null;
|
||||
when?: string | null;
|
||||
}
|
||||
|
||||
function CommandsDetails({ plugin, items }: { plugin: PluginInfo; items: UiItem<CommandDecl>[] }) {
|
||||
const runnable = plugin.status === "active" || plugin.status === "inactive";
|
||||
return (
|
||||
<ul className={styles.items}>
|
||||
{items.map(({ decl: c }) => {
|
||||
const actionId = pluginActionId(plugin.id, c.id);
|
||||
return (
|
||||
<li key={c.id} className={styles.item}>
|
||||
<span className={styles.itemMain}>{c.title}</span>
|
||||
<Kbd action={actionId} />
|
||||
<span className={styles.mono} title={tx("Action id (bind it in Keymap)")}>
|
||||
{actionId}
|
||||
</span>
|
||||
<Button
|
||||
size="small"
|
||||
variant="ghost"
|
||||
icon="run"
|
||||
disabled={!runnable}
|
||||
onClick={() => void runPluginCommand(plugin.id, c.id)}
|
||||
aria-label={tx`Run ${c.title}`}
|
||||
>
|
||||
<T>Run</T>
|
||||
</Button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function ThemesDetails({ plugin, items }: { plugin: PluginInfo; items: UiItem<ThemeDef>[] }) {
|
||||
// The selection is the Appearance setting; these buttons write it as the theme pickers do.
|
||||
useProject((s) => s.settings?.appearance);
|
||||
useThemeOverride((s) => s.theme);
|
||||
const selected = currentThemeChoice();
|
||||
const live = isLive(plugin.status);
|
||||
return (
|
||||
<ul className={styles.items}>
|
||||
{items.map(({ decl: t }) => {
|
||||
const isActive = selected === pluginThemeRef(plugin.id, t.id);
|
||||
return (
|
||||
<li key={t.id} className={styles.item}>
|
||||
<span className={styles.itemMain}>{t.name}</span>
|
||||
<span className={styles.muted}>{t.kind === "dark" ? tx("Dark") : tx("Light")}</span>
|
||||
{isActive ? (
|
||||
<Button
|
||||
size="small"
|
||||
variant="secondary"
|
||||
onClick={() => void setTheme(t.kind === "light" ? "light" : "dark")}
|
||||
>
|
||||
<T>Use Default Theme</T>
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="small"
|
||||
variant="ghost"
|
||||
disabled={!live}
|
||||
onClick={() => void setTheme(pluginThemeRef(plugin.id, t.id))}
|
||||
aria-label={tx`Apply theme ${t.name}`}
|
||||
>
|
||||
<T>Apply</T>
|
||||
</Button>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
interface IconThemeDecl {
|
||||
id: string;
|
||||
label: string;
|
||||
icons: number;
|
||||
}
|
||||
|
||||
function IconThemesDetails({ plugin, items }: { plugin: PluginInfo; items: UiItem<IconThemeDecl>[] }) {
|
||||
const selected = useSelectedIconTheme();
|
||||
return (
|
||||
<ul className={styles.items}>
|
||||
{items.map(({ decl: t }) => {
|
||||
const key = iconThemeKey(plugin.id, t.id);
|
||||
return (
|
||||
<li key={t.id} className={styles.item}>
|
||||
<span className={styles.itemMain}>{t.label}</span>
|
||||
<span className={styles.muted}>{tx`${t.icons} icons`}</span>
|
||||
{selected === key ? (
|
||||
<Button size="small" variant="secondary" onClick={() => void selectIconTheme(null)}>
|
||||
<T>Use Default Icons</T>
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="small"
|
||||
variant="ghost"
|
||||
onClick={() => void selectIconTheme(key)}
|
||||
aria-label={tx`Apply icon theme ${t.label}`}
|
||||
>
|
||||
<T>Apply</T>
|
||||
</Button>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
const endpointPlugins = new Map<string, { declarations: number; dispose: () => void }>();
|
||||
|
||||
/** One endpoint provider per plugin, however many `[[contributes.endpoints]]` it declares. */
|
||||
function providePluginEndpoints(pluginId: string): () => void {
|
||||
let entry = endpointPlugins.get(pluginId);
|
||||
if (!entry) {
|
||||
const dispose = registerEndpointProvider({
|
||||
id: `plugin:${pluginId}`,
|
||||
endpoints: async (root): Promise<EndpointEntry[]> =>
|
||||
(await pluginsBackend().endpoints(pluginId)).map((e) => ({
|
||||
method: e.method ?? "*",
|
||||
url: e.path,
|
||||
framework: e.framework,
|
||||
handler: e.handler ?? undefined,
|
||||
controller: e.framework,
|
||||
methodName: e.handler ?? "",
|
||||
pluginId,
|
||||
path: e.location.path,
|
||||
rel: e.location.path.startsWith(`${root}/`) ? e.location.path.slice(root.length + 1) : e.location.path,
|
||||
line: e.location.range.start.line,
|
||||
col: e.location.range.start.col,
|
||||
})),
|
||||
});
|
||||
entry = { declarations: 0, dispose };
|
||||
endpointPlugins.set(pluginId, entry);
|
||||
}
|
||||
const held = entry;
|
||||
held.declarations++;
|
||||
return () => {
|
||||
if (--held.declarations > 0) return;
|
||||
held.dispose();
|
||||
endpointPlugins.delete(pluginId);
|
||||
};
|
||||
}
|
||||
|
||||
/** Registers the editor-free UI points (commands, themes, icon themes, secrets, endpoints). */
|
||||
export function defineCoreUiPoints(): () => void {
|
||||
const disposers = [
|
||||
defineUiPoint("mcpTools", {}),
|
||||
defineUiPoint("serverCommands", {}),
|
||||
defineUiPoint("endpoints", { project: ({ pluginId }) => providePluginEndpoints(pluginId) }),
|
||||
defineUiPoint<CommandDecl>("commands", {
|
||||
title: "Commands",
|
||||
project: ({ pluginId, decl }, { plugin }) => {
|
||||
let disposed = false;
|
||||
const action = {
|
||||
id: pluginActionId(pluginId, decl.id),
|
||||
title: decl.title,
|
||||
category: decl.category ?? plugin.name,
|
||||
icon:
|
||||
decl.icon && !decl.icon.endsWith(".svg")
|
||||
? decl.icon
|
||||
: plugin.icon
|
||||
? pluginIconName(pluginId, plugin.icon)
|
||||
: "package",
|
||||
when: decl.when ?? undefined,
|
||||
verbatim: true,
|
||||
// A command can call a model or a server; its toolbar button must show the click was taken.
|
||||
indicatesRunning: true,
|
||||
keywords: ["plugin", plugin.name, pluginId],
|
||||
description: tx`From plugin ${plugin.name}`,
|
||||
run: async ({ arg }: { arg?: unknown }) => {
|
||||
const [path, paths] = commandArgs(arg);
|
||||
await runPluginCommand(pluginId, decl.id, path, paths);
|
||||
},
|
||||
};
|
||||
let off = registerAction(action);
|
||||
if (decl.icon?.endsWith(".svg"))
|
||||
void pluginsBackend()
|
||||
.assets(pluginId, `commandIcon/${decl.id}`)
|
||||
.then((assets) => {
|
||||
const svg = assets.find(([id]) => id === `commandIcon/${decl.id}`)?.[1];
|
||||
if (!svg || disposed) return;
|
||||
off();
|
||||
off = registerAction({ ...action, icon: pluginIconName(pluginId, { light: svg, dark: null }) });
|
||||
})
|
||||
.catch(console.warn);
|
||||
return () => {
|
||||
disposed = true;
|
||||
off();
|
||||
};
|
||||
},
|
||||
Details: CommandsDetails,
|
||||
}),
|
||||
// Offered by every theme picker while the plugin is live; `followThemeSetting` applies the selected one.
|
||||
defineUiPoint<ThemeDef>("themes", {
|
||||
title: "Themes",
|
||||
project: ({ pluginId, decl }, { plugin }) =>
|
||||
addContributedTheme({
|
||||
id: pluginThemeRef(pluginId, decl.id),
|
||||
label: decl.name,
|
||||
kind: decl.kind === "light" ? "light" : "dark",
|
||||
origin: plugin.name,
|
||||
}),
|
||||
Details: ThemesDetails,
|
||||
}),
|
||||
defineUiPoint<IconThemeDecl>("iconThemes", {
|
||||
title: "File Icon Themes",
|
||||
project: ({ pluginId, decl }, { plugin }) =>
|
||||
addIconTheme({
|
||||
pluginId,
|
||||
id: decl.id,
|
||||
label: decl.label,
|
||||
origin: plugin.name,
|
||||
settingsPage: `${pluginSettingsPageId(pluginId)}.${decl.id.replace(/\./g, "-")}`,
|
||||
}),
|
||||
Details: IconThemesDetails,
|
||||
}),
|
||||
// Stored by the backend; listed here with a field per secret.
|
||||
defineUiPoint<SecretDecl>("secrets", { title: "Secrets", Details: SecretsDetails }),
|
||||
];
|
||||
return () => disposers.reverse().forEach((d) => d());
|
||||
}
|
||||
@@ -3,21 +3,21 @@
|
||||
* commands get it (path, language, selections in line / UTF-16 column). Tool
|
||||
* windows' renders and events carry it too, so their buttons act on what the
|
||||
* user is editing; a custom editor's calls carry its own document instead.
|
||||
*
|
||||
* Provided by the workbench (`points.tsx`) so editor-free windows (Settings)
|
||||
* do not pull in `@/editor/api` and CodeMirror.
|
||||
*/
|
||||
import type { PluginEditor } from "@/bindings";
|
||||
import { activeEditor } from "@/editor/api";
|
||||
|
||||
export function editorContext(): PluginEditor | null {
|
||||
const editor = activeEditor();
|
||||
if (!editor?.ctx.path) return null;
|
||||
const { doc, selection } = editor.view.state;
|
||||
const pos = (offset: number) => {
|
||||
const line = doc.lineAt(offset);
|
||||
return { line: line.number - 1, col: offset - line.from };
|
||||
};
|
||||
return {
|
||||
path: editor.ctx.path,
|
||||
language: editor.ctx.language,
|
||||
selections: selection.ranges.map((r) => ({ start: pos(r.from), end: pos(r.to) })),
|
||||
let provider: (() => PluginEditor | null) | null = null;
|
||||
|
||||
export function providePluginEditorContext(fn: () => PluginEditor | null): () => void {
|
||||
provider = fn;
|
||||
return () => {
|
||||
if (provider === fn) provider = null;
|
||||
};
|
||||
}
|
||||
|
||||
export function editorContext(): PluginEditor | null {
|
||||
return provider?.() ?? null;
|
||||
}
|
||||
@@ -16,66 +16,22 @@ import { pluginLanguageVisuals } from "./languageVisuals";
|
||||
* `line-markers` providers (`lineMarkerGutter.ts`).
|
||||
*/
|
||||
import { registerEditorContribution } from "@/editor/api";
|
||||
import { lazyComponent, lazyWhen } from "@/ui";
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { editorService, registerOverlay, registerSettingsPage } from "@/workbench/contributions";
|
||||
import {
|
||||
followPluginChanges,
|
||||
providePluginThemePreviews,
|
||||
startPluginBridge,
|
||||
syncProjection,
|
||||
trackPluginTheme,
|
||||
} from "./bridge";
|
||||
import { editorService, registerOverlay } from "@/workbench/contributions";
|
||||
import { providePluginThemePreviews, startPluginBridge } from "./bridge";
|
||||
import { ConsentDialogHost, provideConsentDialog } from "./consent";
|
||||
import { trackIconTheme } from "./iconThemes";
|
||||
import { pluginLineMarkerGutter } from "./lineMarkerGutter";
|
||||
import { defineBuiltinUiPoints } from "./points";
|
||||
import { startViewUi } from "./uiPoints";
|
||||
import { showInstalledIntellijThemes, useIntellijThemesDialog } from "./intellijThemesDialogStore";
|
||||
import { showInstalledIntellijThemes } from "./intellijThemesDialogStore";
|
||||
import { startWorkspaceContains } from "./workspaceContains";
|
||||
import { startPluginDecorations } from "./decorations";
|
||||
import { startOneDarkNotice } from "./oneDarkNotice";
|
||||
import { startIndexedMarkers } from "./indexedMarkers";
|
||||
import { startRunTargets } from "./runTargets";
|
||||
import { startPluginNavigation } from "./navigation";
|
||||
import { IntellijThemesDialogHost, registerPluginsPage } from "./settingsPages";
|
||||
import { installFromDisk, refreshPlugins, reloadPlugin, SETTINGS_PAGE_ID, updateAllPlugins, usePlugins } from "./store";
|
||||
|
||||
function registerPluginsPage(): () => void {
|
||||
return registerSettingsPage({
|
||||
id: SETTINGS_PAGE_ID,
|
||||
title: "Plugins",
|
||||
// After Editor, as in IntelliJ IDEA.
|
||||
order: 250,
|
||||
bleed: true,
|
||||
keywords: ["plugin", "extension", "wasm", "install", "theme", "marketplace"],
|
||||
component: lazyComponent(() => import("./PluginsPage").then((m) => m.PluginsPage)),
|
||||
});
|
||||
}
|
||||
|
||||
/** Settings › Plugins for the Settings window: the page plus the plugin theme. */
|
||||
const useIntellijThemesOpen = () => useIntellijThemesDialog((s) => s.open);
|
||||
const IntellijThemesDialogHost = lazyWhen(useIntellijThemesOpen, () =>
|
||||
import("./IntellijThemesDialog").then((m) => m.IntellijThemesDialogHost),
|
||||
);
|
||||
|
||||
export function activateSettingsPages(): () => void {
|
||||
const disposers = [
|
||||
registerPluginsPage(),
|
||||
registerOverlay({ id: "plugins.consent", component: ConsentDialogHost }),
|
||||
registerOverlay({ id: "plugins.intellijThemes", component: IntellijThemesDialogHost }),
|
||||
provideConsentDialog(),
|
||||
defineBuiltinUiPoints(),
|
||||
followPluginChanges(),
|
||||
startRunTargets(false),
|
||||
syncProjection(),
|
||||
trackPluginTheme(),
|
||||
trackIconTheme(),
|
||||
];
|
||||
void refreshPlugins();
|
||||
return () => disposers.reverse().forEach((d) => d());
|
||||
}
|
||||
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
registerPluginsPage(),
|
||||
|
||||
+19
-254
@@ -3,266 +3,31 @@
|
||||
* declaration is projected onto the workbench, and how its items appear on
|
||||
* the plugin details page. One `defineUiPoint` per contribution type.
|
||||
*/
|
||||
import { registerEndpointProvider, type EndpointEntry } from "@/workbench/contributions";
|
||||
import type { PluginInfo, ThemeDef } from "@/bindings";
|
||||
import { pluginIconName } from "./pluginIcon";
|
||||
import { registerAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { addContributedTheme, pluginThemeRef } from "@/platform/themes";
|
||||
import { currentThemeChoice, setTheme, useThemeOverride } from "@/workbench/theme";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { Button, Kbd, T } from "@/ui";
|
||||
import { addIconTheme, iconThemeKey, selectIconTheme, useSelectedIconTheme } from "./iconThemes";
|
||||
import { defineUiPoint, type UiItem } from "./projection";
|
||||
import { SecretsDetails, type SecretDecl } from "./secrets";
|
||||
import { defineViewUiPoints, pluginSettingsPageId } from "./uiPoints";
|
||||
import { pluginsBackend } from "./backend";
|
||||
import { isLive, runPluginCommand } from "./store";
|
||||
import styles from "./PluginsPage.module.css";
|
||||
import type { PluginEditor } from "@/bindings";
|
||||
import { activeEditor } from "@/editor/api";
|
||||
import { defineCoreUiPoints } from "./corePoints";
|
||||
import { providePluginEditorContext } from "./editorContext";
|
||||
import { defineViewUiPoints } from "./uiPoints";
|
||||
|
||||
/** Unpacks an action argument: a bare path, or a menu's `{ path, paths }`. */
|
||||
export function commandArgs(arg: unknown): [string | null, string[]] {
|
||||
if (typeof arg === "string") return [arg, []];
|
||||
const { path, paths, line, column } = (arg ?? {}) as {
|
||||
path?: unknown;
|
||||
paths?: unknown;
|
||||
line?: unknown;
|
||||
column?: unknown;
|
||||
export { commandArgs, pluginActionId } from "./corePoints";
|
||||
|
||||
function activePluginEditor(): PluginEditor | null {
|
||||
const editor = activeEditor();
|
||||
if (!editor?.ctx.path) return null;
|
||||
const { doc, selection } = editor.view.state;
|
||||
const pos = (offset: number) => {
|
||||
const line = doc.lineAt(offset);
|
||||
return { line: line.number - 1, col: offset - line.from };
|
||||
};
|
||||
if (typeof path !== "string" || !Array.isArray(paths)) return [null, []];
|
||||
if (typeof line === "number" && typeof column === "number")
|
||||
return [JSON.stringify({ path, line, column }), paths.filter((p): p is string => typeof p === "string")];
|
||||
return [path, paths.filter((p): p is string => typeof p === "string")];
|
||||
}
|
||||
|
||||
export const pluginActionId = (pluginId: string, commandId: string) => `plugin.${pluginId}.${commandId}`;
|
||||
|
||||
interface CommandDecl {
|
||||
id: string;
|
||||
title: string;
|
||||
icon?: string | null;
|
||||
category?: string | null;
|
||||
when?: string | null;
|
||||
}
|
||||
|
||||
function CommandsDetails({ plugin, items }: { plugin: PluginInfo; items: UiItem<CommandDecl>[] }) {
|
||||
const runnable = plugin.status === "active" || plugin.status === "inactive";
|
||||
return (
|
||||
<ul className={styles.items}>
|
||||
{items.map(({ decl: c }) => {
|
||||
const actionId = pluginActionId(plugin.id, c.id);
|
||||
return (
|
||||
<li key={c.id} className={styles.item}>
|
||||
<span className={styles.itemMain}>{c.title}</span>
|
||||
<Kbd action={actionId} />
|
||||
<span className={styles.mono} title={tx("Action id (bind it in Keymap)")}>
|
||||
{actionId}
|
||||
</span>
|
||||
<Button
|
||||
size="small"
|
||||
variant="ghost"
|
||||
icon="run"
|
||||
disabled={!runnable}
|
||||
onClick={() => void runPluginCommand(plugin.id, c.id)}
|
||||
aria-label={tx`Run ${c.title}`}
|
||||
>
|
||||
<T>Run</T>
|
||||
</Button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function ThemesDetails({ plugin, items }: { plugin: PluginInfo; items: UiItem<ThemeDef>[] }) {
|
||||
// The selection is the Appearance setting; these buttons write it as the theme pickers do.
|
||||
useProject((s) => s.settings?.appearance);
|
||||
useThemeOverride((s) => s.theme);
|
||||
const selected = currentThemeChoice();
|
||||
const live = isLive(plugin.status);
|
||||
return (
|
||||
<ul className={styles.items}>
|
||||
{items.map(({ decl: t }) => {
|
||||
const isActive = selected === pluginThemeRef(plugin.id, t.id);
|
||||
return (
|
||||
<li key={t.id} className={styles.item}>
|
||||
<span className={styles.itemMain}>{t.name}</span>
|
||||
<span className={styles.muted}>{t.kind === "dark" ? tx("Dark") : tx("Light")}</span>
|
||||
{isActive ? (
|
||||
<Button
|
||||
size="small"
|
||||
variant="secondary"
|
||||
onClick={() => void setTheme(t.kind === "light" ? "light" : "dark")}
|
||||
>
|
||||
<T>Use Default Theme</T>
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="small"
|
||||
variant="ghost"
|
||||
disabled={!live}
|
||||
onClick={() => void setTheme(pluginThemeRef(plugin.id, t.id))}
|
||||
aria-label={tx`Apply theme ${t.name}`}
|
||||
>
|
||||
<T>Apply</T>
|
||||
</Button>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
interface IconThemeDecl {
|
||||
id: string;
|
||||
label: string;
|
||||
icons: number;
|
||||
}
|
||||
|
||||
function IconThemesDetails({ plugin, items }: { plugin: PluginInfo; items: UiItem<IconThemeDecl>[] }) {
|
||||
const selected = useSelectedIconTheme();
|
||||
return (
|
||||
<ul className={styles.items}>
|
||||
{items.map(({ decl: t }) => {
|
||||
const key = iconThemeKey(plugin.id, t.id);
|
||||
return (
|
||||
<li key={t.id} className={styles.item}>
|
||||
<span className={styles.itemMain}>{t.label}</span>
|
||||
<span className={styles.muted}>{tx`${t.icons} icons`}</span>
|
||||
{selected === key ? (
|
||||
<Button size="small" variant="secondary" onClick={() => void selectIconTheme(null)}>
|
||||
<T>Use Default Icons</T>
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="small"
|
||||
variant="ghost"
|
||||
onClick={() => void selectIconTheme(key)}
|
||||
aria-label={tx`Apply icon theme ${t.label}`}
|
||||
>
|
||||
<T>Apply</T>
|
||||
</Button>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
const endpointPlugins = new Map<string, { declarations: number; dispose: () => void }>();
|
||||
|
||||
/** One endpoint provider per plugin, however many `[[contributes.endpoints]]` it declares. */
|
||||
function providePluginEndpoints(pluginId: string): () => void {
|
||||
let entry = endpointPlugins.get(pluginId);
|
||||
if (!entry) {
|
||||
const dispose = registerEndpointProvider({
|
||||
id: `plugin:${pluginId}`,
|
||||
endpoints: async (root): Promise<EndpointEntry[]> =>
|
||||
(await pluginsBackend().endpoints(pluginId)).map((e) => ({
|
||||
method: e.method ?? "*",
|
||||
url: e.path,
|
||||
framework: e.framework,
|
||||
handler: e.handler ?? undefined,
|
||||
controller: e.framework,
|
||||
methodName: e.handler ?? "",
|
||||
pluginId,
|
||||
path: e.location.path,
|
||||
rel: e.location.path.startsWith(`${root}/`) ? e.location.path.slice(root.length + 1) : e.location.path,
|
||||
line: e.location.range.start.line,
|
||||
col: e.location.range.start.col,
|
||||
})),
|
||||
});
|
||||
entry = { declarations: 0, dispose };
|
||||
endpointPlugins.set(pluginId, entry);
|
||||
}
|
||||
const held = entry;
|
||||
held.declarations++;
|
||||
return () => {
|
||||
if (--held.declarations > 0) return;
|
||||
held.dispose();
|
||||
endpointPlugins.delete(pluginId);
|
||||
return {
|
||||
path: editor.ctx.path,
|
||||
language: editor.ctx.language,
|
||||
selections: selection.ranges.map((r) => ({ start: pos(r.from), end: pos(r.to) })),
|
||||
};
|
||||
}
|
||||
|
||||
/** Registers the client side of every first-party UI point. */
|
||||
export function defineBuiltinUiPoints(): () => void {
|
||||
const disposers = [
|
||||
defineUiPoint("mcpTools", {}),
|
||||
defineUiPoint("serverCommands", {}),
|
||||
defineUiPoint("endpoints", { project: ({ pluginId }) => providePluginEndpoints(pluginId) }),
|
||||
defineUiPoint<CommandDecl>("commands", {
|
||||
title: "Commands",
|
||||
project: ({ pluginId, decl }, { plugin }) => {
|
||||
let disposed = false;
|
||||
const action = {
|
||||
id: pluginActionId(pluginId, decl.id),
|
||||
title: decl.title,
|
||||
category: decl.category ?? plugin.name,
|
||||
icon:
|
||||
decl.icon && !decl.icon.endsWith(".svg")
|
||||
? decl.icon
|
||||
: plugin.icon
|
||||
? pluginIconName(pluginId, plugin.icon)
|
||||
: "package",
|
||||
when: decl.when ?? undefined,
|
||||
verbatim: true,
|
||||
// A command can call a model or a server; its toolbar button must show the click was taken.
|
||||
indicatesRunning: true,
|
||||
keywords: ["plugin", plugin.name, pluginId],
|
||||
description: tx`From plugin ${plugin.name}`,
|
||||
run: async ({ arg }: { arg?: unknown }) => {
|
||||
const [path, paths] = commandArgs(arg);
|
||||
await runPluginCommand(pluginId, decl.id, path, paths);
|
||||
},
|
||||
};
|
||||
let off = registerAction(action);
|
||||
if (decl.icon?.endsWith(".svg"))
|
||||
void pluginsBackend()
|
||||
.assets(pluginId, `commandIcon/${decl.id}`)
|
||||
.then((assets) => {
|
||||
const svg = assets.find(([id]) => id === `commandIcon/${decl.id}`)?.[1];
|
||||
if (!svg || disposed) return;
|
||||
off();
|
||||
off = registerAction({ ...action, icon: pluginIconName(pluginId, { light: svg, dark: null }) });
|
||||
})
|
||||
.catch(console.warn);
|
||||
return () => {
|
||||
disposed = true;
|
||||
off();
|
||||
};
|
||||
},
|
||||
Details: CommandsDetails,
|
||||
}),
|
||||
// Offered by every theme picker while the plugin is live; `followThemeSetting` applies the selected one.
|
||||
defineUiPoint<ThemeDef>("themes", {
|
||||
title: "Themes",
|
||||
project: ({ pluginId, decl }, { plugin }) =>
|
||||
addContributedTheme({
|
||||
id: pluginThemeRef(pluginId, decl.id),
|
||||
label: decl.name,
|
||||
kind: decl.kind === "light" ? "light" : "dark",
|
||||
origin: plugin.name,
|
||||
}),
|
||||
Details: ThemesDetails,
|
||||
}),
|
||||
defineUiPoint<IconThemeDecl>("iconThemes", {
|
||||
title: "File Icon Themes",
|
||||
project: ({ pluginId, decl }, { plugin }) =>
|
||||
addIconTheme({
|
||||
pluginId,
|
||||
id: decl.id,
|
||||
label: decl.label,
|
||||
origin: plugin.name,
|
||||
settingsPage: `${pluginSettingsPageId(pluginId)}.${decl.id.replace(/\./g, "-")}`,
|
||||
}),
|
||||
Details: IconThemesDetails,
|
||||
}),
|
||||
// Stored by the backend; listed here with a field per secret.
|
||||
defineUiPoint<SecretDecl>("secrets", { title: "Secrets", Details: SecretsDetails }),
|
||||
defineViewUiPoints(),
|
||||
];
|
||||
const disposers = [providePluginEditorContext(activePluginEditor), defineCoreUiPoints(), defineViewUiPoints()];
|
||||
return () => disposers.reverse().forEach((d) => d());
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Settings › Plugins for the standalone Settings window: registers the Plugins
|
||||
* page, projects plugin commands/keymaps/settings/themes, and follows plugin
|
||||
* updates without pulling in CodeMirror editor extensions.
|
||||
*/
|
||||
import { isMacHost, registerExtensionBindings } from "@/platform/keymap";
|
||||
import { languageListChanged } from "@/platform/languageList";
|
||||
import { lazyComponent, lazyWhen } from "@/ui";
|
||||
import { registerOverlay, registerSettingsPage } from "@/workbench/contributions";
|
||||
import { pluginsBackend } from "./backend";
|
||||
import { ConsentDialogHost, provideConsentDialog } from "./consent";
|
||||
import { defineCoreUiPoints, pluginActionId } from "./corePoints";
|
||||
import { trackIconTheme } from "./iconThemes";
|
||||
import { useIntellijThemesDialog } from "./intellijThemesDialogStore";
|
||||
import { defineUiPoint } from "./projection";
|
||||
import { refreshRunTargets, startRunTargets } from "./runTargets";
|
||||
import { projectSettings, type SettingsDecl } from "./settings";
|
||||
import { refreshPlugins, SETTINGS_PAGE_ID, usePlugins } from "./store";
|
||||
import { syncPluginProjection, trackPluginTheme } from "./themeRuntime";
|
||||
|
||||
export function registerPluginsPage(): () => void {
|
||||
return registerSettingsPage({
|
||||
id: SETTINGS_PAGE_ID,
|
||||
title: "Plugins",
|
||||
// After Editor, as in IntelliJ IDEA.
|
||||
order: 250,
|
||||
bleed: true,
|
||||
keywords: ["plugin", "extension", "wasm", "install", "theme", "marketplace"],
|
||||
component: lazyComponent(() => import("./PluginsPage").then((m) => m.PluginsPage)),
|
||||
});
|
||||
}
|
||||
|
||||
const useIntellijThemesOpen = () => useIntellijThemesDialog((s) => s.open);
|
||||
export const IntellijThemesDialogHost = lazyWhen(useIntellijThemesOpen, () =>
|
||||
import("./IntellijThemesDialog").then((m) => m.IntellijThemesDialogHost),
|
||||
);
|
||||
|
||||
interface KeymapDecl {
|
||||
command: string;
|
||||
key: string;
|
||||
mac?: string | null;
|
||||
when?: string | null;
|
||||
}
|
||||
|
||||
const VIEW_ONLY_POINTS: ReadonlyArray<[string, string]> = [
|
||||
["menus", "Menus"],
|
||||
["statusBar", "Status Bar Items"],
|
||||
["views", "Tool Windows"],
|
||||
["customEditors", "Editors"],
|
||||
["editorPanels", "Editor Panels"],
|
||||
["markerIcons", "Marker Icons"],
|
||||
["fileIcons", "File Icons"],
|
||||
["commitChecks", "Commit Checks"],
|
||||
["snippets", "Snippets"],
|
||||
["fileTemplates", "File Templates"],
|
||||
];
|
||||
|
||||
function defineSettingsUiPoints(): () => void {
|
||||
const disposers = [
|
||||
defineCoreUiPoints(),
|
||||
defineUiPoint<KeymapDecl>("keymaps", {
|
||||
title: "Shortcuts",
|
||||
project: ({ pluginId, decl }) =>
|
||||
decl.key === "Escape" && decl.when
|
||||
? undefined
|
||||
: registerExtensionBindings(pluginActionId(pluginId, decl.command), [
|
||||
isMacHost() ? (decl.mac ?? decl.key) : decl.key,
|
||||
]),
|
||||
}),
|
||||
defineUiPoint<SettingsDecl>("settings", {
|
||||
title: "Settings",
|
||||
project: ({ pluginId, decl }) => projectSettings(pluginId, decl),
|
||||
}),
|
||||
...VIEW_ONLY_POINTS.map(([point, title]) => defineUiPoint(point, { title })),
|
||||
];
|
||||
return () => disposers.reverse().forEach((d) => d());
|
||||
}
|
||||
|
||||
function followSettingsPluginChanges(): () => void {
|
||||
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const off = pluginsBackend().onEvent((e) => {
|
||||
switch (e.type) {
|
||||
case "runTargetsChanged":
|
||||
void refreshRunTargets(false).catch(() => {});
|
||||
break;
|
||||
case "commandsChanged":
|
||||
if (!refreshTimer) {
|
||||
refreshTimer = setTimeout(() => {
|
||||
refreshTimer = null;
|
||||
void refreshPlugins();
|
||||
}, 30);
|
||||
}
|
||||
break;
|
||||
case "themeChanged":
|
||||
usePlugins.setState({ activeTheme: e.theme });
|
||||
break;
|
||||
case "languagesChanged":
|
||||
languageListChanged();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
if (refreshTimer) clearTimeout(refreshTimer);
|
||||
off();
|
||||
};
|
||||
}
|
||||
|
||||
export function activateSettingsPages(): () => void {
|
||||
const disposers = [
|
||||
registerPluginsPage(),
|
||||
registerOverlay({ id: "plugins.consent", component: ConsentDialogHost }),
|
||||
registerOverlay({ id: "plugins.intellijThemes", component: IntellijThemesDialogHost }),
|
||||
provideConsentDialog(),
|
||||
defineSettingsUiPoints(),
|
||||
followSettingsPluginChanges(),
|
||||
startRunTargets(false),
|
||||
syncPluginProjection(),
|
||||
trackPluginTheme(),
|
||||
trackIconTheme(),
|
||||
];
|
||||
void refreshPlugins();
|
||||
return () => disposers.reverse().forEach((d) => d());
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
/**
|
||||
* Editor-free plugin theme application and UI contribution projection, shared
|
||||
* between the workbench bridge and the Settings window.
|
||||
*/
|
||||
import type { ActiveTheme } from "@/bindings";
|
||||
import { useI18n } from "@/platform/i18n";
|
||||
import { useProducerNames } from "@/platform/inspections";
|
||||
import { useProject } from "@/platform/project";
|
||||
import {
|
||||
isThemeAvailable,
|
||||
parsePluginThemeRef,
|
||||
providePluginThemePreview,
|
||||
useContributedThemes,
|
||||
} from "@/platform/themes";
|
||||
import {
|
||||
applyThemeAttributes,
|
||||
currentThemeChoice,
|
||||
currentThemeId,
|
||||
subscribeScheme,
|
||||
syncWindowBackground,
|
||||
useThemeOverride,
|
||||
windowBackgroundHex,
|
||||
} from "@/workbench/theme";
|
||||
import { pluginsBackend } from "./backend";
|
||||
import { loadPluginCatalogs, localizeContributions, usePluginCatalogs } from "./pluginText";
|
||||
import { clearUiContributions, syncUiContributions } from "./projection";
|
||||
import { selectPluginTheme, usePlugins } from "./store";
|
||||
|
||||
/** Keeps the projected UI contributions in line with the plugin list. */
|
||||
export function syncPluginProjection(onPluginsChanged?: () => void): () => void {
|
||||
const apply = () => {
|
||||
const s = usePlugins.getState();
|
||||
syncUiContributions(localizeContributions(s.ui, usePluginCatalogs.getState().catalogs), s.plugins);
|
||||
// Their problems are listed by name in Settings › Inspections.
|
||||
useProducerNames.setState({
|
||||
names: new Map(
|
||||
s.plugins.flatMap((p): [string, string][] => [
|
||||
[`plugin:${p.id}`, p.name],
|
||||
[`plugin-provider:${p.id}`, p.name],
|
||||
]),
|
||||
),
|
||||
});
|
||||
};
|
||||
const loadCatalogs = () => void loadPluginCatalogs(usePlugins.getState().ui, useI18n.getState().locale);
|
||||
apply();
|
||||
loadCatalogs();
|
||||
const unsubscribe = [
|
||||
usePlugins.subscribe((s, prev) => {
|
||||
if (s.ui !== prev.ui) loadCatalogs();
|
||||
if (s.ui !== prev.ui || s.plugins !== prev.plugins) {
|
||||
onPluginsChanged?.();
|
||||
apply();
|
||||
}
|
||||
}),
|
||||
usePluginCatalogs.subscribe((s, prev) => s.catalogs !== prev.catalogs && apply()),
|
||||
useI18n.subscribe((s, prev) => s.locale !== prev.locale && loadCatalogs()),
|
||||
];
|
||||
return () => {
|
||||
unsubscribe.forEach((u) => u());
|
||||
clearUiContributions();
|
||||
};
|
||||
}
|
||||
|
||||
export const PLUGIN_THEME_STYLE_ID = "openidea-plugin-theme";
|
||||
|
||||
/** Stylesheet for a plugin theme. Its selector outranks every built-in theme block. */
|
||||
export function pluginThemeCss(theme: ActiveTheme["theme"]): string {
|
||||
const kind = theme.kind === "light" ? "light" : "dark";
|
||||
const decls = [` color-scheme: ${kind};`];
|
||||
for (const [name, value] of Object.entries(theme.tokens)) {
|
||||
// Backend validates; keep the guard so a malformed payload can't inject declarations.
|
||||
if (!/^--[a-z0-9-]+$/.test(name) || value == null || /[;{}<>\\]/.test(value)) continue;
|
||||
decls.push(` ${name}: ${value};`);
|
||||
}
|
||||
return `:root[data-plugin-theme]:not([data-plugin-theme=""]) {\n${decls.join("\n")}\n}\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a plugin theme (null restores the built-in one): its tokens as a
|
||||
* stylesheet over the built-in light or dark base named by its `kind`. A
|
||||
* stylesheet rather than inline styles, so the accent picked in Settings ›
|
||||
* Appearance and the editor colour scheme still layer on top.
|
||||
*/
|
||||
export function applyPluginTheme(theme: ActiveTheme | null, root: HTMLElement = document.documentElement) {
|
||||
const doc = root.ownerDocument;
|
||||
const current = doc.getElementById(PLUGIN_THEME_STYLE_ID);
|
||||
const id = theme && `${theme.pluginId}/${theme.theme.id}`;
|
||||
const css = theme && pluginThemeCss(theme.theme);
|
||||
// The same theme again (each window hears every selection): replacing its stylesheet restyles the page.
|
||||
if (theme && current?.textContent === css && root.dataset.pluginTheme === id) return;
|
||||
current?.remove();
|
||||
const had = root.dataset.pluginTheme !== undefined;
|
||||
if (!theme) {
|
||||
delete root.dataset.pluginTheme;
|
||||
delete root.dataset.pluginThemeKind;
|
||||
if (had) applyThemeAttributes(currentThemeId(), root);
|
||||
} else {
|
||||
const style = doc.createElement("style");
|
||||
style.id = PLUGIN_THEME_STYLE_ID;
|
||||
style.textContent = css;
|
||||
doc.head.appendChild(style);
|
||||
root.dataset.pluginTheme = id!;
|
||||
root.dataset.pluginThemeKind = theme.theme.kind === "light" ? "light" : "dark";
|
||||
applyThemeAttributes(currentThemeId(), root);
|
||||
}
|
||||
if (had || theme) syncWindowBackground();
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick Switch's theme preview of plugin themes: a live plugin's theme as it
|
||||
* contributes it, shown in this window only; nothing is selected or saved.
|
||||
*/
|
||||
export function providePluginThemePreviews(): () => void {
|
||||
return providePluginThemePreview((ref) => {
|
||||
const state = usePlugins.getState();
|
||||
if (ref === "selected") return applyPluginTheme(state.activeTheme);
|
||||
const want = ref ? parsePluginThemeRef(ref) : null;
|
||||
const item = want
|
||||
? state.ui.find((c) => c.point === "themes" && c.pluginId === want.pluginId && c.key === want.themeId)
|
||||
: undefined;
|
||||
applyPluginTheme(item ? { pluginId: item.pluginId, theme: item.decl as ActiveTheme["theme"] } : null);
|
||||
});
|
||||
}
|
||||
|
||||
/** localStorage key read by public/boot.js: the selected theme's stylesheet, applied before the app loads. */
|
||||
export const PLUGIN_THEME_CACHE_KEY = "openidea.pluginTheme";
|
||||
|
||||
export interface CachedPluginTheme {
|
||||
/** `data-plugin-theme`: `<pluginId>/<themeId>`. */
|
||||
id: string;
|
||||
kind: "light" | "dark";
|
||||
css: string;
|
||||
}
|
||||
|
||||
function cachePluginTheme(theme: ActiveTheme | null) {
|
||||
try {
|
||||
if (!theme) {
|
||||
localStorage.removeItem(PLUGIN_THEME_CACHE_KEY);
|
||||
return;
|
||||
}
|
||||
const cached: CachedPluginTheme = {
|
||||
id: `${theme.pluginId}/${theme.theme.id}`,
|
||||
kind: theme.theme.kind === "light" ? "light" : "dark",
|
||||
css: pluginThemeCss(theme.theme),
|
||||
};
|
||||
localStorage.setItem(PLUGIN_THEME_CACHE_KEY, JSON.stringify(cached));
|
||||
} catch {
|
||||
/* storage unavailable */
|
||||
}
|
||||
}
|
||||
|
||||
let reportedFrame: string | undefined;
|
||||
|
||||
/**
|
||||
* Tells the backend the theme's resolved frame colour, which new windows open
|
||||
* in. Selecting a theme clears it there, so it is sent once per selection.
|
||||
*/
|
||||
function reportThemeFrame(theme: ActiveTheme | null) {
|
||||
const frame = theme ? windowBackgroundHex() : null;
|
||||
if (!theme || !frame) {
|
||||
reportedFrame = undefined;
|
||||
return;
|
||||
}
|
||||
const key = `${theme.pluginId}/${theme.theme.id}|${frame}`;
|
||||
if (key === reportedFrame) return;
|
||||
reportedFrame = key;
|
||||
void pluginsBackend()
|
||||
.setThemeFrame(frame)
|
||||
.catch(() => (reportedFrame = undefined));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the selected plugin theme and keeps it for the next start-up. Until
|
||||
* the first plugin list arrives, the theme public/boot.js restored stays.
|
||||
*/
|
||||
export function trackPluginTheme(): () => void {
|
||||
const sync = (s: ReturnType<typeof usePlugins.getState>) => {
|
||||
if (!s.activeTheme && (!s.loaded || s.error)) return;
|
||||
applyPluginTheme(s.activeTheme);
|
||||
cachePluginTheme(s.activeTheme);
|
||||
reportThemeFrame(s.activeTheme);
|
||||
};
|
||||
sync(usePlugins.getState());
|
||||
const unsubscribe = usePlugins.subscribe((s, prev) => {
|
||||
if (s.activeTheme !== prev.activeTheme || s.loaded !== prev.loaded) sync(s);
|
||||
});
|
||||
return () => {
|
||||
unsubscribe();
|
||||
applyPluginTheme(null);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes the plugin host's theme the one the Appearance settings select: a
|
||||
* plugin theme (`plugin:<id>/<theme>`, from any theme picker, the OS mode with
|
||||
* "Sync with OS", or the plugin's details page) is selected there once its
|
||||
* plugin is live; a built-in one clears it. While the selected plugin is off,
|
||||
* its built-in base shows and the selection is kept for when it is back.
|
||||
*/
|
||||
export function followThemeSetting(): () => void {
|
||||
let requested: string | undefined;
|
||||
const reconcile = () => {
|
||||
const plugins = usePlugins.getState();
|
||||
if (!plugins.loaded || plugins.error || !useProject.getState().settings?.appearance) return;
|
||||
const choice = currentThemeChoice();
|
||||
const want = parsePluginThemeRef(choice);
|
||||
const target = want && isThemeAvailable(choice) ? choice : null;
|
||||
const active = plugins.activeTheme;
|
||||
const current = active ? `plugin:${active.pluginId}/${active.theme.id}` : null;
|
||||
if (target === current || (want && !target && !current)) {
|
||||
requested = undefined;
|
||||
return;
|
||||
}
|
||||
// A selected plugin that is off: leave the host's selection for when it is back.
|
||||
if (want && !target) {
|
||||
if (requested === "") return;
|
||||
requested = "";
|
||||
void selectPluginTheme(null, null);
|
||||
return;
|
||||
}
|
||||
if (requested === (target ?? "")) return;
|
||||
requested = target ?? "";
|
||||
void selectPluginTheme(want && target ? want.pluginId : null, want && target ? want.themeId : null);
|
||||
};
|
||||
reconcile();
|
||||
const disposers = [
|
||||
// Not on the host's theme changing: another window selects it before this one's settings
|
||||
// say so, and selecting this window's choice back would flip it until they agree.
|
||||
usePlugins.subscribe((s, prev) => {
|
||||
if (s.loaded !== prev.loaded) reconcile();
|
||||
}),
|
||||
useProject.subscribe((s, prev) => {
|
||||
if (s.settings?.appearance !== prev.settings?.appearance) reconcile();
|
||||
}),
|
||||
useThemeOverride.subscribe(reconcile),
|
||||
useContributedThemes.subscribe(reconcile),
|
||||
subscribeScheme(reconcile),
|
||||
];
|
||||
return () => disposers.forEach((d) => d());
|
||||
}
|
||||
@@ -279,7 +279,7 @@ interface StatusDecl {
|
||||
|
||||
// --- settings ---------------------------------------------------------------------
|
||||
|
||||
export { withPluginSetting, pluginSettingsPageId } from "./settings";
|
||||
export { withPluginSetting } from "./settings";
|
||||
|
||||
// --- views and custom editors -----------------------------------------------------
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { Action } from "@/platform/actions";
|
||||
import { nativeToAsciiAction } from "./nativeToAscii";
|
||||
|
||||
/** Java's page first: JDK, Maven and the language server are what new projects most often need. */
|
||||
export const NEW_PROJECTS_PAGE = "languages.java";
|
||||
|
||||
export function settingsActions(open: (page?: string, newProjects?: boolean) => void): Action[] {
|
||||
return [
|
||||
nativeToAsciiAction(),
|
||||
{
|
||||
id: "file.settings",
|
||||
title: "Settings…",
|
||||
category: "File",
|
||||
icon: "settings",
|
||||
keywords: ["preferences", "options", "configure"],
|
||||
run: ({ arg }) => open(typeof arg === "string" ? arg : undefined),
|
||||
},
|
||||
{
|
||||
id: "file.newProjectsSettings",
|
||||
title: "Settings for New Projects…",
|
||||
category: "File",
|
||||
icon: "settings",
|
||||
keywords: ["new projects setup", "default settings", "default project", "default jdk", "global settings"],
|
||||
run: ({ arg }) => open(typeof arg === "string" ? arg : NEW_PROJECTS_PAGE, true),
|
||||
},
|
||||
{
|
||||
id: "settings.keymap",
|
||||
title: "Keymap…",
|
||||
category: "File",
|
||||
icon: "keyboard",
|
||||
keywords: ["shortcuts", "keyboard", "bindings"],
|
||||
run: () => open("keymap"),
|
||||
},
|
||||
{
|
||||
id: "settings.appearance",
|
||||
title: "Appearance…",
|
||||
category: "View",
|
||||
icon: "sun",
|
||||
keywords: ["theme", "accent", "font size"],
|
||||
run: () => open("appearance"),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -12,32 +12,20 @@
|
||||
* `file.newProjectsSettings` (IDEA's Settings for New Projects) edits the
|
||||
* global layer only, which new projects inherit.
|
||||
*/
|
||||
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
import { registerActions, type Action } from "@/platform/actions";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { isPopupOpen, lazyComponent, lazyWhen } from "@/ui";
|
||||
import { loadSettings, useProject } from "@/platform/project";
|
||||
import { logError } from "@/platform/errorLog";
|
||||
import { restoreRemote } from "@/platform/remote";
|
||||
import { lazyWhen } from "@/ui";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { provideSettingsSearchIndex, registerOverlay } from "@/workbench/contributions";
|
||||
import { windowBackgroundHex } from "@/workbench/theme";
|
||||
import { settingsActions } from "./actions";
|
||||
import {
|
||||
LazyProjectStructureDialog,
|
||||
LazySettingsDialog,
|
||||
loadBuiltinPages,
|
||||
unloadBuiltinPages,
|
||||
} from "./dialog/LazySettingsDialog";
|
||||
import {
|
||||
closeSettings,
|
||||
openProjectStructure,
|
||||
openSettings,
|
||||
rebaseSettings,
|
||||
selectPage,
|
||||
setNewProjects,
|
||||
setQuery,
|
||||
settingsTitle,
|
||||
useSettingsDialog,
|
||||
} from "./model/staging";
|
||||
import { openProjectStructure, openSettings, useSettingsDialog } from "./model/staging";
|
||||
import {
|
||||
appearanceToggleActions,
|
||||
navigationBarActions,
|
||||
@@ -47,62 +35,15 @@ import {
|
||||
import { PresentationAssistant } from "./presentation/PresentationAssistant";
|
||||
import { activateFileTypes } from "./fileTypesRuntime";
|
||||
import { trackRuntimeSettings } from "./runtime";
|
||||
import { installActionProxies, installSettingsHost } from "./window/bridge";
|
||||
import { activateSettingsWindow, relaunchSettings } from "./settingsWindow";
|
||||
import { installSettingsHost } from "./window/bridge";
|
||||
import { showAssignShortcut, useAssignShortcut } from "./keymap/assignShortcutStore";
|
||||
import { settingsSearchEntries } from "./searchIndex";
|
||||
import { activatePythonStatus } from "./languages/PythonStatus";
|
||||
import { activatePhpStatus } from "./languages/PhpStatus";
|
||||
import { nativeToAsciiAction } from "./nativeToAscii";
|
||||
import { isImeKey } from "@/platform/ime";
|
||||
import { trackIconThemePages } from "./iconThemePages";
|
||||
|
||||
/** Settings-driven runtime state (zoom, fonts, theme) of a secondary window. */
|
||||
export const activateRuntimeSettings = trackRuntimeSettings;
|
||||
export const SettingsWindow = lazyComponent(() => import("./window/SettingsWindow").then((m) => m.SettingsWindow));
|
||||
|
||||
/** Same event as `windows::LAUNCH_EVENT`: a pending launch (page) is waiting. */
|
||||
const LAUNCH_EVENT = "openidea://launch";
|
||||
|
||||
/** Java's page first: JDK, Maven and the language server are what new projects most often need. */
|
||||
const NEW_PROJECTS_PAGE = "languages.java";
|
||||
|
||||
function settingsActions(open: (page?: string, newProjects?: boolean) => void): Action[] {
|
||||
return [
|
||||
nativeToAsciiAction(),
|
||||
{
|
||||
id: "file.settings",
|
||||
title: "Settings…",
|
||||
category: "File",
|
||||
icon: "settings",
|
||||
keywords: ["preferences", "options", "configure"],
|
||||
run: ({ arg }) => open(typeof arg === "string" ? arg : undefined),
|
||||
},
|
||||
{
|
||||
id: "file.newProjectsSettings",
|
||||
title: "Settings for New Projects…",
|
||||
category: "File",
|
||||
icon: "settings",
|
||||
keywords: ["new projects setup", "default settings", "default project", "default jdk", "global settings"],
|
||||
run: ({ arg }) => open(typeof arg === "string" ? arg : NEW_PROJECTS_PAGE, true),
|
||||
},
|
||||
{
|
||||
id: "settings.keymap",
|
||||
title: "Keymap…",
|
||||
category: "File",
|
||||
icon: "keyboard",
|
||||
keywords: ["shortcuts", "keyboard", "bindings"],
|
||||
run: () => open("keymap"),
|
||||
},
|
||||
{
|
||||
id: "settings.appearance",
|
||||
title: "Appearance…",
|
||||
category: "View",
|
||||
icon: "sun",
|
||||
keywords: ["theme", "accent", "font size"],
|
||||
run: () => open("appearance"),
|
||||
},
|
||||
];
|
||||
}
|
||||
export { activateSettingsWindow };
|
||||
|
||||
const separateWindow = () => useProject.getState().settings?.appearance?.settingsInSeparateWindow !== false;
|
||||
|
||||
@@ -118,7 +59,7 @@ async function showSettings(page?: string, newProjects = false) {
|
||||
}
|
||||
await loadBuiltinPages();
|
||||
// Like a launch into the open window: go to the page, keep the edits not applied yet.
|
||||
if (useSettingsDialog.getState().open) relaunch({ page, newProjects });
|
||||
if (useSettingsDialog.getState().open) relaunchSettings({ page, newProjects });
|
||||
else openSettings(page, { newProjects });
|
||||
}
|
||||
|
||||
@@ -171,104 +112,3 @@ export function activate(): () => void {
|
||||
];
|
||||
return () => disposers.reverse().forEach((d) => d());
|
||||
}
|
||||
|
||||
function navigate(page: string | undefined) {
|
||||
if (!page) return;
|
||||
setQuery("");
|
||||
selectPage(page);
|
||||
}
|
||||
|
||||
interface SettingsLaunch {
|
||||
page?: string;
|
||||
newProjects: boolean;
|
||||
}
|
||||
|
||||
async function takeLaunch(): Promise<SettingsLaunch | null> {
|
||||
const launch = await commands.windowTakeLaunch().catch(() => null);
|
||||
return launch && { page: launch.settingsPage ?? undefined, newProjects: launch.newProjects };
|
||||
}
|
||||
|
||||
/** A launch for the open window: its page, and the mode when it asks for new projects. */
|
||||
function relaunch(launch: SettingsLaunch | null) {
|
||||
if (!launch) return;
|
||||
if (launch.newProjects) setNewProjects(true);
|
||||
navigate(launch.page);
|
||||
}
|
||||
|
||||
function listenLaunch(): () => void {
|
||||
let disposed = false;
|
||||
let off: (() => void) | undefined;
|
||||
void getCurrentWebviewWindow()
|
||||
.listen(LAUNCH_EVENT, () => void takeLaunch().then(relaunch))
|
||||
.then((u) => {
|
||||
if (disposed) return u();
|
||||
off = u;
|
||||
// A page requested before we listened: its event is gone, the launch is not.
|
||||
void takeLaunch().then(relaunch);
|
||||
});
|
||||
return () => {
|
||||
disposed = true;
|
||||
off?.();
|
||||
};
|
||||
}
|
||||
|
||||
/** Esc and ⌘W cancel, like closing the window; ⌘, stays here. */
|
||||
function installWindowKeys(): () => void {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.defaultPrevented || isImeKey(e)) return;
|
||||
const mod = e.metaKey || e.ctrlKey;
|
||||
if ((e.key === "Escape" && !isPopupOpen()) || (mod && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "w")) {
|
||||
e.preventDefault();
|
||||
closeSettings();
|
||||
} else if (mod && e.key === ",") {
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* The settings window (`settings-<parent>`): settings pages only, working on
|
||||
* the parent's project; Cancel / OK / Esc close the window.
|
||||
*/
|
||||
export function activateSettingsWindow(parent: string): () => void {
|
||||
const disposers = [
|
||||
trackRuntimeSettings(),
|
||||
trackIconThemePages(),
|
||||
unloadBuiltinPages,
|
||||
registerActions(settingsActions((page, newProjects) => relaunch({ page, newProjects: !!newProjects }))),
|
||||
installActionProxies(parent),
|
||||
listenLaunch(),
|
||||
installWindowKeys(),
|
||||
useSettingsDialog.subscribe((s, prev) => {
|
||||
if (prev.open && !s.open) void getCurrentWebviewWindow().close();
|
||||
if (s.newProjects !== prev.newProjects) {
|
||||
void getCurrentWebviewWindow()
|
||||
.setTitle(settingsTitle(s.newProjects))
|
||||
.catch(() => {});
|
||||
}
|
||||
}),
|
||||
];
|
||||
void (async () => {
|
||||
useSettingsDialog.setState({ pagesLoading: true });
|
||||
openSettings();
|
||||
try {
|
||||
const launch = await takeLaunch();
|
||||
relaunch(launch);
|
||||
await Promise.all([
|
||||
loadBuiltinPages().catch((e) => logError("cannot register settings pages", e)),
|
||||
(async () => {
|
||||
await restoreRemote();
|
||||
const project = await commands.projectCurrent().catch(() => null);
|
||||
if (project) useProject.setState({ project, settings: project.settings });
|
||||
else await loadSettings().catch((e) => console.warn("cannot load settings", e));
|
||||
rebaseSettings();
|
||||
})(),
|
||||
]);
|
||||
} finally {
|
||||
useSettingsDialog.setState({ pagesLoading: false });
|
||||
}
|
||||
})().catch((e) => logError("settings window startup failed", e));
|
||||
return () => disposers.reverse().forEach((d) => d());
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* Standalone native Settings window (`settings-<parent>`): settings pages only,
|
||||
* working on the parent's project without importing workbench status bar widgets
|
||||
* or CodeMirror.
|
||||
*/
|
||||
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { logError } from "@/platform/errorLog";
|
||||
import { isImeKey } from "@/platform/ime";
|
||||
import { commands } from "@/platform/ipc";
|
||||
import { loadSettings, useProject } from "@/platform/project";
|
||||
import { restoreRemote } from "@/platform/remote";
|
||||
import { isPopupOpen } from "@/ui";
|
||||
import { settingsActions } from "./actions";
|
||||
import { loadBuiltinPages, unloadBuiltinPages } from "./dialog/LazySettingsDialog";
|
||||
import { trackIconThemePages } from "./iconThemePages";
|
||||
import {
|
||||
closeSettings,
|
||||
openSettings,
|
||||
rebaseSettings,
|
||||
selectPage,
|
||||
setNewProjects,
|
||||
setQuery,
|
||||
settingsTitle,
|
||||
useSettingsDialog,
|
||||
} from "./model/staging";
|
||||
import { trackRuntimeSettings } from "./runtime";
|
||||
import { installActionProxies } from "./window/bridge";
|
||||
|
||||
/** Same event as `windows::LAUNCH_EVENT`: a pending launch (page) is waiting. */
|
||||
const LAUNCH_EVENT = "openidea://launch";
|
||||
|
||||
export interface SettingsLaunch {
|
||||
page?: string;
|
||||
newProjects: boolean;
|
||||
}
|
||||
|
||||
function navigate(page: string | undefined) {
|
||||
if (!page) return;
|
||||
setQuery("");
|
||||
selectPage(page);
|
||||
}
|
||||
|
||||
async function takeLaunch(): Promise<SettingsLaunch | null> {
|
||||
const launch = await commands.windowTakeLaunch().catch(() => null);
|
||||
return launch && { page: launch.settingsPage ?? undefined, newProjects: launch.newProjects };
|
||||
}
|
||||
|
||||
/** A launch for the open window: its page, and the mode when it asks for new projects. */
|
||||
export function relaunchSettings(launch: SettingsLaunch | null) {
|
||||
if (!launch) return;
|
||||
if (launch.newProjects) setNewProjects(true);
|
||||
navigate(launch.page);
|
||||
}
|
||||
|
||||
function listenLaunch(): () => void {
|
||||
let disposed = false;
|
||||
let off: (() => void) | undefined;
|
||||
void getCurrentWebviewWindow()
|
||||
.listen(LAUNCH_EVENT, () => void takeLaunch().then(relaunchSettings))
|
||||
.then((u) => {
|
||||
if (disposed) return u();
|
||||
off = u;
|
||||
// A page requested before we listened: its event is gone, the launch is not.
|
||||
void takeLaunch().then(relaunchSettings);
|
||||
});
|
||||
return () => {
|
||||
disposed = true;
|
||||
off?.();
|
||||
};
|
||||
}
|
||||
|
||||
/** Esc and ⌘W cancel, like closing the window; ⌘, stays here. */
|
||||
function installWindowKeys(): () => void {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.defaultPrevented || isImeKey(e)) return;
|
||||
const mod = e.metaKey || e.ctrlKey;
|
||||
if ((e.key === "Escape" && !isPopupOpen()) || (mod && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "w")) {
|
||||
e.preventDefault();
|
||||
closeSettings();
|
||||
} else if (mod && e.key === ",") {
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* The settings window (`settings-<parent>`): settings pages only, working on
|
||||
* the parent's project; Cancel / OK / Esc close the window.
|
||||
*/
|
||||
export function activateSettingsWindow(parent: string): () => void {
|
||||
const disposers = [
|
||||
trackRuntimeSettings(),
|
||||
trackIconThemePages(),
|
||||
unloadBuiltinPages,
|
||||
registerActions(settingsActions((page, newProjects) => relaunchSettings({ page, newProjects: !!newProjects }))),
|
||||
installActionProxies(parent),
|
||||
listenLaunch(),
|
||||
installWindowKeys(),
|
||||
useSettingsDialog.subscribe((s, prev) => {
|
||||
if (prev.open && !s.open) void getCurrentWebviewWindow().close();
|
||||
if (s.newProjects !== prev.newProjects) {
|
||||
void getCurrentWebviewWindow()
|
||||
.setTitle(settingsTitle(s.newProjects))
|
||||
.catch(() => {});
|
||||
}
|
||||
}),
|
||||
];
|
||||
void (async () => {
|
||||
useSettingsDialog.setState({ pagesLoading: true });
|
||||
openSettings();
|
||||
try {
|
||||
const launch = await takeLaunch();
|
||||
relaunchSettings(launch);
|
||||
await Promise.all([
|
||||
loadBuiltinPages().catch((e) => logError("cannot register settings pages", e)),
|
||||
(async () => {
|
||||
await restoreRemote();
|
||||
const project = await commands.projectCurrent().catch(() => null);
|
||||
if (project) useProject.setState({ project, settings: project.settings });
|
||||
else await loadSettings().catch((e) => console.warn("cannot load settings", e));
|
||||
rebaseSettings();
|
||||
})(),
|
||||
]);
|
||||
} finally {
|
||||
useSettingsDialog.setState({ pagesLoading: false });
|
||||
}
|
||||
})().catch((e) => logError("settings window startup failed", e));
|
||||
return () => disposers.reverse().forEach((d) => d());
|
||||
}
|
||||
@@ -3,17 +3,16 @@
|
||||
* (`expr.if` …), Emmet (Tab expansion, Update Tag with Emmet) and file
|
||||
* templates ("New ▸ …").
|
||||
*/
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { registerActions, type Action } from "@/platform/actions";
|
||||
import { activeEditor, registerEditorContribution } from "@/editor/api";
|
||||
import {
|
||||
notifications,
|
||||
registerMenuGroup,
|
||||
registerOverlay,
|
||||
registerSettingsPages,
|
||||
hasRunConfiguration,
|
||||
type MenuGroupContext,
|
||||
} from "@/workbench/contributions";
|
||||
import { activateSettingsPages } from "./settingsPages";
|
||||
import { insertLiveTemplate, surroundTarget, surroundWith, templateEditorExtension } from "./editor";
|
||||
import { ChooserHost } from "./popup/Chooser";
|
||||
import { NewFileDialogHost, openNewFileDialog } from "./files/NewFileDialog";
|
||||
@@ -164,37 +163,6 @@ function registerFileTemplateActions(): () => void {
|
||||
};
|
||||
}
|
||||
|
||||
/** Live / postfix / file template pages (also used by the Settings window). */
|
||||
export function activateSettingsPages(): () => void {
|
||||
return registerSettingsPages([
|
||||
{
|
||||
id: "editor.liveTemplates",
|
||||
title: "Live Templates",
|
||||
group: "Editor",
|
||||
order: 28,
|
||||
keywords: ["snippet", "abbreviation", "surround", "template"],
|
||||
component: lazyComponent(() => import("./settings/LiveTemplatesPage").then((m) => m.LiveTemplatesPage)),
|
||||
},
|
||||
{
|
||||
// IDEA: Editor › General › Postfix Completion.
|
||||
id: "editor.general.postfixCompletion",
|
||||
title: "Postfix Completion",
|
||||
group: "Editor",
|
||||
order: 7,
|
||||
keywords: ["postfix", "template", ".if", ".var", ".for"],
|
||||
component: lazyComponent(() => import("./settings/PostfixPage").then((m) => m.PostfixPage)),
|
||||
},
|
||||
{
|
||||
id: "editor.fileTemplates",
|
||||
title: "File and Code Templates",
|
||||
group: "Editor",
|
||||
order: 26,
|
||||
keywords: ["new file", "class", "template", "package", "includes", "file header", "code", "scheme", "reformat"],
|
||||
component: lazyComponent(() => import("./settings/FileTemplatesPage").then((m) => m.FileTemplatesPage)),
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
registerEditorContribution({ id: "templates", order: 90, extensions: templateEditorExtension }),
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { registerSettingsPages } from "@/workbench/contributions";
|
||||
|
||||
/** Live / postfix / file template pages (also used by the Settings window). */
|
||||
export function activateSettingsPages(): () => void {
|
||||
return registerSettingsPages([
|
||||
{
|
||||
id: "editor.liveTemplates",
|
||||
title: "Live Templates",
|
||||
group: "Editor",
|
||||
order: 28,
|
||||
keywords: ["snippet", "abbreviation", "surround", "template"],
|
||||
component: lazyComponent(() => import("./settings/LiveTemplatesPage").then((m) => m.LiveTemplatesPage)),
|
||||
},
|
||||
{
|
||||
// IDEA: Editor › General › Postfix Completion.
|
||||
id: "editor.general.postfixCompletion",
|
||||
title: "Postfix Completion",
|
||||
group: "Editor",
|
||||
order: 7,
|
||||
keywords: ["postfix", "template", ".if", ".var", ".for"],
|
||||
component: lazyComponent(() => import("./settings/PostfixPage").then((m) => m.PostfixPage)),
|
||||
},
|
||||
{
|
||||
id: "editor.fileTemplates",
|
||||
title: "File and Code Templates",
|
||||
group: "Editor",
|
||||
order: 26,
|
||||
keywords: ["new file", "class", "template", "package", "includes", "file header", "code", "scheme", "reformat"],
|
||||
component: lazyComponent(() => import("./settings/FileTemplatesPage").then((m) => m.FileTemplatesPage)),
|
||||
},
|
||||
]);
|
||||
}
|
||||
@@ -1,24 +1,13 @@
|
||||
/** TODO tool window, project TODO index and in-editor TODO highlighting. */
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { registerEditorContribution } from "@/editor/api";
|
||||
import { registerSettingsPage, registerToolWindow, toolWindowService } from "@/workbench/contributions";
|
||||
import { hasIcon, lazyComponent } from "@/ui";
|
||||
import { registerToolWindow, toolWindowService } from "@/workbench/contributions";
|
||||
import { hasIcon } from "@/ui";
|
||||
import { activateSettingsPages } from "./settingsPages";
|
||||
import { TodoHeaderActions, TodoTabs, TodoView, useTodoBadge, useTodoHeaderMenu, useTodoView } from "./TodoView";
|
||||
import { todoEditorExtension } from "./highlight";
|
||||
import { installTodoIndex, scanProject, syncTodoSettingsFromStorage } from "./store";
|
||||
|
||||
/** Settings › Editor › TODO (also used by the Settings window). */
|
||||
export function activateSettingsPages(): () => void {
|
||||
return registerSettingsPage({
|
||||
id: "editor.todo",
|
||||
title: "TODO",
|
||||
group: "Editor",
|
||||
order: 40,
|
||||
keywords: ["todo", "fixme", "hack", "pattern"],
|
||||
component: lazyComponent(() => import("./TodoSettingsPage").then((m) => m.TodoSettingsPage)),
|
||||
});
|
||||
}
|
||||
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
installTodoIndex(),
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { registerSettingsPage } from "@/workbench/contributions";
|
||||
|
||||
/** Settings › Editor › TODO (also used by the Settings window). */
|
||||
export function activateSettingsPages(): () => void {
|
||||
return registerSettingsPage({
|
||||
id: "editor.todo",
|
||||
title: "TODO",
|
||||
group: "Editor",
|
||||
order: 40,
|
||||
keywords: ["todo", "fixme", "hack", "pattern"],
|
||||
component: lazyComponent(() => import("./TodoSettingsPage").then((m) => m.TodoSettingsPage)),
|
||||
});
|
||||
}
|
||||
@@ -5,9 +5,7 @@
|
||||
* Actions: `tools.languageServers` (open the page), `tools.install` (arg: tool name),
|
||||
* `java.downloadJdk` (arg: `DownloadJdkArgs`).
|
||||
*/
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
import { registerSettingsPage } from "@/workbench/contributions";
|
||||
import { installExpiredServerPrompts } from "./expired";
|
||||
import { installJdkPrompts, registerJdkActions } from "./jdk";
|
||||
import {
|
||||
@@ -16,32 +14,9 @@ import {
|
||||
installServerWarningPrompts,
|
||||
promptInstall,
|
||||
} from "./missing";
|
||||
import { activateSettingsPages } from "./settingsPages";
|
||||
import { installTool, refreshTools, SETTINGS_PAGE_ID, toolByName, useTools } from "./store";
|
||||
|
||||
/** The Language Servers page (also used by the Settings window). */
|
||||
export function activateSettingsPages(): () => void {
|
||||
return registerSettingsPage({
|
||||
id: SETTINGS_PAGE_ID,
|
||||
title: "Language Servers",
|
||||
group: "Languages & Frameworks",
|
||||
order: 400,
|
||||
keywords: [
|
||||
"lsp",
|
||||
"language server",
|
||||
"debugger",
|
||||
"adapter",
|
||||
"dap",
|
||||
"install",
|
||||
"initialization options",
|
||||
"rust-analyzer",
|
||||
"gopls",
|
||||
"pyright",
|
||||
],
|
||||
projectScope: true,
|
||||
component: lazyComponent(() => import("./LanguageServersPage").then((m) => m.LanguageServersPage)),
|
||||
});
|
||||
}
|
||||
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
activateSettingsPages(),
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { registerSettingsPage } from "@/workbench/contributions";
|
||||
import { SETTINGS_PAGE_ID } from "./store";
|
||||
|
||||
/** The Language Servers page (also used by the Settings window). */
|
||||
export function activateSettingsPages(): () => void {
|
||||
return registerSettingsPage({
|
||||
id: SETTINGS_PAGE_ID,
|
||||
title: "Language Servers",
|
||||
group: "Languages & Frameworks",
|
||||
order: 400,
|
||||
keywords: [
|
||||
"lsp",
|
||||
"language server",
|
||||
"debugger",
|
||||
"adapter",
|
||||
"dap",
|
||||
"install",
|
||||
"initialization options",
|
||||
"rust-analyzer",
|
||||
"gopls",
|
||||
"pyright",
|
||||
],
|
||||
projectScope: true,
|
||||
component: lazyComponent(() => import("./LanguageServersPage").then((m) => m.LanguageServersPage)),
|
||||
});
|
||||
}
|
||||
@@ -67,7 +67,7 @@ import {
|
||||
import { applyStash, commitChanges, deleteFiles, dropStash, showUnstashDialog, stashChanges } from "./changeOps";
|
||||
import { CommitOptionsPopup } from "./CommitOptions";
|
||||
import { DEFAULT_LIST_NAME, useChangelists, withListDefaults } from "./changelists";
|
||||
import { inclusionChecks, isCommitAll, useStagingArea } from "./staging";
|
||||
import { inclusionChecks, isCommitAll, stagingAreaOn, useStagingArea } from "./staging";
|
||||
import { addToChangelist, commitFiles } from "./changelistsUi";
|
||||
import { acceptSide } from "./conflictsUi";
|
||||
import { copyChangesAsPatch } from "./patches";
|
||||
@@ -345,13 +345,18 @@ export function nodeMenu(
|
||||
{ kind: "separator" as const },
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: "Commit File…",
|
||||
icon: "commit",
|
||||
disabled: !files.some((f) => groupOf(f) === "changes"),
|
||||
run: () => commitFiles(paths),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
// With the staging area a commit takes the whole index: there is no committing one file.
|
||||
...(stagingAreaOn()
|
||||
? []
|
||||
: [
|
||||
{
|
||||
label: "Commit File…",
|
||||
icon: "commit" as const,
|
||||
disabled: !files.some((f) => groupOf(f) === "changes"),
|
||||
run: () => commitFiles(paths),
|
||||
},
|
||||
{ kind: "separator" as const },
|
||||
]),
|
||||
// Under the modal interface the node itself, like double-click, in the front window.
|
||||
vcsDiffInFront() && opts?.roots && first
|
||||
? {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import type { Branch } from "@/bindings";
|
||||
import {
|
||||
branchFolderKeys,
|
||||
branchNamePrefixes,
|
||||
buildBranchRows,
|
||||
buildBranchTree,
|
||||
filterBranchTree,
|
||||
@@ -183,6 +184,19 @@ describe("buildBranchRows", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("branchNamePrefixes", () => {
|
||||
it("lists local branch folders shallowest first, once each, without remote ones", () => {
|
||||
const prefixes = branchNamePrefixes([
|
||||
b("feat/2610/08/login"),
|
||||
b("feat/2610/signup"),
|
||||
b("fix/crash"),
|
||||
b("main"),
|
||||
b("origin/release/1.0"),
|
||||
]);
|
||||
expect(prefixes).toEqual(["feat/", "fix/", "feat/2610/", "feat/2610/08/"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pushRecent", () => {
|
||||
it("moves a branch to the front without duplicates", () => {
|
||||
expect(pushRecent(["a", "b", "c"], "b")).toEqual(["b", "a", "c"]);
|
||||
|
||||
@@ -129,6 +129,15 @@ describe("staging operations of the tree's nodes", () => {
|
||||
enabled(nodeMenu([underUnstaged], []), "Unstage"),
|
||||
]).toEqual([true, false]);
|
||||
});
|
||||
|
||||
it("has no Commit File…: a commit takes the whole index", () => {
|
||||
useSettings(true);
|
||||
const labels = (items: MenuItem[]) => items.map((i) => ("label" in i ? i.label : null));
|
||||
for (const node of [group("staged").children![0]!, group("unstaged").children![0]!])
|
||||
expect(labels(nodeMenu([node], []))).not.toContain("Commit File…");
|
||||
useSettings(false);
|
||||
expect(labels(nodeMenu([group("unstaged").children![0]!], []))).toContain("Commit File…");
|
||||
});
|
||||
});
|
||||
|
||||
describe("the Commit tool window with the staging area", () => {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { executeAction } from "@/platform/actions";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { isFavoriteBranch, pushRecent, shortRemoteName } from "./branches";
|
||||
import { branchNamePrefixes, isFavoriteBranch, pushRecent, shortRemoteName } from "./branches";
|
||||
import { showCommitRange } from "./CompareBranches";
|
||||
import { confirmDialog, promptText } from "./dialogs";
|
||||
import { cleanUpBranchNameOnTyping } from "@/platform/gitRefName";
|
||||
@@ -199,6 +199,7 @@ export async function newBranch(from?: string, repo = currentRepo()) {
|
||||
label: "New branch name:",
|
||||
// Kept even when that branch exists (the current one always does): the user edits it.
|
||||
initial: suggestion,
|
||||
prefixes: branchNamePrefixes(branches),
|
||||
mono: true,
|
||||
okLabel: "Create",
|
||||
sanitize: cleanUpBranchNameOnTyping,
|
||||
|
||||
@@ -176,6 +176,23 @@ export function shortRemoteName(name: string): string {
|
||||
return i < 0 ? name : name.slice(i + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* The folders of local branch names, shallowest first (`feat/ui/login` contributes `feat/` and
|
||||
* `feat/ui/`): what the New Branch dialog suggests while typing. Remote branches are left out.
|
||||
*/
|
||||
export function branchNamePrefixes(branches: readonly Branch[]): string[] {
|
||||
const prefixes = new Map<string, number>();
|
||||
for (const branch of branches) {
|
||||
if (branch.remote) continue;
|
||||
const name = branch.name;
|
||||
let depth = 1;
|
||||
for (let slash = name.indexOf("/"); slash !== -1; slash = name.indexOf("/", slash + 1)) {
|
||||
prefixes.set(name.slice(0, slash + 1), depth++);
|
||||
}
|
||||
}
|
||||
return [...prefixes.keys()].sort((a, b) => prefixes.get(a)! - prefixes.get(b)! || a.localeCompare(b));
|
||||
}
|
||||
|
||||
export const MAX_RECENT = 5;
|
||||
|
||||
/** Recently checked-out local branches other than the current one, newest first. */
|
||||
|
||||
@@ -391,6 +391,12 @@
|
||||
.targetList {
|
||||
flex: 1;
|
||||
}
|
||||
.prefixPopup {
|
||||
padding-block: var(--space-1);
|
||||
}
|
||||
.prefixList {
|
||||
height: 100%;
|
||||
}
|
||||
.targetRow {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
/** Imperative dialogs for VCS actions, rendered by one overlay contribution. */
|
||||
import { Fragment, useState, type ReactNode } from "react";
|
||||
import { Fragment, useId, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import { create } from "zustand";
|
||||
import { Checkbox, Dialog, Input, T, useSanitizedField } from "@/ui";
|
||||
import { Checkbox, Dialog, HighlightedText, Input, List, Popup, T, listNavigate, useSanitizedField } from "@/ui";
|
||||
import { isImeKey } from "@/platform/ime";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import styles from "./common.module.css";
|
||||
|
||||
@@ -50,6 +52,8 @@ export interface PromptOptions {
|
||||
/** Optional checkbox below the field. */
|
||||
checkbox?: { label: string; initial: boolean };
|
||||
overwriteBranch?: (value: string) => boolean;
|
||||
/** Branch name prefixes in the order the New Branch dialog should suggest them. */
|
||||
prefixes?: readonly string[];
|
||||
}
|
||||
|
||||
export interface PromptResult {
|
||||
@@ -73,18 +77,65 @@ export function promptText(opts: PromptOptions): Promise<PromptResult | null> {
|
||||
}
|
||||
|
||||
function PromptDialog(props: PromptOptions & { onDone: (r: PromptResult | null) => void }) {
|
||||
const { title, label, initial = "", placeholder, okLabel = "OK", mono, validate, sanitize, checkbox, onDone } = props;
|
||||
const {
|
||||
title,
|
||||
label,
|
||||
initial = "",
|
||||
placeholder,
|
||||
okLabel = "OK",
|
||||
mono,
|
||||
validate,
|
||||
sanitize,
|
||||
checkbox,
|
||||
prefixes,
|
||||
onDone,
|
||||
} = props;
|
||||
const tx = useTx();
|
||||
const listId = useId();
|
||||
const { ref, clean } = useSanitizedField(sanitize);
|
||||
const [value, setValue] = useState(initial);
|
||||
const [checked, setChecked] = useState(checkbox?.initial ?? false);
|
||||
const [overwrite, setOverwrite] = useState(false);
|
||||
const [touched, setTouched] = useState(!!props.validateInitial && initial !== "");
|
||||
const [completing, setCompleting] = useState(false);
|
||||
const [active, setActive] = useState(-1);
|
||||
const hasPrefixes = !!prefixes?.length;
|
||||
const suggestions =
|
||||
completing && value ? (prefixes?.filter((p) => p.length > value.length && p.startsWith(value)) ?? []) : [];
|
||||
const shown = suggestions.length > 0;
|
||||
const canOverwrite = props.overwriteBranch?.(value) ?? false;
|
||||
const error = validate ? validate(value, canOverwrite && overwrite) : value.trim() ? null : "Value must not be empty";
|
||||
const submit = () => {
|
||||
setTouched(true);
|
||||
if (!error) onDone({ value: value.trim(), checked, ...(canOverwrite ? { overwrite } : {}) });
|
||||
};
|
||||
|
||||
const acceptPrefix = (prefix: string) => {
|
||||
setValue(prefix);
|
||||
setOverwrite(false);
|
||||
// A trailing slash is expected while the user finishes the name.
|
||||
setTouched(false);
|
||||
setCompleting(false);
|
||||
};
|
||||
|
||||
const onPrefixKey = (e: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (!shown || isImeKey(e.nativeEvent) || e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return;
|
||||
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
|
||||
const next = listNavigate(e.key, { items: suggestions, active, wrap: true });
|
||||
if (next !== null) {
|
||||
e.preventDefault();
|
||||
setActive(next);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const prefix = suggestions[active];
|
||||
if (e.key === "Enter" || (e.key === "Tab" && prefix)) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (prefix) acceptPrefix(prefix);
|
||||
else submit();
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
@@ -112,6 +163,11 @@ function PromptDialog(props: PromptOptions & { onDone: (r: PromptResult | null)
|
||||
ref={ref}
|
||||
data-autofocus
|
||||
aria-label={label ?? title}
|
||||
role={hasPrefixes ? "combobox" : undefined}
|
||||
aria-autocomplete={hasPrefixes ? "list" : undefined}
|
||||
aria-expanded={hasPrefixes ? shown : undefined}
|
||||
aria-controls={shown ? listId : undefined}
|
||||
aria-activedescendant={shown && suggestions[active] ? `${listId}-${active}` : undefined}
|
||||
value={value}
|
||||
mono={mono}
|
||||
placeholder={placeholder}
|
||||
@@ -122,8 +178,47 @@ function PromptDialog(props: PromptOptions & { onDone: (r: PromptResult | null)
|
||||
const next = clean(e);
|
||||
if (next.trim() !== value.trim()) setOverwrite(false);
|
||||
setValue(next);
|
||||
if (hasPrefixes) {
|
||||
setActive(-1);
|
||||
setCompleting(true);
|
||||
}
|
||||
}}
|
||||
onKeyDown={hasPrefixes ? onPrefixKey : undefined}
|
||||
onBlur={hasPrefixes ? () => setCompleting(false) : undefined}
|
||||
/>
|
||||
<Popup
|
||||
open={shown}
|
||||
anchor={ref}
|
||||
matchWidth
|
||||
role="presentation"
|
||||
autoFocus={false}
|
||||
restoreFocus={false}
|
||||
onClose={() => setCompleting(false)}
|
||||
className={styles.prefixPopup}
|
||||
>
|
||||
<div style={{ height: Math.min(suggestions.length, 8) * 24 }}>
|
||||
<List
|
||||
id={listId}
|
||||
items={suggestions}
|
||||
getKey={(prefix) => prefix}
|
||||
activeIndex={active}
|
||||
onActivate={acceptPrefix}
|
||||
focusable={false}
|
||||
rowHeight={24}
|
||||
aria-label={tx("Branch name prefixes")}
|
||||
className={styles.prefixList}
|
||||
renderItem={(prefix, state) => (
|
||||
<span className={styles.targetName} title={prefix}>
|
||||
<HighlightedText
|
||||
text={prefix}
|
||||
indices={Array.from({ length: value.length }, (_, i) => i)}
|
||||
tone={state.active ? "accent" : "strong"}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</Popup>
|
||||
{touched && error && value && <div className={styles.error}>{error}</div>}
|
||||
{checkbox && <Checkbox checked={checked} onChange={setChecked} label={checkbox.label} />}
|
||||
{canOverwrite && <Checkbox checked={overwrite} onChange={setOverwrite} label="Overwrite existing branch" />}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { registerEditorKind } from "@/workbench/contributions";
|
||||
import { COMBINED_DIFF_KIND, type CombinedDiffData } from "./allInOneDiff";
|
||||
import { DIFF_KIND, diffInputAtCaret, diffTitle, type DiffData } from "./diffInput";
|
||||
|
||||
/** The diff viewer (editor kind `diff`), also for windows that show diffs without Git (deployment). */
|
||||
export function activateDiffViewer(): () => void {
|
||||
const single = registerEditorKind({
|
||||
kind: DIFF_KIND,
|
||||
standalone: true,
|
||||
component: lazyComponent(() => import("./diff-editor-tab").then((m) => m.DiffEditorTab)),
|
||||
title: (input) => diffTitle(input.data as DiffData),
|
||||
icon: () => "diff",
|
||||
navigationInput: diffInputAtCaret,
|
||||
});
|
||||
const combined = registerEditorKind({
|
||||
kind: COMBINED_DIFF_KIND,
|
||||
standalone: true,
|
||||
component: lazyComponent(() => import("./CombinedDiff").then((m) => m.CombinedDiffTab)),
|
||||
title: (input) => (input.data as CombinedDiffData).title ?? tx("Combined Changes Diff"),
|
||||
icon: () => "diff",
|
||||
});
|
||||
return () => {
|
||||
single();
|
||||
combined();
|
||||
};
|
||||
}
|
||||
@@ -4,14 +4,12 @@
|
||||
* merge and Local History editors, remote operations.
|
||||
*/
|
||||
import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowSettings";
|
||||
import { COMBINED_DIFF_KIND, type CombinedDiffData } from "./allInOneDiff";
|
||||
import { editorsFor, registerEditorContribution } from "@/editor/api";
|
||||
import {
|
||||
notifications,
|
||||
registerEditorKind,
|
||||
registerMenuGroup,
|
||||
registerOverlay,
|
||||
registerSettingsPage,
|
||||
registerTitleItem,
|
||||
registerToolWindow,
|
||||
} from "@/workbench/contributions";
|
||||
@@ -30,7 +28,7 @@ import { BranchWidget, BranchesPopupHost, useBranchesPopup } from "./BranchWidge
|
||||
import { SyncCommitsPopupHost } from "./SyncCommitsPopup";
|
||||
import { showConflictsDialog, takeContinueWhenResolved } from "./conflictsUi";
|
||||
import { registerCompareActions } from "./compare";
|
||||
import { DIFF_KIND, diffInputAtCaret, diffTitle, type DiffData } from "./diffInput";
|
||||
import { activateDiffViewer } from "./diffViewer";
|
||||
import { installDiffEditorHost } from "./DiffWindow";
|
||||
import { VcsDialogHost } from "./dialogs";
|
||||
import { changeMarkers } from "./gutter";
|
||||
@@ -55,6 +53,7 @@ import { installVcsStore, onConflictsAppeared, onConflictsCleared, useVcs } from
|
||||
import { installRootSync } from "./rootSync";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { openOnRemoteActions, registerOpenOnRemote } from "./openOnRemote";
|
||||
import { activateSettingsPages } from "./settingsPages";
|
||||
|
||||
/** The Resolve/Continue/Abort buttons exist in the title bar only while there is something to resolve. */
|
||||
function trackMergeRebaseItem(): () => void {
|
||||
@@ -155,43 +154,6 @@ function conflictsBody(names: string[]): string {
|
||||
: tx`${names.length} files have conflicts: ${list}`;
|
||||
}
|
||||
|
||||
/** Settings › Version Control › Log (also used by the Settings window). */
|
||||
export { activateComparisonWindow, ComparisonWindow } from "./ComparisonWindow";
|
||||
export { activateDiffWindow, DiffWindow } from "./DiffWindow";
|
||||
|
||||
/** The diff viewer (editor kind `diff`), also for windows that show diffs without Git (deployment). */
|
||||
export function activateDiffViewer(): () => void {
|
||||
const single = registerEditorKind({
|
||||
kind: DIFF_KIND,
|
||||
standalone: true,
|
||||
component: lazyComponent(() => import("./diff-editor-tab").then((m) => m.DiffEditorTab)),
|
||||
title: (input) => diffTitle(input.data as DiffData),
|
||||
icon: () => "diff",
|
||||
navigationInput: diffInputAtCaret,
|
||||
});
|
||||
const combined = registerEditorKind({
|
||||
kind: COMBINED_DIFF_KIND,
|
||||
standalone: true,
|
||||
component: lazyComponent(() => import("./CombinedDiff").then((m) => m.CombinedDiffTab)),
|
||||
title: (input) => (input.data as CombinedDiffData).title ?? tx("Combined Changes Diff"),
|
||||
icon: () => "diff",
|
||||
});
|
||||
return () => {
|
||||
single();
|
||||
combined();
|
||||
};
|
||||
}
|
||||
|
||||
export function activateSettingsPages(): () => void {
|
||||
return registerSettingsPage({
|
||||
id: "vcs.log",
|
||||
title: "Log",
|
||||
order: 6,
|
||||
keywords: ["git log", "references", "tags", "columns", "commit time"],
|
||||
component: lazyComponent(() => import("./LogSettingsPage").then((m) => m.LogSettingsPage)),
|
||||
});
|
||||
}
|
||||
|
||||
export function activate(): () => void {
|
||||
onConflictsAppeared((files) =>
|
||||
notifications().notify({
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { registerSettingsPage } from "@/workbench/contributions";
|
||||
|
||||
/** Settings › Version Control › Log (also used by the Settings window). */
|
||||
export function activateSettingsPages(): () => void {
|
||||
return registerSettingsPage({
|
||||
id: "vcs.log",
|
||||
title: "Log",
|
||||
order: 6,
|
||||
keywords: ["git log", "references", "tags", "columns", "commit time"],
|
||||
component: lazyComponent(() => import("./LogSettingsPage").then((m) => m.LogSettingsPage)),
|
||||
});
|
||||
}
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
import { publishPreviewSelection, publishPreviewTop, stepMarkdownPreviewFontZoom, useLiveMarkdown } from "./live";
|
||||
import { subscribeTheme, themeKey } from "@/platform/themeWatch";
|
||||
import { hasMermaid, MERMAID_SELECTOR, renderMermaidIn } from "./mermaid";
|
||||
import { renderMath } from "@/editor/lsp/markdownMath";
|
||||
import { modeOf, useMarkdownModes } from "./modes";
|
||||
import { MarkdownLayoutActions } from "./MarkdownLayoutActions";
|
||||
import {
|
||||
@@ -184,8 +185,11 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
});
|
||||
}, [html]);
|
||||
|
||||
// Math before the preview index: typesetting changes the blocks' heights.
|
||||
useLayoutEffect(() => {
|
||||
if (ref.current) invalidatePreviewIndex(ref.current);
|
||||
if (!ref.current) return;
|
||||
renderMath(ref.current);
|
||||
invalidatePreviewIndex(ref.current);
|
||||
}, [html]);
|
||||
|
||||
// Mermaid diagrams: before paint, so cached ones don't flash their source.
|
||||
|
||||
@@ -97,6 +97,7 @@ function collectRuns(root: Node): TextRun[] {
|
||||
const el = node as Element;
|
||||
const tag = el.tagName.toUpperCase();
|
||||
if (SKIP_TAGS.has(tag)) return;
|
||||
if (el.classList.contains("katex-mathml")) return;
|
||||
if (tag === "PRE" && el.parentElement?.getAttribute("data-mermaid-state") === "ok") return;
|
||||
const isBlock = BLOCK_TAGS.has(tag);
|
||||
if (isBlock) flush();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { renderMath } from "@/editor/lsp/markdownMath";
|
||||
import {
|
||||
createMarkdownRenderer,
|
||||
frontMatter,
|
||||
@@ -280,6 +281,17 @@ describe("markdown preview rendering", () => {
|
||||
expect(previewLineAtOffset(blocks, 5000)).toBe(20);
|
||||
expect(previewLineAtOffset([], 50)).toBe(0);
|
||||
});
|
||||
|
||||
it("renders LaTeX math blocks with source lines and inline math", () => {
|
||||
const root = document.createElement("div");
|
||||
root.innerHTML = renderMarkdown("# Heading\n\n$$\nx^2 + y^2 = z^2\n$$\n\nInline $a_1 + b_2$.\n");
|
||||
expect(root.querySelectorAll("[data-math]")).toHaveLength(2);
|
||||
renderMath(root);
|
||||
const lines = [...root.querySelectorAll<HTMLElement>(":scope > [data-line]")].map((e) => e.dataset.line);
|
||||
expect(lines).toEqual(["0", "2", "6"]);
|
||||
expect(root.querySelector(".katex-display")).not.toBeNull();
|
||||
expect(root.querySelectorAll(".katex")).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("markdown preview re-rendering", () => {
|
||||
@@ -300,6 +312,8 @@ describe("markdown preview re-rendering", () => {
|
||||
"| a | b |\n|---|---|\n| 1 | <b>2</b> |",
|
||||
'<span is="x-span">custom</span> and <body class="x"> and </body> text',
|
||||
"> quote\n> more",
|
||||
"$$\nx^2 + y^2 = z^2\n$$",
|
||||
"Inline $a_1 + b_2$ math.",
|
||||
"Last paragraph.",
|
||||
];
|
||||
const doc = (parts: readonly string[]) => parts.join("\n\n") + "\n";
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
* blocks inside one HTML container) is wrapped in an element carrying its
|
||||
* 0-based source line (`data-line`) for scroll sync; images keep their source in `data-src` and are loaded by the preview
|
||||
* (local files through the backend, as the CSP blocks file URLs). Mermaid
|
||||
* blocks become `[data-mermaid]` placeholders, drawn by `./mermaid`. YAML front matter is shown
|
||||
* blocks become `[data-mermaid]` placeholders, drawn by `./mermaid`; math becomes `[data-math]`
|
||||
* placeholders, typeset by the preview (`renderMath`). YAML front matter is shown
|
||||
* as a table of its top-level fields.
|
||||
*/
|
||||
import { Marked, type Token, type TokensList } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { mathExtension } from "@/editor/lsp/markdownMath";
|
||||
import { opensOtherShare } from "@/platform/paths";
|
||||
|
||||
const escapeHtml = (s: string) =>
|
||||
@@ -22,7 +24,7 @@ const marked = new Marked({
|
||||
return `<div data-mermaid=""><pre><code class="language-mermaid">${escapeHtml(text)}</code></pre></div>\n`;
|
||||
},
|
||||
},
|
||||
});
|
||||
}).use(mathExtension());
|
||||
|
||||
// Own instance: hooks must not leak into the hover / documentation renderer.
|
||||
let purifier: ReturnType<typeof DOMPurify> | null = null;
|
||||
@@ -180,7 +182,7 @@ function blocks(text: string): { line: number; html: string }[] {
|
||||
|
||||
const SANITIZE = {
|
||||
USE_PROFILES: { html: true },
|
||||
ADD_ATTR: ["data-src", "data-line", "data-front-matter"],
|
||||
ADD_ATTR: ["data-src", "data-line", "data-front-matter", "data-math"],
|
||||
// The preview shares the IDE's document: a `<style>` in a file would restyle the whole IDE.
|
||||
// `srcset` and `<source>` would pick an image past the one the preview loads.
|
||||
FORBID_TAGS: ["style", "form", "source"],
|
||||
|
||||
@@ -8,27 +8,13 @@ import { executeAction, registerActions } from "@/platform/actions";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { registerKeyClaim } from "@/platform/keymap";
|
||||
import { registerEditorContribution } from "@/editor/api";
|
||||
import { registerSettingsPage, registerStatusItem, showStatusInfo } from "@/workbench/contributions";
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { registerStatusItem, showStatusInfo } from "@/workbench/contributions";
|
||||
import { vimKeyClaim } from "./conflicts";
|
||||
import { loadRcFile } from "./rcFile";
|
||||
import { setVimEnabled, syncVimSettingsFromStorage, useVimSettings } from "./settings";
|
||||
import { activateSettingsPages, VIM_SETTINGS_PAGE } from "./settingsPages";
|
||||
import { VimStatus } from "./VimStatus";
|
||||
|
||||
export const VIM_SETTINGS_PAGE = "editor.vim";
|
||||
|
||||
/** Settings › Editor › Vim (also used by the Settings window). */
|
||||
export function activateSettingsPages(): () => void {
|
||||
return registerSettingsPage({
|
||||
id: VIM_SETTINGS_PAGE,
|
||||
title: "Vim",
|
||||
group: "Editor",
|
||||
order: 45,
|
||||
keywords: ["vim", "ideavim", "ideavimrc", "emulation", "shortcut conflicts", "handler"],
|
||||
component: lazyComponent(() => import("./VimSettingsPage").then((m) => m.VimSettingsPage)),
|
||||
});
|
||||
}
|
||||
|
||||
type Engine = typeof import("./engine");
|
||||
|
||||
export function activate(): () => void {
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { registerSettingsPage } from "@/workbench/contributions";
|
||||
|
||||
export const VIM_SETTINGS_PAGE = "editor.vim";
|
||||
|
||||
/** Settings › Editor › Vim (also used by the Settings window). */
|
||||
export function activateSettingsPages(): () => void {
|
||||
return registerSettingsPage({
|
||||
id: VIM_SETTINGS_PAGE,
|
||||
title: "Vim",
|
||||
group: "Editor",
|
||||
order: 45,
|
||||
keywords: ["vim", "ideavim", "ideavimrc", "emulation", "shortcut conflicts", "handler"],
|
||||
component: lazyComponent(() => import("./VimSettingsPage").then((m) => m.VimSettingsPage)),
|
||||
});
|
||||
}
|
||||
+10
-115
@@ -1,122 +1,17 @@
|
||||
import React, { useEffect } from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import "./styles/global.css";
|
||||
import { Workbench } from "./workbench/Workbench";
|
||||
import { activateSecondaryWindow, activateWorkbench } from "./workbench/activate";
|
||||
import {
|
||||
activateComparisonWindowFeatures,
|
||||
activateDeploymentWindowFeatures,
|
||||
activateDiffWindowFeatures,
|
||||
activateFeatures,
|
||||
activateSettingsWindowFeatures,
|
||||
ComparisonWindow,
|
||||
DeploymentWindow,
|
||||
DiffWindow,
|
||||
SettingsWindow,
|
||||
} from "./features";
|
||||
import { auxiliaryWindow } from "./platform/auxWindow";
|
||||
import { installRepeatedDoubleClick } from "./platform/doubleClick";
|
||||
import { installErrorLogging, logError } from "./platform/errorLog";
|
||||
import { guessOs } from "./platform/platformInfo";
|
||||
import { installReorderedTapClick } from "./platform/reordered-tap-click";
|
||||
import { installWebKitClipboardGuard } from "./platform/webkitClipboard";
|
||||
import { installPageSwipeTracking } from "./platform/pageSwipe";
|
||||
import { installImeKeyGuard } from "./platform/ime";
|
||||
import { installKeyboardDispatcher } from "./platform/keymap";
|
||||
import { installPointerFocus } from "./platform/pointerFocus";
|
||||
import { call, commands, isTauri } from "./platform/ipc";
|
||||
import { hideSplash } from "./platform/splash";
|
||||
import { prefetchLazyComponents } from "./ui";
|
||||
import { installWindowDrag } from "./workbench/window-drag";
|
||||
import { installFullscreenEscapeGuard } from "./workbench/fullscreenEscape";
|
||||
import { installCommonWindowBoot } from "./windowBoot";
|
||||
|
||||
if (import.meta.env.DEV && isTauri()) {
|
||||
// The Tauri MCP bridge returns eval results via `window.__TAURI__` on Windows/Linux
|
||||
// (macOS evaluates natively). Dev only, so release builds keep withGlobalTauri off.
|
||||
const [{ invoke }, { emit }] = await Promise.all([import("@tauri-apps/api/core"), import("@tauri-apps/api/event")]);
|
||||
(window as unknown as { __TAURI__?: unknown }).__TAURI__ ??= { core: { invoke }, event: { emit } };
|
||||
}
|
||||
await installCommonWindowBoot();
|
||||
|
||||
installRepeatedDoubleClick();
|
||||
// WebKit only (bug 219670). In Chromium (the e2e browser) a scripted double-click stamps its
|
||||
// second press like the release before it, which the shim would take for a reordered tap and
|
||||
// click twice.
|
||||
if (guessOs() === "macos" && !/Chrome|Firefox/.test(navigator.userAgent)) installReorderedTapClick();
|
||||
if (guessOs() === "linux" && isTauri()) installWebKitClipboardGuard();
|
||||
// A double click on the title bar fills the work area; the backend steps the frame once per
|
||||
// presented webview frame, because AppKit's own zoom hides the page until the resize ends.
|
||||
installWindowDrag({
|
||||
toggleMaximize: () => call(commands.windowToggleZoom()).catch((e) => console.warn("cannot zoom the window", e)),
|
||||
});
|
||||
installPointerFocus();
|
||||
installImeKeyGuard();
|
||||
installErrorLogging();
|
||||
installPageSwipeTracking(window);
|
||||
|
||||
// Auxiliary windows (Settings `settings-<parent>`, comparisons `comparison-<parent>-<n>`, Sync with
|
||||
// Deployed `deployment-<parent>`) load this page too.
|
||||
// Auxiliary windows (`settings-<parent>`, `comparison-<parent>-<n>`, `diff-<parent>-<n>`,
|
||||
// `deployment-<parent>`) load only their own module graph, without Workbench or CodeMirror
|
||||
// when not needed.
|
||||
const aux = auxiliaryWindow();
|
||||
|
||||
if (aux?.kind === "settings") {
|
||||
activateSecondaryWindow();
|
||||
activateSettingsWindowFeatures(aux.parent);
|
||||
} else if (aux?.kind === "comparison") {
|
||||
activateSecondaryWindow();
|
||||
activateComparisonWindowFeatures(aux.parent);
|
||||
installKeyboardDispatcher();
|
||||
} else if (aux?.kind === "diff") {
|
||||
activateSecondaryWindow();
|
||||
activateDiffWindowFeatures(aux.parent);
|
||||
installKeyboardDispatcher();
|
||||
} else if (aux?.kind === "deployment") {
|
||||
activateSecondaryWindow();
|
||||
activateDeploymentWindowFeatures(aux.parent);
|
||||
if (aux) {
|
||||
const { bootAuxiliaryWindow } = await import("./auxiliaryBoot");
|
||||
await bootAuxiliaryWindow(aux);
|
||||
} else {
|
||||
// Before the features' and the dispatcher's key handlers: it wraps the Escape they see.
|
||||
installFullscreenEscapeGuard();
|
||||
activateWorkbench();
|
||||
// `vite build --mode perf` is a production bundle for the performance harness (`perf/`).
|
||||
const perfBuild = import.meta.env.MODE === "perf";
|
||||
if ((import.meta.env.DEV || perfBuild) && !isTauri()) {
|
||||
const { registerDevSamples } = await import("./workbench/devSamples");
|
||||
registerDevSamples();
|
||||
}
|
||||
if (import.meta.env.DEV || perfBuild) {
|
||||
const { installPerfProbe } = await import("./workbench/perfProbe");
|
||||
installPerfProbe();
|
||||
}
|
||||
// Order matters: features (e.g. the terminal) install capture-phase key handlers
|
||||
// that must run before the global dispatcher.
|
||||
activateFeatures();
|
||||
installKeyboardDispatcher();
|
||||
const { bootWorkbenchWindow } = await import("./workbenchBoot");
|
||||
await bootWorkbenchWindow();
|
||||
}
|
||||
|
||||
function App() {
|
||||
useEffect(() => {
|
||||
hideSplash();
|
||||
// Views split out of the start-up bundle load in the background once the UI is up.
|
||||
if (!aux) return prefetchLazyComponents();
|
||||
}, []);
|
||||
return aux?.kind === "settings" ? (
|
||||
<SettingsWindow />
|
||||
) : aux?.kind === "comparison" ? (
|
||||
<ComparisonWindow />
|
||||
) : aux?.kind === "diff" ? (
|
||||
<DiffWindow />
|
||||
) : aux?.kind === "deployment" ? (
|
||||
<DeploymentWindow />
|
||||
) : (
|
||||
<Workbench />
|
||||
);
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement, {
|
||||
onUncaughtError: (error) => {
|
||||
logError("Uncaught render error", error);
|
||||
window.dispatchEvent(new CustomEvent("openidea:boot-error", { detail: error }));
|
||||
},
|
||||
}).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
@@ -1333,6 +1333,7 @@
|
||||
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.": "Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.",
|
||||
"No matching remote branches": "No matching remote branches",
|
||||
"Remote branches": "Remote branches",
|
||||
"Branch name prefixes": "Branch name prefixes",
|
||||
"Maven project could not be configured": "Maven project could not be configured",
|
||||
"Change font size with Ctrl/Command+Mouse Wheel": "Change font size with Ctrl/Command+Mouse Wheel",
|
||||
"Active editor": "Active editor",
|
||||
@@ -2458,6 +2459,22 @@
|
||||
"Resize Markdown preview": "Resize Markdown preview",
|
||||
"Run a Python script or module": "Run a Python script or module",
|
||||
"Replace every occurrence of '{pattern}' with '{replacement}' in the scope? The search hit its limit, so it runs again to find the occurrences not listed.": "Replace every occurrence of '{pattern}' with '{replacement}' in the scope? The search hit its limit, so it runs again to find the occurrences not listed.",
|
||||
"Server default": "Server default",
|
||||
"New Database": "New Database",
|
||||
"Owner:": "Owner:",
|
||||
"Restoring a dump needs template0: template1 can already hold extensions and schemas.": "Restoring a dump needs template0: template1 can already hold extensions and schemas.",
|
||||
"Encoding:": "Encoding:",
|
||||
"Tablespace:": "Tablespace:",
|
||||
"Collation:": "Collation:",
|
||||
"New Schema": "New Schema",
|
||||
"Character set:": "Character set:",
|
||||
"Drop database": "Drop database",
|
||||
"The IDE closes its own connections to the database first.": "The IDE closes its own connections to the database first.",
|
||||
"Close the sessions of other clients": "Close the sessions of other clients",
|
||||
"Cannot drop database {database}": "Cannot drop database {database}",
|
||||
"Cannot create database": "Cannot create database",
|
||||
"Database…": "Database…",
|
||||
"Schema…": "Schema…",
|
||||
"Alignment": "Alignment",
|
||||
"Align key-value pairs": "Align key-value pairs",
|
||||
"Align consecutive assignments": "Align consecutive assignments",
|
||||
|
||||
@@ -6020,6 +6020,7 @@
|
||||
"Copy Branch Name": "复制分支名称",
|
||||
"Remote branches are not available for private forks": "私有派生仓库的远程分支不可用",
|
||||
"Remote branches": "远程分支",
|
||||
"Branch name prefixes": "分支名称前缀",
|
||||
"Show Diff in a New Tab or Window": "在新标签页或窗口中显示差异",
|
||||
"Pull request does not contain any changes": "拉取请求不包含任何更改",
|
||||
"Mark as Viewed": "标记为已查看",
|
||||
@@ -8833,6 +8834,22 @@
|
||||
"This Maven project is not loaded": "此 Maven 项目尚未加载",
|
||||
"Load Maven Project": "加载 Maven 项目",
|
||||
"Resize Markdown preview": "调整 Markdown 预览宽度",
|
||||
"Server default": "服务器默认值",
|
||||
"New Database": "新建数据库",
|
||||
"Owner:": "所有者:",
|
||||
"Restoring a dump needs template0: template1 can already hold extensions and schemas.": "恢复转储需要 template0:template1 中可能已有扩展和架构。",
|
||||
"Encoding:": "编码:",
|
||||
"Tablespace:": "表空间:",
|
||||
"Collation:": "排序规则:",
|
||||
"New Schema": "新建架构",
|
||||
"Character set:": "字符集:",
|
||||
"Drop database": "删除数据库",
|
||||
"The IDE closes its own connections to the database first.": "IDE 会先关闭它自己与该数据库的连接。",
|
||||
"Close the sessions of other clients": "关闭其他客户端的会话",
|
||||
"Cannot drop database {database}": "无法删除数据库 {database}",
|
||||
"Cannot create database": "无法创建数据库",
|
||||
"Database…": "数据库…",
|
||||
"Schema…": "架构…",
|
||||
"Alignment": "对齐",
|
||||
"Align key-value pairs": "对齐键值对",
|
||||
"Align consecutive assignments": "对齐连续赋值",
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// @vitest-environment node
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import ts from "typescript";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const SRC = resolve(import.meta.dirname);
|
||||
const EXTS = [".ts", ".tsx", "/index.ts", "/index.tsx"];
|
||||
|
||||
function resolveLocal(fromFile: string, spec: string): string | null {
|
||||
const base = spec.startsWith("@/") ? resolve(SRC, spec.slice(2)) : resolve(dirname(fromFile), spec);
|
||||
if (existsSync(base) && /\.(tsx?|css|json)$/.test(base)) return base;
|
||||
for (const ext of EXTS) {
|
||||
if (existsSync(base + ext)) return base + ext;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
describe("settingsWindowBoot static module graph", () => {
|
||||
it("stays isolated from Workbench, CodeMirror, xterm, and non-settings editor modules", () => {
|
||||
const root = resolve(SRC, "settingsWindowBoot.ts");
|
||||
const visited = new Set<string>();
|
||||
const forbidden: string[] = [];
|
||||
|
||||
const walk = (file: string, chain: string[]) => {
|
||||
if (visited.has(file) || !/\.(ts|tsx)$/.test(file)) return;
|
||||
visited.add(file);
|
||||
const source = readFileSync(file, "utf8");
|
||||
const ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
||||
for (const stmt of ast.statements) {
|
||||
if (
|
||||
(!ts.isImportDeclaration(stmt) && !ts.isExportDeclaration(stmt)) ||
|
||||
!stmt.moduleSpecifier ||
|
||||
!ts.isStringLiteral(stmt.moduleSpecifier)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
// Type-only imports erase completely at build time.
|
||||
if (ts.isImportDeclaration(stmt) && stmt.importClause?.isTypeOnly) continue;
|
||||
if (ts.isExportDeclaration(stmt) && stmt.isTypeOnly) continue;
|
||||
|
||||
const spec = stmt.moduleSpecifier.text;
|
||||
if (
|
||||
spec.startsWith("@codemirror/") ||
|
||||
spec.startsWith("@xterm/") ||
|
||||
spec === "mermaid" ||
|
||||
spec === "marked" ||
|
||||
spec.startsWith("@/editor")
|
||||
) {
|
||||
forbidden.push([...chain, spec].join(" -> "));
|
||||
continue;
|
||||
}
|
||||
if (spec.startsWith(".") || spec.startsWith("@/")) {
|
||||
const target = resolveLocal(file, spec);
|
||||
if (!target) continue;
|
||||
const rel = target.slice(SRC.length + 1).replaceAll("\\", "/");
|
||||
if (rel === "workbench/Workbench.tsx" || rel.startsWith("editor/") || rel === "features/index.ts") {
|
||||
forbidden.push([...chain, rel].join(" -> "));
|
||||
continue;
|
||||
}
|
||||
walk(target, [...chain, rel]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
walk(root, ["settingsWindowBoot.ts"]);
|
||||
expect(visited.size).toBeGreaterThan(20);
|
||||
expect(forbidden).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { ComponentType } from "react";
|
||||
import { activateSettingsPages as agentsPages } from "./features/agents/settingsPages";
|
||||
import { installLocaleSync } from "./features/app/locale";
|
||||
import { activateSettingsPages as databasePages } from "./features/database/settingsPages";
|
||||
import { activateSettingsPages as githubPages } from "./features/github/settingsPages";
|
||||
import { activateSettingsPages as pluginsPages } from "./features/plugins/settingsPages";
|
||||
import { activate as projectTrust } from "./features/project-trust";
|
||||
import { activateSettingsWindow } from "./features/settings/settingsWindow";
|
||||
import { SettingsWindow } from "./features/settings/window/SettingsWindow";
|
||||
import { activateSettingsPages as templatesPages } from "./features/templates/settingsPages";
|
||||
import { activateSettingsPages as todoPages } from "./features/todo/settingsPages";
|
||||
import { activateSettingsPages as toolsPages } from "./features/tools/settingsPages";
|
||||
import { activateSettingsPages as vcsPages } from "./features/vcs/settingsPages";
|
||||
import { activateSettingsPages as vimPages } from "./features/vim/settingsPages";
|
||||
import { activateList } from "./windowBoot";
|
||||
|
||||
/**
|
||||
* Native Settings window of project window `parent`: only the settings pages
|
||||
* (no workbench, project services, CodeMirror editors or tool windows).
|
||||
*/
|
||||
export function bootSettingsWindow(parent: string): ComponentType {
|
||||
activateList("settings pages", [
|
||||
["project-trust", projectTrust],
|
||||
["locale", installLocaleSync],
|
||||
["settings", () => activateSettingsWindow(parent)],
|
||||
["templates", templatesPages],
|
||||
["todo", todoPages],
|
||||
["plugins", pluginsPages],
|
||||
["tools", toolsPages],
|
||||
["agents", agentsPages],
|
||||
["vim", vimPages],
|
||||
["vcs", vcsPages],
|
||||
["github", githubPages],
|
||||
["database", databasePages],
|
||||
]);
|
||||
return SettingsWindow;
|
||||
}
|
||||
@@ -384,6 +384,7 @@ const ICONS = {
|
||||
"db-foreign-key": "openidea/database/foreignKey",
|
||||
"db-index": "openidea/database/index",
|
||||
"db-schema": "openidea/database/schema",
|
||||
"db-database": "openidea/database/database",
|
||||
"db-console": "openidea/database/console",
|
||||
"db-matview": "openidea/database/matview",
|
||||
"db-routine": "openidea/database/routine",
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
<!-- OpenIDEA: database (two stacked rounded squares) -->
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M5.5 4.5V3.5C5.5 2.94772 5.94772 2.5 6.5 2.5H12.5C13.0523 2.5 13.5 2.94772 13.5 3.5V9.5C13.5 10.0523 13.0523 10.5 12.5 10.5H11.5" stroke="#3574F0"/><rect x="2.5" y="4.5" width="9" height="9" rx="1" fill="#EDF3FF" stroke="#3574F0"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 402 B |
@@ -0,0 +1,4 @@
|
||||
<!-- OpenIDEA: database (two stacked rounded squares) -->
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M5.5 4.5V3.5C5.5 2.94772 5.94772 2.5 6.5 2.5H12.5C13.0523 2.5 13.5 2.94772 13.5 3.5V9.5C13.5 10.0523 13.0523 10.5 12.5 10.5H11.5" stroke="#548AF7"/><rect x="2.5" y="4.5" width="9" height="9" rx="1" fill="#25324D" stroke="#548AF7"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 402 B |
@@ -0,0 +1,77 @@
|
||||
import React, { useEffect, type ComponentType } from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import "./styles/global.css";
|
||||
import { installRepeatedDoubleClick } from "./platform/doubleClick";
|
||||
import { installErrorLogging, logError } from "./platform/errorLog";
|
||||
import { installImeKeyGuard } from "./platform/ime";
|
||||
import { call, commands, isTauri } from "./platform/ipc";
|
||||
import { installPageSwipeTracking } from "./platform/pageSwipe";
|
||||
import { guessOs } from "./platform/platformInfo";
|
||||
import { installPointerFocus } from "./platform/pointerFocus";
|
||||
import { installReorderedTapClick } from "./platform/reordered-tap-click";
|
||||
import { hideSplash } from "./platform/splash";
|
||||
import { installWebKitClipboardGuard } from "./platform/webkitClipboard";
|
||||
import { prefetchLazyComponents } from "./ui";
|
||||
import { installWindowDrag } from "./workbench/window-drag";
|
||||
|
||||
export type Activate = () => void | (() => void);
|
||||
|
||||
export function activateList(what: string, list: ReadonlyArray<readonly [string, Activate]>): () => void {
|
||||
const disposers: Array<() => void> = [];
|
||||
for (const [name, activate] of list) {
|
||||
try {
|
||||
const d = activate();
|
||||
if (d) disposers.push(d);
|
||||
} catch (e) {
|
||||
console.error(`${what} of ${name} failed to activate`, e);
|
||||
}
|
||||
}
|
||||
return () => disposers.reverse().forEach((d) => d());
|
||||
}
|
||||
|
||||
export async function installCommonWindowBoot(): Promise<void> {
|
||||
if (import.meta.env.DEV && isTauri()) {
|
||||
// The Tauri MCP bridge returns eval results via `window.__TAURI__` on Windows/Linux
|
||||
// (macOS evaluates natively). Dev only, so release builds keep withGlobalTauri off.
|
||||
const [{ invoke }, { emit }] = await Promise.all([import("@tauri-apps/api/core"), import("@tauri-apps/api/event")]);
|
||||
(window as unknown as { __TAURI__?: unknown }).__TAURI__ ??= { core: { invoke }, event: { emit } };
|
||||
}
|
||||
|
||||
installRepeatedDoubleClick();
|
||||
// WebKit only (bug 219670). In Chromium (the e2e browser) a scripted double-click stamps its
|
||||
// second press like the release before it, which the shim would take for a reordered tap and
|
||||
// click twice.
|
||||
if (guessOs() === "macos" && !/Chrome|Firefox/.test(navigator.userAgent)) installReorderedTapClick();
|
||||
if (guessOs() === "linux" && isTauri()) installWebKitClipboardGuard();
|
||||
// A double click on the title bar fills the work area; the backend steps the frame once per
|
||||
// presented webview frame, because AppKit's own zoom hides the page until the resize ends.
|
||||
installWindowDrag({
|
||||
toggleMaximize: () => call(commands.windowToggleZoom()).catch((e) => console.warn("cannot zoom the window", e)),
|
||||
});
|
||||
installPointerFocus();
|
||||
installImeKeyGuard();
|
||||
installErrorLogging();
|
||||
installPageSwipeTracking(window);
|
||||
}
|
||||
|
||||
export function mountWindowRoot(View: ComponentType, { prefetchLazy = false }: { prefetchLazy?: boolean } = {}): void {
|
||||
function App() {
|
||||
useEffect(() => {
|
||||
hideSplash();
|
||||
// Views split out of the start-up bundle load in the background once the UI is up.
|
||||
if (prefetchLazy) return prefetchLazyComponents();
|
||||
}, []);
|
||||
return <View />;
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement, {
|
||||
onUncaughtError: (error) => {
|
||||
logError("Uncaught render error", error);
|
||||
window.dispatchEvent(new CustomEvent("openidea:boot-error", { detail: error }));
|
||||
},
|
||||
}).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
}
|
||||
@@ -99,10 +99,3 @@ export function activateWorkbench(): () => void {
|
||||
];
|
||||
return () => disposers.reverse().forEach((d) => d());
|
||||
}
|
||||
|
||||
/** Shell services for a secondary window (Settings): notifications, platform info, browser guards. */
|
||||
export function activateSecondaryWindow(): () => void {
|
||||
provideNotificationService(notificationServiceImpl);
|
||||
void loadPlatformInfo();
|
||||
return installBrowserGuards();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Shell services for a secondary window (Settings, Compare, Diff, Sync with Deployed):
|
||||
* notifications, platform info and browser guards, without pulling in workbench UI.
|
||||
*/
|
||||
import { loadPlatformInfo } from "@/platform/platformInfo";
|
||||
import { installBrowserGuards } from "./browserGuards";
|
||||
import { provideNotificationService } from "./contributions";
|
||||
import { notificationServiceImpl } from "./notificationStore";
|
||||
|
||||
export function activateSecondaryWindow(): () => void {
|
||||
provideNotificationService(notificationServiceImpl);
|
||||
void loadPlatformInfo();
|
||||
return installBrowserGuards();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { activateFeatures } from "./features";
|
||||
import { isTauri } from "./platform/ipc";
|
||||
import { installKeyboardDispatcher } from "./platform/keymap";
|
||||
import { mountWindowRoot } from "./windowBoot";
|
||||
import { activateWorkbench } from "./workbench/activate";
|
||||
import { installFullscreenEscapeGuard } from "./workbench/fullscreenEscape";
|
||||
import { Workbench } from "./workbench/Workbench";
|
||||
|
||||
export async function bootWorkbenchWindow(): Promise<void> {
|
||||
// Before the features' and the dispatcher's key handlers: it wraps the Escape they see.
|
||||
installFullscreenEscapeGuard();
|
||||
activateWorkbench();
|
||||
// `vite build --mode perf` is a production bundle for the performance harness (`perf/`).
|
||||
const perfBuild = import.meta.env.MODE === "perf";
|
||||
if ((import.meta.env.DEV || perfBuild) && !isTauri()) {
|
||||
const { registerDevSamples } = await import("./workbench/devSamples");
|
||||
registerDevSamples();
|
||||
}
|
||||
if (import.meta.env.DEV || perfBuild) {
|
||||
const { installPerfProbe } = await import("./workbench/perfProbe");
|
||||
installPerfProbe();
|
||||
}
|
||||
// Order matters: features (e.g. the terminal) install capture-phase key handlers
|
||||
// that must run before the global dispatcher.
|
||||
activateFeatures();
|
||||
installKeyboardDispatcher();
|
||||
mountWindowRoot(Workbench, { prefetchLazy: true });
|
||||
}
|
||||
Reference in new issue
Block a user