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

...
Автор SHA1 Повідомлення Дата
l0ng-ai f92efa83cd feat(workbench): keep rarely used tool windows off the stripe by default
Bookmarks and TODO are listed under the stripe's "…" until first opened. The Database
window is on the stripe by default only while the project has data sources. Of the
Flutter DevTools windows only Flutter Inspector has a stripe button; Deep Links,
DevTools and DevTools Extensions wait under "…". A user's own stripe choice still wins.
2026-11-24 11:28:46 +08:00
l0ng-ai e27fc0d867 refactor(run): remove the npm tool window
Detected npm scripts are already in the run configuration list and runnable from the
package.json gutter. Remove the separate npm tool window, its package scan and e2e spec.
The editor context menu Run / Debug on a package.json script line stays.
2026-11-24 10:59:41 +08:00
l0ng-ai c50c2ea629 feat(editor): support Helm and Go templates (#5522)
Helm chart manifests and .tpl helpers keep YAML highlighting with Go template actions and are served by helm-ls (installable from Settings › Language Servers, pinned 0.5.4). Standalone .gotmpl / .tmpl / .go.tmpl files are a Go Template language: template actions highlighted, the Go icon, and gopls. Adds a small chart fixture.
2026-11-24 10:50:03 +08:00
l0ng-ai 3e9e86edf1 fix(services): keep a disconnected Docker connection disconnected across restarts (#5519)
Disconnecting a Docker connection in Services was remembered only in memory, so after a restart opening Services dialled every saved connection again (including SSH ones the user had disconnected). The Disconnect intent is now saved per connection; panel startup and the 10 s poll skip it until Connect clears the flag. Older settings keep connecting automatically.
2026-11-24 10:36:20 +08:00
l0ng-ai cb24be4c19 docs(readme): switch the WeChat group QR code to group 4 2026-11-24 10:32:53 +08:00
l0ng-ai 52e3276f93 test(ide-host): compile the code action stub only where its test runs (#5516)
The code action stub carries the cfg(unix) of its only test, fixing Windows clippy on main.
2026-11-24 10:24:30 +08:00
l0ng-ai fcf5406de0 fix(keymap): list Smart Type completion and Rearrange Code in every preset (#5515)
Smart Type completion is in the VS Code preset and Rearrange Code is listed (no default shortcut) in the IntelliJ and VS Code presets, fixing the keymap and Vim :action tests on main.
2026-11-24 10:22:47 +08:00
Deng Liuтаdengliu aee72d994e chore(dev): replace dogfood:build/install with dogfood:local and dogfood:all (#5271)
dogfood:local builds and installs the local dogfood app (--build-only skips installation); dogfood:all <remote_name> runs it alongside dogfood:remote in parallel with [local]/[remote] prefixed output, validates the SSH configuration before the local build starts, stops the sibling process tree on failure, and runs the remote restart prompt once after both finish. AGENTS.md, mise tasks and the setup docs use the new names.

Co-authored-by: dengliu <[email protected]>
2026-11-24 08:57:51 +08:00
LU XIANGRUIтаwildcatDownstairs 397522e099 feat(editor): show language server colors in the gutter (#5229)
Tailwind color classes (`bg-red-500`, `text-brand-700`, `@apply bg-brand-500` in CSS) and the colors a CSS server knows beyond the built-in literal detector (`hwb()`…) now show swatches in the editor gutter. This was the remaining acceptance criterion of #5154. The editor never asked language servers for `textDocument/documentColor`; it only drew swatches for literals it found itself and for colors that plugins reported.
- Backend (`ide-lsp`): the client advertises `colorProvider`. `document_colors` asks every server that has it and tags each color with its server, then drops the answer if the document version changed in the meantime. `color_presentations` asks that server for `textDocument/colorPresentation`. A presentation without its own `textEdit` replaces the color's range with its label. New commands `lsp_document_colors` / `lsp_color_presentations`; bindings regenerated.
- Frontend (`color-preview`): `lspColors.ts` sits next to the plugin source and shares its swatch and picker flow, now in `providerSwatch.ts`. A server color gets no swatch when the built-in detector already shows a literal at the same range, and two servers reporting the same range (CSS + Tailwind) get one swatch. The gutter follows Settings › Editor › General › Gutter Icons › Color preview, and while that is off the editor sends no requests. Picking a color applies the server's single presentation, or offers a menu when there are several.
- Tailwind only presents arbitrary values (`border-[#16a34a]` → `border-[#2563eb]` / `[rgb(…)]` / `[hsl(…)]`). For palette classes like `bg-red-500` it returns none, as in VS Code. In that case a hint says the color can't be changed with the picker (new string, en + zh).

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-24 08:45:02 +08:00
65 змінених файлів з 1535 додано та 634 видалено

No files matched your search

Бінарний файл не відображається.

До

Ширина:  |  Висота:  |  Розмір: 138 KiB

Бінарний файл не відображається.

Після

Ширина:  |  Висота:  |  Розмір: 169 KiB

+2 -1
Переглянути файл
@@ -79,8 +79,9 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
this worktree's running MCP bridges and actual ports.
- `pnpm build` — typecheck + bundle frontend.
- `pnpm dogfood:build` / `pnpm dogfood:install` (or `mise run dogfood:build` / `mise run dogfood:install`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
- `pnpm dogfood:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
+1 -1
Переглянути файл
@@ -68,7 +68,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
- WeChat group — scan to join:
<img src=".github/assets/wechat-group-3.png" alt="WeChat group QR code" width="200">
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
+1 -1
Переглянути файл
@@ -68,7 +68,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
- WeChat grubu, katılmak için kodu okut:
<img src=".github/assets/wechat-group-3.png" alt="WeChat grubu QR kodu" width="200">
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
+1 -1
Переглянути файл
@@ -66,7 +66,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
- 微信群,扫码加入:
<img src=".github/assets/wechat-group-3.png" alt="微信群二维码" width="200">
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
+28 -2
Переглянути файл
@@ -143,6 +143,9 @@ pub struct DockerConnection {
pub id: String,
pub name: String,
pub endpoint: DockerEndpoint,
/// Whether the user explicitly disconnected this connection in Services.
#[serde(default)]
pub disconnected: bool,
}
/// A registry to log in to (Docker Hub, GHCR, a private one). The password is stored separately.
@@ -414,6 +417,7 @@ mod tests {
id: "c1".into(),
name: "Build box".into(),
endpoint: DockerEndpoint::Tcp { host: "build:2376".into(), tls_cert_dir: None },
disconnected: true,
}],
registries: vec![DockerRegistry {
id: "r1".into(),
@@ -435,12 +439,34 @@ mod tests {
assert!(load_settings(dir).connections.is_empty());
}
#[test]
fn connection_intent_defaults_to_connected_and_round_trips() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
std::fs::write(
dir.join(SETTINGS_FILE),
r#"{"connections":[{"id":"box","name":"Box","endpoint":{"kind":"ssh","config":"build"}}]}"#,
)
.unwrap();
let mut settings = load_settings(dir);
assert!(!settings.connections[0].disconnected);
for disconnected in [true, false] {
settings.connections[0].disconnected = disconnected;
save_settings(dir, &settings).unwrap();
assert_eq!(load_settings(dir), settings);
}
}
#[test]
fn load_drops_the_injected_default_connection() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
let injected =
|| DockerConnection { id: "default".into(), name: "Docker".into(), endpoint: DockerEndpoint::Default };
let injected = || DockerConnection {
id: "default".into(),
name: "Docker".into(),
endpoint: DockerEndpoint::Default,
disconnected: false,
};
let registry =
DockerRegistry { id: "r1".into(), name: "GHCR".into(), address: "ghcr.io".into(), username: "me".into() };
// Saved untouched by an older version (e.g. along with a registry): dropped on load.
+20
Переглянути файл
@@ -1834,6 +1834,23 @@ pub async fn lsp_document_links(host: &Host, window: &str, doc: DocId) -> IdeRes
Ok(out)
}
/// Colors in a document from its language servers (Tailwind classes, CSS values…).
#[command(trust = trusted)]
pub async fn lsp_document_colors(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<DocumentColor>> {
host.project(window)?.lsp.document_colors(doc).await
}
/// How the server that reported `color` writes it with new components.
#[command(trust = trusted)]
pub async fn lsp_color_presentations(
host: &Host,
window: &str,
doc: DocId,
color: DocumentColor,
) -> IdeResult<Vec<ColorPresentation>> {
host.project(window)?.lsp.color_presentations(doc, color).await
}
#[command(trust = trusted)]
pub async fn lsp_call_hierarchy(
host: &Host,
@@ -2302,6 +2319,7 @@ mod tests {
assert_eq!(result.unwrap_err().kind, ErrorKind::Cancelled);
}
#[cfg(unix)]
fn action_stub() -> CodeAction {
CodeAction {
title: String::new(),
@@ -3046,7 +3064,9 @@ ide_command::domain!(
lsp_code_action_query,
lsp_code_actions,
lsp_code_lens,
lsp_color_presentations,
lsp_completion,
lsp_document_colors,
lsp_document_highlights,
lsp_document_links,
lsp_exception_class_at,
+3
Переглянути файл
@@ -121,6 +121,9 @@ pub struct FrameworkFiles {
pub extensions: Vec<String>,
/// Matched like language servers' `root-markers`, e.g. `manage.py`.
pub root_markers: Vec<String>,
/// Require the marker directly beside `folder`.
#[serde(default)]
pub root_marker_in_parent: bool,
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize, Type)]
+62 -18
Переглянути файл
@@ -33,6 +33,7 @@ const BUILTIN: &[(&str, &str)] = &[
("gdscript", include_str!("../../../languages/gdscript.toml")),
("gdshader", include_str!("../../../languages/gdshader.toml")),
("go", include_str!("../../../languages/go.toml")),
("gotmpl", include_str!("../../../languages/gotmpl.toml")),
("gherkin", include_str!("../../../languages/gherkin.toml")),
("gomod", include_str!("../../../languages/gomod.toml")),
("gowork", include_str!("../../../languages/gowork.toml")),
@@ -406,7 +407,14 @@ impl LanguageRegistry {
if let Some((_, i)) = t.name_globs.iter().find(|(p, _)| wildcard_match(p, file_name)) {
return languages[*i].id.clone();
}
if let Some(l) = languages.iter().find(|l| l.framework_files.iter().any(|f| is_framework_file(f, path))) {
let framework_language = |root_marker_in_parent| {
languages.iter().find(|l| {
l.framework_files
.iter()
.any(|f| f.root_marker_in_parent == root_marker_in_parent && is_framework_file(f, path))
})
};
if let Some(l) = framework_language(true).or_else(|| framework_language(false)) {
return l.id.clone();
}
let lower = file_name.to_ascii_lowercase();
@@ -429,17 +437,21 @@ impl LanguageRegistry {
}
}
/// `path` is one of `files`: its extension is listed, and the nearest folder above it named
/// `files.folder` has a root marker in a directory above that folder.
/// `path` has a listed extension and lies under a matching folder with a root marker.
fn is_framework_file(files: &crate::FrameworkFiles, path: &Path) -> bool {
let Some(ext) = path.extension().and_then(|e| e.to_str()) else { return false };
if !files.extensions.iter().any(|e| e.eq_ignore_ascii_case(ext)) {
return false;
}
path.ancestors()
.skip(1)
.find(|dir| dir.file_name().is_some_and(|name| name == files.folder.as_str()))
.is_some_and(|folder| crate::marked_root(None, folder, &files.root_markers).is_some())
let mut folders =
path.ancestors().skip(1).filter(|dir| dir.file_name().is_some_and(|name| name == files.folder.as_str()));
if files.root_marker_in_parent {
folders
.filter_map(Path::parent)
.any(|parent| crate::marked_root(Some(parent), parent, &files.root_markers).is_some())
} else {
folders.next().is_some_and(|folder| crate::marked_root(None, folder, &files.root_markers).is_some())
}
}
/// `*` matches any (possibly empty) run of characters, `?` exactly one; everything else is literal.
@@ -486,6 +498,7 @@ mod tests {
"CQL",
"CSS",
"Go",
"Go Template",
"HTML",
"Java",
"JavaScript",
@@ -997,21 +1010,52 @@ mod tests {
std::fs::create_dir_all(root.join("charts/podinfo/templates/tests")).unwrap();
std::fs::create_dir_all(root.join("k8s/templates")).unwrap();
std::fs::write(root.join("charts/podinfo/Chart.yaml"), "apiVersion: v2\nname: podinfo\n").unwrap();
assert_eq!(detect("charts/podinfo/Chart.yaml"), "yaml");
assert_eq!(detect("charts/podinfo/values.yaml"), "yaml");
assert_eq!(detect("charts/podinfo/templates/deployment.yaml"), "helm-template");
assert_eq!(detect("charts/podinfo/templates/tests/connection.yml"), "helm-template");
assert_eq!(detect("charts/podinfo/templates/_helpers.tpl"), "helm-template");
assert_eq!(detect("charts/podinfo/templates/NOTES.txt"), "helm-template");
// No `Chart.yaml` / `Chart.yml` above this `templates` folder.
assert_eq!(detect("k8s/templates/deployment.yaml"), "yaml");
assert_eq!(detect("common.gotmpl"), "helm-template");
// Outside a chart, `.tpl` belongs to other template engines (Smarty, Terraform).
assert_ne!(detect("site/index.tpl"), "helm-template");
std::fs::write(root.join("manage.py"), "").unwrap();
for file in [
"deployment.yaml",
"tests/connection.yml",
"_helpers.tpl",
"NOTES.txt",
"dashboard.json",
"config.yaml.gotmpl",
"config.yaml.go.tmpl",
"tests/templates/check.YAML",
] {
let path = format!("charts/podinfo/templates/{file}");
assert_eq!(detect(&path), "helm-template", "{path}");
}
for (path, language) in [
("charts/podinfo/Chart.yaml", "yaml"),
("charts/podinfo/values.yaml", "yaml"),
("charts/podinfo/docs/templates/deployment.yaml", "yaml"),
("charts/podinfo/docs/templates/_helpers.tpl", "plaintext"),
("charts/podinfo/docs/templates/sample.tmpl", "gotmpl"),
("charts/podinfo/docs/templates/notes.txt", "django-html"),
("k8s/templates/deployment.yaml", "yaml"),
("site/index.tpl", "plaintext"),
] {
assert_eq!(detect(path), language, "{path}");
}
assert!(reg.is_framework_marker(&root.join("charts/podinfo/Chart.yaml")));
assert!(reg.is_framework_marker(&root.join("charts/podinfo/Chart.yml")));
}
#[test]
fn standalone_go_templates_are_detected_by_extension() {
let reg = reg();
for (path, language) in [
("common.gotmpl", "gotmpl"),
("email.tmpl", "gotmpl"),
("config.go.tmpl", "gotmpl"),
("config.GO.TMPL", "gotmpl"),
("docker-stack.yaml.tmpl", "gotmpl"),
("docker-stack.yaml", "yaml"),
("main.go", "go"),
] {
assert_eq!(reg.detect(Path::new(path), None).as_str(), language, "{path}");
}
}
#[test]
fn the_django_fixture_has_templates_and_a_page() {
let reg = reg();
+1
Переглянути файл
@@ -122,6 +122,7 @@ pub fn client_capabilities() -> Value {
},
"codeLens": { "dynamicRegistration": false },
"documentLink": { "dynamicRegistration": false, "tooltipSupport": true },
"colorProvider": { "dynamicRegistration": false },
"formatting": { "dynamicRegistration": false },
"rangeFormatting": { "dynamicRegistration": false },
"rename": {
+68
Переглянути файл
@@ -1036,6 +1036,29 @@ pub fn document_link(conv: &Conv, path: &Path, l: lsp::DocumentLink) -> Option<D
})
}
pub fn document_color(conv: &Conv, path: &Path, server: ServerId, c: lsp::ColorInformation) -> DocumentColor {
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
DocumentColor {
range: conv.range(path, c.range),
red: unit(c.color.red),
green: unit(c.color.green),
blue: unit(c.color.blue),
alpha: unit(c.color.alpha),
server,
}
}
/// Without its own edit, a presentation's label replaces the color.
pub fn color_presentation(conv: &Conv, path: &Path, range: Range, p: lsp::ColorPresentation) -> ColorPresentation {
let main = match p.text_edit {
Some(e) => conv.text_edit(path, e),
None => TextEdit { range, new_text: p.label.clone() },
};
let mut edits = vec![main];
edits.extend(conv.text_edits(path, p.additional_text_edits.unwrap_or_default()));
ColorPresentation { label: p.label, edits }
}
pub fn call_item(conv: &Conv, item: &lsp::CallHierarchyItem, from_ranges: Vec<Range>) -> Option<HierarchyItem> {
let (path, uri) = uri_target(item.uri.as_str());
Some(HierarchyItem {
@@ -1634,6 +1657,51 @@ mod tests {
assert_eq!(h.kind, InlayKind::Other);
}
#[test]
fn document_colors_keep_their_server_and_clamp_components() {
let conv = Conv::utf16();
let info = serde_json::from_value::<lsp::ColorInformation>(json!({
"range": { "start": { "line": 2, "character": 14 }, "end": { "line": 2, "character": 24 } },
"color": { "red": 0.937, "green": 0.267, "blue": 0.267, "alpha": 1.5 },
}))
.unwrap();
let c = document_color(&conv, Path::new("/p/a.html"), ServerId(3), info);
assert_eq!(c.range, Range::new(p(2, 14), p(2, 24)));
assert_eq!((c.red, c.green, c.blue, c.alpha), (0.937, 0.267, 0.267, 1.0));
assert_eq!(c.server, ServerId(3));
}
#[test]
fn color_presentations_replace_the_color_unless_the_server_gives_an_edit() {
let conv = Conv::utf16();
let here = Path::new("/p/a.css");
let color = Range::new(p(0, 7), p(0, 10));
let plain = serde_json::from_value::<lsp::ColorPresentation>(json!({ "label": "#00ff00" })).unwrap();
let plain = color_presentation(&conv, here, color, plain);
assert_eq!(plain.label, "#00ff00");
assert_eq!(plain.edits, vec![TextEdit { range: color, new_text: "#00ff00".into() }]);
let edited = serde_json::from_value::<lsp::ColorPresentation>(json!({
"label": "rgb(0 255 0)",
"textEdit": {
"range": { "start": { "line": 0, "character": 7 }, "end": { "line": 0, "character": 10 } },
"newText": "rgb(0 255 0)",
},
"additionalTextEdits": [{
"range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } },
"newText": "/* x */",
}],
}))
.unwrap();
let edited = color_presentation(&conv, here, color, edited);
assert_eq!(
edited.edits,
vec![
TextEdit { range: color, new_text: "rgb(0 255 0)".into() },
TextEdit { range: Range::new(p(0, 0), p(0, 0)), new_text: "/* x */".into() },
]
);
}
#[cfg(unix)]
#[test]
fn document_links_split_file_targets_and_urls() {
+65
Переглянути файл
@@ -3401,6 +3401,71 @@ impl LspManager {
out.finish(Vec::new())
}
/// The colors the servers find in the document (`textDocument/documentColor`), each tagged with
/// its server for [`Self::color_presentations`]. An answer for an older version is dropped.
pub async fn document_colors(&self, doc: DocId) -> IdeResult<Vec<DocumentColor>> {
let (snap, targets) = self.doc_targets(doc, "document colors", |c| c.has("colorProvider")).await?;
let requests = targets.iter().map(|t| {
let params = json!({ "textDocument": snap.ident() });
async move {
let colors = self
.call_retrying::<_, Option<Vec<lsp::ColorInformation>>>(
t,
"textDocument/documentColor",
params,
DEFAULT_TIMEOUT,
)
.await;
(t, colors)
}
});
let mut out = Outcome::new();
for (t, r) in join_all(requests).await {
match r {
Ok(colors) => {
let conv = self.conv(t.enc());
let acc = out.value.get_or_insert_with(Vec::new);
acc.extend(
colors
.unwrap_or_default()
.into_iter()
.map(|c| convert::document_color(&conv, &snap.path, t.server.id, c)),
);
}
Err(e) => out.fail(e),
}
}
if self.docs.lock().get(&doc).is_none_or(|d| d.version != snap.version) {
return Err(IdeError::cancelled());
}
out.finish(Vec::new())
}
/// How `color.server` would write `color` at its range (`textDocument/colorPresentation`).
pub async fn color_presentations(&self, doc: DocId, color: DocumentColor) -> IdeResult<Vec<ColorPresentation>> {
let snap = self.snapshot(doc)?;
let Some(server) = snap.servers.iter().find(|s| s.id == color.server) else { return Ok(Vec::new()) };
let Some(t) = self.ready_targets(std::slice::from_ref(server), |c| c.has("colorProvider")).await.pop() else {
return Ok(Vec::new());
};
let params = json!({
"textDocument": snap.ident(),
"color": { "red": color.red, "green": color.green, "blue": color.blue, "alpha": color.alpha },
"range": snap.range(&t, color.range),
});
let list: Option<Vec<lsp::ColorPresentation>> =
self.call(&t, "textDocument/colorPresentation", params, None, DEFAULT_TIMEOUT).await?;
if self.docs.lock().get(&doc).is_none_or(|d| d.version != snap.version) {
return Err(IdeError::cancelled());
}
let conv = self.conv(t.enc());
Ok(list
.unwrap_or_default()
.into_iter()
.map(|p| convert::color_presentation(&conv, &snap.path, color.range, p))
.collect())
}
pub async fn call_hierarchy(
&self,
doc: DocId,
+21
Переглянути файл
@@ -307,6 +307,27 @@ pub struct DocumentLink {
pub tooltip: Option<String>,
}
/// A color a server found in a document (`textDocument/documentColor`); components are 0–1.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DocumentColor {
pub range: Range,
pub red: f32,
pub green: f32,
pub blue: f32,
pub alpha: f32,
pub server: ServerId,
}
/// One way to write a picked color (`textDocument/colorPresentation`): `edits` replace the
/// color's range (with `label` unless the server gave its own edit), then any extra edits.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ColorPresentation {
pub label: String,
pub edits: Vec<TextEdit>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum HierarchyDirection {
+49 -25
Переглянути файл
@@ -1439,26 +1439,10 @@ impl Tools {
sha256: Some(sha256.into()),
checksum_url: None,
}),
ReleaseSource::GitHub { repo } => match http.get_text(&sources::github_latest_url(repo), cancel) {
Ok(json) => sources::github_pick(&json, assets, self.platform),
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
// Without a token the API allows 60 requests an hour per IP address, often used
// up behind a shared one (403/429); the release's web pages have no such limit.
Err(api) => self.resolve_github_web(http, repo, assets, cancel).map_err(|web| {
if web.kind == ErrorKind::Cancelled {
return web;
}
tracing::warn!("GitHub release lookup for {repo} failed: {api}; web pages: {web}");
IdeError::new(
api.kind,
format!(
"{}\nDownload it from {} and set its Path in Settings › Languages & Frameworks › Language Servers.",
api.message,
sources::github_latest_page(repo)
),
)
}),
},
ReleaseSource::GitHub { repo } => self.resolve_github_release(http, repo, None, assets, cancel),
ReleaseSource::GitHubTag { repo, tag } => {
self.resolve_github_release(http, repo, Some(tag), assets, cancel)
}
ReleaseSource::HashiCorp { product } => {
let json = http.get_text(&sources::hashicorp_latest_url(product), cancel)?;
sources::hashicorp_pick(&json, assets, self.platform)
@@ -1485,17 +1469,53 @@ impl Tools {
}
}
/// [`resolve_release`](Self::resolve_release) for a GitHub release, from its web pages.
fn resolve_github_release(
&self,
http: &Http,
repo: &str,
tag: Option<&str>,
assets: &[platform::AssetRule],
cancel: &CancellationToken,
) -> IdeResult<sources::Download> {
let api_url = tag.map_or_else(|| sources::github_latest_url(repo), |tag| sources::github_tag_url(repo, tag));
match http.get_text(&api_url, cancel) {
Ok(json) => sources::github_pick(&json, assets, self.platform),
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
// Shared IP addresses can run out of unauthenticated API requests (403/429).
Err(api) => self.resolve_github_web(http, repo, tag, assets, cancel).map_err(|web| {
if web.kind == ErrorKind::Cancelled {
return web;
}
let page = tag.map_or_else(|| sources::github_latest_page(repo), |tag| sources::github_tag_page(repo, tag));
tracing::warn!("GitHub release lookup for {repo} failed: {api}; web pages: {web}");
IdeError::new(
api.kind,
format!(
"{}\nDownload it from {page} and set its Path in Settings › Languages & Frameworks › Language Servers.",
api.message
),
)
}),
}
}
/// Resolve a GitHub release from its web pages when the API is unavailable.
fn resolve_github_web(
&self,
http: &Http,
repo: &str,
tag: Option<&str>,
assets: &[platform::AssetRule],
cancel: &CancellationToken,
) -> IdeResult<sources::Download> {
let page = http.effective_url(&sources::github_latest_page(repo), cancel)?;
let tag = sources::github_tag_from_url(&page)
.ok_or_else(|| IdeError::unavailable(format!("{repo} has no published release")))?;
let tag = match tag {
Some(tag) => tag.to_owned(),
None => {
let page = http.effective_url(&sources::github_latest_page(repo), cancel)?;
sources::github_tag_from_url(&page)
.ok_or_else(|| IdeError::unavailable(format!("{repo} has no published release")))?
}
};
let list = http.get_text(&sources::github_assets_page(repo, &tag), cancel)?;
match sources::github_pick_web(repo, &tag, &list, None, assets, self.platform) {
Err(e) if e.kind == ErrorKind::Unavailable => {
@@ -1516,7 +1536,11 @@ impl Tools {
emit: Emit,
) -> IdeResult<()> {
let http = Http::new(&self.system_path)?;
emit(InstallEvent::Line { text: "Resolving the latest release…".into() });
let message = match source {
ReleaseSource::GitHubTag { tag, .. } => format!("Resolving release {tag}…"),
_ => "Resolving the latest release…".into(),
};
emit(InstallEvent::Line { text: message });
let dl = self.resolve_release(&http, source, assets, cancel)?;
emit(InstallEvent::Line { text: format!("Downloading {} ({})", dl.name, dl.url) });
let staging = self.root.join(format!(".staging-{}", spec.name));
+45
Переглянути файл
@@ -24,6 +24,8 @@ pub enum ReleaseSource {
Fixed { version: &'static str, url: &'static str, sha256: &'static str },
/// Latest GitHub release of `owner/repo`; assets plus links in the release notes.
GitHub { repo: &'static str },
/// Assets from a specific GitHub release tag.
GitHubTag { repo: &'static str, tag: &'static str },
/// `api.releases.hashicorp.com` product.
HashiCorp { product: &'static str },
/// Latest Eclipse JDT LS milestone tarball from download.eclipse.org.
@@ -604,6 +606,27 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/samehelhawary/phoxite",
needs: &[],
},
ToolSpec {
name: "helm-ls",
display: "helm-ls",
kind: LanguageServer,
commands: &["helm_ls"],
method: Method::Release {
source: ReleaseSource::GitHubTag { repo: "mrjosh/helm-ls", tag: "v0.5.4" },
assets: &[
rule(Mac, Arm64, "helm_ls_darwin_arm64"),
rule(Mac, X64, "helm_ls_darwin_amd64"),
rule(Linux, Arm64, "helm_ls_linux_arm64"),
rule(Linux, X64, "helm_ls_linux_amd64"),
rule(Windows, X64, "helm_ls_windows_amd64.exe"),
],
locate: &["helm_ls"],
},
fallback: None,
version: Some(("helm_ls", &["version"])),
homepage: "https://github.com/mrjosh/helm-ls",
needs: &[],
},
ToolSpec {
name: "gopls",
display: "gopls",
@@ -1362,6 +1385,28 @@ mod tests {
}
}
#[test]
fn helm_ls_picks_the_pinned_native_binary() {
use crate::platform::{Platform, select_asset};
let spec = find("helm-ls").unwrap();
assert!(matches!(
spec.method,
Method::Release { source: ReleaseSource::GitHubTag { repo: "mrjosh/helm-ls", tag: "v0.5.4" }, .. }
));
let releases = [
(Mac, Arm64, "helm_ls_darwin_arm64"),
(Mac, X64, "helm_ls_darwin_amd64"),
(Linux, Arm64, "helm_ls_linux_arm64"),
(Linux, X64, "helm_ls_linux_amd64"),
(Windows, X64, "helm_ls_windows_amd64.exe"),
];
let checksums = releases.map(|(_, _, name)| format!("{name}.sha256sum"));
let names: Vec<_> = checksums.iter().map(String::as_str).chain(releases.map(|(_, _, name)| name)).collect();
for (os, arch, name) in releases {
assert_eq!(select_asset(&names, spec.asset_rules(), Platform { os, arch }), Some(name));
}
}
/// The v263 kotlin-server-* release notes: the CLI distribution archives plus
/// the VS Code extension and checksums; each platform must pick its native
/// distribution and the aarch64 archive must never be picked on x64.
+4
Переглянути файл
@@ -47,6 +47,10 @@ pub fn github_latest_url(repo: &str) -> String {
format!("https://api.github.com/repos/{repo}/releases/latest")
}
pub fn github_tag_url(repo: &str, tag: &str) -> String {
format!("https://api.github.com/repos/{repo}/releases/tags/{tag}")
}
/// The latest release's web page; it redirects to `…/releases/tag/<tag>`. Web pages don't
/// count against the API's rate limit for unauthenticated clients (60 requests an hour).
pub fn github_latest_page(repo: &str) -> String {
+1 -1
Переглянути файл
@@ -67,7 +67,7 @@ mise run dev
`setup` runs `pnpm install` in this worktree. `dev` and `dev:app` use the same worktree-aware launchers as the direct commands. No shell activation is needed for `mise run`.
Run `mise tasks` to list all tasks. `mise run build` builds the frontend (not a desktop installer); `mise run dogfood:build` and `mise run dogfood:install` build and locally install a grey-icon dogfood desktop app that shares settings and data with the release app. Only one of the two apps runs at a time, since they share one instance; settings written by the newer dogfood build can make an older release ignore the settings file. The dogfood app never updates itself: run `dogfood:install` again to pick up new changes. `mise run dogfood:remote <remote_name>` builds and stages `openidea-server` on an SSH host configured in **Tools › SSH Configurations** (`--clean` removes the override). `mise run test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target.
Run `mise tasks` to list all tasks. `mise run build` builds the frontend (not a desktop installer); `mise run dogfood:local` builds and locally installs a grey-icon dogfood desktop app (`--build-only` skips installation) that shares settings and data with the release app. Only one of the two apps runs at a time, since they share one instance; settings written by the newer dogfood build can make an older release ignore the settings file. The dogfood app never updates itself: run `dogfood:local` again to pick up new changes. `mise run dogfood:remote <remote_name>` builds and stages `openidea-server` on an SSH host configured in **Tools › SSH Configurations** (`--clean` removes the override), and `mise run dogfood:all <remote_name>` runs `dogfood:local` and `dogfood:remote <remote_name>` in parallel. `mise run test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target.
## Worktrees
+1 -1
Переглянути файл
@@ -67,7 +67,7 @@ mise run dev
`setup` 在当前 worktree 中执行 `pnpm install`。`dev` 和 `dev:app` 都沿用原来的启动脚本,保留 worktree 隔离。使用 `mise run` 不需要在 shell 中激活 mise。
运行 `mise tasks` 可以查看全部任务。`mise run build` 构建前端,不生成桌面安装包;`mise run dogfood:build` 和 `mise run dogfood:install` 用于构建并在本地安装灰色图标的 dogfood 桌面版(与正式版共享设置和数据)。两者共用同一个实例,同一时间只能运行一个;较新的 dogfood 版写入的设置可能让较旧的正式版忽略整个设置文件。dogfood 版不会自动更新,需要更新时重新运行 `dogfood:install`。`mise run dogfood:remote <remote_name>` 在 **工具 › SSH 配置** 中指定的远程主机上构建并部署 `openidea-server`(`--clean` 可移除覆盖)。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。
运行 `mise tasks` 可以查看全部任务。`mise run build` 构建前端,不生成桌面安装包;`mise run dogfood:local` 用于构建并在本地安装灰色图标的 dogfood 桌面版(与正式版共享设置和数据;`--build-only` 仅构建不安装)。两者共用同一个实例,同一时间只能运行一个;较新的 dogfood 版写入的设置可能让较旧的正式版忽略整个设置文件。dogfood 版不会自动更新,需要更新时重新运行 `dogfood:local`。`mise run dogfood:remote <remote_name>` 在 **工具 › SSH 配置** 中指定的远程主机上构建并部署 `openidea-server`(`--clean` 可移除覆盖),`mise run dogfood:all <remote_name>` 则并行执行 `dogfood:local` 与 `dogfood:remote <remote_name>`。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。
## Worktree
-44
Переглянути файл
@@ -1,44 +0,0 @@
/** The npm tool window lists package.json scripts without run configurations and runs them. */
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const PKG = JSON.stringify({ name: "acme-api", scripts: { dev: "vite", build: "vite build" } });
/** The root package.json has scripts; there are no run configurations. */
async function stubNpm(page: Page) {
await stubDesktop(page);
await page.evaluate(async (pkg) => {
const h = window.__ipc.handlers;
h.fs_read_text = (args) => (String(args.path).endsWith("/package.json") ? pkg : "");
h.run_configs = () => [];
h.run_start = (args) => {
const config = args.config as { id: string; name: string };
return { id: 8, configId: config.id, name: config.name, pid: 4242, running: true, pty: false };
};
const npmModule = "/src/features/run/npmScripts.ts";
const { loadNpmScripts } = await import(/* @vite-ignore */ npmModule);
await loadNpmScripts();
}, PKG);
}
test("lists scripts without run configurations and runs one on double-click", async ({ workbench: page }) => {
await stubNpm(page);
await page.getByRole("button", { name: "npm", exact: true }).click();
const tree = page.getByRole("tree", { name: "npm scripts" });
await expect(tree).toBeVisible();
await expect(tree.getByRole("treeitem", { name: /^acme-api/ })).toBeVisible();
await expect(tree.getByRole("treeitem", { name: "dev" })).toBeVisible();
await expect(tree.getByRole("treeitem", { name: "build" })).toBeVisible();
await tree.getByRole("treeitem", { name: "dev" }).dblclick();
const [started] = await ipcCalls(page, "run_start");
expect(started).toMatchObject({ config: { args: ["run", "dev"], kind: "npm" } });
});
test("offers Run / Debug in a script's context menu", async ({ workbench: page }) => {
await stubNpm(page);
await page.getByRole("button", { name: "npm", exact: true }).click();
const tree = page.getByRole("tree", { name: "npm scripts" });
await tree.getByRole("treeitem", { name: "build" }).click({ button: "right" });
await expect(page.getByRole("menuitem", { name: /Run '.*run build'/ })).toBeVisible();
await expect(page.getByRole("menuitem", { name: /Debug '.*run build'/ })).toBeVisible();
});
+3 -1
Переглянути файл
@@ -5,8 +5,10 @@ test("keeps the file count visible beside a long directory in the TODO pane", as
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const todoModule = "/src/features/todo/store.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { useTodos } = await import(/* @vite-ignore */ todoModule);
const { showToolWindow } = await import(/* @vite-ignore */ layoutModule);
const directory = "src/features/checkout/shared/services/with-a-long-directory-name/for-order-processing";
const path = `${useProject.getState().project.root}/${directory}/orders.ts`;
useTodos.setState({
@@ -14,9 +16,9 @@ test("keeps the file count visible beside a long directory in the TODO pane", as
error: null,
scanned: new Map([[path, [{ path, line: 8, col: 3, keyword: "TODO", text: "TODO: validate orders" }]]]),
});
showToolWindow("todo", true);
});
await page.getByRole("button", { name: "TODO" }).click();
const pane = page.locator('[data-toolwindow="todo"]');
const toolbar = pane.getByRole("toolbar", { name: "TODO actions" });
await expect(toolbar).toHaveAttribute("aria-orientation", "vertical");
+4
Переглянути файл
@@ -0,0 +1,4 @@
apiVersion: v2
name: hello
description: A sample chart for template editing
version: 0.1.0
+7
Переглянути файл
@@ -0,0 +1,7 @@
services:
web:
image: {{ printf "nginx:%s" .Tag }}
{{- if .Replicas }}
deploy:
replicas: {{ .Replicas }}
{{- end }}
+3
Переглянути файл
@@ -0,0 +1,3 @@
{{- define "hello.name" -}}
{{ .Release.Name }}
{{- end -}}
+6
Переглянути файл
@@ -0,0 +1,6 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: {{ include "hello.name" . }}
data:
message: {{ .Values.message | quote }}
+1
Переглянути файл
@@ -0,0 +1 @@
message: Hello from Helm
+12
Переглянути файл
@@ -0,0 +1,12 @@
id = "gotmpl"
name = "Go Template"
extensions = ["gotmpl", "tmpl"]
block-comment = ["{{/*", "*/}}"]
ui-mode = "Go Template"
[[language-servers]]
name = "gopls"
command = "gopls"
initialization-options = { semanticTokens = true, vulncheck = "Imports", hints = { constantValues = true } }
root-markers = ["go.work", "go.mod"]
install-hint = "go install golang.org/x/tools/gopls@latest"
+11 -6
Переглянути файл
@@ -1,16 +1,21 @@
id = "helm-template"
name = "Helm Template"
# `.tpl` is Smarty, Terraform and other template engines too: only charts claim it (below).
extensions = ["gotmpl"]
line-comment = "#"
block-comment = ["{{/*", "*/}}"]
indent = { tab-size = 2, insert-spaces = true }
ui-mode = "Helm Template"
# Helm charts: YAML, template and notes files in a `templates` folder.
# No YAML formatter or strict YAML language server: Go `{{ … }}` actions are
# not valid YAML until rendered by `helm template`.
# Helm charts: YAML, templates and notes in the chart's `templates` folder.
[[framework-files]]
folder = "templates"
extensions = ["yaml", "yml", "tpl", "txt"]
extensions = ["yaml", "yml", "json", "tpl", "txt", "gotmpl", "tmpl"]
root-markers = ["Chart.yaml", "Chart.yml"]
root-marker-in-parent = true
[[language-servers]]
name = "helm-ls"
command = "helm_ls"
args = ["serve"]
root-markers = ["Chart.yaml"]
require-root-marker = true
install-hint = "https://github.com/mrjosh/helm-ls/releases/tag/v0.5.4"
+7 -8
Переглянути файл
@@ -20,19 +20,18 @@ run = "pnpm dev:app"
description = "Typecheck, bundle and verify the frontend"
run = "pnpm build"
[tasks."dogfood:build"]
description = "Build a local dogfood desktop app bundle"
run = "pnpm dogfood:build"
[tasks."dogfood:install"]
description = "Build and install the local dogfood desktop app"
depends = ["dogfood:build"]
run = "pnpm dogfood:install --no-build"
[tasks."dogfood:local"]
description = "Build and locally install the dogfood desktop app"
run = "pnpm dogfood:local"
[tasks."dogfood:remote"]
description = "Build and install a local dogfood openidea-server on a configured SSH remote"
run = "pnpm dogfood:remote"
[tasks."dogfood:all"]
description = "Build and install the local dogfood desktop app and remote openidea-server in parallel"
run = "pnpm dogfood:all"
[tasks.test]
description = "Run the frontend and Rust workspace tests"
run = ["pnpm test", "cargo test --workspace"]
+3 -3
Переглянути файл
@@ -34,9 +34,9 @@
"perf:rust": "node perf/rust.ts",
"eval": "node evals/run.ts",
"release:prepare": "node scripts/release-prepare.ts",
"dogfood:build": "node scripts/dogfood.ts build",
"dogfood:install": "node scripts/dogfood.ts install",
"dogfood:remote": "node scripts/dogfood-remote.ts"
"dogfood:local": "node scripts/dogfood.ts local",
"dogfood:remote": "node scripts/dogfood-remote.ts",
"dogfood:all": "node scripts/dogfood.ts all"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged"
+36 -10
Переглянути файл
@@ -1058,16 +1058,48 @@ async function handleRunningRemoteServers(
}
}
export async function runDogfoodRemote(root: string, cliArgs: readonly string[]) {
const parsed = parseDogfoodRemoteArgs(cliArgs);
export interface DogfoodRemoteTarget {
remoteConfig: SshRemoteConfig;
remoteContext: RemoteContext;
sshArgs: string[];
version: string;
rustVersion: string;
localDataDir: string;
}
export function resolveDogfoodRemoteTarget(root: string, parsed: DogfoodRemoteArgs): DogfoodRemoteTarget {
const { version, rustVersion } = readWorkspaceMetadata(root);
const { configDir, localDataDir } = resolveAppDirs();
const envOpts = (process.env.DOGFOOD_SSH_OPTS ?? "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
const extraSshOpts = [...envOpts, ...parsed.sshOpts];
const configs = loadSshConfigs(configDir, root);
const remoteConfig = resolveSshConfig(configs, parsed.remoteName!);
const remoteContext: RemoteContext = {
name: remoteConfig.name,
endpoint: formatRemoteEndpoint(remoteConfig),
};
const sshArgs = buildSshArgs(remoteConfig, extraSshOpts);
return { remoteConfig, remoteContext, sshArgs, version, rustVersion, localDataDir };
}
export async function finishDogfoodRemoteRestart(root: string, parsed: DogfoodRemoteArgs) {
if (parsed.restart === "never" || !parsed.remoteName) return;
const { remoteContext, sshArgs, version, localDataDir } = resolveDogfoodRemoteTarget(root, parsed);
const { os, arch } = probeRemote(sshArgs, remoteContext);
const markerPath = join(localDataDir, "server", version, `${os}-${arch}`, DOGFOOD_MARKER_FILE);
if (!existsSync(markerPath)) return;
const buildId = readFileSync(markerPath, "utf8").trim();
if (!buildId) return;
await handleRunningRemoteServers(sshArgs, remoteContext, buildId, parsed.restart);
}
export async function runDogfoodRemote(root: string, cliArgs: readonly string[]) {
const parsed = parseDogfoodRemoteArgs(cliArgs);
const { version } = readWorkspaceMetadata(root);
const { localDataDir } = resolveAppDirs();
if (parsed.clean && !parsed.remoteName) {
const cleaned = cleanLocalDogfoodServers(localDataDir, version);
@@ -1083,13 +1115,7 @@ export async function runDogfoodRemote(root: string, cliArgs: readonly string[])
return;
}
const configs = loadSshConfigs(configDir, root);
const remoteConfig = resolveSshConfig(configs, parsed.remoteName!);
const remoteContext: RemoteContext = {
name: remoteConfig.name,
endpoint: formatRemoteEndpoint(remoteConfig),
};
const sshArgs = buildSshArgs(remoteConfig, extraSshOpts);
const { remoteConfig, remoteContext, sshArgs, rustVersion } = resolveDogfoodRemoteTarget(root, parsed);
const probe = probeRemote(sshArgs, remoteContext);
const { os, arch } = probe;
const platformKey = `${os}-${arch}`;
+76 -8
Переглянути файл
@@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import {
DEFAULT_DOGFOOD_APP_NAME,
deferRestartArgs,
dogfoodBuildEnv,
dogfoodCliArgs,
dogfoodPaths,
@@ -13,18 +14,85 @@ import {
generateDogfoodIcons,
installDogfood,
parseDogfoodArgs,
runParallelTasks,
} from "./dogfood.ts";
const root = fileURLToPath(new URL("..", import.meta.url));
describe("dogfood build and install", () => {
it("parses build and install arguments, including pnpm separator flags", () => {
expect(parseDogfoodArgs(["build"])).toEqual({ action: "build", skipBuild: false });
expect(parseDogfoodArgs(["install"])).toEqual({ action: "install", skipBuild: false });
expect(parseDogfoodArgs(["install", "--no-build"])).toEqual({ action: "install", skipBuild: true });
expect(parseDogfoodArgs(["install", "--", "--no-build"])).toEqual({ action: "install", skipBuild: true });
expect(() => parseDogfoodArgs([])).toThrow(/Expected 'build' or 'install'/);
expect(() => parseDogfoodArgs(["build", "--no-build"])).toThrow(/Unexpected option/);
describe("dogfood local and all", () => {
it("parses local and all arguments, including pnpm separator flags", () => {
expect(parseDogfoodArgs(["local"])).toEqual({ action: "local", buildOnly: false });
expect(parseDogfoodArgs(["local", "--build-only"])).toEqual({ action: "local", buildOnly: true });
expect(parseDogfoodArgs(["local", "--", "--build-only"])).toEqual({ action: "local", buildOnly: true });
expect(parseDogfoodArgs(["all", "--", "my-remote", "--build-only", "--restart", "--ssh-opt", "Port=2222"])).toEqual(
{
action: "all",
buildOnly: true,
remoteArgs: ["my-remote", "--restart", "--ssh-opt", "Port=2222"],
remote: {
remoteName: "my-remote",
clean: false,
installRust: false,
restart: "always",
sshOpts: ["Port=2222"],
},
},
);
expect(deferRestartArgs(["my-remote", "--restart", "--ssh-opt", "Port=2222"])).toEqual([
"my-remote",
"--ssh-opt",
"Port=2222",
"--no-restart",
]);
expect(() => parseDogfoodArgs([])).toThrow(/Expected 'local' or 'all'/);
expect(() => parseDogfoodArgs(["build"])).toThrow(/Expected 'local' or 'all'/);
expect(() => parseDogfoodArgs(["local", "my-remote"])).toThrow(/Unexpected option/);
expect(() => parseDogfoodArgs(["all"])).toThrow(/Usage: dogfood:all <remote_name>/);
expect(() => parseDogfoodArgs(["all", "my-remote", "--clean"])).toThrow(/dogfood:remote <remote_name> --clean/);
});
it("runs parallel tasks concurrently, prefixes lines, and terminates siblings on failure", async () => {
const out: string[] = [];
const err: string[] = [];
await runParallelTasks(
[
{
label: "local",
command: process.execPath,
args: ["-e", 'process.stdout.write("step 1\\nstep "); setTimeout(() => process.stdout.write("2"), 40);'],
},
{
label: "remote",
command: process.execPath,
args: ["-e", 'process.stderr.write("warn line\\n"); process.stdout.write("done\\n");'],
},
],
{ stdout: (line) => out.push(line), stderr: (line) => err.push(line) },
);
expect(out).toContain("[local] step 1\n");
expect(out).toContain("[local] step 2\n");
expect(out).toContain("[remote] done\n");
expect(err).toEqual(["[remote] warn line\n"]);
const started = Date.now();
await expect(
runParallelTasks(
[
{
label: "local",
command: process.execPath,
args: ["-e", "setTimeout(() => {}, 10_000)"],
},
{
label: "remote",
command: process.execPath,
args: ["-e", "setTimeout(() => process.exit(2), 50)"],
},
],
{ stdout: () => {}, stderr: () => {} },
),
).rejects.toThrow(/\[remote\] exited with status 2/);
expect(Date.now() - started).toBeLessThan(3_000);
});
it("keeps the vanilla app identifier so settings, MCP, Skills and agent sessions are shared, without updates", () => {
+200 -23
Переглянути файл
@@ -1,4 +1,4 @@
import { spawnSync } from "node:child_process";
import { spawn, spawnSync, type ChildProcess } from "node:child_process";
import { createHash } from "node:crypto";
import {
chmodSync,
@@ -16,16 +16,29 @@ import { createRequire } from "node:module";
import { homedir } from "node:os";
import { dirname, join, relative } from "node:path";
import { fileURLToPath } from "node:url";
import {
finishDogfoodRemoteRestart,
parseDogfoodRemoteArgs,
resolveDogfoodRemoteTarget,
type DogfoodRemoteArgs,
} from "./dogfood-remote.ts";
export const DEFAULT_DOGFOOD_APP_NAME = "openidea_dogfood";
const LSREGISTER_PATH =
"/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";
export interface DogfoodCommand {
action: "build" | "install";
skipBuild: boolean;
}
export type DogfoodCommand =
| {
action: "local";
buildOnly: boolean;
}
| {
action: "all";
buildOnly: boolean;
remoteArgs: string[];
remote: DogfoodRemoteArgs;
};
export interface DogfoodPaths {
bundlePath: string;
@@ -35,18 +48,39 @@ export interface DogfoodPaths {
export function parseDogfoodArgs(args: readonly string[]): DogfoodCommand {
const filtered = args.filter((arg) => arg !== "--");
const action = filtered[0];
if (action !== "build" && action !== "install") {
throw new Error(`Expected 'build' or 'install', got ${action ? `'${action}'` : "no command"}`);
if (action !== "local" && action !== "all") {
throw new Error(`Expected 'local' or 'all', got ${action ? `'${action}'` : "no command"}`);
}
let skipBuild = false;
for (const flag of filtered.slice(1)) {
if (action === "install" && flag === "--no-build") {
skipBuild = true;
let buildOnly = false;
const rest: string[] = [];
for (const arg of filtered.slice(1)) {
if (arg === "--build-only") {
buildOnly = true;
} else if (action === "local") {
throw new Error(`Unexpected option '${arg}' for 'local'`);
} else {
throw new Error(`Unexpected option '${flag}' for '${action}'`);
rest.push(arg);
}
}
return { action, skipBuild };
if (action === "local") {
return { action: "local", buildOnly };
}
if (rest.includes("--clean")) {
throw new Error("Unexpected option '--clean' for 'all'; use 'dogfood:remote <remote_name> --clean' instead");
}
let remote: DogfoodRemoteArgs;
try {
remote = parseDogfoodRemoteArgs(rest);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(
message.startsWith("Usage:")
? "Usage: dogfood:all <remote_name> [--build-only] [--install-rust] [--restart | --no-restart] [--ssh-opt key=value]"
: message,
{ cause: error },
);
}
return { action: "all", buildOnly, remoteArgs: rest, remote };
}
/**
@@ -218,7 +252,7 @@ export function buildDogfood(root: string, appName: string) {
const SHARED_DATA_NOTES = [
"The dogfood app shares its single instance with OpenIDEA: quit one before opening the other.",
"It writes OpenIDEA's settings and data; a setting only newer builds know can make an older OpenIDEA ignore your settings file.",
"It never updates itself: run 'pnpm dogfood:install' again to pick up new changes.",
"It never updates itself: run 'pnpm dogfood:local' again to pick up new changes.",
];
export function installDogfood(
@@ -240,7 +274,7 @@ function installBundle(
installPath: string,
) {
if (!existsSync(bundlePath)) {
throw new Error(`Dogfood build output not found at ${bundlePath}; run 'mise run dogfood:build' first`);
throw new Error(`Dogfood build output not found at ${bundlePath}; run 'mise run dogfood:local --build-only' first`);
}
if (platform === "darwin") {
@@ -297,21 +331,164 @@ function installBundle(
console.log(`Installed ${appName} to ${installPath}`);
}
function main() {
const root = realpathSync(fileURLToPath(new URL("..", import.meta.url)));
const { action, skipBuild } = parseDogfoodArgs(process.argv.slice(2));
const appName = process.env.DOGFOOD_APP_NAME?.trim() || DEFAULT_DOGFOOD_APP_NAME;
if (action === "build" || !skipBuild) {
buildDogfood(root, appName);
export interface ParallelTaskSpec {
label: string;
command: string;
args: string[];
cwd?: string;
env?: NodeJS.ProcessEnv;
}
function stopProcessTree(child: ChildProcess, signal: NodeJS.Signals) {
if (!child.pid) return;
if (process.platform === "win32") {
spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
} else {
try {
process.kill(-child.pid, signal);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
}
}
if (action === "install") {
}
function pipePrefixedLines(
stream: NodeJS.ReadableStream | null,
prefix: string,
writeLine: (line: string) => void,
): Promise<void> {
if (!stream) return Promise.resolve();
return new Promise((resolve) => {
let remainder = "";
stream.setEncoding("utf8");
stream.on("data", (chunk: string) => {
remainder += chunk;
let newline = remainder.indexOf("\n");
while (newline !== -1) {
const line = remainder.slice(0, newline).replace(/\r$/, "");
writeLine(`[${prefix}] ${line}\n`);
remainder = remainder.slice(newline + 1);
newline = remainder.indexOf("\n");
}
});
stream.on("end", () => {
if (remainder.length > 0) {
writeLine(`[${prefix}] ${remainder.replace(/\r$/, "")}\n`);
}
resolve();
});
stream.on("error", () => resolve());
});
}
export async function runParallelTasks(
specs: readonly ParallelTaskSpec[],
writers: {
stdout?: (text: string) => void;
stderr?: (text: string) => void;
} = {},
): Promise<void> {
const writeOut = writers.stdout ?? ((text: string) => process.stdout.write(text));
const writeErr = writers.stderr ?? ((text: string) => process.stderr.write(text));
const children: ChildProcess[] = [];
let firstError: Error | null = null;
let killTimer: ReturnType<typeof setTimeout> | undefined;
const stopAll = (signal: NodeJS.Signals) => {
for (const child of children) stopProcessTree(child, signal);
if (signal === "SIGTERM") {
killTimer ??= setTimeout(() => {
for (const child of children) stopProcessTree(child, "SIGKILL");
}, 5000);
killTimer.unref();
}
};
const onSigint = () => stopAll("SIGTERM");
const onSigterm = () => stopAll("SIGTERM");
process.on("SIGINT", onSigint);
process.on("SIGTERM", onSigterm);
try {
await Promise.all(
specs.map(
(spec) =>
new Promise<void>((resolve) => {
const child = spawn(spec.command, spec.args, {
cwd: spec.cwd,
env: spec.env,
stdio: ["ignore", "pipe", "pipe"],
detached: process.platform !== "win32",
});
children.push(child);
const outDone = pipePrefixedLines(child.stdout, spec.label, writeOut);
const errDone = pipePrefixedLines(child.stderr, spec.label, writeErr);
child.once("error", (err) => {
if (!firstError) {
firstError = new Error(`[${spec.label}] ${err.message}`);
stopAll("SIGTERM");
}
void Promise.all([outDone, errDone]).then(() => resolve());
});
child.once("close", (code, signal) => {
if (code !== 0 && !firstError) {
firstError = new Error(
`[${spec.label}] exited with ${code !== null ? `status ${code}` : `signal ${signal}`}`,
);
stopAll("SIGTERM");
}
void Promise.all([outDone, errDone]).then(() => resolve());
});
}),
),
);
} finally {
if (killTimer) clearTimeout(killTimer);
process.off("SIGINT", onSigint);
process.off("SIGTERM", onSigterm);
}
if (firstError) throw firstError;
}
export function deferRestartArgs(remoteArgs: readonly string[]): string[] {
return [...remoteArgs.filter((arg) => arg !== "--restart" && arg !== "--no-restart"), "--no-restart"];
}
async function runDogfoodAll(root: string, command: Extract<DogfoodCommand, { action: "all" }>) {
// Validate the SSH remote exists in settings.toml before starting the local Cargo build.
resolveDogfoodRemoteTarget(root, command.remote);
const localArgs = [join(root, "scripts", "dogfood.ts"), "local"];
if (command.buildOnly) localArgs.push("--build-only");
const remoteScriptArgs = [join(root, "scripts", "dogfood-remote.ts"), ...deferRestartArgs(command.remoteArgs)];
await runParallelTasks([
{ label: "local", command: process.execPath, args: localArgs, cwd: root, env: process.env },
{ label: "remote", command: process.execPath, args: remoteScriptArgs, cwd: root, env: process.env },
]);
await finishDogfoodRemoteRestart(root, command.remote);
}
async function main() {
const root = realpathSync(fileURLToPath(new URL("..", import.meta.url)));
const parsed = parseDogfoodArgs(process.argv.slice(2));
if (parsed.action === "all") {
await runDogfoodAll(root, parsed);
return;
}
const appName = process.env.DOGFOOD_APP_NAME?.trim() || DEFAULT_DOGFOOD_APP_NAME;
buildDogfood(root, appName);
if (!parsed.buildOnly) {
installDogfood(root, appName);
}
}
if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) {
try {
main();
await main();
} catch (error) {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
+2
Переглянути файл
@@ -348,7 +348,9 @@ lsp_change_signature trusted project_host bin
lsp_code_action_query trusted project_host bindings async
lsp_code_actions trusted project_host bindings async
lsp_code_lens trusted project_host bindings async
lsp_color_presentations trusted project_host bindings async
lsp_completion trusted project_host bindings async
lsp_document_colors trusted project_host bindings async
lsp_document_highlights trusted project_host bindings async
lsp_document_links trusted project_host bindings async
lsp_exception_class_at trusted project_host bindings async
+25
Переглянути файл
@@ -859,7 +859,11 @@ export const commands = {
lspCodeActionQuery: (request: RequestId, doc: DocId, range: Range, only: string[]) => typedError<CodeActionQuery, IdeError>(__TAURI_INVOKE("lsp_code_action_query", { request, doc, range, only })),
lspCodeActions: (doc: DocId, range: Range, only: string[]) => typedError<CodeAction[], IdeError>(__TAURI_INVOKE("lsp_code_actions", { doc, range, only })),
lspCodeLens: (doc: DocId) => typedError<CodeLens[], IdeError>(__TAURI_INVOKE("lsp_code_lens", { doc })),
/** How the server that reported `color` writes it with new components. */
lspColorPresentations: (doc: DocId, color: DocumentColor) => typedError<ColorPresentation[], IdeError>(__TAURI_INVOKE("lsp_color_presentations", { doc, color })),
lspCompletion: (request: RequestId, doc: DocId, pos: Pos, trigger: string | null) => typedError<CompletionList, IdeError>(__TAURI_INVOKE("lsp_completion", { request, doc, pos, trigger })),
/** Colors in a document from its language servers (Tailwind classes, CSS values…). */
lspDocumentColors: (doc: DocId) => typedError<DocumentColor[], IdeError>(__TAURI_INVOKE("lsp_document_colors", { doc })),
lspDocumentHighlights: (doc: DocId, pos: Pos) => typedError<Highlight[], IdeError>(__TAURI_INVOKE("lsp_document_highlights", { doc, pos })),
/** Links in a document (`href`s, Markdown links, `#include`s…) from its language servers. */
lspDocumentLinks: (doc: DocId) => typedError<DocumentLink[], IdeError>(__TAURI_INVOKE("lsp_document_links", { doc })),
@@ -4231,6 +4235,15 @@ export type ColorInfo = {
alpha: number | null,
};
/**
* One way to write a picked color (`textDocument/colorPresentation`): `edits` replace the
* color's range (with `label` unless the server gave its own edit), then any extra edits.
*/
export type ColorPresentation = {
label: string,
edits: TextEdit[],
};
export type Command = {
title: string,
command: string,
@@ -6019,6 +6032,8 @@ export type DockerConnection = {
id: string,
name: string,
endpoint: DockerEndpoint,
/** Whether the user explicitly disconnected this connection in Services. */
disconnected?: boolean,
};
export type DockerContainer = {
@@ -6183,6 +6198,16 @@ export type DocumentChanged = {
changes: DocumentTextChange[],
};
/** A color a server found in a document (`textDocument/documentColor`); components are 0–1. */
export type DocumentColor = {
range: Range,
red: number | null,
green: number | null,
blue: number | null,
alpha: number | null,
server: ServerId,
};
/** Encoding and BOM currently applied to an open document. */
export type DocumentEncoding = {
encoding: string,
+20 -2
Переглянути файл
@@ -4,8 +4,8 @@ import { completedSyntaxTree } from "@/test/syntax";
import { classHighlighter, highlightTree } from "@lezer/highlight";
import { findLanguageDescription, loadSupport } from "./languages";
async function tokens(source: string) {
const desc = findLanguageDescription("Helm Template", "templates/applications.yaml")!;
async function tokens(source: string, mode = "Helm Template") {
const desc = findLanguageDescription(mode, "")!;
const support = await loadSupport(desc);
const state = EditorState.create({ doc: source, extensions: [support!] });
const result: { text: string; style: string }[] = [];
@@ -52,3 +52,21 @@ describe("Helm Template mode", () => {
expect(out).toContainEqual(expect.objectContaining({ text: "replicas", style: "tok-propertyName" }));
});
});
describe("Go Template mode", () => {
it.each(["common.gotmpl", "message.tmpl", "docker-stack.yaml.go.tmpl"])("loads for %s", (path) => {
expect(findLanguageDescription(null, path)?.name).toBe("Go Template");
});
it("highlights actions and keeps host text plain", async () => {
const out = await tokens(
'services:\n web: {{- if .Image }}{{ printf "nginx:%s" .Image }}{{ end -}}\n{{/* note */}}',
"Go Template",
);
expect(out).toContainEqual({ text: "if", style: "tok-keyword" });
expect(out).toContainEqual({ text: ".Image", style: "tok-propertyName" });
expect(out).toContainEqual({ text: '"nginx:%s"', style: "tok-string" });
expect(out.some(({ text }) => /services|web/.test(text))).toBe(false);
expect(out).toContainEqual({ text: "{{/* note */}}", style: "tok-comment" });
});
});
+53 -44
Переглянути файл
@@ -1,16 +1,14 @@
// Helm Template editor mode: YAML outside `{{ … }}`, Go `text/template` + Sprig/Helm
// actions and `{{/* … */}}` comments inside. Each region runs on a sub-stream bounded
// at the next delimiter so `{{ … }}` never breaks YAML key/value tokenization.
// Go text/template actions over plain text or Helm YAML. The YAML parser reads up to the
// next template delimiter so the action never breaks YAML key/value tokenization.
import { LanguageSupport, StreamLanguage, StringStream, type StreamParser } from "@codemirror/language";
import { tags } from "@lezer/highlight";
type HelmState<Y> = {
type TemplateState<Y> = {
yaml: Y;
inAction: boolean;
inComment: boolean;
inRawString: boolean;
quote: '"' | "'" | null;
indentUnit: number;
};
const OPEN = /\{\{-?/;
@@ -21,56 +19,60 @@ const COMMENT_CLOSE = /\*\/\s*-?\}\}/;
const KEYWORDS = new Set(["if", "else", "end", "range", "with", "define", "template", "block", "break", "continue"]);
const ATOMS = new Set(["true", "false", "nil"]);
const FUNCTIONS = new Set([
const BUILTINS = new Set([
"and",
"call",
"eq",
"ge",
"gt",
"html",
"index",
"js",
"le",
"len",
"lt",
"ne",
"not",
"or",
"print",
"printf",
"println",
"slice",
"urlquery",
]);
const HELM_FUNCTIONS = new Set([
"b64dec",
"b64enc",
"call",
"coalesce",
"contains",
"default",
"dict",
"empty",
"eq",
"fail",
"first",
"fromJson",
"fromYaml",
"ge",
"get",
"gt",
"has",
"hasKey",
"hasPrefix",
"hasSuffix",
"html",
"include",
"indent",
"index",
"int",
"int64",
"join",
"js",
"keys",
"kindIs",
"kindOf",
"last",
"le",
"len",
"list",
"lookup",
"lower",
"lt",
"merge",
"mustMerge",
"ne",
"nindent",
"not",
"or",
"pluck",
"print",
"printf",
"println",
"quote",
"regexMatch",
"replace",
@@ -78,7 +80,6 @@ const FUNCTIONS = new Set([
"semverCompare",
"set",
"sha256sum",
"slice",
"snakecase",
"squote",
"ternary",
@@ -99,11 +100,10 @@ const FUNCTIONS = new Set([
"typeOf",
"unset",
"upper",
"urlquery",
"values",
]);
function tokenAction<Y>(stream: StringStream, state: HelmState<Y>): string | null {
function tokenAction<Y>(stream: StringStream, state: TemplateState<Y>, helm: boolean): string | null {
if (state.inRawString) {
const end = stream.string.indexOf("`", stream.pos);
if (end < 0) {
@@ -122,14 +122,14 @@ function tokenAction<Y>(stream: StringStream, state: HelmState<Y>): string | nul
if (close?.index === 0) {
stream.pos += close[0].length;
state.inAction = false;
return "helmDelimiter";
return "templateDelimiter";
}
const ch = stream.peek();
if (ch === "`") {
stream.next();
state.inRawString = true;
return tokenAction(stream, state);
return tokenAction(stream, state, helm);
}
if (ch === '"') {
stream.match(/^"(?:[^"\\]|\\.)*"?/);
@@ -158,7 +158,7 @@ function tokenAction<Y>(stream: StringStream, state: HelmState<Y>): string | nul
const word = stream.current();
if (KEYWORDS.has(word)) return "keyword";
if (ATOMS.has(word)) return "bool";
if (FUNCTIONS.has(word)) return "helmFunc";
if (BUILTINS.has(word) || (helm && HELM_FUNCTIONS.has(word))) return "templateFunc";
return "variableName";
}
@@ -166,7 +166,8 @@ function tokenAction<Y>(stream: StringStream, state: HelmState<Y>): string | nul
return null;
}
export function helmParser<Y>(yaml: StreamParser<Y>): StreamParser<HelmState<Y>> {
function templateParser<Y>(yaml?: StreamParser<Y>): StreamParser<TemplateState<Y | undefined>> {
const helm = yaml !== undefined;
const copy = (base: StreamParser<Y>, state: Y): Y =>
base.copyState
? base.copyState(state)
@@ -174,7 +175,11 @@ export function helmParser<Y>(yaml: StreamParser<Y>): StreamParser<HelmState<Y>>
Object.entries(state as object).map(([k, v]) => [k, Array.isArray(v) ? v.slice() : v]),
) as Y);
const withinYaml = (stream: StringStream, end: number, state: HelmState<Y>): string | null => {
const tokenHost = (stream: StringStream, end: number, state: TemplateState<Y | undefined>): string | null => {
if (!yaml || state.yaml === undefined) {
stream.pos = end;
return null;
}
if (state.quote) {
const q = state.quote;
while (stream.pos < end) {
@@ -220,30 +225,30 @@ export function helmParser<Y>(yaml: StreamParser<Y>): StreamParser<HelmState<Y>>
return style;
};
const block = { open: "{{/*", close: "*/}}" };
return {
name: "helm-template",
name: helm ? "helm-template" : "gotmpl",
languageData: {
...yaml.languageData,
commentTokens: { line: "#", block: { open: "{{/*", close: "*/}}" } },
...yaml?.languageData,
commentTokens: helm ? { line: "#", block } : { block },
},
tokenTable: {
...yaml.tokenTable,
...yaml?.tokenTable,
atom: tags.propertyName,
helmDelimiter: tags.special(tags.brace),
helmFunc: tags.function(tags.variableName),
templateDelimiter: tags.special(tags.brace),
templateFunc: tags.function(tags.variableName),
},
startState: (indentUnit) => ({
yaml: yaml.startState!(indentUnit),
yaml: yaml?.startState?.(indentUnit),
inAction: false,
inComment: false,
inRawString: false,
quote: null,
indentUnit,
}),
copyState: (s) => ({ ...s, yaml: copy(yaml, s.yaml) }),
copyState: (s) => ({ ...s, yaml: yaml && s.yaml !== undefined ? copy(yaml, s.yaml) : s.yaml }),
blankLine: (s, unit) => {
s.quote = null;
yaml.blankLine?.(s.yaml, unit);
if (yaml && s.yaml !== undefined) yaml.blankLine?.(s.yaml, unit);
},
token(stream, state) {
if (stream.sol()) state.quote = null;
@@ -261,7 +266,7 @@ export function helmParser<Y>(yaml: StreamParser<Y>): StreamParser<HelmState<Y>>
}
if (state.inAction) {
return tokenAction(stream, state);
return tokenAction(stream, state, helm);
}
const rest = stream.string.slice(stream.pos);
@@ -281,16 +286,20 @@ export function helmParser<Y>(yaml: StreamParser<Y>): StreamParser<HelmState<Y>>
}
stream.pos += open[0].length;
state.inAction = true;
return "helmDelimiter";
return "templateDelimiter";
}
const end = open ? stream.pos + open.index : stream.string.length;
return withinYaml(stream, end, state);
return tokenHost(stream, end, state);
},
};
}
export async function helmTemplate(): Promise<LanguageSupport> {
const { yaml } = await import("@codemirror/legacy-modes/mode/yaml");
return new LanguageSupport(StreamLanguage.define(helmParser(yaml)));
return new LanguageSupport(StreamLanguage.define(templateParser(yaml)));
}
export function goTemplate(): LanguageSupport {
return new LanguageSupport(StreamLanguage.define(templateParser()));
}
+7 -2
Переглянути файл
@@ -248,10 +248,15 @@ const OWN_MODES = [
extensions: ["djhtml"],
load: () => import("./django").then((m) => m.django()),
}),
LanguageDescription.of({
name: "Go Template",
alias: ["gotmpl", "tmpl"],
extensions: ["gotmpl", "tmpl"],
load: () => import("./helm").then((m) => m.goTemplate()),
}),
LanguageDescription.of({
name: "Helm Template",
alias: ["helm-template", "gotmpl"],
extensions: ["gotmpl"],
alias: ["helm-template"],
load: () => import("./helm").then((m) => m.helmTemplate()),
}),
LanguageDescription.of({
+7 -6
Переглянути файл
@@ -2,7 +2,7 @@
* Color preview gutter: a swatch on each line with a color literal (the first one), as IDEA's
* color gutter icons. Picking a color replaces the literal in its own format.
*/
import { StateEffect, StateField, type Extension } from "@codemirror/state";
import { StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";
import { Decoration, EditorView, GutterMarker, WidgetType, gutter } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands";
import { syntaxTree } from "@codemirror/language";
@@ -63,12 +63,13 @@ class Swatch extends GutterMarker {
}
}
function lineColor(view: EditorView, pos: number, language: string): ColorMatch | null {
const line = view.state.doc.lineAt(pos);
/** The literal the built-in preview shows on the line at `pos`. */
export function lineColor(state: EditorState, pos: number, language: string): ColorMatch | null {
const line = state.doc.lineAt(pos);
if (line.length > MAX_LINE) return null;
const matches = findColors(line.text, language, isColorName);
if (!isMarkupLanguage(language)) return matches[0] ?? null;
const tree = syntaxTree(view.state);
const tree = syntaxTree(state);
return (
matches.find((color) => {
let node: ReturnType<typeof tree.resolveInner> | null = tree.resolveInner(line.from + color.from + 1);
@@ -168,7 +169,7 @@ export function colorPreviewGutter(ctx: EditorDocContext): Extension {
gutter({
class: `${styles.gutter} cm-openidea-gutter-colors`,
lineMarker: (view, block) => {
const color = lineColor(view, block.from, ctx.language);
const color = lineColor(view.state, block.from, ctx.language);
return color ? new Swatch(color, !view.state.readOnly) : null;
},
lineMarkerChange: (update) => update.docChanged || update.startState.readOnly !== update.state.readOnly,
@@ -178,7 +179,7 @@ export function colorPreviewGutter(ctx: EditorDocContext): Extension {
const swatch = e.target instanceof Element ? e.target.closest(`.${styles.swatch}`) : null;
if (e.button !== 0 || !swatch || view.state.readOnly) return false;
const line = view.state.doc.lineAt(block.from);
const color = lineColor(view, block.from, ctx.language);
const color = lineColor(view.state, block.from, ctx.language);
if (!color) return false;
e.preventDefault();
const rect = swatch.getBoundingClientRect();
+2
Переглянути файл
@@ -1,6 +1,7 @@
/** Color swatches in the editor gutter for color literals (Settings › Editor › General › Gutter Icons). */
import { registerEditorContribution } from "@/editor/api";
import { pluginColorPreview } from "./pluginColors";
import { lspColorPreview } from "./lspColors";
import { colorPreviewGutter } from "./gutter";
import { closeColorPickerFor, disposeColorPicker } from "./ColorPicker";
import { ViewPlugin } from "@codemirror/view";
@@ -12,6 +13,7 @@ export function activate(): () => void {
extensions: (ctx) => [
colorPreviewGutter(ctx),
pluginColorPreview(ctx),
lspColorPreview(ctx),
ViewPlugin.define((view) => ({ destroy: () => closeColorPickerFor(view) })),
],
});
+164
Переглянути файл
@@ -0,0 +1,164 @@
import { afterEach, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { act, fireEvent, screen } from "@testing-library/react";
import type { DocumentColor } from "@/platform/ipc";
const ipc = vi.hoisted(() => ({
lspDocumentColors: vi.fn(),
lspColorPresentations: vi.fn(),
}));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
commands: ipc,
}));
const menu = vi.hoisted(() => vi.fn());
vi.mock("@/ui", async (original) => ({ ...(await original<typeof import("@/ui")>()), showContextMenu: menu }));
const { lspColorPreview, serverOnlyColors } = await import("./lspColors");
const { disposeColorPicker } = await import("./ColorPicker");
const { useProject } = await import("@/platform/project");
const views: EditorView[] = [];
afterEach(() => {
views.splice(0).forEach((v) => v.destroy());
disposeColorPicker();
useProject.setState({ settings: null });
vi.useRealTimers();
vi.clearAllMocks();
});
const color = (line: number, start: number, end: number, rgb: [number, number, number]): DocumentColor => ({
range: { start: { line, col: start }, end: { line, col: end } },
red: rgb[0],
green: rgb[1],
blue: rgb[2],
alpha: 1,
server: 7,
});
const CSS = "a { color: #ff0000; }\n.b { @apply bg-red-500; }";
const literal = color(0, 11, 18, [1, 0, 0]);
const tailwind = color(1, 12, 22, [0.937, 0.267, 0.267]);
function open(doc: string, language: string) {
const view = new EditorView({
state: EditorState.create({
doc,
extensions: lspColorPreview({ doc: 1, path: "/p/a.css", language, uiMode: null, readOnly: false }),
}),
parent: document.body,
});
views.push(view);
return view;
}
const swatches = (view: EditorView) => [
...view.dom.querySelectorAll<HTMLButtonElement>(".cm-lsp-color-preview button"),
];
it("drops server colors the built-in literal preview already shows at the same range", () => {
const state = EditorState.create({ doc: CSS });
expect(serverOnlyColors(state, "css", [literal, tailwind])).toEqual([tailwind]);
// Outside style sheets a bare hex value is no literal, so the server's swatch stays.
expect(serverOnlyColors(state, "javascript", [literal, tailwind])).toEqual([literal, tailwind]);
// A literal inside a larger server range (`text-[#f00]`) is not the same color.
const wider = color(0, 10, 18, [1, 0, 0]);
expect(serverOnlyColors(state, "css", [wider])).toEqual([wider]);
// Two servers reporting one range show one swatch.
expect(serverOnlyColors(state, "css", [tailwind, { ...tailwind, server: 8 }])).toEqual([tailwind]);
});
it("keeps the server's swatch for the second literal on a line", () => {
const state = EditorState.create({ doc: "a { color: #ff0000; background: #00ff00; }" });
const second = color(0, 32, 39, [0, 1, 0]);
expect(serverOnlyColors(state, "css", [literal, second])).toEqual([second]);
});
it("keeps valid swatches when a server reports a range outside the document", async () => {
vi.useFakeTimers();
ipc.lspDocumentColors.mockResolvedValue({ status: "ok", data: [color(2, 0, 6, [0, 1, 0]), tailwind] });
const view = open(CSS, "css");
await vi.advanceTimersByTimeAsync(300);
expect(swatches(view).map((swatch) => swatch.title)).toEqual(["rgba(239, 68, 68, 1)"]);
});
it("shows a swatch per server color and writes the server's presentation on commit", async () => {
vi.useFakeTimers();
ipc.lspDocumentColors.mockResolvedValue({ status: "ok", data: [literal, tailwind] });
ipc.lspColorPresentations.mockResolvedValue({
status: "ok",
data: [{ label: "bg-[#00ff00]", edits: [{ range: tailwind.range, new_text: "bg-[#00ff00]" }] }],
});
const view = open(CSS, "css");
await vi.advanceTimersByTimeAsync(300);
expect(ipc.lspDocumentColors).toHaveBeenCalledWith(1);
const [swatch, ...rest] = swatches(view);
expect(rest).toHaveLength(0);
expect(swatch!.title).toBe("rgba(239, 68, 68, 1)");
await act(async () => swatch!.click());
const hex = document.querySelector<HTMLInputElement>('input[aria-label="Hexadecimal"]')!;
await act(async () => fireEvent.change(hex, { target: { value: "00FF00" } }));
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Apply" })));
await vi.advanceTimersByTimeAsync(0);
expect(ipc.lspColorPresentations).toHaveBeenCalledWith(
1,
expect.objectContaining({ range: tailwind.range, red: 0, green: 1, blue: 0, alpha: 1, server: 7 }),
);
expect(view.state.doc.line(2).text).toBe(".b { @apply bg-[#00ff00]; }");
});
it("offers a choice when the server presents a color several ways", async () => {
vi.useFakeTimers();
ipc.lspDocumentColors.mockResolvedValue({ status: "ok", data: [tailwind] });
ipc.lspColorPresentations.mockResolvedValue({
status: "ok",
data: ["#00ff00", "rgb(0, 255, 0)"].map((label) => ({
label,
edits: [{ range: tailwind.range, new_text: label }],
})),
});
const view = open(CSS, "css");
await vi.advanceTimersByTimeAsync(300);
await act(async () => swatches(view)[0]!.click());
const hex = document.querySelector<HTMLInputElement>('input[aria-label="Hexadecimal"]')!;
await act(async () => fireEvent.change(hex, { target: { value: "00FF00" } }));
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Apply" })));
await vi.advanceTimersByTimeAsync(0);
expect(view.state.doc.toString()).toBe(CSS);
const items = menu.mock.calls[0]![1] as { label: string; run: () => void }[];
expect(items.map((i) => i.label)).toEqual(["#00ff00", "rgb(0, 255, 0)"]);
items[1]!.run();
expect(view.state.doc.line(2).text).toBe(".b { @apply rgb(0, 255, 0); }");
});
it("says so when the server can't write the picked color", async () => {
vi.useFakeTimers();
ipc.lspDocumentColors.mockResolvedValue({ status: "ok", data: [tailwind] });
ipc.lspColorPresentations.mockResolvedValue({ status: "ok", data: [] });
const view = open(CSS, "css");
await vi.advanceTimersByTimeAsync(300);
await act(async () => swatches(view)[0]!.click());
const hex = document.querySelector<HTMLInputElement>('input[aria-label="Hexadecimal"]')!;
await act(async () => fireEvent.change(hex, { target: { value: "00FF00" } }));
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Apply" })));
await vi.advanceTimersByTimeAsync(0);
expect(view.state.doc.toString()).toBe(CSS);
expect(view.dom.querySelector(".cm-lsp-hint")?.textContent).toBe("This color can't be changed with the picker");
});
it("asks nothing while color gutter icons are off and drops stale answers", async () => {
vi.useFakeTimers();
useProject.setState({ settings: { editor: { gutterIconsDisabled: ["colors"] } } as never });
ipc.lspDocumentColors.mockResolvedValue({ status: "ok", data: [tailwind] });
const view = open(CSS, "css");
await vi.advanceTimersByTimeAsync(300);
expect(ipc.lspDocumentColors).not.toHaveBeenCalled();
useProject.setState({ settings: null });
let answer!: (v: unknown) => void;
ipc.lspDocumentColors.mockReturnValueOnce(new Promise((resolve) => (answer = resolve)));
await vi.advanceTimersByTimeAsync(300);
expect(ipc.lspDocumentColors).toHaveBeenCalledTimes(1);
view.dispatch({ changes: { from: 0, insert: " " } });
answer({ status: "ok", data: [tailwind] });
await vi.advanceTimersByTimeAsync(0);
expect(swatches(view)).toHaveLength(0);
await vi.advanceTimersByTimeAsync(300);
expect(swatches(view)).toHaveLength(1);
});
+135
Переглянути файл
@@ -0,0 +1,135 @@
/**
* Colors the language servers report (`textDocument/documentColor`: Tailwind classes, CSS values…).
* A color the built-in literal preview already shows at the same range gets no second swatch, and
* picking a color writes it the way the server presents it (`textDocument/colorPresentation`).
*/
import { RangeSet, StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";
import { ViewPlugin, gutter, type ViewUpdate } from "@codemirror/view";
import {
offsetsToRange,
rangeToOffsets,
shownAgain,
textEditsToChanges,
whenSynced,
type EditorDocContext,
} from "@/editor/api";
import { onServerSettled } from "@/editor/lsp/availability";
import { comparePos } from "@/editor/lsp/positions";
import { editorPrefs } from "@/platform/editorSettings";
import { call, commands, type DocumentColor } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { lineColor } from "./gutter";
import { ProviderSwatch } from "./providerSwatch";
import styles from "./ColorPreview.module.css";
const setColors = StateEffect.define<DocumentColor[]>();
const colors = StateField.define<DocumentColor[]>({
create: () => [],
update(v, tr) {
for (const e of tr.effects) if (e.is(setColors)) return e.value;
return tr.docChanged ? [] : v;
},
});
/** Settings › Editor › General › Gutter Icons › Color preview. */
function colorsShown(settings?: unknown): boolean {
const prefs = editorPrefs(settings);
return prefs.showGutterIcons && !prefs.gutterIconsDisabled.includes("colors");
}
/**
* The server colors without a built-in swatch for the same text, one per range when several
* servers (CSS and Tailwind) report it.
*/
export function serverOnlyColors(state: EditorState, language: string, list: DocumentColor[]): DocumentColor[] {
const scanned = new Set<number>();
const taken = new Set<string>();
return list.filter((color) => {
const { from, to } = rangeToOffsets(state.doc, color.range);
const { start, end } = offsetsToRange(state.doc, from, to);
if (from === to || comparePos(start, color.range.start) || comparePos(end, color.range.end)) return false;
const line = state.doc.lineAt(from);
if (!scanned.has(line.number)) {
scanned.add(line.number);
const literal = lineColor(state, line.from, language);
if (literal) taken.add(`${line.from + literal.from}:${line.from + literal.to}`);
}
const key = `${from}:${to}`;
if (taken.has(key)) return false;
taken.add(key);
return true;
});
}
export function lspColorPreview(ctx: EditorDocContext): Extension {
if (ctx.doc < 0) return [];
return [
colors,
gutter({
class: `${styles.gutter} cm-openidea-gutter-colors cm-lsp-color-preview`,
markers: (view) =>
RangeSet.of(
view.state.field(colors).map((c) =>
new ProviderSwatch(`lsp:${c.server}`, c, view, async (chosen) => {
const list = await call(commands.lspColorPresentations(ctx.doc, chosen));
return list.map((p) => ({ label: p.label, changes: textEditsToChanges(view.state.doc, p.edits) }));
}).range(view.state.doc.line(c.range.start.line + 1).from),
),
true,
),
}),
ViewPlugin.define(
(view) =>
new (class {
timer: ReturnType<typeof setTimeout> | undefined;
generation = 0;
skipped = false;
shown = colorsShown();
off: () => void;
constructor() {
const offs = [
onServerSettled(() => this.schedule()),
useProject.subscribe((s, prev) => {
if (s.settings !== prev.settings && colorsShown(s.settings) !== this.shown) this.schedule();
}),
];
this.off = () => offs.forEach((f) => f());
this.schedule();
}
schedule() {
this.generation++;
clearTimeout(this.timer);
this.timer = setTimeout(() => void this.run(), 300);
}
update(u: ViewUpdate) {
if (u.docChanged || (this.skipped && shownAgain(u))) this.schedule();
}
clear() {
if (view.dom.isConnected && view.state.field(colors).length) view.dispatch({ effects: setColors.of([]) });
}
async run() {
const gen = this.generation;
const text = view.state.doc;
this.shown = colorsShown();
if (!this.shown) return this.clear();
try {
await whenSynced(view);
const list = await call(commands.lspDocumentColors(ctx.doc));
if (gen !== this.generation || view.state.doc !== text) return;
this.skipped = !view.dom.isConnected;
if (!this.skipped)
view.dispatch({ effects: setColors.of(serverOnlyColors(view.state, ctx.language, list)) });
} catch {
// No server colors this document, or it went away.
if (gen === this.generation) this.clear();
}
}
destroy() {
this.generation++;
clearTimeout(this.timer);
this.off();
}
})(),
),
];
}
+8 -83
Переглянути файл
@@ -1,12 +1,10 @@
/** Plugin colors use the shared picker and provider-supplied replacement strings. */
import { RangeSet, StateEffect, StateField, type Extension } from "@codemirror/state";
import { GutterMarker, ViewPlugin, gutter, type EditorView, type ViewUpdate } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands";
import { onNavigationProvidersChanged, rangeToOffsets, shownAgain, type EditorDocContext } from "@/editor/api";
import { ViewPlugin, gutter, type ViewUpdate } from "@codemirror/view";
import { onNavigationProvidersChanged, shownAgain, type EditorDocContext } from "@/editor/api";
import { pluginVisuals } from "@/editor/lsp/pluginVisuals";
import { call, commands, type ColorInfo } from "@/platform/ipc";
import { showContextMenu } from "@/ui";
import { openColorPicker } from "./ColorPicker";
import { ProviderSwatch, replaceRange } from "./providerSwatch";
import styles from "./ColorPreview.module.css";
const setColors = StateEffect.define<[string, ColorInfo][]>();
const colors = StateField.define<[string, ColorInfo][]>({
@@ -16,83 +14,6 @@ const colors = StateField.define<[string, ColorInfo][]>({
return tr.docChanged ? [] : v;
},
});
class Swatch extends GutterMarker {
constructor(
readonly plugin: string,
readonly color: ColorInfo,
readonly view: EditorView,
readonly ctx: EditorDocContext,
) {
super();
}
override eq(other: GutterMarker) {
return (
other instanceof Swatch &&
this.plugin === other.plugin &&
JSON.stringify(this.color) === JSON.stringify(other.color)
);
}
override toDOM() {
const el = document.createElement("button");
el.type = "button";
el.className = styles.swatch!;
el.title = `rgba(${this.color.red}, ${this.color.green}, ${this.color.blue}, ${this.color.alpha})`;
el.setAttribute("aria-label", el.title);
const fill = document.createElement("span");
fill.style.background = `rgba(${(this.color.red ?? 0) * 255}, ${(this.color.green ?? 0) * 255}, ${(this.color.blue ?? 0) * 255}, ${this.color.alpha})`;
el.append(fill);
el.onclick = () => {
if (this.view.state.readOnly) return;
const rect = el.getBoundingClientRect();
pick(this.view, this.ctx, this.plugin, this.color, rect.left, rect.bottom);
};
return el;
}
}
function pick(view: EditorView, ctx: EditorDocContext, plugin: string, color: ColorInfo, x: number, y: number) {
const text = view.state.doc;
const { from, to } = rangeToOffsets(text, color.range);
const initial = [
Math.round((color.red ?? 0) * 255),
Math.round((color.green ?? 0) * 255),
Math.round((color.blue ?? 0) * 255),
color.alpha ?? 1,
] as const;
openColorPicker({
view,
anchor: { x, y },
value: [...initial],
onCommit: ([r, g, b, a]) => {
if (r === initial[0] && g === initial[1] && b === initial[2] && a === initial[3]) return;
const chosen = {
...color,
red: r / 255,
green: g / 255,
blue: b / 255,
alpha: a,
};
void call(commands.pluginColorPresentations(ctx.doc, plugin, chosen))
.then((list) => {
const apply = (insert: string) => {
if (view.dom.isConnected && view.state.doc === text && !view.state.readOnly)
view.dispatch({
changes: { from, to, insert },
userEvent: "input.color",
annotations: isolateHistory.of("full"),
});
};
if (!view.dom.isConnected || view.state.doc !== text) return;
if (list.length === 1) apply(list[0]!);
else if (list.length)
showContextMenu(
{ x, y },
list.map((label) => ({ label, verbatim: true, run: () => apply(label) })),
);
})
.catch(console.warn);
},
});
}
export function pluginColorPreview(ctx: EditorDocContext): Extension {
if (ctx.doc < 0) return [];
return [
@@ -103,7 +24,11 @@ export function pluginColorPreview(ctx: EditorDocContext): Extension {
RangeSet.of(
view.state
.field(colors)
.map(([p, c]) => new Swatch(p, c, view, ctx).range(view.state.doc.line(c.range.start.line + 1).from)),
.map(([p, c]) =>
new ProviderSwatch(`plugin:${p}`, c, view, async (chosen) =>
replaceRange(view, c.range, await call(commands.pluginColorPresentations(ctx.doc, p, chosen))),
).range(view.state.doc.line(c.range.start.line + 1).from),
),
true,
),
}),
+113
Переглянути файл
@@ -0,0 +1,113 @@
/** Swatches for colors a provider (a plugin or a language server) reports, and its picker flow. */
import { GutterMarker, type EditorView } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands";
import { rangeToOffsets } from "@/editor/api";
import { showHint } from "@/editor/lsp/hint";
import type { Range } from "@/platform/ipc";
import { showContextMenu } from "@/ui";
import { openColorPicker } from "./ColorPicker";
import styles from "./ColorPreview.module.css";
/** Components are 0–1. */
export interface ProviderColor {
range: Range;
red: number | null;
green: number | null;
blue: number | null;
alpha: number | null;
}
/** One way to write the picked color: a menu label and the document changes it makes. */
export interface ColorChoice {
label: string;
changes: { from: number; to: number; insert: string }[];
}
type Present<C> = (chosen: C) => Promise<ColorChoice[]>;
const byte = (v: number | null) => Math.round((v ?? 0) * 255);
export class ProviderSwatch<C extends ProviderColor> extends GutterMarker {
constructor(
/** Identifies the provider, so equal colors from different providers stay distinct. */
readonly source: string,
readonly color: C,
readonly view: EditorView,
readonly present: Present<C>,
) {
super();
}
override eq(other: GutterMarker) {
return (
other instanceof ProviderSwatch &&
this.source === other.source &&
JSON.stringify(this.color) === JSON.stringify(other.color)
);
}
override toDOM() {
const { red, green, blue, alpha } = this.color;
const el = document.createElement("button");
el.type = "button";
el.className = this.view.state.readOnly ? styles.swatch! : `${styles.swatch} ${styles.editable}`;
el.title = `rgba(${byte(red)}, ${byte(green)}, ${byte(blue)}, ${Number((alpha ?? 1).toFixed(2))})`;
el.setAttribute("aria-label", el.title);
const fill = document.createElement("span");
fill.style.background = el.title;
el.append(fill);
el.onclick = () => {
if (this.view.state.readOnly) return;
const rect = el.getBoundingClientRect();
pickProviderColor(this.view, this.color, { x: rect.left, y: rect.bottom }, this.present);
};
return el;
}
}
/**
* Opens the picker; on commit the provider's choices are applied (one), offered in a menu (several),
* or a hint says there is none.
*/
export function pickProviderColor<C extends ProviderColor>(
view: EditorView,
color: C,
at: { x: number; y: number },
present: Present<C>,
) {
const text = view.state.doc;
const initial = [byte(color.red), byte(color.green), byte(color.blue), color.alpha ?? 1] as const;
openColorPicker({
view,
anchor: at,
value: [...initial],
onCommit: ([r, g, b, a]) => {
if (r === initial[0] && g === initial[1] && b === initial[2] && a === initial[3]) return;
const current = () => view.dom.isConnected && view.state.doc === text && !view.state.readOnly;
void present({ ...color, red: r / 255, green: g / 255, blue: b / 255, alpha: a })
.then((choices) => {
const apply = ({ changes }: ColorChoice) => {
if (current() && changes.length)
view.dispatch({ changes, userEvent: "input.color", annotations: isolateHistory.of("full") });
};
if (!current()) return;
if (!choices.length)
// Tailwind presents only arbitrary values (`bg-[#f00]`), not palette classes (`bg-red-500`).
showHint(view, "This color can't be changed with the picker", {
pos: rangeToOffsets(text, color.range).from,
});
else if (choices.length === 1) apply(choices[0]!);
else
showContextMenu(
at,
choices.map((choice) => ({ label: choice.label, verbatim: true, run: () => apply(choice) })),
);
})
.catch(console.warn);
},
});
}
/** A provider's replacement strings for the color's own range. */
export function replaceRange(view: EditorView, range: Range, labels: string[]): ColorChoice[] {
const { from, to } = rangeToOffsets(view.state.doc, range);
return labels.map((label) => ({ label, changes: [{ from, to, insert: label }] }));
}
+44 -7
Переглянути файл
@@ -7,7 +7,7 @@
import { lazyComponent, lazyWhen, type MenuItem } from "@/ui";
import { activeEditor, lazyEditorExtension, registerEditorContribution } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { onIdeEvent } from "@/platform/ipc";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { registerActions, type ActionContext } from "@/platform/actions";
import { activeCellGrid } from "./cellActions";
import {
@@ -81,21 +81,58 @@ function tableTarget(arg: unknown): TableCommandTarget {
return { rows: activeCellGrid()?.selectedRows() ?? [], editor: null };
}
export function activate(): () => void {
const disposers = [
onIdeEvent("dbSourcesChanged", () => {
void loadSources();
}),
registerToolWindow({
/** The Database window, on the stripe by default only while the project has data sources. */
function registerDatabaseWindow(): () => void {
let withSources: boolean | null = null;
let dispose = () => {};
const sync = (next: boolean) => {
if (next === withSources) return;
withSources = next;
// Registering the same id again replaces the contribution in place.
dispose = registerToolWindow({
id: DB_TOOL_WINDOW,
title: "Database",
icon: "toolwindow-database",
anchor: "right",
order: 20,
...(next ? {} : { stripe: "onUse" as const }),
component: lazyComponent(() => import("./DatabaseView").then((m) => m.DatabaseView)),
headerMenu: useDatabaseHeaderMenu,
headerActions: lazyComponent(() => import("./DatabaseView").then((m) => m.DatabaseHeaderActions)),
});
};
// Until the window loads the sources, a quiet probe decides; a failed one leaves it under "…".
let probe = 0;
const check = () => {
const seq = ++probe;
sync(false);
if (!useProject.getState().project) return;
call(commands.dbSources()).then(
(sources) => seq === probe && !useDatabase.getState().loaded && sync(sources.length > 0),
() => {},
);
};
check();
const offSources = useDatabase.subscribe((s) => {
if (s.loaded) sync(s.sources.length > 0);
});
const offProject = useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) check();
});
return () => {
probe++;
offSources();
offProject();
dispose();
};
}
export function activate(): () => void {
const disposers = [
onIdeEvent("dbSourcesChanged", () => {
void loadSources();
}),
registerDatabaseWindow(),
registerServiceView({
id: RESULTS_VIEW,
title: "Database",
+56
Переглянути файл
@@ -0,0 +1,56 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { waitFor } from "@testing-library/react";
import { useContributions } from "@/workbench/contributions";
import { useProject } from "@/platform/project";
import type { DataSource } from "@/platform/ipc";
const mocks = vi.hoisted(() => ({ sources: vi.fn(async (): Promise<unknown> => []) }));
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
commands: { ...actual.commands, dbSources: () => "dbSources" },
call: (request: unknown) => (request === "dbSources" ? mocks.sources() : Promise.reject(new Error("unmocked"))),
};
});
import { activate } from "./index";
import { DB_TOOL_WINDOW, useDatabase } from "./store";
const stripe = () => useContributions.getState().toolWindows.get(DB_TOOL_WINDOW)?.stripe;
describe("Database tool window", () => {
let dispose = () => {};
afterEach(() => {
dispose();
dispose = () => {};
useProject.setState({ project: null });
useDatabase.setState({ sources: [], loaded: false });
});
it("is on the stripe by default only while there are data sources", () => {
dispose = activate();
expect(stripe()).toBe("onUse");
useDatabase.setState({ sources: [{ id: "pg" } as DataSource], loaded: true });
expect(stripe()).toBeUndefined();
useDatabase.setState({ sources: [] });
expect(stripe()).toBe("onUse");
dispose();
dispose = () => {};
expect(useContributions.getState().toolWindows.has(DB_TOOL_WINDOW)).toBe(false);
});
it("asks for the sources quietly when a project opens, before the window loads them", async () => {
dispose = activate();
mocks.sources.mockResolvedValueOnce([{ id: "pg" }]);
useProject.setState({ project: { root: "/app" } as never });
await waitFor(() => expect(stripe()).toBeUndefined());
mocks.sources.mockRejectedValueOnce(new Error("no backend"));
useProject.setState({ project: { root: "/other" } as never });
await waitFor(() => expect(mocks.sources).toHaveBeenCalledTimes(2));
expect(stripe()).toBe("onUse");
expect(useDatabase.getState().loaded).toBe(false);
});
});
+10
Переглянути файл
@@ -76,6 +76,16 @@ describe("Flutter DevTools windows", () => {
const dispose = registerDevToolsWindows();
await waitFor(() => expect(ids()).toEqual(expect.arrayContaining(DEVTOOLS_WINDOWS.map((w) => w.id))));
expect(getContext().flutterDevTools).toBe(true);
// One stripe button: the others wait under "…" until first opened.
const stripes = Object.fromEntries(
DEVTOOLS_WINDOWS.map((w) => [w.id, useContributions.getState().toolWindows.get(w.id)?.stripe]),
);
expect(stripes).toEqual({
"flutter-deep-links": "onUse",
"flutter-devtools": "onUse",
"flutter-devtools-extensions": "onUse",
"flutter-inspector": undefined,
});
useProject.setState({ project: { root: "/tool" } as never });
await waitFor(() => expect(ids()).not.toContain("flutter-inspector"));
+2
Переглянути файл
@@ -114,6 +114,8 @@ export function registerDevToolsWindows(): () => void {
icon: w.icon,
anchor: "right",
order: 40 + i,
// Only the Inspector is on the stripe until the others are first opened.
...(w.id === "flutter-inspector" ? {} : { stripe: "onUse" as const }),
component: view("FlutterDevToolsView"),
headerActions: view("FlutterDevToolsRefresh"),
...(w.app === "each" ? { headerContent: view("FlutterDevToolsTabs") } : {}),
-77
Переглянути файл
@@ -1,77 +0,0 @@
/** The npm tool window: the project's packages and their scripts; activating a script runs it. */
import { useMemo, useState, type ReactNode } from "react";
import { tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { Icon, Tree, showContextMenu, type MenuItem, type TreeRowState } from "@/ui";
import { runScriptNode, useNpmScripts, type NpmNode } from "./npmScripts";
import { scriptMenuItems } from "./npmGutter";
import { call, commands } from "@/platform/ipc";
import styles from "./Run.module.css";
function scriptMenuItemsFor(node: NpmNode): Promise<MenuItem[]> {
if (node.kind !== "script") return Promise.resolve([]);
return call(commands.fsReadText(node.path))
.catch(() => "")
.then((content) => scriptMenuItems({ name: node.name, line: 0 }, node.path, content ?? ""));
}
export function NpmScriptsView() {
const packages = useNpmScripts((s) => s.packages);
const loaded = useNpmScripts((s) => s.loaded);
const hasProject = useProject((s) => !!s.project);
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
const roots = useMemo(() => packages, [packages]);
const expanded = useMemo(
() => new Set(roots.filter((n) => n.kind === "package" && !collapsed.has(n.key)).map((n) => n.key)),
[roots, collapsed],
);
if (!loaded || !hasProject || roots.length === 0) return null;
const renderNode = (n: NpmNode, state: TreeRowState): ReactNode => {
if (n.kind === "package") {
return (
<span className={styles.scriptsRow} title={n.label}>
<Icon name="file-npm" size={16} />
<span className={state.selected ? styles.scriptsStrong : undefined}>{n.label}</span>
<span className={styles.scriptsMeta}>{n.scripts.length}</span>
</span>
);
}
return (
<span className={styles.scriptsRow} title={n.name}>
<Icon name="runnable-mark" size={14} />
<span>{n.name}</span>
</span>
);
};
return (
<Tree<NpmNode>
aria-label={tx`npm scripts`}
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => (n.kind === "package" ? n.label : n.name)}
getChildren={(n) => (n.kind === "package" ? n.scripts : undefined)}
isExpandable={(n) => n.kind === "package"}
expanded={expanded}
onExpandedChange={(_next, node, isOpen) =>
setCollapsed((prev) => {
const s = new Set(prev);
if (isOpen) s.delete(node.key);
else s.add(node.key);
return s;
})
}
onActivate={(n) => {
if (n.kind === "script") void runScriptNode(n, false);
}}
onContextMenu={(n, _sel, e) => {
if (n?.kind !== "script") return;
void scriptMenuItemsFor(n).then((items) => showContextMenu({ clientX: e.clientX, clientY: e.clientY }, items));
}}
renderNode={renderNode}
/>
);
}
-17
Переглянути файл
@@ -6,23 +6,6 @@
min-width: 0;
}
.scriptsRow {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: 0;
}
.scriptsStrong {
font-weight: 500;
}
.scriptsMeta {
flex: none;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.tabs {
min-width: 0;
border: 0;
-2
Переглянути файл
@@ -72,7 +72,6 @@ import { junitType } from "./junitType";
import { listenForApplicationDeactivation, showApplicationUpdate, updatableSessions } from "./applicationUpdate";
import { hotReload, hotReloadSession, hotRestart } from "./flutterHotReload";
import { npmGutter } from "./npmGutter";
import { startNpmScriptsWatch } from "./npmScripts";
import { launchSettingsGutter } from "./launchSettingsGutter";
import { runGutter } from "./runGutter";
import { markdownCommandGutter } from "./markdownCommands";
@@ -438,7 +437,6 @@ export function activate(): () => void {
headerContent: lazyComponent(() => import("./RunView").then((m) => m.RunTabs)),
useBadge: useRunningCount,
}),
startNpmScriptsWatch(),
registerTitleItem({ id: "run.widget", title: "Run Widget", align: "right", priority: 0, component: RunWidget }),
registerRunAnythingProvider(runConfigsRunAnything),
registerBuiltinTypes(),
-186
Переглянути файл
@@ -1,186 +0,0 @@
/**
* The npm tool window's data: the project's `package.json` files (root, workspace members and
* detected module roots) read from disk, independent of run configuration detection. Running a
* script goes through `scriptMenuItems`, which reuses a matching configuration or makes a temporary one.
*/
import { create } from "zustand";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useProjectRoots } from "@/platform/projectRoots";
import { lazyComponent } from "@/ui";
import { registerToolWindow } from "@/workbench/contributions";
import { objectEntries, scriptMenuItems, type ScriptEntry } from "./npmGutter";
/** A package (the directory of a `package.json`) or one of its scripts. */
export type NpmNode = { kind: "package"; key: string; label: string; scripts: NpmScript[] } | NpmScript;
export interface NpmScript {
kind: "script";
key: string;
/** Directory relative to the project root ("" for the root package). */
dir: string;
/** Absolute path of the `package.json`. */
path: string;
name: string;
}
interface NpmScriptsState {
loaded: boolean;
packages: NpmNode[];
}
export const useNpmScripts = create<NpmScriptsState>(() => ({ loaded: false, packages: [] }));
const safeJson = (text: string): Record<string, unknown> | null => {
try {
return JSON.parse(text) as Record<string, unknown>;
} catch {
return null;
}
};
/** Member directories (relative to the root) of the root package's `workspaces`: plain paths and one `*` level. */
async function workspaceDirs(pkg: Record<string, unknown>, root: string): Promise<string[]> {
const ws = pkg.workspaces;
const list = Array.isArray(ws)
? (ws as unknown[])
: Array.isArray((ws as { packages?: unknown[] })?.packages)
? (ws as { packages: unknown[] }).packages
: [];
const out: string[] = [];
for (const pattern of list) {
if (typeof pattern !== "string" || !pattern || pattern.includes("..")) continue;
const star = pattern.indexOf("*");
if (star < 0) {
out.push(pattern.replace(/\/+$/, ""));
continue;
}
const parent = pattern.slice(0, star).replace(/\/+$/, "");
const suffix = pattern.slice(star + 1);
const entries = await call(commands.fsReadDir(parent ? `${root}/${parent}` : root)).catch(() => []);
for (const e of entries) {
const isDir = e.kind === "dir" || e.targetKind === "dir";
if (!isDir || e.ignored || e.excluded || e.name === "node_modules") continue;
if (suffix && !e.name.endsWith(suffix)) continue;
out.push(parent ? `${parent}/${e.name}` : e.name);
}
}
return out;
}
let loadGen = 0;
/** Rescans the packages and their scripts. */
export async function loadNpmScripts(): Promise<void> {
const root = useProject.getState().project?.root ?? null;
const gen = ++loadGen;
if (!root || !isTauri()) {
useNpmScripts.setState({ loaded: true, packages: [] });
return;
}
const rootName = useProject.getState().project?.name ?? root;
const dirs = new Set([""]);
const rootText = await call(commands.fsReadText(`${root}/package.json`)).catch(() => null);
const rootPkg = rootText !== null ? safeJson(rootText) : null;
if (rootPkg) for (const dir of await workspaceDirs(rootPkg, root)) dirs.add(dir);
// Detected roots cover a front end in a subdirectory. A node module's own directory only shows
// up in `detectedFrom` ("<dir>/package.json"). Roots outside the project (absolute) are skipped.
for (const r of useProjectRoots.getState().detected) {
const abs = r.path.startsWith(`${root}/`) ? r.path.slice(root.length + 1) : r.path;
const rel = /^[A-Za-z]:[\\/]|^\//.test(abs) ? null : abs;
if (rel === null) continue;
if (r.kind !== "excluded" && rel) dirs.add(rel);
if (r.detectedFrom) {
const moduleDir = r.detectedFrom.replace(/\/[^/]+$/, "");
if (moduleDir && !/^[A-Za-z]:[\\/]|^\//.test(moduleDir)) dirs.add(moduleDir);
}
}
// Any other package.json the index knows, outside node_modules.
const indexed = await call(commands.findFilesNamed("package.json")).catch(() => []);
for (const file of indexed.slice(0, 500)) {
const path = String(file).replace(/\\/g, "/");
if (!path.startsWith(`${root}/`) || path.includes("/node_modules/")) continue;
dirs.add(path.slice(root.length + 1).replace(/\/?package\.json$/, ""));
}
const packages: NpmNode[] = [];
await Promise.all(
[...dirs].map(async (dir) => {
const path = dir ? `${root}/${dir}/package.json` : `${root}/package.json`;
const text = await call(commands.fsReadText(path)).catch(() => null);
if (text === null) return;
const scripts: NpmScript[] = objectEntries(text, "scripts").map((e: ScriptEntry) => ({
kind: "script" as const,
key: `npm:${dir ? `${dir}:` : ""}${e.name}`,
dir,
path,
name: e.name,
}));
if (scripts.length === 0) return;
scripts.sort((a, b) => a.name.localeCompare(b.name));
packages.push({ kind: "package", key: `pkg:${dir}`, label: dir === "" ? rootName : dir, scripts });
}),
);
if (gen !== loadGen) return;
packages.sort((a, b) =>
a.kind === "package" && b.kind === "package"
? a.label === rootName
? -1
: b.label === rootName
? 1
: a.label.localeCompare(b.label)
: 0,
);
useNpmScripts.setState({ loaded: true, packages });
}
/** Runs or debugs a script the way its gutter icon does. */
export async function runScriptNode(node: NpmScript, debug: boolean): Promise<void> {
const content = await call(commands.fsReadText(node.path)).catch(() => "");
const entry: ScriptEntry = { name: node.name, line: 0 };
const items = await scriptMenuItems(entry, node.path, content ?? "");
const item = items[debug ? 1 : 0];
if (item && "run" in item) item.run?.();
}
/** Keeps the scripts current and shows the npm tool window while the project has any. */
export function startNpmScriptsWatch(): () => void {
let unregister: (() => void) | null = null;
let indexing = true;
const syncToolWindow = (has: boolean) => {
if (has && !unregister)
unregister = registerToolWindow({
id: "npm-scripts",
title: "npm",
icon: "file-npm",
anchor: "right",
order: 13,
component: lazyComponent(() => import("./NpmScriptsView").then((m) => m.NpmScriptsView)),
});
else if (!has && unregister) {
unregister();
unregister = null;
}
};
const disposers = [
useNpmScripts.subscribe((s) => syncToolWindow(s.packages.length > 0)),
useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) void loadNpmScripts();
}),
useProjectRoots.subscribe((s, prev) => {
if (s.detected !== prev.detected || s.root !== prev.root) void loadNpmScripts();
}),
onIdeEvent("indexState", (e) => {
if (indexing && !e.indexing) void loadNpmScripts();
indexing = e.indexing;
}),
onIdeEvent("fsChanged", (e) => {
const changed = [...e.created, ...e.modified, ...e.removed];
if (changed.some((p) => /(^|\/)package\.json$/.test(p) && !p.includes("/node_modules/"))) void loadNpmScripts();
}),
];
void loadNpmScripts();
return () => {
disposers.forEach((d) => d());
syncToolWindow(false);
};
}
+1
Переглянути файл
@@ -218,6 +218,7 @@ export function activate(): void | (() => void) {
anchor: "left",
secondary: true,
order: 30,
stripe: "onUse",
component: lazyComponent(() => import("./bookmarks/BookmarksView").then((m) => m.BookmarksView)),
headerActions: lazyComponent(() => import("./bookmarks/BookmarksView").then((m) => m.BookmarksActions)),
useBadge: () => null,
+49 -9
Переглянути файл
@@ -51,14 +51,41 @@ beforeEach(() => {
});
describe("Docker connections", () => {
it("skips a saved disconnected connection on startup and during polling", async () => {
vi.resetModules();
const { connectionState, watch } = await import("./store");
const paused = { id: "paused", name: "Paused", endpoint: { kind: "ssh", config: "build" }, disconnected: true };
const active = { id: "active", name: "Active", endpoint: { kind: "tcp", host: "build:2376" } };
backend.settings.mockResolvedValueOnce(ok({ connections: [paused, active], registries: [] }));
backend.snapshot.mockResolvedValue(ok({ availability: { kind: "daemonDown", message: "Offline" }, errors: [] }));
vi.useFakeTimers();
const stop = watch();
try {
await vi.advanceTimersByTimeAsync(0);
expect(backend.snapshot.mock.calls).toEqual([[active.endpoint]]);
expect(connectionState(paused.id)).toMatchObject({ disconnected: true, snapshot: null });
await vi.advanceTimersByTimeAsync(10_000);
expect(backend.snapshot.mock.calls).toEqual([[active.endpoint], [active.endpoint]]);
} finally {
stop();
vi.useRealTimers();
}
});
it("stop talking to the daemon while disconnected, and connect again on Connect", async () => {
const stop = watch();
await vi.waitFor(() => expect(connectionState("box").snapshot).not.toBeNull());
expect(backend.events).toHaveBeenCalledOnce();
disconnectConnection("box");
await disconnectConnection("box");
expect(backend.cancel).toHaveBeenCalledOnce();
expect(connectionState("box")).toMatchObject({ snapshot: null, disconnected: true });
expect(backend.saveSettings).toHaveBeenLastCalledWith({
connections: [expect.objectContaining({ id: "box", disconnected: true })],
registries: [],
});
backend.snapshot.mockClear();
await refresh("box");
expect(backend.snapshot).not.toHaveBeenCalled();
@@ -66,9 +93,22 @@ describe("Docker connections", () => {
await connectConnection("box");
expect(backend.snapshot).toHaveBeenCalledOnce();
expect(connectionState("box")).toMatchObject({ disconnected: false, snapshot: ready });
expect(backend.saveSettings).toHaveBeenLastCalledWith({
connections: [expect.objectContaining({ id: "box", disconnected: false })],
registries: [],
});
stop();
});
it("preserves the saved disconnect when editing the connection concurrently", async () => {
const edited = { id: "box", name: "Edited box", endpoint: { kind: "default" } } as const;
await Promise.all([disconnectConnection("box"), saveConnection(edited)]);
expect(backend.saveSettings).toHaveBeenLastCalledWith({
connections: [{ ...edited, disconnected: true }],
registries: [],
});
});
describe("over SSH", () => {
const box = { id: "box", name: "Box", endpoint: { kind: "ssh", config: "build" } };
const twin = { id: "twin", name: "Box again", endpoint: { kind: "ssh", config: "build" } };
@@ -81,7 +121,7 @@ describe("Docker connections", () => {
let finish!: () => void;
backend.snapshot.mockReturnValueOnce(new Promise((resolve) => (finish = () => resolve(ok(ready)))));
const reading = refresh("box");
disconnectConnection("box");
await disconnectConnection("box");
await Promise.resolve();
expect(backend.disconnect).not.toHaveBeenCalled();
finish();
@@ -95,20 +135,20 @@ describe("Docker connections", () => {
let finish!: () => void;
backend.snapshot.mockReturnValueOnce(new Promise((resolve) => (finish = () => resolve(ok(ready)))));
const reading = refresh("box");
disconnectConnection("box");
const disconnecting = disconnectConnection("box");
const connecting = connectConnection("box");
finish();
await Promise.all([reading, connecting]);
await Promise.all([reading, disconnecting, connecting]);
await vi.waitFor(() => expect(connectionState("box").snapshot).toEqual(ready));
expect(backend.disconnect).not.toHaveBeenCalled();
});
it("keeps a tunnel another connected connection uses, until that one disconnects too", async () => {
connect(box, twin);
disconnectConnection("box");
await disconnectConnection("box");
await new Promise((r) => setTimeout(r, 0));
expect(backend.disconnect).not.toHaveBeenCalled();
disconnectConnection("twin");
await disconnectConnection("twin");
await vi.waitFor(() => expect(backend.disconnect).toHaveBeenCalledExactlyOnceWith(box.endpoint));
});
@@ -121,7 +161,7 @@ describe("Docker connections", () => {
it("leaves other endpoints alone: they keep nothing open", async () => {
connect(local);
disconnectConnection("local");
await disconnectConnection("local");
await removeConnection("local");
await new Promise((r) => setTimeout(r, 0));
expect(backend.disconnect).not.toHaveBeenCalled();
@@ -129,7 +169,7 @@ describe("Docker connections", () => {
it("matches the configuration as the backend does, ignoring surrounding spaces", async () => {
connect(box, { ...twin, endpoint: { kind: "ssh", config: " build " } });
disconnectConnection("box");
await disconnectConnection("box");
await new Promise((r) => setTimeout(r, 0));
expect(backend.disconnect).not.toHaveBeenCalled();
});
@@ -144,7 +184,7 @@ describe("Docker connections", () => {
connect(box);
let closed!: () => void;
backend.disconnect.mockReturnValueOnce(new Promise((resolve) => (closed = () => resolve(ok(null)))));
disconnectConnection("box");
await disconnectConnection("box");
await vi.waitFor(() => expect(backend.disconnect).toHaveBeenCalledOnce());
backend.snapshot.mockClear();
const connecting = connectConnection("box");
+1 -1
Переглянути файл
@@ -256,7 +256,7 @@ function menu(item: ServiceTreeItem): MenuItem[] {
{ kind: "separator" },
connectionState(c.id).disconnected
? { label: "Connect", run: () => void connectConnection(c.id) }
: { label: "Disconnect", run: () => disconnectConnection(c.id) },
: { label: "Disconnect", run: () => void disconnectConnection(c.id) },
{ label: "Edit Connection…", icon: "edit", run: () => openConnectionDialog(c) },
{ label: "Remove Connection", icon: "trash", danger: true, run: () => void removeConnectionPrompt(c) },
);
+1 -1
Переглянути файл
@@ -169,7 +169,7 @@ export function activate(): () => void {
when: PROJECT,
run: () => {
const id = currentConnection();
if (id && !connectionState(id).disconnected) disconnectConnection(id);
if (id && !connectionState(id).disconnected) void disconnectConnection(id);
},
},
{
+72 -35
Переглянути файл
@@ -58,7 +58,7 @@ export interface ConnectionState {
snapshot: DockerSnapshot | null;
loading: boolean;
error: string | null;
/** Disconnected for this session: no snapshots, events or polling until Connect. */
/** Explicitly disconnected: no snapshots, events or polling until Connect. */
disconnected?: boolean;
/** Containers with a start / stop / … / remove in progress, by id: the operation. */
busy?: Record<string, ContainerOp | "remove">;
@@ -128,9 +128,18 @@ export function loadSettings(): Promise<void> {
return Promise.resolve();
}
settingsLoad ??= call(commands.dockerSettings())
.then((s: DockerSettings) =>
useServices.setState({ settings: { connections: s.connections ?? [], registries: s.registries ?? [] } }),
)
.then((s: DockerSettings) => {
const connections = s.connections ?? [];
useServices.setState((state) => ({
settings: { connections, registries: s.registries ?? [] },
conns: {
...state.conns,
...Object.fromEntries(
connections.filter((c) => c.disconnected).map((c) => [c.id, { ...IDLE, disconnected: true }]),
),
},
}));
})
.catch((e) => {
settingsLoad = null;
notifications().notify({
@@ -143,32 +152,43 @@ export function loadSettings(): Promise<void> {
return settingsLoad;
}
async function saveSettings(settings: Settings): Promise<boolean> {
try {
if (isTauri()) await call(commands.dockerSaveSettings(settings));
useServices.setState({ settings });
return true;
} catch (e) {
notifications().notify({
group: "run",
level: "error",
title: "Cannot save Docker settings",
body: errorMessage(e),
});
return false;
}
let settingsWrite = Promise.resolve(true);
function saveSettings(update: (current: Settings) => Settings): Promise<boolean> {
// Each write replaces the settings file, so derive it after the previous save.
settingsWrite = settingsWrite.then(async () => {
try {
const current = useServices.getState().settings ?? { connections: [], registries: [] };
const settings = update(current);
if (settings === current) return true;
if (isTauri()) await call(commands.dockerSaveSettings(settings));
useServices.setState({ settings });
return true;
} catch (e) {
notifications().notify({
group: "run",
level: "error",
title: "Cannot save Docker settings",
body: errorMessage(e),
});
return false;
}
});
return settingsWrite;
}
export const newId = (prefix: string) => `${prefix}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
/** Adds or replaces (same id) a connection; the tree picks it up right away. */
export async function saveConnection(c: DockerConnection): Promise<boolean> {
export async function saveConnection(c: Pick<DockerConnection, "id" | "name" | "endpoint">): Promise<boolean> {
await loadSettings();
const s = useServices.getState().settings ?? { connections: [], registries: [] };
const old = s.connections.find((x) => x.id === c.id)?.endpoint;
const ok = await saveSettings({
...s,
connections: old ? s.connections.map((x) => (x.id === c.id ? c : x)) : [...s.connections, c],
let old: DockerEndpoint | undefined;
const ok = await saveSettings((s) => {
old = s.connections.find((x) => x.id === c.id)?.endpoint;
return {
...s,
connections: old ? s.connections.map((x) => (x.id === c.id ? { ...x, ...c } : x)) : [...s.connections, c],
};
});
if (ok) {
stopEvents(c.id);
@@ -183,7 +203,7 @@ export async function removeConnection(id: string): Promise<void> {
if (!s) return;
stopEvents(id);
const endpoint = endpointOf(id);
if (await saveSettings({ ...s, connections: s.connections.filter((c) => c.id !== id) })) {
if (await saveSettings((s) => ({ ...s, connections: s.connections.filter((c) => c.id !== id) }))) {
useServices.setState((st) => {
const conns = { ...st.conns };
delete conns[id];
@@ -196,11 +216,12 @@ export async function removeConnection(id: string): Promise<void> {
/** Adds or replaces a registry; `password` undefined keeps the saved one, null forgets it. */
export async function saveRegistry(r: DockerRegistry, password: string | null | undefined): Promise<boolean> {
await loadSettings();
const s = useServices.getState().settings ?? { connections: [], registries: [] };
const exists = s.registries.some((x) => x.id === r.id);
const ok = await saveSettings({
...s,
registries: exists ? s.registries.map((x) => (x.id === r.id ? r : x)) : [...s.registries, r],
const ok = await saveSettings((s) => {
const exists = s.registries.some((x) => x.id === r.id);
return {
...s,
registries: exists ? s.registries.map((x) => (x.id === r.id ? r : x)) : [...s.registries, r],
};
});
if (ok && password !== undefined && isTauri()) {
try {
@@ -219,7 +240,18 @@ export async function saveRegistry(r: DockerRegistry, password: string | null |
export async function removeRegistry(id: string): Promise<void> {
const s = useServices.getState().settings;
if (s) await saveSettings({ ...s, registries: s.registries.filter((r) => r.id !== id) });
if (s) await saveSettings((s) => ({ ...s, registries: s.registries.filter((r) => r.id !== id) }));
}
function saveConnectionDisconnected(id: string, disconnected: boolean): Promise<boolean> {
return saveSettings((s) => {
const existing = s.connections.find((c) => c.id === id);
if (!existing || (existing.disconnected ?? false) === disconnected) return s;
return {
...s,
connections: s.connections.map((c) => (c.id === id ? { ...c, disconnected } : c)),
};
});
}
/** Test login; resolves to docker's answer, rejects with its error. */
@@ -311,7 +343,9 @@ export function watch(): () => void {
if (watchers === 1) {
pollTimer = setInterval(() => {
for (const c of connections()) {
const ready = connectionState(c.id).snapshot?.availability.kind === "ready";
const state = connectionState(c.id);
if (state.disconnected) continue;
const ready = state.snapshot?.availability.kind === "ready";
if (!ready || !events.has(c.id)) void refresh(c.id);
}
}, 10_000);
@@ -327,21 +361,24 @@ export function watch(): () => void {
/**
* Disconnect: stops talking to the connection's daemon (its event stream and polling; for an
* SSH connection, its tunnel and SSH connection) until Connect. Not saved: a new session connects.
* SSH connection, its tunnel and SSH connection) until Connect, even across restarts.
*/
export function disconnectConnection(id: string): void {
export async function disconnectConnection(id: string): Promise<void> {
stopEvents(id);
clearTimeout(debounces.get(id));
again.delete(id);
patchConn(id, { snapshot: null, error: null, loading: false, disconnected: true });
closeEndpoint(id, endpointOf(id));
await saveConnectionDisconnected(id, true);
}
export async function connectConnection(id: string): Promise<void> {
patchConn(id, { disconnected: false });
const saving = saveConnectionDisconnected(id, false);
// A tunnel being closed would take this connection's next snapshot down with it.
await closing.get(id);
return refresh(id);
await refresh(id);
await saving;
}
/** The SSH configuration an endpoint tunnels through (as the backend keys its tunnels). */
+1
Переглянути файл
@@ -21,6 +21,7 @@ export function activate(): () => void {
icon: hasIcon("toolwindow-todo") ? "toolwindow-todo" : "list",
anchor: "bottom",
order: 40,
stripe: "onUse",
component: TodoView,
headerContent: TodoTabs,
headerMenu: useTodoHeaderMenu,
+1
Переглянути файл
@@ -90,6 +90,7 @@ export const intellijMacos: Record<string, string[]> = {
"code.showIntentions": ["Alt+Enter"],
"code.applyQuickFix": ["Alt+Shift+Enter"],
"code.reformat": ["Meta+Alt+L"],
"code.rearrange": [],
"code.reformatDialog": ["Meta+Alt+Shift+L"],
"code.optimizeImports": ["Ctrl+Alt+O"],
"code.commentLine": ["Meta+/"],
+1
Переглянути файл
@@ -91,6 +91,7 @@ export const intellijWindows: Record<string, string[]> = {
"code.showIntentions": ["Alt+Enter"],
"code.applyQuickFix": ["Alt+Shift+Enter"],
"code.reformat": ["Ctrl+Alt+L"],
"code.rearrange": [],
"code.reformatDialog": ["Ctrl+Alt+Shift+L"],
"code.optimizeImports": ["Ctrl+Alt+O"],
"code.commentLine": ["Ctrl+/"],
+2
Переглянути файл
@@ -128,6 +128,7 @@ export const vscodeMacos: Record<string, string[]> = {
// Code
"code.completion": ["Ctrl+Space"],
"code.smartTypeCompletion": [],
"editor.inlineCompletion.trigger": ["Alt+\\"],
"editor.inlineCompletion.accept": ["Tab"],
"editor.inlineCompletion.acceptWord": ["Meta+Right"],
@@ -141,6 +142,7 @@ export const vscodeMacos: Record<string, string[]> = {
"code.applyQuickFix": [],
"code.generate": [],
"code.reformat": ["Alt+Shift+F"],
"code.rearrange": [],
"code.reformatDialog": [],
"code.optimizeImports": ["Alt+Shift+O"],
"code.commentLine": ["Meta+/"],
+4 -2
Переглянути файл
@@ -934,6 +934,8 @@
"Shell": "Shell",
"C/C++": "C/C++",
"Go": "Go",
"Go Template": "Go Template",
"Helm Template": "Helm Template",
"Rust": "Rust",
"Python": "Python",
"JavaScript": "JavaScript",
@@ -1889,7 +1891,6 @@
"Updated to {0}. New sessions will use this version.": "Updated to {0}. New sessions will use this version.",
"Installed: {0} · No newer npm release.": "Installed: {0} · No newer npm release.",
"Installed: {0}. Use your installer to manage this release channel.": "Installed: {0}. Use your installer to manage this release channel.",
"npm scripts": "npm scripts",
"database": "database",
"npm could not complete the operation ({0}).": "npm could not complete the operation ({0}).",
"An update for this agent is already running.": "An update for this agent is already running.",
@@ -3821,5 +3822,6 @@
"Implementation": "Implementation",
"No stub or implementation found": "No stub or implementation found",
"Implementation of {name} in {file}": "Implementation of {name} in {file}",
"Stub of {name} in {file}": "Stub of {name} in {file}"
"Stub of {name} in {file}": "Stub of {name} in {file}",
"This color can't be changed with the picker": "This color can't be changed with the picker"
}
+4 -2
Переглянути файл
@@ -737,6 +737,8 @@
"Shell": "Shell",
"C/C++": "C/C++",
"Go": "Go",
"Go Template": "Go 模板",
"Helm Template": "Helm 模板",
"Rust": "Rust",
"Python": "Python",
"JavaScript": "JavaScript",
@@ -8323,7 +8325,6 @@
"Updated to {0}. New sessions will use this version.": "已更新到 {0}。新会话将使用此版本。",
"Installed: {0} · No newer npm release.": "已安装:{0} · 没有更新的 npm 版本。",
"Installed: {0}. Use your installer to manage this release channel.": "已安装:{0}。请使用原安装工具管理此发布渠道。",
"npm scripts": "npm 脚本",
"npm could not complete the operation ({0}).": "npm 无法完成操作({0})。",
"An update for this agent is already running.": "此智能体已有更新正在进行。",
"This is not a global npm install OpenIDEA can update. Use its original installer.": "这不是 OpenIDEA 能更新的 npm 全局安装。请使用原安装工具更新。",
@@ -10052,5 +10053,6 @@
"Implementation": "实现",
"No stub or implementation found": "未找到存根或实现",
"Implementation of {name} in {file}": "{file} 中 {name} 的实现",
"Stub of {name} in {file}": "{file} 中 {name} 的存根"
"Stub of {name} in {file}": "{file} 中 {name} 的存根",
"This color can't be changed with the picker": "无法用颜色选择器修改此颜色"
}
+6 -2
Переглянути файл
@@ -196,6 +196,9 @@ describe("fileIconName", () => {
["schema.graphql", "file-graphql"],
["api.proto", "file-proto"],
["main.go", "file-go"],
["page.gotmpl", "file-go"],
["message.tmpl", "file-go"],
["docker-stack.yaml.go.tmpl", "file-go"],
["main.c", "file-c"],
["util.h", "file-h"],
["util.hpp", "file-h"],
@@ -254,7 +257,7 @@ describe("fileIconName", () => {
expect(fileIconName(file)).toBe(icon);
});
it("gives every detected language file a specific icon", () => {
it("gives every built-in filename and extension association a specific icon", () => {
const dir = path.join(process.cwd(), "languages");
const list = (src: string, key: string) =>
[...(new RegExp(`^${key}\\s*=\\s*\\[([^\\]]*)\\]`, "m").exec(src)?.[1] ?? "").matchAll(/"([^"]+)"/g)].map(
@@ -264,7 +267,8 @@ describe("fileIconName", () => {
const misses: string[] = [];
for (const file of fs.readdirSync(dir).filter((f) => f.endsWith(".toml"))) {
if (file === "plaintext.toml") continue;
const src = fs.readFileSync(path.join(dir, file), "utf8");
// Framework tables describe associations that require project context.
const src = fs.readFileSync(path.join(dir, file), "utf8").split(/^\[/m, 1)[0]!;
const names = [
...list(src, "extensions").map((e) => `name.${e}`),
...list(src, "filenames").map((n) => n.replace("*", "x")),
+2 -2
Переглянути файл
@@ -1141,7 +1141,7 @@ const EXT_ICONS = table({
"file-word": "doc docx rtf odt",
"file-pdf": "pdf",
"file-rst": "rst",
"file-yaml": "yaml yml gotmpl",
"file-yaml": "yaml yml",
"file-toml": "toml",
"file-text": "txt text",
"file-log": "log",
@@ -1188,7 +1188,7 @@ const EXT_ICONS = table({
"file-csharp": "cs csx",
"file-fsharp": "fs fsi fsx",
"file-swift": "swift swiftinterface",
"file-go": "go",
"file-go": "go gotmpl tmpl",
"file-rust": "rs",
"file-ruby": "rb rake gemspec ru rbi jbuilder podspec erb rhtml",
"file-lua": "lua luau rockspec",