дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
feat(plugins): icon theme choices that switch pattern groups, shown as radio buttons (#7694)
A choice option of an icon theme can list the groups it turns on (those groups are owned by the choice and leave the checkbox list), and can set the theme's default folder icons (folder, folderExpanded, folderOpen). A choice settings item takes presentation select, radio or segmented. Themes may declare up to 64 choices. Themes using none of the new keys produce the same mapping and page as before; stored per-group values of owned groups are ignored, not deleted. Part of #7688. Co-authored-by: Bruno0416 <[email protected]>
Цей коміт міститься в:
1 джерело
c9a2b6200e
коміт
3f7a072fa1
10 files changed
+751
-45
No files matched your search
@@ -5,7 +5,7 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::PathBuf;
|
||||
|
||||
const MAX_GROUPS: usize = 64;
|
||||
const MAX_CHOICES: usize = 16;
|
||||
const MAX_CHOICES: usize = 64;
|
||||
const MAX_CHOICE_OPTIONS: usize = 16;
|
||||
const MAX_NAME_LEN: usize = 255;
|
||||
pub(super) const DARK_SUFFIX: &str = "_dark";
|
||||
@@ -84,16 +84,37 @@ pub(super) struct Group {
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(super) struct ChoiceOption {
|
||||
pub(super) id: String,
|
||||
pub(super) name: String,
|
||||
/// An icon of the theme shown next to the option on the settings page.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) icon: Option<String>,
|
||||
/// Groups this option turns on. A group listed by a choice is owned by it: it is on exactly
|
||||
/// while a selected option lists it.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
groups: Vec<String>,
|
||||
/// Replaces the theme's `folder` icon while this option is selected. Only one choice of a
|
||||
/// theme may set `folder`, `folderExpanded` or `folderOpen`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
folder: Option<String>,
|
||||
/// Replaces the theme's `folderExpanded` icon while this option is selected.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
folder_expanded: Option<String>,
|
||||
/// Replaces the theme's `folderOpen` icon while this option is selected.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
folder_open: Option<String>,
|
||||
#[serde(default)]
|
||||
overrides: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl ChoiceOption {
|
||||
fn folder_icons(&self) -> impl Iterator<Item = &String> {
|
||||
[&self.folder, &self.folder_expanded, &self.folder_open].into_iter().flatten()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct Choice {
|
||||
@@ -144,10 +165,16 @@ fn check_unique<'a>(ids: impl Iterator<Item = &'a String>, what: &str) -> Result
|
||||
|
||||
impl Extensions {
|
||||
pub(super) fn mappings(&self) -> usize {
|
||||
let chosen: usize = self.choices.iter().flat_map(|c| &c.options).map(|o| o.overrides.len()).sum();
|
||||
let chosen: usize =
|
||||
self.choices.iter().flat_map(|c| &c.options).map(|o| o.overrides.len() + o.groups.len()).sum();
|
||||
self.patterns.len() + self.overrides.len() + chosen
|
||||
}
|
||||
|
||||
/// The groups some choice lists: their state follows that choice, not the group's own setting.
|
||||
pub(super) fn owned_groups(&self) -> BTreeSet<&str> {
|
||||
self.choices.iter().flat_map(|c| &c.options).flat_map(|o| &o.groups).map(String::as_str).collect()
|
||||
}
|
||||
|
||||
pub(super) fn validate(&self, check_ref: &dyn Fn(&str, &str) -> Result<(), String>) -> Result<(), String> {
|
||||
self.validate_groups()?;
|
||||
for p in &self.patterns {
|
||||
@@ -174,6 +201,9 @@ impl Extensions {
|
||||
if let Some(icon) = &option.icon {
|
||||
check_ref(icon, "choices")?;
|
||||
}
|
||||
for icon in option.folder_icons() {
|
||||
check_ref(icon, "choices")?;
|
||||
}
|
||||
check_overrides(&option.overrides, check_ref, "choices")?;
|
||||
}
|
||||
}
|
||||
@@ -184,6 +214,8 @@ impl Extensions {
|
||||
if self.groups.len() > MAX_GROUPS || self.choices.len() > MAX_CHOICES {
|
||||
return Err(format!("too many groups or choices (max {MAX_GROUPS} and {MAX_CHOICES})"));
|
||||
}
|
||||
let mut owners: BTreeMap<&str, &str> = BTreeMap::new();
|
||||
let mut folder_choice: Option<&str> = None;
|
||||
for g in &self.groups {
|
||||
check_named(&g.id, &g.name, "group")?;
|
||||
}
|
||||
@@ -196,6 +228,29 @@ impl Extensions {
|
||||
}
|
||||
for option in &choice.options {
|
||||
check_named(&option.id, &option.name, "choice option")?;
|
||||
if option.folder_icons().next().is_some()
|
||||
&& let Some(other) = folder_choice.replace(&choice.id)
|
||||
&& other != choice.id
|
||||
{
|
||||
return Err(format!(
|
||||
"choices {other:?} and {:?} both set folder icons; only one choice may set folder, folderExpanded or folderOpen",
|
||||
choice.id
|
||||
));
|
||||
}
|
||||
check_unique(option.groups.iter(), "group in a choice option")?;
|
||||
for group in &option.groups {
|
||||
if !self.groups.iter().any(|g| &g.id == group) {
|
||||
return Err(format!("choice {:?} option {:?}: unknown group {group:?}", choice.id, option.id));
|
||||
}
|
||||
if let Some(other) = owners.insert(group, &choice.id)
|
||||
&& other != choice.id
|
||||
{
|
||||
return Err(format!(
|
||||
"group {group:?} is listed by choices {other:?} and {:?}; a group belongs to one choice",
|
||||
choice.id
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
check_unique(choice.options.iter().map(|o| &o.id), "choice option")?;
|
||||
if !choice.options.iter().any(|o| o.id == choice.default) {
|
||||
|
||||
@@ -7,6 +7,14 @@ const MAX_TEXT_LEN: usize = 255;
|
||||
const MAX_HINT_LEN: usize = 512;
|
||||
const MAX_COLUMNS: u8 = 4;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(super) enum Presentation {
|
||||
Select,
|
||||
Radio,
|
||||
Segmented,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(super) enum SettingOption {
|
||||
@@ -47,6 +55,9 @@ pub(super) struct SettingItem {
|
||||
choice: Option<String>,
|
||||
#[serde(default)]
|
||||
columns: Option<u8>,
|
||||
/// How a `choice` item is drawn: a dropdown (`select`, the default), radio buttons or a segmented control.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
presentation: Option<Presentation>,
|
||||
#[serde(default)]
|
||||
default: Option<SettingDefault>,
|
||||
}
|
||||
@@ -126,6 +137,9 @@ impl SettingItem {
|
||||
{
|
||||
return Err(format!("settings: columns are 1 to {MAX_COLUMNS}, for groups only"));
|
||||
}
|
||||
if self.presentation.is_some() && self.option != SettingOption::Choice {
|
||||
return Err("settings: presentation is only for choice items".into());
|
||||
}
|
||||
match (self.option, &self.choice) {
|
||||
(SettingOption::Choice, Some(id)) if !ext.choices.iter().any(|c| &c.id == id) => {
|
||||
return Err(format!("settings: unknown choice {id:?}"));
|
||||
@@ -170,6 +184,8 @@ pub(super) fn validate(sections: &[SettingsSection], ext: &Extensions) -> Result
|
||||
}
|
||||
|
||||
pub(super) fn summary(sections: &[SettingsSection], ext: &Extensions) -> serde_json::Value {
|
||||
let owned = ext.owned_groups();
|
||||
let groups: Vec<_> = ext.groups.iter().filter(|g| !owned.contains(g.id.as_str())).collect();
|
||||
let choices: Vec<ChoiceSummary> = ext
|
||||
.choices
|
||||
.iter()
|
||||
@@ -185,7 +201,7 @@ pub(super) fn summary(sections: &[SettingsSection], ext: &Extensions) -> serde_j
|
||||
})
|
||||
.collect();
|
||||
serde_json::json!({
|
||||
"groups": ext.groups,
|
||||
"groups": groups,
|
||||
"choices": choices,
|
||||
"accent": ext.accent,
|
||||
"settings": sections,
|
||||
|
||||
@@ -828,6 +828,141 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
const FAMILIES: &str = r#","groups":[{"id":"alt-kt","name":"Kotlin alt","enabled":false},
|
||||
{"id":"alt-kt-2","name":"Kotlin alt 2"},{"id":"tests","name":"Tests"}],
|
||||
"choices":[{"id":"family-kt","name":"Kotlin","default":"base","options":[
|
||||
{"id":"base","name":"Base","icon":"rust"},
|
||||
{"id":"alt","name":"Alt","groups":["alt-kt"]},
|
||||
{"id":"alt-2","name":"Alt 2","groups":["alt-kt-2"]},
|
||||
{"id":"alt-again","name":"Alt 3","groups":["alt-kt"]}]}]"#;
|
||||
|
||||
fn families_with(items: &str) -> Result<UiDecl, String> {
|
||||
load(&with(&format!(r#"{FAMILIES},"settings":[{{"title":"T","items":[{items}]}}]"#)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choice_options_turn_groups_on() {
|
||||
let d = families_with(r#"{"option":"groups"},{"option":"choice","choice":"family-kt","presentation":"radio"}"#)
|
||||
.unwrap();
|
||||
let map = map_of(&d);
|
||||
assert_eq!(map["choices"][0]["options"][1]["groups"], serde_json::json!(["alt-kt"]));
|
||||
assert!(map["choices"][0]["options"][0].get("groups").is_none());
|
||||
assert_eq!(map["groups"].as_array().unwrap().len(), 3, "the mapping keeps every group");
|
||||
let s = settings_of(&d).unwrap();
|
||||
assert_eq!(s["groups"], serde_json::json!([{"id":"tests","name":"Tests","enabled":true}]));
|
||||
assert_eq!(s["settings"][0]["items"][1]["presentation"], "radio");
|
||||
assert!(s["settings"][0]["items"][0].get("presentation").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choice_option_groups_are_validated() {
|
||||
let choices = |a: &str, b: &str| {
|
||||
format!(
|
||||
r#","groups":[{{"id":"a","name":"A"}},{{"id":"b","name":"B"}}],"choices":[
|
||||
{{"id":"c1","name":"C1","default":"x","options":[{{"id":"x","name":"X","groups":{a}}}]}},
|
||||
{{"id":"c2","name":"C2","default":"y","options":[{{"id":"y","name":"Y","groups":{b}}}]}}]"#
|
||||
)
|
||||
};
|
||||
let one_choice = r#","groups":[{"id":"a","name":"A"}],"choices":[{"id":"c","name":"C","default":"x","options":[
|
||||
{"id":"x","name":"X","groups":["a"]},{"id":"y","name":"Y","groups":["a"]},{"id":"z","name":"Z"}]}]"#;
|
||||
assert!(load(&with(one_choice)).is_ok(), "several options of one choice may list a group");
|
||||
assert!(load(&with(&choices(r#"["a"]"#, r#"["b"]"#))).is_ok());
|
||||
let unknown =
|
||||
r#","choices":[{"id":"c","name":"C","default":"x","options":[{"id":"x","name":"X","groups":["a"]}]}]"#;
|
||||
let cases = [
|
||||
(choices(r#"["nope"]"#, "[]"), "unknown group"),
|
||||
(choices(r#"["a"]"#, r#"["a"]"#), "one choice"),
|
||||
(choices(r#"["a","a"]"#, "[]"), "duplicate"),
|
||||
(unknown.to_string(), "unknown group"),
|
||||
];
|
||||
for (extra, needle) in cases {
|
||||
let err = load(&with(&extra)).err().unwrap_or_else(|| panic!("accepted: {extra}"));
|
||||
assert!(err.contains(needle), "{extra}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choices_are_limited_to_64() {
|
||||
let choices = |n: usize| {
|
||||
let one =
|
||||
|i: usize| format!(r#"{{"id":"c{i}","name":"C","default":"x","options":[{{"id":"x","name":"X"}}]}}"#);
|
||||
let all: Vec<String> = (0..n).map(one).collect();
|
||||
format!(r#","choices":[{}]"#, all.join(","))
|
||||
};
|
||||
assert!(load(&with(&choices(64))).is_ok());
|
||||
assert!(load(&with(&choices(65))).err().unwrap().contains("too many groups or choices"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choice_presentation_is_validated() {
|
||||
for presentation in ["select", "radio", "segmented"] {
|
||||
let item = format!(r#"{{"option":"choice","choice":"family-kt","presentation":"{presentation}"}}"#);
|
||||
assert!(families_with(&item).is_ok(), "{presentation}");
|
||||
}
|
||||
let cases = [
|
||||
(r#"{"option":"choice","choice":"family-kt","presentation":"slider"}"#, "unknown variant"),
|
||||
(r#"{"option":"choice","choice":"family-kt","presentation":"Radio"}"#, "unknown variant"),
|
||||
(r#"{"option":"groups","presentation":"radio"}"#, "only for choice"),
|
||||
(r#"{"option":"hideFiles","label":"F","presentation":"radio"}"#, "only for choice"),
|
||||
];
|
||||
for (item, needle) in cases {
|
||||
let err = families_with(item).err().unwrap_or_else(|| panic!("accepted: {item}"));
|
||||
assert!(err.contains(needle), "{item}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
const FOLDER_CHOICE: &str = r#","choices":[{"id":"default-folder","name":"Default folder","default":"plain","options":[
|
||||
{"id":"plain","name":"Plain","icon":"folder"},
|
||||
{"id":"src","name":"Src","folder":"folder-src","folderExpanded":"folder-src-open","folderOpen":"folder-src-open"},
|
||||
{"id":"only","name":"Only","folder":"folder-src"}]}]"#;
|
||||
|
||||
#[test]
|
||||
fn choice_options_set_the_default_folder_icons() {
|
||||
let map = map_of(&load(&with(FOLDER_CHOICE)).unwrap());
|
||||
let options = &map["choices"][0]["options"];
|
||||
assert_eq!(options[1]["folder"], "folder-src");
|
||||
assert_eq!(options[1]["folderExpanded"], "folder-src-open");
|
||||
assert_eq!(options[1]["folderOpen"], "folder-src-open");
|
||||
assert_eq!(options[2]["folder"], "folder-src");
|
||||
for key in ["folder", "folderExpanded", "folderOpen"] {
|
||||
assert!(options[0].get(key).is_none(), "{key} is only serialized when set");
|
||||
}
|
||||
assert!(options[2].get("folderExpanded").is_none());
|
||||
assert!(options[2].get("folderOpen").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choice_option_folder_icons_are_validated() {
|
||||
let option = |key: &str| {
|
||||
format!(
|
||||
r#","choices":[{{"id":"c","name":"C","default":"x","options":[{{"id":"x","name":"X","{key}":"nope"}}]}}]"#
|
||||
)
|
||||
};
|
||||
for key in ["folder", "folderExpanded", "folderOpen"] {
|
||||
let err = load(&with(&option(key))).err().unwrap_or_else(|| panic!("accepted {key}"));
|
||||
assert!(err.contains("unknown icon"), "{key}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_one_choice_sets_folder_icons() {
|
||||
let two = |a: &str, b: &str| {
|
||||
format!(
|
||||
r#","choices":[
|
||||
{{"id":"c1","name":"C1","default":"x","options":[{{"id":"x","name":"X"{a}}}]}},
|
||||
{{"id":"c2","name":"C2","default":"y","options":[{{"id":"y","name":"Y"{b}}}]}}]"#
|
||||
)
|
||||
};
|
||||
let folder = r#","folder":"folder-src""#;
|
||||
let expanded = r#","folderExpanded":"folder-src-open""#;
|
||||
assert!(load(&with(&two(folder, ""))).is_ok());
|
||||
assert!(load(&with(&two("", folder))).is_ok());
|
||||
for (a, b) in [(folder, folder), (folder, expanded), (expanded, folder)] {
|
||||
let err = load(&with(&two(a, b))).err().unwrap_or_else(|| panic!("accepted: {a} {b}"));
|
||||
assert!(err.contains("only one choice") && err.contains("c1") && err.contains("c2"), "{err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn themes_without_extensions_keep_their_mapping() {
|
||||
let map = map_of(&load(&with("")).unwrap());
|
||||
|
||||
@@ -74,7 +74,8 @@ Matching:
|
||||
`roleFolderNames` (below), which makes them match by name too.
|
||||
- Names are case-insensitive.
|
||||
|
||||
Limits: up to 5000 icons of at most 64 KiB each, and 20,000 mappings in all. Every SVG is
|
||||
Limits: up to 5000 icons of at most 64 KiB each, and 20,000 mappings in all (patterns, overrides
|
||||
and the `overrides` and `groups` entries of choice options). Every SVG is
|
||||
sanitised on install: allow-listed elements and attributes only; no scripts, event
|
||||
handlers, external references, `url()` or entities.
|
||||
|
||||
@@ -135,7 +136,21 @@ handlers, external references, `url()` or entities.
|
||||
theme's own package icon if `overrides` defines one for `package`.
|
||||
- **`groups`** are packs of patterns the user turns on or off; `enabled` is the default.
|
||||
- **`choices`** are variants the user picks one of; the chosen option's `overrides` win over
|
||||
the top-level `overrides`.
|
||||
the top-level `overrides`. A theme has up to 64 choices of up to 16 options each.
|
||||
- **`groups` on a choice option** lists the groups that option turns on, so a choice can switch
|
||||
the file icons of a family between variants (see the example below). A group a choice lists
|
||||
is _owned_ by it: it is on exactly while the selected option (the user's pick, else the
|
||||
choice's `default`) lists it, whatever its own `enabled` or the user's earlier pick of that
|
||||
group. Owned groups are not shown among the `groups` checkboxes. Every id must be a group of
|
||||
the theme; one group can be listed by several options of the same choice, but not by two
|
||||
different choices.
|
||||
- **`folder`, `folderExpanded` and `folderOpen` on a choice option** are `iconDefinitions` ids that
|
||||
replace the theme's own top-level `folder`, `folderExpanded` and `folderOpen` (the generic
|
||||
folder, the expanded one, and the one for folders holding open files with hollow folders)
|
||||
while that option is selected. A key an option leaves out keeps the theme's value, so the
|
||||
default option can set none. Named folders and folder patterns are not affected. Only one
|
||||
choice of a theme may set these keys; an unknown id, or a second choice that sets them, is
|
||||
refused.
|
||||
- **`icon`** (on a group, or on a choice option) is an `iconDefinitions` id of the same theme.
|
||||
The settings page shows it before the group's checkbox label, or next to the option in the
|
||||
choice's dropdown, so users can see what each pack or variant looks like. It appears even
|
||||
@@ -145,6 +160,86 @@ handlers, external references, `url()` or entities.
|
||||
- Elements with `data-themed="true"` take the accent colour of **Settings › Appearance &
|
||||
Behavior › Appearance**, or the colour theme's custom accent.
|
||||
|
||||
### One of several icon sets for a file type
|
||||
|
||||
```json
|
||||
{
|
||||
"groups": [
|
||||
{ "id": "alt-kotlin", "name": "Kotlin, alternative", "enabled": false, "icon": "kotlin-alt" },
|
||||
{ "id": "alt-kotlin-2", "name": "Kotlin, alternative 2", "enabled": false, "icon": "kotlin-alt-2" }
|
||||
],
|
||||
"patterns": [
|
||||
{ "pattern": "^.*\\.kts?$", "icon": "kotlin-alt", "group": "alt-kotlin" },
|
||||
{ "pattern": "^.*\\.kts?$", "icon": "kotlin-alt-2", "group": "alt-kotlin-2" }
|
||||
],
|
||||
"fileExtensions": { "kt": "kotlin", "kts": "kotlin" },
|
||||
"choices": [
|
||||
{
|
||||
"id": "family-kotlin",
|
||||
"name": "Kotlin",
|
||||
"default": "base",
|
||||
"options": [
|
||||
{ "id": "base", "name": "Base", "icon": "kotlin" },
|
||||
{ "id": "alt", "name": "Alternative", "icon": "kotlin-alt", "groups": ["alt-kotlin"] },
|
||||
{ "id": "alt-2", "name": "Alternative 2", "icon": "kotlin-alt-2", "groups": ["alt-kotlin-2"] }
|
||||
]
|
||||
}
|
||||
],
|
||||
"settings": [
|
||||
{
|
||||
"title": "Icons per family",
|
||||
"items": [{ "option": "choice", "choice": "family-kotlin", "presentation": "radio" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`Base` lists no group, so Kotlin files get their `fileExtensions` icon; `Alternative` turns on
|
||||
`alt-kotlin`, whose pattern wins. The two groups do not appear as checkboxes: the choice
|
||||
decides.
|
||||
|
||||
### Pick the default folder icon
|
||||
|
||||
```json
|
||||
{
|
||||
"folder": "folder",
|
||||
"folderExpanded": "folder-open",
|
||||
"choices": [
|
||||
{
|
||||
"id": "default-folder",
|
||||
"name": "Default folder",
|
||||
"default": "plain",
|
||||
"options": [
|
||||
{ "id": "plain", "name": "Plain", "icon": "folder" },
|
||||
{
|
||||
"id": "blue",
|
||||
"name": "Blue",
|
||||
"icon": "folder-blue",
|
||||
"folder": "folder-blue",
|
||||
"folderExpanded": "folder-blue-open"
|
||||
},
|
||||
{
|
||||
"id": "green",
|
||||
"name": "Green",
|
||||
"icon": "folder-green",
|
||||
"folder": "folder-green",
|
||||
"folderExpanded": "folder-green-open"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"settings": [
|
||||
{
|
||||
"title": "Folders",
|
||||
"items": [{ "option": "choice", "choice": "default-folder", "presentation": "radio" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`Plain` sets no key, so folders keep the theme's `folder` and `folderExpanded`; `Blue` and
|
||||
`Green` replace both.
|
||||
|
||||
## A settings page
|
||||
|
||||
`settings` describes the theme's page under **Settings › Plugins**, named after the theme's
|
||||
@@ -170,13 +265,18 @@ links to the page with a **Settings…** button next to **Apply**.
|
||||
Sections have a `title` and `items`. Each item names an `option` the IDE implements, with
|
||||
the theme's `label`, an optional `hint` and, where the option needs one, a `default`:
|
||||
|
||||
| `option` | Control | Item fields |
|
||||
| ---------------------------------------------------------------------------------------------- | -------------------- | ---------------------------------------------------- |
|
||||
| `hideFiles`, `hideFolders`, `hideUiIcons`, `hidePsiIcons`, `hollowFolders`, `fileIconsForCode` | Checkbox | `invert`: checked means off |
|
||||
| `groups` | A checkbox per group | `columns` (1–4), `label?` (group names are shown) |
|
||||
| `choice` | The choice's options | `choice` (its id), `label?` (default: its name) |
|
||||
| `accent`, `monochrome` | Checkbox and colour | `default` (`#rrggbb`); `accent` needs `accent: true` |
|
||||
| `saturation` (0–20), `opacity` (10–100), `iconSize` (12–32), `rowHeight` (16–48 px) | Checkbox and number | `default` within the range |
|
||||
| `option` | Control | Item fields |
|
||||
| ---------------------------------------------------------------------------------------------- | -------------------- | ---------------------------------------------------------------- |
|
||||
| `hideFiles`, `hideFolders`, `hideUiIcons`, `hidePsiIcons`, `hollowFolders`, `fileIconsForCode` | Checkbox | `invert`: checked means off |
|
||||
| `groups` | A checkbox per group | `columns` (1–4), `label?` (group names are shown) |
|
||||
| `choice` | The choice's options | `choice` (its id), `label?` (default: its name), `presentation?` |
|
||||
| `accent`, `monochrome` | Checkbox and colour | `default` (`#rrggbb`); `accent` needs `accent: true` |
|
||||
| `saturation` (0–20), `opacity` (10–100), `iconSize` (12–32), `rowHeight` (16–48 px) | Checkbox and number | `default` within the range |
|
||||
|
||||
A `choice` item is a dropdown by default. `presentation` takes the values of the plugin
|
||||
settings controls: `"select"` (the dropdown), `"radio"` (radio buttons, in a wrapping row) or
|
||||
`"segmented"` (a segmented control). Radio buttons and segments are best for a few short
|
||||
options. Each option shows its `icon` in all three. `presentation` is refused on other items.
|
||||
|
||||
Values are kept per theme in the `appearance.fileIconThemeOptions` setting and apply while
|
||||
the theme is selected.
|
||||
@@ -202,6 +302,15 @@ iconDark = "icons/graphviz_dark.svg" # optional
|
||||
[Graphviz](https://github.com/l0ng-ai/openidea/tree/main/plugins/official/graphviz) uses it
|
||||
for `.dot` files. SVGs are sanitised like icon theme SVGs.
|
||||
|
||||
## Older IDEs
|
||||
|
||||
`theme.json` is read strictly: an IDE that does not know a field refuses the theme file, and
|
||||
the theme does not load. `groups`, `folder`, `folderExpanded` and `folderOpen` on a choice
|
||||
option and `presentation` on a choice item are new, like `icon` on groups and options, so a theme that uses them loads only in an IDE release
|
||||
that includes them. `engines.openidea` does not enforce this for theme files: if the theme must
|
||||
also work in older IDEs, publish a second build without these fields (choices that only use
|
||||
`overrides`, and `groups` checkboxes). See [API versions and compatibility](/en/plugins/versioning).
|
||||
|
||||
## Tips
|
||||
|
||||
- Material Icons generates its SVGs and `theme.json` with a script (`generate.py`, not part
|
||||
|
||||
@@ -66,7 +66,7 @@ path = "icons/theme.json"
|
||||
- 文件夹先按名称匹配,再用 `folder` / `folderExpanded`。有特殊角色的文件夹(源码根目录、包、已排除、模块)保留角色图标,除非主题在 `roleFolderNames`(见下文)中列出该角色,列出后这些文件夹也按名称匹配。
|
||||
- 名称不区分大小写。
|
||||
|
||||
限制:最多 5000 个图标,每个最大 64 KiB,映射总数最多 20,000 条。每个 SVG 在安装时都会被净化:只允许白名单内的元素和属性,
|
||||
限制:最多 5000 个图标,每个最大 64 KiB,映射总数最多 20,000 条(包括模式、`overrides`,以及 `choices` 选项里的 `overrides` 和 `groups` 条目)。每个 SVG 在安装时都会被净化:只允许白名单内的元素和属性,
|
||||
不允许脚本、事件处理器、外部引用、`url()` 或实体。
|
||||
|
||||
## 可选字段
|
||||
@@ -114,13 +114,99 @@ path = "icons/theme.json"
|
||||
列出 `folder-source` 和 `package`,且 `folderNames` 为 `{ "kotlin": "folder-kotlin", "config": "folder-config" }`,
|
||||
这两个文件夹都会显示各自的命名图标。没有对应条目的包(如 `utils`)显示主题的文件夹图标;若主题在 `overrides` 中为 `package` 定义了图标,则显示该图标。
|
||||
- **`groups`** 是用户可以整组开关的模式集合;`enabled` 为默认状态。
|
||||
- **`choices`** 是用户从中选一个的变体;所选选项的 `overrides` 优先于顶层的 `overrides`。
|
||||
- **`choices`** 是用户从中选一个的变体;所选选项的 `overrides` 优先于顶层的 `overrides`。一个主题最多有 64 个 `choices`,每个最多 16 个选项。
|
||||
- **`choices` 选项上的 `groups`** 列出该选项要打开的分组,这样一个 `choices` 就能在同一类文件的多个变体图标之间切换(见下面的示例)。
|
||||
被某个 `choices` 列出的分组归它**所有**:只有当前选中的选项(用户的选择,否则为该 `choices` 的 `default`)列出它时它才是开启的,
|
||||
与分组自己的 `enabled` 以及用户之前对该分组的勾选无关。归 `choices` 所有的分组不会出现在 `groups` 复选框中。
|
||||
每个 id 都必须是该主题的分组;同一个 `choices` 的多个选项可以列出同一个分组,但两个不同的 `choices` 不能列出同一个分组。
|
||||
- **`choices` 选项上的 `folder`、`folderExpanded` 和 `folderOpen`** 是 `iconDefinitions` 中的图标 id,
|
||||
在该选项被选中时,分别替换主题顶层的 `folder`、`folderExpanded` 和 `folderOpen`(通用文件夹、展开的文件夹,
|
||||
以及启用空心文件夹时包含已打开文件的文件夹)。选项省略的键沿用主题自己的值,因此默认选项可以不设置任何键。
|
||||
命名文件夹和文件夹模式不受影响。一个主题只能有一个 `choices` 设置这些键;未知的 id,或第二个设置它们的 `choices`,都会被拒绝。
|
||||
- **`icon`**(可用于分组,也可用于 `choices` 的选项)是同一主题 `iconDefinitions` 中的图标 id。设置页面会把它显示在分组复选框的文字之前,
|
||||
或显示在选项下拉框里对应选项的旁边,让用户直观看到每个图标包或变体的样子。即使该主题当前没有被选中,图标也会显示。
|
||||
引用不存在的 id 会被拒绝;不写 `icon` 则什么都不显示。
|
||||
- **`accent: true`**:带 `data-tint="true"` 的元素使用用户选择的颜色。
|
||||
- 带 `data-themed="true"` 的元素使用 **设置 › 外观与行为 › 外观** 中的强调色,或配色主题自定义的强调色。
|
||||
|
||||
### 同一类文件的多套图标,选其一
|
||||
|
||||
```json
|
||||
{
|
||||
"groups": [
|
||||
{ "id": "alt-kotlin", "name": "Kotlin, alternative", "enabled": false, "icon": "kotlin-alt" },
|
||||
{ "id": "alt-kotlin-2", "name": "Kotlin, alternative 2", "enabled": false, "icon": "kotlin-alt-2" }
|
||||
],
|
||||
"patterns": [
|
||||
{ "pattern": "^.*\\.kts?$", "icon": "kotlin-alt", "group": "alt-kotlin" },
|
||||
{ "pattern": "^.*\\.kts?$", "icon": "kotlin-alt-2", "group": "alt-kotlin-2" }
|
||||
],
|
||||
"fileExtensions": { "kt": "kotlin", "kts": "kotlin" },
|
||||
"choices": [
|
||||
{
|
||||
"id": "family-kotlin",
|
||||
"name": "Kotlin",
|
||||
"default": "base",
|
||||
"options": [
|
||||
{ "id": "base", "name": "Base", "icon": "kotlin" },
|
||||
{ "id": "alt", "name": "Alternative", "icon": "kotlin-alt", "groups": ["alt-kotlin"] },
|
||||
{ "id": "alt-2", "name": "Alternative 2", "icon": "kotlin-alt-2", "groups": ["alt-kotlin-2"] }
|
||||
]
|
||||
}
|
||||
],
|
||||
"settings": [
|
||||
{
|
||||
"title": "Icons per family",
|
||||
"items": [{ "option": "choice", "choice": "family-kotlin", "presentation": "radio" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`Base` 不列出任何分组,因此 Kotlin 文件使用 `fileExtensions` 中的图标;`Alternative` 会打开 `alt-kotlin`,它的模式优先。
|
||||
这两个分组不会显示为复选框,由 `choices` 决定。
|
||||
|
||||
### 选择默认文件夹图标
|
||||
|
||||
```json
|
||||
{
|
||||
"folder": "folder",
|
||||
"folderExpanded": "folder-open",
|
||||
"choices": [
|
||||
{
|
||||
"id": "default-folder",
|
||||
"name": "Default folder",
|
||||
"default": "plain",
|
||||
"options": [
|
||||
{ "id": "plain", "name": "Plain", "icon": "folder" },
|
||||
{
|
||||
"id": "blue",
|
||||
"name": "Blue",
|
||||
"icon": "folder-blue",
|
||||
"folder": "folder-blue",
|
||||
"folderExpanded": "folder-blue-open"
|
||||
},
|
||||
{
|
||||
"id": "green",
|
||||
"name": "Green",
|
||||
"icon": "folder-green",
|
||||
"folder": "folder-green",
|
||||
"folderExpanded": "folder-green-open"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"settings": [
|
||||
{
|
||||
"title": "Folders",
|
||||
"items": [{ "option": "choice", "choice": "default-folder", "presentation": "radio" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`Plain` 不设置任何键,因此文件夹沿用主题的 `folder` 和 `folderExpanded`;`Blue` 和 `Green` 会同时替换这两个。
|
||||
|
||||
## 设置页面
|
||||
|
||||
`settings` 描述主题在 **设置 › 插件** 下的页面,页面以主题的 label 命名。没有 `settings` 的主题没有设置页面。插件详情窗格中,主题行的 **应用** 按钮旁会有一个 **设置…** 按钮,点击即可跳转到该页面。
|
||||
@@ -143,13 +229,17 @@ path = "icons/theme.json"
|
||||
|
||||
每个分区有 `title` 和 `items`。每一项指定一个由 IDE 实现的 `option`,附上主题提供的 `label`、可选的 `hint`,以及该选项需要时的 `default`:
|
||||
|
||||
| `option` | 控件 | 字段 |
|
||||
| ---------------------------------------------------------------------------------------------- | ------------------ | ---------------------------------------------------- |
|
||||
| `hideFiles`、`hideFolders`、`hideUiIcons`、`hidePsiIcons`、`hollowFolders`、`fileIconsForCode` | 复选框 | `invert`:勾选表示关闭 |
|
||||
| `groups` | 每个分组一个复选框 | `columns`(1–4)、`label?`(显示分组名) |
|
||||
| `choice` | 该变体的选项 | `choice`(其 id)、`label?`(默认为其名称) |
|
||||
| `accent`、`monochrome` | 复选框和颜色 | `default`(`#rrggbb`);`accent` 需要 `accent: true` |
|
||||
| `saturation`(0–20)、`opacity`(10–100)、`iconSize`(12–32)、`rowHeight`(16–48 px) | 复选框和数字 | `default`,须在范围内 |
|
||||
| `option` | 控件 | 字段 |
|
||||
| ---------------------------------------------------------------------------------------------- | ------------------ | ------------------------------------------------------------ |
|
||||
| `hideFiles`、`hideFolders`、`hideUiIcons`、`hidePsiIcons`、`hollowFolders`、`fileIconsForCode` | 复选框 | `invert`:勾选表示关闭 |
|
||||
| `groups` | 每个分组一个复选框 | `columns`(1–4)、`label?`(显示分组名) |
|
||||
| `choice` | 该变体的选项 | `choice`(其 id)、`label?`(默认为其名称)、`presentation?` |
|
||||
| `accent`、`monochrome` | 复选框和颜色 | `default`(`#rrggbb`);`accent` 需要 `accent: true` |
|
||||
| `saturation`(0–20)、`opacity`(10–100)、`iconSize`(12–32)、`rowHeight`(16–48 px) | 复选框和数字 | `default`,须在范围内 |
|
||||
|
||||
`choice` 项默认显示为下拉框。`presentation` 取值与插件设置控件相同:`"select"`(下拉框)、`"radio"`(单选按钮,换行排列)或
|
||||
`"segmented"`(分段控件)。单选按钮和分段控件适合选项少且文字短的情况。三种方式下每个选项都会显示它的 `icon`。
|
||||
在其他类型的项上写 `presentation` 会被拒绝。
|
||||
|
||||
这些值按主题保存在 `appearance.fileIconThemeOptions` 设置中,在该主题被选中时生效。
|
||||
|
||||
@@ -170,6 +260,13 @@ iconDark = "icons/graphviz_dark.svg" # 可选
|
||||
[Graphviz](https://github.com/l0ng-ai/openidea/tree/main/plugins/official/graphviz) 用它为 `.dot` 文件提供图标。
|
||||
这些 SVG 与图标主题的 SVG 一样会被净化。
|
||||
|
||||
## 旧版 IDE
|
||||
|
||||
`theme.json` 的读取是严格的:IDE 不认识的字段会导致主题文件被拒绝,主题无法加载。`choices` 选项上的 `groups`、`folder`、`folderExpanded`、`folderOpen` 和 `choice` 项上的
|
||||
`presentation` 与分组和选项上的 `icon` 一样是新增字段,因此使用它们的主题只能在包含这些功能的 IDE 版本中加载。
|
||||
`engines.openidea` 不会对主题文件强制这一点:如果主题还要在旧版 IDE 中工作,请另外发布一个不含这些字段的版本
|
||||
(`choices` 只用 `overrides`,分组仍用 `groups` 复选框)。参见 [API 版本与兼容](/zh/plugins/versioning)。
|
||||
|
||||
## 建议
|
||||
|
||||
- Material Icons 的 SVG 和 `theme.json` 由脚本生成(`generate.py`,不属于插件包);图标很多时,生成比手工编辑更可靠。
|
||||
|
||||
@@ -207,6 +207,150 @@ describe("icon theme resolver", () => {
|
||||
const theme = iconResolver(map, name, (n) => n !== name("missing"), { hidden: HIDDEN, options: {} });
|
||||
expect(theme.file("a.spec.ts")).toBe(name("ts"));
|
||||
});
|
||||
|
||||
describe("groups owned by a choice", () => {
|
||||
const pattern = (ext: string, icon: string, group: string | null): IconThemePattern => ({
|
||||
...SPEC,
|
||||
pattern: `^.*\\.${ext}$`,
|
||||
icon,
|
||||
group,
|
||||
});
|
||||
const FAMILIES: IconThemeMap = {
|
||||
...MAP,
|
||||
patterns: [
|
||||
pattern("kt", "kt-alt", "alt-kt"),
|
||||
pattern("kt", "kt-alt-2", "alt-kt-2"),
|
||||
pattern("go", "go-pack", "go"),
|
||||
],
|
||||
overrides: {},
|
||||
groups: [
|
||||
{ id: "alt-kt", name: "Kotlin alt", enabled: true },
|
||||
{ id: "alt-kt-2", name: "Kotlin alt 2", enabled: true },
|
||||
{ id: "go", name: "Go", enabled: false },
|
||||
],
|
||||
choices: [
|
||||
{
|
||||
id: "family-kt",
|
||||
name: "Kotlin",
|
||||
default: "base",
|
||||
options: [
|
||||
{ id: "base", name: "Base", overrides: {} },
|
||||
{ id: "alt", name: "Alt", groups: ["alt-kt"], overrides: {} },
|
||||
{ id: "alt-2", name: "Alt 2", groups: ["alt-kt-2"], overrides: {} },
|
||||
],
|
||||
},
|
||||
],
|
||||
fileExtensions: { kt: "kt" },
|
||||
};
|
||||
const families = (options = {}) => iconResolver(FAMILIES, name, () => true, { hidden: HIDDEN, options });
|
||||
|
||||
it("turns on the groups the selected option lists, and none for the base option", () => {
|
||||
expect(families().file("a.kt")).toBe(name("kt"));
|
||||
expect(families({ choices: { "family-kt": "alt" } }).file("a.kt")).toBe(name("kt-alt"));
|
||||
expect(families({ choices: { "family-kt": "alt-2" } }).file("a.kt")).toBe(name("kt-alt-2"));
|
||||
expect(families({ choices: { "family-kt": "gone" } }).file("a.kt")).toBe(name("kt"));
|
||||
});
|
||||
|
||||
it("ignores the group's own default and any stored per-group value", () => {
|
||||
// `enabled: true` in the theme does not turn an owned group on.
|
||||
expect(families().file("a.kt")).toBe(name("kt"));
|
||||
expect(families({ groups: { "alt-kt": true } }).file("a.kt")).toBe(name("kt"));
|
||||
expect(families({ choices: { "family-kt": "alt" }, groups: { "alt-kt": false } }).file("a.kt")).toBe(
|
||||
name("kt-alt"),
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves the groups no choice lists to their defaults and the user's value", () => {
|
||||
expect(families().file("a.go")).toBe(name("file"));
|
||||
expect(families({ groups: { go: true } }).file("a.go")).toBe(name("go-pack"));
|
||||
expect(families({ choices: { "family-kt": "alt" }, groups: { go: true } }).file("a.go")).toBe(name("go-pack"));
|
||||
});
|
||||
|
||||
it("follows the choice's default when the stored value is missing", () => {
|
||||
const map: IconThemeMap = {
|
||||
...FAMILIES,
|
||||
choices: [{ ...FAMILIES.choices![0]!, default: "alt-2" }],
|
||||
};
|
||||
const theme = iconResolver(map, name, () => true, { hidden: HIDDEN, options: {} });
|
||||
expect(theme.file("a.kt")).toBe(name("kt-alt-2"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("default folder choice", () => {
|
||||
const FOLDERS: IconThemeMap = {
|
||||
...MAP,
|
||||
folder: "folder",
|
||||
folderExpanded: "folder-expanded",
|
||||
folderOpen: "folder-open",
|
||||
choices: [
|
||||
{
|
||||
id: "default-folder",
|
||||
name: "Default folder",
|
||||
default: "plain",
|
||||
options: [
|
||||
{ id: "plain", name: "Plain", overrides: {} },
|
||||
{
|
||||
id: "blue",
|
||||
name: "Blue",
|
||||
folder: "folder-blue",
|
||||
folderExpanded: "folder-blue-expanded",
|
||||
folderOpen: "folder-blue-open",
|
||||
overrides: {},
|
||||
},
|
||||
{ id: "red", name: "Red", folder: "folder-red", overrides: {} },
|
||||
],
|
||||
},
|
||||
...MAP.choices!,
|
||||
],
|
||||
};
|
||||
const folders = (options = {}) => iconResolver(FOLDERS, name, () => true, { hidden: HIDDEN, options });
|
||||
const pick = (id: string) => ({ choices: { "default-folder": id } });
|
||||
|
||||
it("keeps the theme's folders for the default option and a stale value", () => {
|
||||
for (const theme of [folders(), folders(pick("plain")), folders(pick("gone"))]) {
|
||||
expect(theme.folder("lib", false)).toBe(name("folder"));
|
||||
expect(theme.folder("lib", true)).toBe(name("folder-expanded"));
|
||||
}
|
||||
});
|
||||
|
||||
it("replaces the generic folder, expanded folder and hollow folder with the selected option's", () => {
|
||||
const blue = folders({ ...pick("blue"), hollowFolders: true });
|
||||
expect(blue.folder("lib", false)).toBe(name("folder-blue"));
|
||||
expect(blue.folder("lib", true)).toBe(name("folder-blue-expanded"));
|
||||
expect(blue.folder("lib", false, true)).toBe(name("folder-blue-open"));
|
||||
expect(folders(pick("blue")).folder("lib", false, true)).toBe(name("folder-blue"));
|
||||
});
|
||||
|
||||
it("keeps the theme's value for keys the option omits", () => {
|
||||
const red = folders({ ...pick("red"), hollowFolders: true });
|
||||
expect(red.folder("lib", false)).toBe(name("folder-red"));
|
||||
expect(red.folder("lib", true)).toBe(name("folder-expanded"));
|
||||
expect(red.folder("lib", false, true)).toBe(name("folder-open"));
|
||||
});
|
||||
|
||||
it("leaves named folders and folder patterns alone", () => {
|
||||
const blue = folders({ ...pick("blue"), hollowFolders: true });
|
||||
expect(blue.folder("docs", false)).toBe(name("folder-docs"));
|
||||
expect(blue.folder("src", false)).toBe(name("folder-src"));
|
||||
expect(blue.folder("src", false, true)).toBe(name("folder-src-open"));
|
||||
});
|
||||
|
||||
it("resolves like a missing theme icon when the option's icon is not in the icon set", () => {
|
||||
const theme = iconResolver(FOLDERS, name, (icon) => icon !== name("folder-blue"), {
|
||||
hidden: HIDDEN,
|
||||
options: pick("blue"),
|
||||
});
|
||||
expect(theme.folder("lib", false)).toBeNull();
|
||||
expect(theme.folder("lib", true)).toBe(name("folder-blue-expanded"));
|
||||
});
|
||||
|
||||
it("still hides folders and applies the other choices", () => {
|
||||
expect(folders({ ...pick("blue"), hideFolders: true }).folder("lib", false)).toBe(HIDDEN);
|
||||
const both = folders({ choices: { "default-folder": "blue", arrows: "plus" } });
|
||||
expect(both.icon("chevron-right")).toBe(name("plus"));
|
||||
expect(both.folder("lib", false)).toBe(name("folder-blue"));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("icon theme resolver: folders with a role", () => {
|
||||
|
||||
@@ -25,6 +25,12 @@ export interface IconThemeChoiceOption {
|
||||
name: string;
|
||||
/** An icon of the theme (`iconDefinitions` id) shown on its settings page. */
|
||||
icon?: string;
|
||||
/** Groups this option turns on. */
|
||||
groups?: string[];
|
||||
/** Replace the theme's `folder`, `folderExpanded` and `folderOpen` icons while this option is selected. */
|
||||
folder?: string;
|
||||
folderExpanded?: string;
|
||||
folderOpen?: string;
|
||||
overrides: Record<string, string>;
|
||||
}
|
||||
|
||||
@@ -72,10 +78,29 @@ const MAX_CACHED = 5000;
|
||||
|
||||
const normalizePath = (path: string | null | undefined) => (path ? path.replace(/\\/g, "/") : null);
|
||||
|
||||
function selectedOption(choice: IconThemeChoice, options: FileIconThemeOptions) {
|
||||
const picked = options.choices?.[choice.id];
|
||||
return choice.options.find((o) => o.id === picked) ?? choice.options.find((o) => o.id === choice.default);
|
||||
}
|
||||
|
||||
/**
|
||||
* The state of every group a choice lists: on while the choice's selected option lists it. Such a
|
||||
* group ignores its own default and any stored per-group value.
|
||||
*/
|
||||
function ownedGroups(map: IconThemeMap, options: FileIconThemeOptions): Map<string, boolean> {
|
||||
const owned = new Map<string, boolean>();
|
||||
for (const choice of map.choices ?? []) {
|
||||
const on = selectedOption(choice, options)?.groups ?? [];
|
||||
for (const option of choice.options) for (const group of option.groups ?? []) owned.set(group, on.includes(group));
|
||||
}
|
||||
return owned;
|
||||
}
|
||||
|
||||
function compile(map: IconThemeMap, target: IconThemePattern["target"], options: FileIconThemeOptions) {
|
||||
const owned = ownedGroups(map, options);
|
||||
const enabled = (group: string | null) => {
|
||||
if (!group) return true;
|
||||
return options.groups?.[group] ?? map.groups?.find((g) => g.id === group)?.enabled ?? true;
|
||||
return owned.get(group) ?? options.groups?.[group] ?? map.groups?.find((g) => g.id === group)?.enabled ?? true;
|
||||
};
|
||||
const compiled: Compiled[] = [];
|
||||
(map.patterns ?? []).forEach((p, order) => {
|
||||
@@ -95,14 +120,23 @@ function compile(map: IconThemeMap, target: IconThemePattern["target"], options:
|
||||
}
|
||||
|
||||
function chosenOverrides(map: IconThemeMap, options: FileIconThemeOptions): Record<string, string> {
|
||||
return Object.assign(
|
||||
{},
|
||||
...(map.choices ?? []).map((c) => {
|
||||
const picked = options.choices?.[c.id];
|
||||
const option = c.options.find((o) => o.id === picked) ?? c.options.find((o) => o.id === c.default);
|
||||
return option?.overrides ?? {};
|
||||
}),
|
||||
);
|
||||
return Object.assign({}, ...(map.choices ?? []).map((c) => selectedOption(c, options)?.overrides ?? {}));
|
||||
}
|
||||
|
||||
/**
|
||||
* The generic folder icons: the theme's own, each replaced by the selected option of the choice
|
||||
* that sets it (a theme has at most one such choice). Keys the option omits keep the theme's value.
|
||||
*/
|
||||
function folderIcons(map: IconThemeMap, options: FileIconThemeOptions) {
|
||||
const icons = { folder: map.folder, folderExpanded: map.folderExpanded, folderOpen: map.folderOpen };
|
||||
for (const choice of map.choices ?? []) {
|
||||
const option = selectedOption(choice, options);
|
||||
if (!option) continue;
|
||||
for (const key of ["folder", "folderExpanded", "folderOpen"] as const) {
|
||||
if (option[key]) icons[key] = option[key];
|
||||
}
|
||||
}
|
||||
return icons;
|
||||
}
|
||||
|
||||
function cached(resolve: (fileName: string, path: string | null) => string | null) {
|
||||
@@ -129,6 +163,7 @@ export function iconResolver(
|
||||
const files = compile(map, "file", options);
|
||||
const folders = compile(map, "folder", options);
|
||||
const chosen = chosenOverrides(map, options);
|
||||
const generic = folderIcons(map, options);
|
||||
const overrides = map.overrides ?? {};
|
||||
const roles = new Set(map.roleFolderNames ?? []);
|
||||
const replaced = (name: string) => {
|
||||
@@ -170,8 +205,8 @@ export function iconResolver(
|
||||
// Unmatched, a folder with a role shows the theme's icon for the role if it has one (the
|
||||
// caller draws it), and the theme's folder otherwise.
|
||||
if (role && (Object.hasOwn(chosen, role) || Object.hasOwn(overrides, role))) return null;
|
||||
if (open && pick(map.folderOpen)) return pick(map.folderOpen);
|
||||
return (expanded && pick(map.folderExpanded)) || pick(map.folder);
|
||||
if (open && pick(generic.folderOpen)) return pick(generic.folderOpen);
|
||||
return (expanded && pick(generic.folderExpanded)) || pick(generic.folder);
|
||||
},
|
||||
icon(name) {
|
||||
return pick(replaced(name));
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
addContributedIconTheme,
|
||||
useContributedIconThemes,
|
||||
type IconThemeChoice,
|
||||
type IconThemeDetails,
|
||||
type IconThemeSettingItem,
|
||||
type IconThemePreviews,
|
||||
} from "@/platform/themes";
|
||||
import { registerExternalIcons } from "@/ui";
|
||||
@@ -257,4 +258,94 @@ describe("icon theme settings page", () => {
|
||||
expect(released).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("choice presentation", () => {
|
||||
const FAMILY: IconThemeDetails = {
|
||||
...WITH_ICONS,
|
||||
groups: [{ id: "docs", name: "Docs", enabled: true }],
|
||||
choices: [
|
||||
{
|
||||
id: "family-kt",
|
||||
name: "Kotlin",
|
||||
default: "base",
|
||||
options: [
|
||||
{ id: "base", name: "Base", icon: "kt" },
|
||||
{ id: "alt", name: "Alt", icon: "kt-alt" },
|
||||
{ id: "alt-2", name: "Alt 2" },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const withItem = (presentation?: IconThemeSettingItem["presentation"]): IconThemeDetails => ({
|
||||
...FAMILY,
|
||||
settings: [
|
||||
{
|
||||
title: "Families",
|
||||
items: [
|
||||
{ option: "groups" },
|
||||
{ option: "choice", choice: "family-kt", hint: "Used by Kotlin files", presentation },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const open = async (details: IconThemeDetails, options: unknown = {}) => {
|
||||
addContributedIconTheme(theme(details, previews));
|
||||
select("", options);
|
||||
await openPage();
|
||||
};
|
||||
|
||||
it("renders radio buttons with each option's preview icon and stages the picked option", async () => {
|
||||
await open(withItem("radio"));
|
||||
const group = await screen.findByRole("radiogroup", { name: "Kotlin" });
|
||||
expect(screen.queryByRole("button", { name: "Kotlin" })).toBeNull();
|
||||
expect(
|
||||
within(group)
|
||||
.getAllByRole("radio")
|
||||
.map((r) => (r as HTMLInputElement).checked),
|
||||
).toEqual([true, false, false]);
|
||||
await waitFor(() => expect(shown(within(group).getByRole("radio", { name: "Base" }))).toEqual(["kt"]));
|
||||
expect(shown(within(group).getByRole("radio", { name: "Alt" }))).toEqual(["kt-alt"]);
|
||||
expect(shown(within(group).getByRole("radio", { name: "Alt 2" }))).toEqual([]);
|
||||
expect(screen.getByText("Used by Kotlin files")).toBeInTheDocument();
|
||||
fireEvent.click(within(group).getByRole("radio", { name: "Alt" }));
|
||||
expect(staged()["p/t"]).toMatchObject({ choices: { "family-kt": "alt" } });
|
||||
});
|
||||
|
||||
it("shows the stored option as selected", async () => {
|
||||
await open(withItem("radio"), { "p/t": { choices: { "family-kt": "alt-2" } } });
|
||||
const group = await screen.findByRole("radiogroup", { name: "Kotlin" });
|
||||
expect(within(group).getByRole("radio", { name: "Alt 2" })).toBeChecked();
|
||||
expect(within(group).getByRole("radio", { name: "Base" })).not.toBeChecked();
|
||||
});
|
||||
|
||||
it("renders a segmented control and stages the picked option", async () => {
|
||||
await open(withItem("segmented"));
|
||||
const group = await screen.findByRole("radiogroup", { name: "Kotlin" });
|
||||
const segments = within(group).getAllByRole("radio");
|
||||
expect(segments.map((b) => b.tagName)).toEqual(["BUTTON", "BUTTON", "BUTTON"]);
|
||||
expect(within(group).getByRole("radio", { name: "Base" })).toHaveAttribute("aria-checked", "true");
|
||||
fireEvent.click(within(group).getByRole("radio", { name: "Alt 2" }));
|
||||
expect(staged()["p/t"]).toMatchObject({ choices: { "family-kt": "alt-2" } });
|
||||
});
|
||||
|
||||
it.each([undefined, "select" as const])("keeps the dropdown for presentation %s", async (presentation) => {
|
||||
await open(withItem(presentation));
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Kotlin" }));
|
||||
expect(await screen.findByRole("option", { name: "Alt 2" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("radiogroup", { name: "Kotlin" })).toBeNull();
|
||||
});
|
||||
|
||||
it("lists only the groups no choice owns", async () => {
|
||||
// The page gets the summary without the owned groups: `Docs` is the only one left.
|
||||
await open(withItem("radio"));
|
||||
expect(await screen.findByRole("checkbox", { name: "Docs" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("checkbox", { name: /Kotlin/ })).toBeNull();
|
||||
});
|
||||
|
||||
it("renders no checkbox list when every group is owned", async () => {
|
||||
await open({ ...withItem("radio"), groups: [] });
|
||||
await screen.findByRole("radiogroup", { name: "Kotlin" });
|
||||
expect(screen.queryByRole("checkbox")).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { CSSProperties, ReactNode } from "react";
|
||||
import type { FileIconThemeOptions as Options } from "@/bindings";
|
||||
import { Checkbox, Icon, Select } from "@/ui";
|
||||
import { useGivenTx } from "@/platform/i18n";
|
||||
import { Checkbox, Icon, RadioGroup, SegmentedControl, Select } from "@/ui";
|
||||
import { useGivenTx, VerbatimTextContext } from "@/platform/i18n";
|
||||
import { ICON_THEME_LIMITS, validateIconThemeOptions } from "@/platform/iconThemeOptions";
|
||||
import type { IconThemeDetails, IconThemeSettingItem } from "@/platform/themes";
|
||||
import { ColorSwatches, NumberInput, Row, Section, Toggle } from "../components/Form";
|
||||
@@ -45,6 +45,8 @@ function FlagItem({ item, options, set, flag }: ItemProps & { flag: Flag }) {
|
||||
|
||||
function GroupsItem({ item, details, options, set, iconName }: ItemProps) {
|
||||
const tx = useGivenTx();
|
||||
// Groups a choice turns on are not listed: the choice owns them.
|
||||
if (details.groups.length === 0) return null;
|
||||
const style = { "--icon-pack-columns": item.columns ?? 1 } as CSSProperties;
|
||||
const icons = details.groups.map((g) => (g.icon ? iconName?.(g.icon) : undefined));
|
||||
// With some previews, the packs without one keep an empty slot so the labels stay aligned.
|
||||
@@ -79,18 +81,35 @@ function GroupsItem({ item, details, options, set, iconName }: ItemProps) {
|
||||
function ChoiceItem({ item, details, options, set, iconName }: ItemProps) {
|
||||
const choice = details.choices.find((c) => c.id === item.choice);
|
||||
if (!choice) return null;
|
||||
const label = item.label ?? choice.name;
|
||||
const value = options.choices?.[choice.id] ?? choice.default;
|
||||
const pick = (picked: string) => set({ choices: { ...options.choices, [choice.id]: picked } });
|
||||
const choices = choice.options.map((o) => ({
|
||||
value: o.id,
|
||||
label: o.name,
|
||||
icon: (o.icon && iconName?.(o.icon)) || undefined,
|
||||
}));
|
||||
const hint = item.hint ? <span>{item.hint}</span> : undefined;
|
||||
if (item.presentation === "radio" || item.presentation === "segmented") {
|
||||
return (
|
||||
<Row label={label} hint={hint}>
|
||||
<VerbatimTextContext.Provider value={true}>
|
||||
{item.presentation === "radio" ? (
|
||||
<RadioGroup aria-label={label} value={value} options={choices} onChange={pick} inline />
|
||||
) : (
|
||||
<SegmentedControl aria-label={label} value={value} options={choices} onChange={pick} />
|
||||
)}
|
||||
</VerbatimTextContext.Provider>
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Row label={item.label ?? choice.name} hint={item.hint ? <span>{item.hint}</span> : undefined}>
|
||||
<Row label={label} hint={hint}>
|
||||
<Select
|
||||
aria-label={item.label ?? choice.name}
|
||||
value={options.choices?.[choice.id] ?? choice.default}
|
||||
options={choice.options.map((o) => ({
|
||||
value: o.id,
|
||||
verbatim: true,
|
||||
label: o.name,
|
||||
icon: (o.icon && iconName?.(o.icon)) || undefined,
|
||||
}))}
|
||||
onChange={(value) => set({ choices: { ...options.choices, [choice.id]: value } })}
|
||||
aria-label={label}
|
||||
value={value}
|
||||
options={choices.map((o) => ({ ...o, verbatim: true }))}
|
||||
onChange={pick}
|
||||
/>
|
||||
</Row>
|
||||
);
|
||||
|
||||
@@ -147,6 +147,7 @@ export function baseTheme(id: ThemeChoiceId, fallback: BuiltinThemeId = "light")
|
||||
|
||||
// --- file icon themes (plugins) -------------------------------------------------
|
||||
|
||||
/** A pack of patterns the user turns on or off. Groups a choice turns on are left out: the choice owns them. */
|
||||
export interface IconThemePack {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -178,6 +179,9 @@ export type IconThemeSettingOption =
|
||||
| "iconSize"
|
||||
| "rowHeight";
|
||||
|
||||
/** How a `choice` item is drawn: a dropdown (the default), radio buttons or a segmented control. */
|
||||
export type IconThemeChoicePresentation = "select" | "radio" | "segmented";
|
||||
|
||||
export interface IconThemeSettingItem {
|
||||
option: IconThemeSettingOption;
|
||||
label?: string | null;
|
||||
@@ -185,6 +189,7 @@ export interface IconThemeSettingItem {
|
||||
invert?: boolean;
|
||||
choice?: string | null;
|
||||
columns?: number | null;
|
||||
presentation?: IconThemeChoicePresentation | null;
|
||||
default?: number | string | null;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Заблокувати користувача