Skip to content

Visual Studio Code, rebuilt in Rust

Rust
28.9 KB
Raw Blame
//! extensionFeaturesTab.ts and the registered `IExtensionFeatureRenderer`s outside AI (menusExtensionPoint.ts,
//! configurationExtensionPoint.ts, languageService.ts, colorExtensionPoint.ts, themeExtensionPoints.ts and the
//! others): the features an extension's manifest contributes, each as a table or as markdown.

use std::cmp::Ordering;

use gpui::{AnyElement, Context, Div, FontWeight, Rgba, div, prelude::*, px};
use serde_json::Value;

use super::Workbench;
use super::markdown_view::MarkdownStyle;
use crate::command_palette::locale_compare;
use crate::notifications::Severity;

/// `runtimeStatusFeature`: listed first, before the sorted registered features.
pub(super) const RUNTIME_STATUS: (&str, &str) = ("runtimeStatus", "Runtime Status");

/// The registered features' ids and labels; the chat, language model and MCP ones are removed with AI.
const FEATURES: [(&str, &str); 17] = [
    ("jsonValidation", "JSON Validation"),
    ("debuggers", "Debuggers"),
    ("enabledApiProposals", "API Proposals"),
    ("activationEvents", "Activation Events"),
    ("configuration", "Settings"),
    ("configurationDefaults", "Settings Default Overrides"),
    ("colors", "Colors"),
    ("themes", "Themes"),
    ("languages", "Programming Languages"),
    ("customEditors", "Custom Editors"),
    ("commands", "Commands"),
    ("localizations", "Language Packs"),
    ("viewsContainers", "View Containers"),
    ("views", "Views"),
    ("authentication", "Authentication"),
    ("notebooks", "Notebooks"),
    ("notebookRenderer", "Notebook Renderers"),
];

/// `IRowData`: a cell of a feature table.
#[derive(Debug, PartialEq)]
pub(super) enum Cell {
    Text(String),
    Markdown(String),
    /// Each resolved keybinding's chords, each chord's key caps.
    Keybindings(Vec<Vec<Vec<String>>>),
    Color(Rgba),
}

