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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 7eed99745a test(plugins): keep the editor panel's problem levels out of the text catalog
The severity map's `hint: "weakWarning"` entry read as UI text to the
text-catalog check (`hint` is a text property), failing it on main since #3885.
A function maps the levels instead.
2026-11-17 12:33:43 +08:00
14 змінених файлів з 28 додано та 383 видалено

No files matched your search

-6
Переглянути файл
@@ -191,12 +191,6 @@ impl Host {
};
host.apply_proxy();
host.apply_added_jdks();
// Before any project starts jdtls; the deleting itself can take a while.
let unused =
ide_sdk::jdtls_workspaces::take_unused(&host.local_data_dir, ide_sdk::jdtls_workspaces::UNUSED_FOR);
if !unused.is_empty() {
std::thread::spawn(move || ide_sdk::jdtls_workspaces::remove(unused));
}
ops::agent::move_user_mcp_values(&host);
host
}
-1
Переглянути файл
@@ -286,7 +286,6 @@ impl Host {
lsp.set_prepare_hook(Box::new(move |cfg, _, cancel| {
let effective = settings.effective();
if cfg.name == "jdtls" {
ide_sdk::jdtls_workspaces::mark_used(cfg);
crate::java_runtime::prepare(
cfg,
&data_dir,
-172
Переглянути файл
@@ -1,172 +0,0 @@
//! jdtls workspaces (`<local data>/lsp/jdtls/<key>`) that no project uses any more.
//!
//! A workspace is keyed by the project folder and by the settings that need a clean import
//! (source paths, output folder, libraries, linked Gradle projects, unlinked Maven poms), so
//! each change of those, and each moved or deleted project, leaves the previous workspace
//! behind: 50–200 MB of imported model and indexes. Like a cache, one unused for a month is
//! removed at start-up; a project that comes back imports again.
use ide_language::LanguageServerConfig;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
/// Touched each time jdtls starts on a workspace.
const USED_MARKER: &str = ".openidea-last-used";
/// Workspaces being removed (renamed first, so a server never starts on a half-deleted one).
const TRASH_PREFIX: &str = ".removed-";
/// How long a workspace may go unused before start-up removes it.
pub const UNUSED_FOR: Duration = Duration::from_secs(30 * 24 * 60 * 60);
fn root(data_dir: &Path) -> PathBuf {
data_dir.join("lsp").join("jdtls")
}
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder).
pub fn mark_used(cfg: &LanguageServerConfig) {
let Some(dir) = cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)) else { return };
let dir = Path::new(dir);
if let Err(e) = std::fs::create_dir_all(dir).and_then(|()| std::fs::write(dir.join(USED_MARKER), b"")) {
tracing::debug!("jdtls: cannot mark {} as used: {e}", dir.display());
}
}
/// When a workspace was last used: the latest of our marker (written when jdtls starts) and what
/// jdtls itself touches while it runs and when it saves on exit (a server can run for weeks).
fn last_used(dir: &Path) -> Option<SystemTime> {
let metadata = dir.join(".metadata");
[
dir.join(USED_MARKER),
metadata.join(".log"),
metadata.join(".plugins").join("org.eclipse.core.resources"),
metadata,
]
.into_iter()
.filter_map(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok())
.max()
}
/// Moves the workspaces unused for longer than `max_age` aside, before any server starts, and
/// returns what [`remove`] deletes. Quick: only renames.
pub fn take_unused(data_dir: &Path, max_age: Duration) -> Vec<PathBuf> {
let root = root(data_dir);
let Ok(entries) = std::fs::read_dir(&root) else { return Vec::new() };
let now = SystemTime::now();
let mut taken = Vec::new();
for entry in entries.flatten() {
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with(TRASH_PREFIX) {
// Left by a start-up that quit before deleting it.
taken.push(path);
continue;
}
let unused = last_used(&path).and_then(|t| now.duration_since(t).ok()).is_some_and(|age| age > max_age);
if !unused {
continue;
}
let trash = root.join(format!("{TRASH_PREFIX}{name}"));
match std::fs::rename(&path, &trash) {
Ok(()) => taken.push(trash),
Err(e) => tracing::debug!("jdtls: cannot move unused workspace {}: {e}", path.display()),
}
}
taken
}
/// Deletes what [`take_unused`] moved aside; slow for large workspaces, so off the start-up path.
pub fn remove(taken: Vec<PathBuf>) {
for dir in taken {
match std::fs::remove_dir_all(&dir) {
Ok(()) => tracing::info!("jdtls: removed unused workspace {}", dir.display()),
Err(e) => tracing::warn!("jdtls: cannot remove unused workspace {}: {e}", dir.display()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn days_ago(days: u64) -> SystemTime {
SystemTime::now() - Duration::from_secs(days * 24 * 60 * 60)
}
/// Back-dates a file, or (on Unix, where a folder opens as a file) a folder.
fn age(path: &Path, days: u64) {
let file =
if path.is_dir() { std::fs::File::open(path) } else { std::fs::File::options().write(true).open(path) };
file.unwrap().set_modified(days_ago(days)).unwrap();
}
fn cfg(data: &Path) -> LanguageServerConfig {
let languages = ide_language::LanguageRegistry::load(None).unwrap();
let mut cfg = languages.get(&ide_core::LanguageId::new("java")).unwrap().language_servers.remove(0);
cfg.args = vec!["-data".into(), data.to_string_lossy().into_owned()];
cfg
}
#[test]
fn removes_workspaces_unused_for_longer_than_the_limit() {
let tmp = tempfile::tempdir().unwrap();
let root = root(tmp.path());
let (old, recent) = (root.join("old"), root.join("recent"));
mark_used(&cfg(&old));
mark_used(&cfg(&recent));
age(&old.join(USED_MARKER), 40);
age(&recent.join(USED_MARKER), 5);
std::fs::write(root.join("defaults.prefs"), "").unwrap();
let taken = take_unused(tmp.path(), UNUSED_FOR);
assert_eq!(taken.len(), 1, "{taken:?}");
assert!(!old.exists() && recent.exists() && root.join("defaults.prefs").exists());
remove(taken);
let mut left: Vec<_> = std::fs::read_dir(&root).unwrap().map(|e| e.unwrap().file_name()).collect();
left.sort();
assert_eq!(left, ["defaults.prefs", "recent"]);
}
#[test]
fn a_started_server_marks_its_workspace_again() {
let tmp = tempfile::tempdir().unwrap();
let ws = root(tmp.path()).join("p");
mark_used(&cfg(&ws));
age(&ws.join(USED_MARKER), 40);
mark_used(&cfg(&ws));
assert!(take_unused(tmp.path(), UNUSED_FOR).is_empty());
assert!(ws.exists());
}
#[cfg(unix)]
#[test]
fn a_workspace_from_before_markers_is_judged_by_its_folders_and_log() {
let tmp = tempfile::tempdir().unwrap();
let ws = root(tmp.path()).join("legacy");
std::fs::create_dir_all(ws.join(".metadata")).unwrap();
std::fs::write(ws.join(".metadata/.log"), "").unwrap();
for p in [ws.join(".metadata/.log"), ws.join(".metadata")] {
age(&p, 90);
}
assert_eq!(take_unused(tmp.path(), UNUSED_FOR).len(), 1);
// The log alone being recent keeps it.
let tmp = tempfile::tempdir().unwrap();
let ws = root(tmp.path()).join("legacy");
std::fs::create_dir_all(ws.join(".metadata")).unwrap();
std::fs::write(ws.join(".metadata/.log"), "").unwrap();
age(&ws.join(".metadata"), 90);
assert!(take_unused(tmp.path(), UNUSED_FOR).is_empty());
}
#[test]
fn leftovers_of_an_interrupted_removal_are_removed() {
let tmp = tempfile::tempdir().unwrap();
let trash = root(tmp.path()).join(format!("{TRASH_PREFIX}gone"));
std::fs::create_dir_all(trash.join(".metadata")).unwrap();
let taken = take_unused(tmp.path(), UNUSED_FOR);
assert_eq!(taken, std::slice::from_ref(&trash));
remove(taken);
assert!(!trash.exists());
}
}
-1
Переглянути файл
@@ -16,7 +16,6 @@ pub mod go;
pub mod godot;
pub mod java;
pub mod jdtls;
pub mod jdtls_workspaces;
pub mod libraries;
pub mod locate;
pub mod lombok;
+4 -1
Переглянути файл
@@ -20,7 +20,7 @@ import { countColumn, Facet, RangeSetBuilder, type EditorState, type Extension }
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { getIndentUnit, matchBrackets, syntaxTree } from "@codemirror/language";
import { LINE_INSET } from "./lineInset";
import { BRACKET_COLORS, LONG_LINE, bracketScanner, type BracketScanner } from "./rainbowBrackets";
import { BRACKET_COLORS, bracketScanner, type BracketScanner } from "./rainbowBrackets";
/** How far (px) a guide sits left of its column, so a caret in that column is right of it (IDEA's indent guide shift). */
const GUIDE_SHIFT = 2;
@@ -188,6 +188,9 @@ export function braceGuide(state: EditorState, step: number): Guide | null {
return blockGuide(state, openLine.number, col, step);
}
/** Lines at least this long get no guides, and open no bracket block for them. */
const LONG_LINE = 10_000;
/**
* Bracket colour (depth within the palette) per guide level on each of the lines `first`..`last` (index `n - first`).
* The guide at `level` belongs to the block opened by the nearest line above indented
+1 -47
Переглянути файл
@@ -6,9 +6,7 @@ import { languages } from "@codemirror/language-data";
import {
BracketScanner,
DEFAULT_RAINBOW_OPTIONS,
LONG_LINE,
bracketClass,
bracketScanner,
rainbowBrackets,
type RainbowBracketOptions,
} from "./rainbowBrackets";
@@ -159,13 +157,7 @@ describe("rainbow brackets", () => {
});
it("keeps interpolation depth across chunks, viewports and edits", async () => {
// Newlines keep every line under `LONG_LINE`; the template still crosses chunk boundaries.
const doc =
"f(`" +
("literal ([ ".repeat(20) + "\n").repeat(30) +
"${g([1])}" +
(" tail ) ".repeat(20) + "\n").repeat(40) +
"`); h()";
const doc = "f(`" + "literal ([ ".repeat(500) + "${g([1])}" + " tail ) ".repeat(700) + "`); h()";
const ext = await javascript();
const scanner = new BracketScanner();
const from = doc.indexOf("[1]");
@@ -233,44 +225,6 @@ describe("rainbow brackets", () => {
expect(new BracketScanner().openAt(js, [js.doc.length]).map((m) => m?.depth)).toEqual([1]);
});
it("jumps over minified lines, keeping the nesting across them", async () => {
// The long line starts inside a scan chunk; one of its brackets is never closed.
const pad = "y()\n".repeat(1100);
const long = `f(${"x({a:[1,2]});".repeat(Math.ceil(LONG_LINE / 13))}`;
const doc = `{\n${pad}${long}\n[z]\n}`;
const from = doc.indexOf(long);
for (const ext of [cStyle, await javascript()]) expect(marks(doc, ext, from)).toEqual(["[1", "]1", "}0"]);
// One character shorter, it is scanned like any other line.
const short = "x({a:[1,2]});".repeat(Math.floor((LONG_LINE - 1) / 13));
expect(marks(`{\n${short}\n[z]\n}`, cStyle).slice(0, 7)).toEqual(["{0", "(1", "{2", "[3", "]3", "}2", ")1"]);
const state = EditorState.create({ doc, extensions: cStyle });
expect(new BracketScanner().openAt(state, [doc.indexOf("[z]") + 1]).map((m) => m?.depth)).toEqual([1]);
});
it("drops a line's brackets once it grows past the limit and brings them back when it shrinks", () => {
// Checkpoints fall inside the line while it is short; its open `f(` must not leak past it once long.
const line = `f(${"x({a:[1,2]});".repeat(Math.floor((LONG_LINE - 100) / 13))}`;
const doc = `${"y()\n".repeat(1100)}${line}\n[z]\n`;
const view = new EditorView({
state: EditorState.create({ doc, extensions: [cStyle, rainbowBrackets()] }),
parent: document.body,
});
const depthOfZ = () => {
const state = view.state;
const at = state.doc.toString().indexOf("[z]");
return bracketScanner(view)!
.marks(state, at, state.doc.length)
.map((m) => m.depth);
};
expect(depthOfZ()).toEqual([1, 1]);
const end = doc.indexOf("\n[z]");
view.dispatch({ changes: { from: end, insert: "x".repeat(200) } });
expect(depthOfZ()).toEqual([0, 0]);
view.dispatch({ changes: { from: end, to: end + 200 } });
expect(depthOfZ()).toEqual([1, 1]);
view.destroy();
});
it("is installed by the Rainbow brackets setting", () => {
const render = (rainbowBrackets: boolean) => {
const view = new EditorView({
+2 -22
Переглянути файл
@@ -64,12 +64,6 @@ const CHUNK = 4096;
const LOOKAHEAD = 64_000;
/** Longest comment / quote token the lexical scanner needs to see past a chunk end. */
const TOKEN_SLACK = 8;
/**
* Lines at least this long (minified code) are jumped over: their brackets are neither
* coloured nor counted, and they get no indent guides. Scanning one would cost time in
* proportion to its length after every keystroke, since the viewport always holds all of it.
*/
export const LONG_LINE = 10_000;
/** Closer char code of each opener char code: `(` `[` `{`. */
const CLOSER: Record<number, number> = { 40: 41, 91: 93, 123: 125 };
@@ -353,19 +347,7 @@ export class BracketScanner {
const blockFirst = comments.block ? comments.block.open.charCodeAt(0) : -1;
const angles: AngleEvents | undefined = tree && this.angleNames ? { doc, kindOf: this.kindOf, out: [] } : undefined;
while (s.pos < end) {
const line = doc.lineAt(s.pos);
if (line.length >= LONG_LINE && s.pos < line.to) {
// Intentionally leave minified lines unmarked and exclude their brackets from nesting.
// Resume at its line break, which ends a line comment or string as on a short line.
s.pos = line.to;
continue;
}
let chunkEnd = Math.min(end, (Math.floor(s.pos / CHUNK) + 1) * CHUNK);
// A long line can start inside this chunk only on the chunk's last line: stop before it.
if (chunkEnd < doc.length) {
const last = doc.lineAt(chunkEnd);
if (last.from > s.pos && last.length >= LONG_LINE) chunkEnd = last.from;
}
const chunkEnd = Math.min(end, (Math.floor(s.pos / CHUNK) + 1) * CHUNK);
const base = s.pos;
const text = doc.sliceString(base, Math.min(doc.length, chunkEnd + TOKEN_SLACK));
const stop = chunkEnd - base;
@@ -570,9 +552,7 @@ const plugin = ViewPlugin.fromClass(
if (reconfigured) this.scanner = new BracketScanner(options);
else if (u.docChanged) {
let first = Infinity;
// From the line start: a line grown past `LONG_LINE` must not keep checkpoints inside it.
const old = u.startState.doc;
u.changes.iterChangedRanges((fromA) => (first = Math.min(first, old.lineAt(fromA).from)));
u.changes.iterChangedRanges((fromA) => (first = Math.min(first, fromA)));
this.scanner.invalidate(first);
}
if (reconfigured || u.docChanged || u.viewportChanged || syntaxTree(u.startState) !== syntaxTree(u.state))
+1 -1
Переглянути файл
@@ -67,7 +67,7 @@ export function installColorScheme(): () => void {
: null;
observer?.observe(document.documentElement, {
attributes: true,
attributeFilter: ["data-theme", "data-contrast", "data-color-theme", "data-plugin-theme", "data-red-green"],
attributeFilter: ["data-theme", "data-contrast", "data-color-theme", "data-plugin-theme"],
});
return () => {
unsubscribe();
+1 -18
Переглянути файл
@@ -2,7 +2,7 @@ import { readFileSync } from "node:fs";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { executeAction } from "@/platform/actions";
import { CLEAR_COLOR, _setSchemeSource } from "@/platform/colorScheme";
import { CLEAR_COLOR } from "@/platform/colorScheme";
import { setLocale } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { DEFAULT_SETTINGS } from "../model/schema";
@@ -260,23 +260,6 @@ describe("Go scheme attributes", () => {
describe("scheme attribute state", () => {
beforeEach(() => schemePage("editor.colorScheme.language-defaults"));
it("shows the red-green colours the editor uses and the setting behind them (#3851)", () => {
_setSchemeSource(readFileSync("src/styles/tokens.css", "utf8"));
try {
act(() => {
stage("editor.colorScheme", "global", "editor.colorScheme", "dark");
stage("appearance", "global", "appearance.redGreenVision", true);
});
expect(screen.getByRole("textbox", { name: "Foreground hex" })).toHaveValue("#597cc2");
const preview = screen.getByLabelText("Color scheme preview");
expect(preview.style.getPropertyValue("--syn-keyword")).toBe("#597cc2");
act(() => fireEvent.click(screen.getByRole("button", { name: "Appearance settings" })));
expect(useSettingsDialog.getState().pageId).toBe("appearance");
} finally {
_setSchemeSource("");
}
});
it("shows checked attributes and inherited colours from the selected scheme", () => {
act(() => {
stage("editor.colorScheme", "global", "editor.customSchemes", {
+6 -23
Переглянути файл
@@ -113,10 +113,9 @@ function previewVars(
o: Record<string, TextAttributesOverride> | undefined,
customs: CustomColorSchemes,
language?: string,
redGreen = false,
): CSSProperties {
const vars: Record<string, string> = {};
const tokens = resolvedSchemeTokens(id, customs, redGreen);
const tokens = resolvedSchemeTokens(id, customs);
for (const [k, v] of tokens)
if (
k.startsWith("--syn-") ||
@@ -1342,7 +1341,6 @@ function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landi
const [overrides, setOverrides] = useSetting<Overrides>("editor.colorOverrides", "global");
const [weight] = useSetting<number>("editor.fontWeight");
const [boldFontWeight] = useSetting<number>("editor.boldFontWeight");
const [redGreen = false] = useSetting<boolean>("appearance.redGreenVision", "global");
const [rawCustoms, setCustoms] = useSetting<CustomColorSchemes>("editor.customSchemes", "global");
const customs = useMemo(() => customSchemes(rawCustoms), [rawCustoms]);
const [report, setReport] = useState("");
@@ -1406,26 +1404,19 @@ function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landi
}, [mine]);
const attr = ATTRIBUTES.find((a) => a.id === selected);
const language = attr?.language;
const inherited = useMemo(
() => (attr ? resolvedAttribute(id, attr.id, customs, redGreen) : {}),
[id, attr, customs, redGreen],
);
const inherited = useMemo(() => (attr ? resolvedAttribute(id, attr.id, customs) : {}), [id, attr, customs]);
const vars = useMemo(() => {
const next = {
...previewVars(id, mine, customs, language, redGreen),
...previewVars(id, mine, customs, language),
...fontWeightVars(weight, boldFontWeight),
} as CSSProperties & Record<string, string>;
// Console preview sits on the console background, not the editor surface.
if (scopes[0] === "Console Colors" && next["--bg-console"]) next["--bg-editor"] = next["--bg-console"];
return next;
}, [id, mine, customs, language, weight, boldFontWeight, scopes, redGreen]);
}, [id, mine, customs, language, weight, boldFontWeight, scopes]);
const baseVars = useMemo(
() =>
({
...previewVars(id, mine, customs, undefined, redGreen),
...fontWeightVars(weight, boldFontWeight),
}) as CSSProperties,
[id, mine, customs, weight, boldFontWeight, redGreen],
() => ({ ...previewVars(id, mine, customs), ...fontWeightVars(weight, boldFontWeight) }) as CSSProperties,
[id, mine, customs, weight, boldFontWeight],
);
const update = (attrId: string, v: TextAttributesOverride | undefined) => {
const next: Overrides = { ...(overrides ?? {}) };
@@ -1582,14 +1573,6 @@ function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landi
{scheme === "theme-default" && (
<div className={styles.note}>{tx`Follows the IDE theme: currently ${schemeName}.`}</div>
)}
{redGreen && (id === "dark" || id === "light") && (
<div className={styles.note}>
<T>Adjust colors for red-green vision deficiency is on, so this scheme shows its red-green colors.</T>{" "}
<button type="button" className={styles.schemeLink} onClick={() => selectPage("appearance")}>
<T>Appearance settings</T>
</button>
</div>
)}
{landing ? (
<nav className={styles.schemeLinks} aria-label={tx("Color scheme pages")}>
{SCHEME_SUBPAGES.map((p) => (
-31
Переглянути файл
@@ -218,37 +218,6 @@ describe("color schemes", () => {
);
});
// #3851: the editor showed the red-green colours while Color Scheme showed the plain ones.
it("resolves the red-green variant of the bundled schemes only", () => {
const rg = (id: Parameters<typeof schemeTokens>[0], name: string) => schemeTokens(id, undefined, true).get(name);
// The reporter's screenshot: keyword, string, function, number, constant.
expect(
["--syn-keyword", "--syn-string", "--syn-function", "--syn-number", "--syn-constant"].map((n) => rg("dark", n)),
).toEqual(["#597cc2", "#94907f", "#d9af6c", "#66a6ff", "#828eba"]);
expect(rg("light", "--syn-keyword")).toBe("#00428c");
for (const id of ["dark-hc", "solarized-dark"] as const)
expect(rg(id, "--syn-keyword")).toBe(schemeTokens(id).get("--syn-keyword"));
// VCS colours follow the setting in every scheme.
expect(rg("dark-hc", "--gutter-added")).not.toBe(schemeTokens("dark-hc").get("--gutter-added"));
expect(schemeTokens("dark").get("--syn-keyword")).toBe("#cf8e6d");
expect(resolvedAttribute("dark", "keyword", {}, true).foreground).toBe("#597cc2");
const customs = { "custom-rg": { name: "Mine", parent: "dark" as const, attributes: {} } };
expect(resolvedAttribute("custom-rg", "keyword", customs, true).foreground).toBe("#cf8e6d");
});
it("gives an explicit bundled scheme its red-green variant", () => {
const root = document.documentElement;
root.dataset.theme = "light";
root.dataset.redGreen = "";
try {
expect(schemeCss("dark", undefined, root)).toContain("--syn-keyword: #597cc2 !important");
delete root.dataset.redGreen;
expect(schemeCss("dark", undefined, root)).toContain("--syn-keyword: #cf8e6d !important");
} finally {
delete root.dataset.redGreen;
}
});
it("applies an explicit scheme over a plugin theme of the same base", () => {
const root = document.documentElement;
root.dataset.theme = "dark";
+11 -54
Переглянути файл
@@ -441,7 +441,7 @@ function blocks(css: string): Array<{ selectors: string[]; decls: Vars }> {
if (!selector.startsWith("@")) {
const decls: Vars = new Map();
for (const m of text.slice(start, i).matchAll(/(--[\w-]+)\s*:\s*([^;]+);/g)) decls.set(m[1]!, m[2]!.trim());
out.push({ selectors: splitSelectors(selector), decls });
out.push({ selectors: selector.split(",").map((s) => s.trim()), decls });
}
start = i + 1;
}
@@ -450,39 +450,6 @@ function blocks(css: string): Array<{ selectors: string[]; decls: Vars }> {
return out;
}
/** A selector list split at its top-level commas, not those inside `:not(…)`. */
function splitSelectors(list: string): string[] {
const out: string[] = [];
let depth = 0;
let start = 0;
for (let i = 0; i < list.length; i++) {
const ch = list[i];
if (ch === "(") depth++;
else if (ch === ")") depth--;
else if (ch === "," && depth === 0) {
out.push(list.slice(start, i).trim());
start = i + 1;
}
}
out.push(list.slice(start).trim());
return out;
}
/** Whether a `[data-red-green]` rule of tokens.css applies to a window showing built-in scheme `id`. */
function redGreenApplies(id: SchemeId, selector: string): boolean {
if (!selector.includes("[data-red-green]") || typeof document === "undefined") return false;
const root = document.implementation.createHTMLDocument("").documentElement;
root.dataset.theme = themeKind(id);
root.dataset.redGreen = "";
if (id === "dark-hc") root.dataset.contrast = "high";
else if (id !== "light" && id !== "dark") root.dataset.colorTheme = id;
try {
return root.matches(selector);
} catch {
return false;
}
}
function themeSelectors(id: SchemeId): string[] {
if (id === "light") return [':root[data-theme="light"]'];
if (id === "dark-hc") return [':root[data-theme="dark-hc"]', ':root[data-theme="dark"][data-contrast="high"]'];
@@ -492,7 +459,7 @@ function themeSelectors(id: SchemeId): string[] {
let source: string = tokensCss;
let parsed: ReturnType<typeof blocks> | null = null;
const resolvedCache = new Map<string, Vars>();
const resolvedCache = new Map<SchemeId, Vars>();
/** Replaces the token source (tests: CSS `?raw` imports are empty under vitest). */
export function _setSchemeSource(css: string) {
@@ -501,22 +468,15 @@ export function _setSchemeSource(css: string) {
resolvedCache.clear();
}
/**
* All tokens of a theme with `var()` references resolved (so they survive under another theme);
* with `redGreen`, as Adjust colors for red-green vision deficiency recolours it.
*/
export function schemeTokens(id: SchemeId, css: string = source, redGreen = false): Vars {
const key = redGreen ? `${id}+red-green` : id;
const cached = css === source ? resolvedCache.get(key) : undefined;
/** All tokens of a theme with `var()` references resolved (so they survive under another theme). */
export function schemeTokens(id: SchemeId, css: string = source): Vars {
const cached = css === source ? resolvedCache.get(id) : undefined;
if (cached) return cached;
const all = css === source ? (parsed ??= blocks(css)) : blocks(css);
const own = themeSelectors(id);
const merged: Vars = new Map();
for (const b of all) if (b.selectors.includes(":root")) for (const [k, v] of b.decls) merged.set(k, v);
for (const b of all) if (b.selectors.some((s) => own.includes(s))) for (const [k, v] of b.decls) merged.set(k, v);
if (redGreen)
for (const b of all)
if (b.selectors.some((s) => redGreenApplies(id, s))) for (const [k, v] of b.decls) merged.set(k, v);
const resolve = (value: string, depth = 0): string =>
depth > 8
? value
@@ -533,7 +493,7 @@ export function schemeTokens(id: SchemeId, css: string = source, redGreen = fals
);
const out: Vars = new Map();
for (const [k, v] of merged) out.set(k, resolve(v));
if (css === source) resolvedCache.set(key, out);
if (css === source) resolvedCache.set(id, out);
return out;
}
@@ -684,12 +644,10 @@ export function listSchemes(customs: CustomColorSchemes = {}) {
return [...SCHEMES, ...Object.entries(customSchemes(customs)).map(([id, s]) => ({ id, name: s.name }))];
}
/** With `redGreen`, a built-in scheme's red-green variant; a custom scheme keeps its parent's own colours. */
export function resolvedSchemeTokens(id: string, customs: CustomColorSchemes = {}, redGreen = false): Vars {
export function resolvedSchemeTokens(id: string, customs: CustomColorSchemes = {}): Vars {
const custom = customSchemes(customs)[id];
const builtin = isBuiltinTheme(id);
const base = builtin ? id : (custom?.parent ?? "light");
const tokens = new Map(schemeTokens(base, source, redGreen && builtin));
const base = isBuiltinTheme(id) ? id : (custom?.parent ?? "light");
const tokens = new Map(schemeTokens(base));
for (const [key, value] of overrideDeclarations(custom?.attributes)) tokens.set(key, value);
return tokens;
}
@@ -729,13 +687,12 @@ export function resolvedAttribute(
id: string,
attrId: string,
customs: CustomColorSchemes = {},
redGreen = false,
): TextAttributesOverride {
const attr = ATTRIBUTES.find((a) => a.id === attrId);
if (!attr) return {};
const custom = customSchemes(customs)[id];
const own = custom?.attributes[attr.id];
const vars = resolvedSchemeTokens(id, customs, redGreen);
const vars = resolvedSchemeTokens(id, customs);
if (attr.language)
for (const [key, value] of overrideDeclarations(custom?.attributes, attr.language)) vars.set(key, value);
@@ -791,7 +748,7 @@ export function schemeCss(
const el = root === undefined ? (typeof document !== "undefined" ? document.documentElement : null) : root;
const pluginTheme = !!el?.dataset.pluginTheme && id === setting;
if (id !== themeScheme(root) || pluginTheme) {
const tokens = resolvedSchemeTokens(id, valid, !!el?.hasAttribute("data-red-green"));
const tokens = resolvedSchemeTokens(id, valid);
for (const [k, v] of tokens)
if (SCHEME_VARS.has(k) || k.startsWith("--syn-")) {
decls.push([k, v]);
+1 -3
Переглянути файл
@@ -2330,7 +2330,5 @@
"Java agent": "Java agent",
"Runs “conda create -n <name> python=<version>”: a new environment with only Python in it, in conda's envs directory; the new interpreter becomes the project interpreter.": "Runs “conda create -n <name> python=<version>”: a new environment with only Python in it, in conda's envs directory; the new interpreter becomes the project interpreter.",
"Java Agents": "Java Agents",
"File at a Git revision (read-only).": "File at a Git revision (read-only).",
"Adjust colors for red-green vision deficiency is on, so this scheme shows its red-green colors.": "Adjust colors for red-green vision deficiency is on, so this scheme shows its red-green colors.",
"Appearance settings": "Appearance settings"
"File at a Git revision (read-only).": "File at a Git revision (read-only)."
}
+1 -3
Переглянути файл
@@ -8713,7 +8713,5 @@
"Java agents of {list} were not added: they load only in local projects.": "未添加 {list} 的 Java 代理:Java 代理只加载到本地项目中。",
"Java agent": "Java 代理",
"Java Agents": "Java 代理",
"File at a Git revision (read-only).": "Git 修订版中的文件(只读)。",
"Adjust colors for red-green vision deficiency is on, so this scheme shows its red-green colors.": "已开启「针对红绿色觉缺陷调整颜色」,此方案显示的是红绿色觉变体的颜色。",
"Appearance settings": "外观设置"
"File at a Git revision (read-only).": "Git 修订版中的文件(只读)。"
}