#[derive(Debug, PartialEq)]
pub(super) enum FeatureData {
    Table { headers: Vec<&'static str>, rows: Vec<Vec<Cell>> },
    Markdown(String),
}

/// `getFeatures`: the features whose renderer `shouldRender` the manifest, by label, the runtime status first when
/// the extension runs and has code.
pub(super) fn features(manifest: &Value, running: bool) -> Vec<(&'static str, &'static str)> {
    let mut features: Vec<_> = FEATURES.into_iter().filter(|(id, _)| should_render(manifest, id)).collect();
    features.sort_by(|a, b| locale_compare(a.1, b.1));
    if running && (truthy(&manifest["main"]) || truthy(&manifest["browser"])) {
        features.insert(0, RUNTIME_STATUS);
    }
    features
}

fn should_render(manifest: &Value, feature: &str) -> bool {
    let contributes = &manifest["contributes"];
    match feature {
        "activationEvents" => truthy(&manifest["activationEvents"]),
        "enabledApiProposals" => [&manifest["originalEnabledApiProposals"], &manifest["enabledApiProposals"]].iter().any(|proposals| proposals.as_array().is_some_and(|proposals| !proposals.is_empty())),
        "themes" => ["themes", "iconThemes", "productIconThemes"].iter().any(|key| truthy(&contributes[key])),
        _ => truthy(&contributes[feature]),
    }
}

/// JavaScript's `!!value`.
fn truthy(value: &Value) -> bool {
    match value {
        Value::Null | Value::Bool(false) => false,
        Value::String(text) => !text.is_empty(),
        Value::Number(number) => number.as_f64().is_some_and(|number| number != 0. && !number.is_nan()),
        _ => true,
    }
}

fn items(value: &Value) -> Vec<&Value> {
    value.as_array().map(|items| items.iter().collect()).unwrap_or_default()
}

fn text(value: &Value) -> String {
    value.as_str().unwrap_or_default().to_owned()
}

fn code(text: &str) -> Cell {
    Cell::Markdown(format!("`{text}`"))
}

/// `MarkdownString.appendCodeblock('json', JSON.stringify(value, null, 2))`.
fn json_code_block(value: &Value) -> Cell {
    Cell::Markdown(format!("\n```json\n{}\n```\n", serde_json::to_string_pretty(value).expect("JSON values serialize")))
}

fn table(headers: Vec<&'static str>, rows: Vec<Vec<Cell>>) -> FeatureData {
    FeatureData::Table { headers, rows }
}

fn by_text(key: impl Fn(&Value) -> &str) -> impl FnMut(&&Value, &&Value) -> Ordering {
    move |a, b| locale_compare(key(a), key(b))
}

/// The registered feature's renderer `render(manifest)`; `runtimeStatus` is the workbench's.
pub(super) fn feature_data(manifest: &Value, feature: &str) -> FeatureData {
    let contributes = &manifest["contributes"];
    let field = |key: &'static str| -> Box<dyn Fn(&Value) -> String> { Box::new(move |item: &Value| item[key].as_str().unwrap_or_default().to_owned()) };
    // The renderers' `if (!contrib.length)`: an empty contribution has no headers either.
    let empty = |key: &str| items(&contributes[key]).is_empty();
    match feature {
        "commands" => commands_table(contributes),
        "configuration" => settings_table(&contributes["configuration"]),
        "configurationDefaults" => configuration_defaults_table(&contributes["configurationDefaults"]),
        "languages" => languages_table(contributes),
        "colors" => colors_table(&contributes["colors"]),
        "themes" => FeatureData::Markdown(themes_markdown(contributes)),
        "activationEvents" => FeatureData::Markdown(code_list(&manifest["activationEvents"])),
        "enabledApiProposals" => {
            let proposals = if manifest["originalEnabledApiProposals"].is_null() { &manifest["enabledApiProposals"] } else { &manifest["originalEnabledApiProposals"] };
            FeatureData::Markdown(code_list(proposals))
        }
        "jsonValidation" | "debuggers" | "customEditors" if empty(feature) => table(Vec::new(), Vec::new()),
        "jsonValidation" => {
            let rows = items(&contributes["jsonValidation"])
                .into_iter()
                .map(|item| {
                    let file_match = match &item["fileMatch"] {
                        Value::Array(patterns) => patterns.iter().map(|pattern| pattern.as_str().unwrap_or_default()).collect::<Vec<_>>().join(", "),
                        pattern => text(pattern),
                    };
                    vec![code(&file_match), Cell::Text(text(&item["url"]))]
                })
                .collect();
            table(vec!["File Match", "Schema"], rows)
        }
        "debuggers" => {
            let rows = items(&contributes["debuggers"]).into_iter().map(|item| vec![Cell::Text(text(&item["label"])), Cell::Text(text(&item["type"]))]).collect();
            table(vec!["Name", "Type"], rows)
        }
        "customEditors" => {
            let rows = items(&contributes["customEditors"])
                .into_iter()
                .map(|item| {
                    let patterns: Vec<&str> = items(&item["selector"]).into_iter().filter_map(|selector| selector["filenamePattern"].as_str()).collect();
                    vec![Cell::Text(text(&item["viewType"])), Cell::Text(custom_editor_priority(&item["priority"])), Cell::Text(patterns.join(", "))]
                })
                .collect();
            table(vec!["View Type", "Priority", "Filename Pattern"], rows)
        }
        "localizations" => sorted_table(&contributes["localizations"], "languageId", vec!["Language ID", "Language Name", "Language Name (Localized)"], &[field("languageId"), field("languageName"), field("localizedLanguageName")]),
        "viewsContainers" => located_table(&contributes["viewsContainers"], vec!["ID", "Title", "Where"], "title"),
        "views" => located_table(&contributes["views"], vec!["ID", "Name", "Where"], "name"),
        "authentication" => {
            let globs = |item: &Value| items(&item["authorizationServerGlobs"]).into_iter().map(|glob| glob.as_str().unwrap_or_default()).collect::<Vec<_>>().join(",\n");
            sorted_table(&contributes["authentication"], "label", vec!["Label", "ID", "MCP Authorization Servers"], &[field("label"), field("id"), Box::new(globs)])
        }
        "notebooks" => sorted_table(&contributes["notebooks"], "type", vec!["ID", "Name"], &[field("type"), field("displayName")]),
        "notebookRenderer" => {
            let mime_types = |item: &Value| items(&item["mimeTypes"]).into_iter().map(|mime| mime.as_str().unwrap_or_default()).collect::<Vec<_>>().join(",");
            sorted_table(&contributes["notebookRenderer"], "displayName", vec!["Name", "Mimetypes"], &[field("displayName"), Box::new(mime_types)])
        }
        _ => table(Vec::new(), Vec::new()),
    }
}

/// A table of text columns sorted by `key`, empty without items.
fn sorted_table(value: &Value, key: &'static str, headers: Vec<&'static str>, columns: &[Box<dyn Fn(&Value) -> String + '_>]) -> FeatureData {
    let mut entries = items(value);
    if entries.is_empty() {
        return table(Vec::new(), Vec::new());
    }
    entries.sort_by(by_text(|item| item[key].as_str().unwrap_or_default()));
    let rows = entries.into_iter().map(|item| columns.iter().map(|column| Cell::Text(column(item))).collect()).collect();
    table(headers, rows)
}

/// viewsExtensionPoint.ts: the views or view containers of every location, by id, with their location.
fn located_table(value: &Value, headers: Vec<&'static str>, name: &str) -> FeatureData {
    let mut entries = Vec::new();
    for (location, items_at) in value.as_object().into_iter().flatten() {
        entries.extend(items(items_at).into_iter().map(|item| (item, location.as_str())));
    }
    if entries.is_empty() {
        return table(Vec::new(), Vec::new());
    }
    entries.sort_by(|a, b| locale_compare(a.0["id"].as_str().unwrap_or_default(), b.0["id"].as_str().unwrap_or_default()));
    let rows = entries.into_iter().map(|(item, location)| vec![Cell::Text(text(&item["id"])), Cell::Text(text(&item[name])), Cell::Text(location.to_owned())]).collect();
    table(headers, rows)
}

/// customEditor/common/extensionPoint.ts `renderPriority`.
fn custom_editor_priority(priority: &Value) -> String {
    match priority {
        Value::String(priority) => priority.clone(),
        Value::Object(_) => {
            let parts = [("textEditor", &priority["textEditor"]), ("diffEditor", &priority["diffEditor"])];
            parts.iter().filter(|(_, value)| truthy(value)).map(|(name, value)| format!("{name}: {}", value.as_str().unwrap_or_default())).collect::<Vec<_>>().join(", ")
        }
        _ => String::new(),
    }
}

fn code_list(values: &Value) -> String {
    items(values).into_iter().map(|value| format!("- `{}`\n", value.as_str().unwrap_or_default())).collect()
}

/// themeExtensionPoints.ts `ThemeDataRenderer`.
fn themes_markdown(contributes: &Value) -> String {
    let mut markdown = String::new();
    for (key, title) in [("themes", "Color Themes"), ("iconThemes", "File Icon Themes"), ("productIconThemes", "Product Icon Themes")] {
        if !truthy(&contributes[key]) {
            continue;
        }
        markdown.push_str(&format!("### {title}\n\n"));
        for theme in items(&contributes[key]) {
            markdown.push_str(&format!("- {}\n", theme["label"].as_str().unwrap_or_default()));
        }
    }
    markdown
}

/// menusExtensionPoint.ts `CommandsTableRenderer`: every command of the commands, menus and keybindings, with its
/// keybindings and the menus it is in, the command palette for one no `commandPalette` entry names.
fn commands_table(contributes: &Value) -> FeatureData {
    struct Command {
        id: String,
        title: String,
        keybindings: Vec<Vec<Vec<String>>>,
        menus: Vec<String>,
    }
    let mut commands: Vec<Command> = items(&contributes["commands"])
        .into_iter()
        .map(|command| {
            let title = match &command["title"] {
                Value::Object(title) => title.get("value").map(text).unwrap_or_default(),
                title => text(title),
            };
            Command { id: text(&command["command"]), title, keybindings: Vec::new(), menus: Vec::new() }
        })
        .collect();
    let menus = contributes["menus"].as_object().cloned().unwrap_or_default();
    let in_palette: Vec<&str> = items(&contributes["menus"]["commandPalette"]).into_iter().filter_map(|entry| entry["command"].as_str()).collect();
    let mut entries: Vec<(String, Value)> = menus.into_iter().collect();
    let implicit: Vec<Value> = commands.iter().filter(|command| !in_palette.contains(&command.id.as_str())).map(|command| serde_json::json!({ "command": command.id })).collect();
    if !implicit.is_empty() {
        match entries.iter_mut().find(|(context, _)| context == "commandPalette") {
            Some((_, palette)) => palette.as_array_mut().expect("a contributed menu is an array").extend(implicit),
            None => entries.push(("commandPalette".into(), Value::Array(implicit))),
        }
    }
    for (context, menu) in &entries {
        for item in items(menu) {
            // Typically a command hidden from the command palette.
            if item["when"] == "false" {
                continue;
            }
            let Some(id) = item["command"].as_str() else { continue };
            match commands.iter_mut().find(|command| command.id == id) {
                Some(command) if !command.menus.contains(context) => command.menus.push(context.clone()),
                Some(_) => {}
                None => commands.push(Command { id: id.to_owned(), title: String::new(), keybindings: Vec::new(), menus: vec![context.clone()] }),
            }
        }
    }
    let keybindings = match &contributes["keybindings"] {
        Value::Array(rules) => rules.iter().collect(),
        Value::Null => Vec::new(),
        rule => vec![rule],
    };
    for rule in keybindings {
        // menusExtensionPoint.ts `resolveKeybinding`: `resolveUserBinding(win, linux or mac ?? key)[0]`; a key that
        // does not parse resolves to nothing.
        let platform_key = match crate::keybindings::OS {
            crate::keybindings::Os::Macintosh => "mac",
            crate::keybindings::Os::Windows => "win",
            crate::keybindings::Os::Linux => "linux",
        };
        let key = rule.get(platform_key).and_then(Value::as_str).or_else(|| rule["key"].as_str()).unwrap_or_default();
        let chords = crate::keybindings::parse_keybinding(key);
        if chords.is_empty() {
            continue;
        }
        let keybinding = chords.iter().map(|chord| chord.key_caps()).collect();
        let id = text(&rule["command"]);
        match commands.iter_mut().find(|command| command.id == id) {
            Some(command) => command.keybindings.push(keybinding),
            None => commands.push(Command { id, title: String::new(), keybindings: vec![keybinding], menus: Vec::new() }),
        }
    }
    if commands.is_empty() {
        return table(Vec::new(), Vec::new());
    }
    commands.sort_by(|a, b| locale_compare(&a.id, &b.id));
    let rows = commands
        .into_iter()
        .map(|mut command| {
            command.menus.sort_by(|a, b| locale_compare(a, b));
            let menus = command.menus.iter().map(|menu| format!("`{menu}`")).collect::<Vec<_>>().join("&nbsp;");
            vec![code(&command.id), Cell::Text(command.title), Cell::Keybindings(command.keybindings), Cell::Markdown(menus)]
        })
        .collect();
    table(vec!["ID", "Title", "Keyboard Shortcuts", "Menu Contexts"], rows)
}

/// configurationExtensionPoint.ts `SettingsTableRenderer`: the settings of every node and its `allOf`, by key.
fn settings_table(configuration: &Value) -> FeatureData {
    let nodes = match configuration {
        Value::Array(nodes) => nodes.iter().collect(),
        Value::Null => Vec::new(),
        node => vec![node],
    };
    let mut properties = serde_json::Map::new();
    collect_properties(&nodes, &mut properties);
    let mut keys: Vec<&String> = properties.keys().collect();
    keys.sort_by(|a, b| locale_compare(a, b));
    let rows = keys
        .into_iter()
        .map(|key| {
            let property = &properties[key];
            let description = match property["markdownDescription"].as_str().filter(|text| !text.is_empty()) {
                Some(markdown) => Cell::Markdown(markdown.to_owned()),
                None => Cell::Text(text(&property["description"])),
            };
            let default = property.get("default").cloned().unwrap_or_else(|| default_value(&property["type"]));
            vec![code(key), description, json_code_block(&default)]
        })
        .collect();
    table(vec!["ID", "Description", "Default"], rows)
}

/// configurationRegistry.ts `getAllConfigurationProperties`.
fn collect_properties(nodes: &[&Value], properties: &mut serde_json::Map<String, Value>) {
    for node in nodes {
        if let Some(own) = node["properties"].as_object() {
            properties.extend(own.clone());
        }
        if let Some(all_of) = node["allOf"].as_array() {
            collect_properties(&all_of.iter().collect::<Vec<_>>(), properties);
        }
    }
}

/// configurationRegistry.ts `getDefaultValue`.
fn default_value(kind: &Value) -> Value {
    let kind = match kind {
        Value::Array(kinds) => kinds.first().and_then(Value::as_str),
        kind => kind.as_str(),
    };
    match kind {
        Some("boolean") => Value::Bool(false),
        Some("integer" | "number") => Value::from(0),
        Some("string") => Value::from(""),
        Some("array") => Value::Array(Vec::new()),
        Some("object") => Value::Object(serde_json::Map::new()),
        _ => Value::Null,
    }
}

/// configurationExtensionPoint.ts `ConfigurationDefaultsTableRenderer`: a row per overridden setting, a language
/// override's settings each with its languages.
fn configuration_defaults_table(defaults: &Value) -> FeatureData {
    let mut rows = Vec::new();
    let entries = defaults.as_object().cloned().unwrap_or_default();
    let mut keys: Vec<&String> = entries.keys().collect();
    keys.sort_by(|a, b| locale_compare(a, b));
    for key in keys {
        let value = &entries[key];
        if !config::model::is_override_key(key) {
            rows.push(vec![Cell::Text(String::new()), code(key), json_code_block(value)]);
            continue;
        }
        let languages = config::model::override_identifiers_from_key(key).join(", ");
        let settings = value.as_object().cloned().unwrap_or_default();
        let mut setting_keys: Vec<&String> = settings.keys().collect();
        setting_keys.sort_by(|a, b| locale_compare(a, b));
        for setting in setting_keys {
            rows.push(vec![Cell::Markdown(languages.clone()), code(setting), json_code_block(&settings[setting])]);
        }
    }
    table(vec!["Languages", "Setting", "Override Value"], rows)
}

/// languageService.ts `LanguageTableRenderer`: the valid languages, and those only a grammar or snippets name.
fn languages_table(contributes: &Value) -> FeatureData {
    struct Language {
        id: String,
        name: String,
        extensions: Vec<String>,
        grammar: bool,
        snippets: bool,
    }
    let mut languages: Vec<Language> = items(&contributes["languages"])
        .into_iter()
        .filter(|language| is_valid_language(language))
        .map(|language| Language {
            id: text(&language["id"]),
            name: language["aliases"].get(0).and_then(Value::as_str).filter(|alias| !alias.is_empty()).map_or_else(|| text(&language["id"]), str::to_owned),
            extensions: items(&language["extensions"]).into_iter().map(text).collect(),
            grammar: false,
            snippets: false,
        })
        .collect();
    for (key, grammar) in [("grammars", true), ("snippets", false)] {
        for item in items(&contributes[key]) {
            let Some(id) = item["language"].as_str() else { continue };
            let index = match languages.iter().position(|language| language.id == id) {
                Some(index) => index,
                None => {
                    languages.push(Language { id: id.to_owned(), name: id.to_owned(), extensions: Vec::new(), grammar: false, snippets: false });
                    languages.len() - 1
                }
            };
            if grammar {
                languages[index].grammar = true;
            } else {
                languages[index].snippets = true;
            }
        }
    }
    if languages.is_empty() {
        return table(Vec::new(), Vec::new());
    }
    languages.sort_by(|a, b| locale_compare(&a.id, &b.id));
    let check = |present: bool| Cell::Text(if present { "\u{2714}\u{fe0e}" } else { "\u{2014}" }.to_owned());
    let rows = languages
        .into_iter()
        .map(|language| {
            let extensions = language.extensions.iter().map(|extension| format!("`{extension}`")).collect::<Vec<_>>().join("&nbsp;");
            vec![Cell::Text(language.id), Cell::Text(language.name), Cell::Markdown(extensions), check(language.grammar), check(language.snippets)]
        })
        .collect();
    table(vec!["ID", "Name", "File Extensions", "Grammar", "Snippets"], rows)
}

/// languageService.ts `isValidLanguageExtensionPoint`.
fn is_valid_language(language: &Value) -> bool {
    let string_array_or_absent = |key: &str| match &language[key] {
        Value::Null => language.get(key).is_none(),
        Value::Array(items) => items.iter().all(Value::is_string),
        _ => false,
    };
    let string_or_absent = |key: &str| language.get(key).is_none() || language[key].is_string();
    truthy(language)
        && language["id"].is_string()
        && ["extensions", "filenames", "aliases", "mimetypes"].iter().all(|key| string_array_or_absent(key))
        && ["firstLine", "configuration"].iter().all(|key| string_or_absent(key))
}

/// colorExtensionPoint.ts `ColorDataRenderer`: a default that is not a hex color is a color id.
fn colors_table(colors: &Value) -> FeatureData {
    let mut colors = items(colors);
    if colors.is_empty() {
        return table(Vec::new(), Vec::new());
    }
    colors.sort_by(by_text(|color| color["id"].as_str().unwrap_or_default()));
    let default = |reference: &Value| {
        let reference = reference.as_str().unwrap_or_default();
        match reference.starts_with('#') {
            // `Color.fromHex`: red for a hex it cannot parse.
            true => Cell::Color(crate::theme::parse_hex(reference).unwrap_or(Rgba { r: 1., g: 0., b: 0., a: 1. })),
            false => code(reference),
        }
    };
    let rows = colors
        .into_iter()
        .map(|color| {
            let defaults = &color["defaults"];
            vec![code(color["id"].as_str().unwrap_or_default()), Cell::Text(text(&color["description"])), default(&defaults["dark"]), default(&defaults["light"]), default(&defaults["highContrast"])]
        })
        .collect();
    table(vec!["ID", "Description", "Dark Default", "Light Default", "High Contrast Default"], rows)
}

/// `RuntimeStatusMarkdownRenderer.createElement` without the feature access data, which only AI features record.
/// The extension's collector messages: those of the points the workbench handles, then the configuration
/// registry's.
pub(super) fn extension_messages(id: &str, registry: &config::registry::Registry) -> Vec<(Severity, String)> {
    let mut messages = crate::perf::messages(id);
    for (extension, message) in &registry.messages {
        match message {
            _ if !extension.eq_ignore_ascii_case(id) => {}
            config::registry::CollectorMessage::Warning(text) => messages.push((Severity::Warning, text.clone())),
            config::registry::CollectorMessage::Error(text) => messages.push((Severity::Error, text.clone())),
        }
    }
    messages
}

pub(super) fn runtime_status_markdown(activation: Option<crate::perf::Activation>, runtime_errors: &[String], messages: &[(Severity, String)]) -> String {
    let state = match activation {
        Some(activation) if activation.startup => format!("Activated on Startup: `{}ms`", activation.activate_call),
        Some(activation) => format!("Activated by `{}` event: `{}ms`", activation.event, activation.activate_call),
        None => "Not yet activated".to_owned(),
    };
    let mut markdown = format!("### Activation\n\n{state}");
    if !runtime_errors.is_empty() {
        markdown += &format!("\n ### Uncaught Errors ({})\n", runtime_errors.len());
        for error in runtime_errors {
            markdown += &format!("$(error)&nbsp;{error}\n\n");
        }
    }
    if !messages.is_empty() {
        markdown += &format!("\n ### Messages ({})\n", messages.len());
        for (severity, message) in messages {
            let icon = match severity {
                Severity::Error => "error",
                Severity::Warning => "warning",
                Severity::Info => "info",
            };
            markdown += &format!("$({icon})&nbsp;{message}\n\n");
        }
    }
    markdown
}

/// `#RRGGBB` (`Color.Format.CSS.formatHex`).
fn format_hex(color: Rgba) -> String {
    let byte = |channel: f32| (channel * 255.).round() as u8;
    format!("#{:02x}{:02x}{:02x}", byte(color.r), byte(color.g), byte(color.b))
}

const ROW_STRIPE: Rgba = Rgba { r: 130. / 255., g: 130. / 255., b: 130. / 255., a: 0.04 };
const ROW_HOVER: Rgba = Rgba { r: 128. / 255., g: 128. / 255., b: 128. / 255., a: 0.15 };
const CODE_BACKGROUND: Rgba = Rgba { r: 128. / 255., g: 128. / 255., b: 128. / 255., a: 0.17 };

impl Workbench {
    pub(super) fn feature_markdown(&self, id: &str, markdown: &str, cx: &mut Context<Self>) -> Div {
        let blocks = crate::markdown::parse(&crate::markdown::MarkdownString { value: markdown, is_trusted: &Value::Bool(false), support_theme_icons: true });
        let style = MarkdownStyle { font_size: 13., line_height: 19.5, foreground: self.foreground_or("foreground"), action_handler: None, code_foreground: None, code_background: None, selectable: false };
        self.markdown_blocks(id, &blocks, style, "", cx)
    }

    /// extensionFeaturesTab.ts `renderTable` with extensionEditor.css `table`: the header row and every other row
    /// striped, the hovered data row highlighted.
    pub(super) fn feature_table(&self, path: &std::path::Path, hovered: Option<usize>, headers: &[&str], rows: &[Vec<Cell>], cx: &mut Context<Self>) -> Div {
        let columns = headers.len();
        let mut grid = div().w_full().grid().grid_cols_min_content(columns.max(1) as u16);
        // `th, td { padding: 2px 16px 2px 4px }`, the last column's `2px 4px`.
        let right_padding = |column: usize| if column + 1 == columns { px(4.) } else { px(16.) };
        for (column, header) in headers.iter().enumerate() {
            grid = grid.child(div().bg(ROW_STRIPE).pl(px(4.)).pr(right_padding(column)).py(px(2.)).font_weight(FontWeight::BOLD).whitespace_nowrap().child(header.to_string()));
        }
        for (index, row) in rows.iter().enumerate() {
            // `tr:nth-child(odd)` counts the header row first.
            let background = if hovered == Some(index) { Some(ROW_HOVER) } else if index % 2 == 1 { Some(ROW_STRIPE) } else { None };
            for (column, cell) in row.iter().enumerate() {
                let path = path.to_owned();
                let content = self.feature_cell(&format!("feature-cell-{index}-{column}"), cell, cx);
                let cell = div()
                    .id(("feature-cell", index * columns + column))
                    .min_w_0()
                    .pl(px(4.))
                    .pr(right_padding(column))
                    .py(px(2.))
                    .when_some(background, |cell, background| cell.bg(background))
                    .child(content)
                    .on_hover(cx.listener(move |workbench, hovered: &bool, _, cx| {
                        let Some(editor) = workbench.extension_editors.iter_mut().find(|editor| editor.path == path) else { return };
                        if *hovered {
                            editor.hovered_feature_row = Some(index);
                        } else if editor.hovered_feature_row == Some(index) {
                            editor.hovered_feature_row = None;
                        }
                        cx.notify();
                    }));
                grid = grid.child(cell);
            }
        }
        grid
    }

    fn feature_cell(&self, id: &str, cell: &Cell, cx: &mut Context<Self>) -> AnyElement {
        match cell {
            Cell::Text(text) => div().child(text.clone()).into_any_element(),
            Cell::Markdown(markdown) => self.feature_markdown(id, markdown, cx).into_any_element(),
            Cell::Keybindings(keybindings) => div()
                .flex()
                .flex_col()
                .children(keybindings.iter().map(|chords| div().flex().children(chords.iter().enumerate().map(|(index, caps)| div().flex().when(index > 0, |chord| chord.ml(px(5.))).children(caps.iter().map(|cap| self.key_cap(cap, false)))))))
                .into_any_element(),
            Cell::Color(color) => {
                // extensionEditor.css `.colorBox`: 0.8em with a 0.1em border, black, light in dark themes.
                let border = if self.theme.kind.is_light() { gpui::rgb(0x000000) } else { gpui::rgb(0xeeeeee) };
                div()
                    .flex()
                    .items_center()
                    .child(div().size(px(10.4)).mx(px(2.6)).border(px(1.3)).border_color(border).bg(*color))
                    .child(div().font_family("Menlo").text_size(px(11.7)).bg(CODE_BACKGROUND).rounded(px(4.)).px(px(4.)).py(px(1.)).child(format_hex(*color)))
                    .into_any_element()
            }
        }
    }
}

#[cfg(test)]
mod tests;