Skip to content

Visual Studio Code, rebuilt in Rust

Rust
8.4 KB
Raw Blame
//! quickPickPin.ts: the pinned items of a quick pick, stored in workspace storage as `{ label, description, detail }`
//! (the run task picker, the terminal's run recent pickers).

use serde_json::{Map, Value, json};

use super::Workbench;
use crate::quick_input::{Button, Entry, Item};

/// The item button handles; a picker using pins keeps its other buttons off these.
pub(super) const PIN_BUTTON: i64 = 2;
pub(super) const PINNED_BUTTON: i64 = 3;

/// `_formatPinnedItems`: a Pin button first on every item (the list shown while the filter has text), and the list
/// shown while it is empty: under a "pinned" separator, a copy of each stored pin found among the items (once each,
/// its pick copied to a new handle) with a Pinned button, then the items.
pub(super) fn format_pinned<P: Clone>(mut entries: Vec<Entry>, picks: &mut Vec<P>, stored: &[Value]) -> (Vec<Entry>, Vec<Entry>) {
    let mut pinned_items: Vec<Item> = Vec::new();
    for stored in stored {
        let wanted = stored_identifier(stored);
        let found = entries.iter().find_map(|entry| match entry {
            Entry::Item(item) if item_identifier(item) == wanted => Some(item.clone()),
            _ => None,
        });
        let Some(mut item) = found else { continue };
        if pinned_items.iter().any(|pinned| item_identifier(pinned) == wanted) {
            continue;
        }
        picks.push(picks[item.handle as usize].clone());
        item.handle = picks.len() as i64 - 1;
        item.buttons.insert(0, pin_button(true));
        pinned_items.push(item);
    }
    for entry in &mut entries {
        if let Entry::Item(item) = entry {
            item.buttons.insert(0, pin_button(false));
        }
    }
    let mut with_pinned = Vec::new();
    if !pinned_items.is_empty() {
        with_pinned.push(Entry::Separator(Some("pinned".into())));
        with_pinned.extend(pinned_items.into_iter().map(Entry::Item));
    }
    with_pinned.extend(entries.iter().cloned());
    (entries, with_pinned)
}

/// `updatePinnedItems`: the Pinned button unpins the item, the Pin button pins it last; `JSON.stringify` leaves out
/// the parts the item lacks.
pub(super) fn toggle_pin(mut stored: Vec<Value>, item: &Item, unpin: bool) -> Vec<Value> {
    let identifier = item_identifier(item);
    if unpin {
        stored.retain(|pin| stored_identifier(pin) != identifier);
        return stored;
    }
    let mut pin = Map::from_iter([("label".to_owned(), json!(item.label))]);
    pin.extend(item.description.clone().map(|description| ("description".to_owned(), json!(description))));
    pin.extend(item.detail.clone().map(|detail| ("detail".to_owned(), json!(detail))));
    pin.extend(item.id.clone().map(|id| ("id".to_owned(), json!(id))));
    stored.push(Value::Object(pin));
    stored
}

fn pin_button(pinned: bool) -> Button {
    let (handle, codicon, tooltip) = if pinned { (PINNED_BUTTON, "pinned", "Pinned command") } else { (PIN_BUTTON, "pin", "Pin command") };
    Button { handle, codicon: Some(codicon.into()), tooltip: Some(tooltip.into()), ..Button::default() }
}

/// `getItemIdentifier`: the item's `id`, else label, description and detail as a template string joins them,
/// `undefined` included.
fn stored_identifier(stored: &Value) -> String {
    match stored["id"].as_str() {
        Some(id) => id.to_owned(),
        None => pin_identifier(stored["label"].as_str().unwrap_or_default(), stored["description"].as_str(), stored["detail"].as_str()),
    }
}

fn pin_identifier(label: &str, description: Option<&str>, detail: Option<&str>) -> String {
    format!("{label}{}{}", description.unwrap_or("undefined"), detail.unwrap_or("undefined"))
}

fn item_identifier(item: &Item) -> String {
    match &item.id {
        Some(id) => id.clone(),
        None => pin_identifier(&item.label, item.description.as_deref(), item.detail.as_deref()),
    }
}

/// `formatPinnedItemForStorage`: the pin without its `id`, which `toggle_pin` puts last.
fn pin_for_storage(pin: &Value) -> Value {
    let mut pin = pin.clone();
    pin.as_object_mut().expect("a pin is an object").remove("id");
    pin
}

impl Workbench {
    /// `getPinnedItems`: the pins stored under `key`, or the same pins as this session last pinned them, with the
    /// `id` storage drops, so a terminal session command pinned before the picker hid stays pinned.
    pub(super) fn pinned_items(&self, key: &str) -> Vec<Value> {
        let stored: Vec<Value> = self.workspace_storage.lock().unwrap().get(key).and_then(|raw| serde_json::from_str(raw).ok()).unwrap_or_default();
        match self.session_pins.get(key) {
            Some(pins) if pins.iter().map(pin_for_storage).eq(stored.iter().cloned()) => pins.clone(),
            _ => stored,
        }
    }

    /// `updatePinnedItems`: storage keeps each pin's label, description and detail; this session keeps its `id` too.
    pub(super) fn toggle_pinned_item(&mut self, key: &str, item: &Item, unpin: bool) {
        let pins = toggle_pin(self.pinned_items(key), item, unpin);
        let stored = pins.iter().map(pin_for_storage).collect();
        self.workspace_storage.lock().unwrap().set(key, Value::Array(stored).to_string());
        self.session_pins.insert(key.to_owned(), pins);
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::*;
    use crate::host_sync::HostSync;
    use crate::languages::Languages;
    use crate::theme::load_theme;

    fn rows(entries: &[Entry]) -> Vec<String> {
        let mut rows = Vec::new();
        for entry in entries {
            match entry {
                Entry::Item(item) => rows.push(format!("{} {}", item.label, item.buttons[0].codicon.clone().unwrap())),
                Entry::Separator(label) => rows.push(format!("-{}", label.clone().unwrap_or_default())),
                Entry::Header(_) => unreachable!(),
            }
        }
        rows
    }

    /// quickPickPin.ts with terminalRunRecentQuickPick.ts items: a session command (`id` its timestamp) matches pins by
    /// id, storage keeps only label and description, and the pin outlives the picker for this session.
    #[gpui::test]
    fn a_pinned_session_command_stays_pinned_until_the_session_ends(cx: &mut gpui::TestAppContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = load_theme(&[themes], "Dark Modern").unwrap();
        let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx));
        let key = "terminal.pinnedRecentCommands.zsh";
        let command = |handle: i64, id: Option<&str>| Item { handle, id: id.map(str::to_owned), label: "ls".into(), description: Some("~".into()), ..Item::default() };
        workbench.update(cx, |workbench, _| {
            workbench.toggle_pinned_item(key, &command(0, Some("100")), false);
            assert_eq!(workbench.workspace_storage.lock().unwrap().get(key), Some(r#"[{"label":"ls","description":"~"}]"#));

            let (_, reopened) = format_pinned(vec![Entry::Item(command(0, Some("100")))], &mut vec![()], &workbench.pinned_items(key));
            assert_eq!(rows(&reopened), ["-pinned", "ls pinned", "ls pin"], "the reopened picker keeps the pin");
            let (_, rerun) = format_pinned(vec![Entry::Item(command(0, Some("200")))], &mut vec![()], &workbench.pinned_items(key));
            assert_eq!(rows(&rerun), ["ls pin"], "another run of the command has its own id");

            workbench.session_pins.clear();
            let items = vec![Entry::Item(command(0, Some("100"))), Entry::Item(command(1, None))];
            let (_, next_session) = format_pinned(items, &mut vec![(), ()], &workbench.pinned_items(key));
            assert_eq!(rows(&next_session), ["-pinned", "ls pinned", "ls pin", "ls pin"], "only a previous session's command matches by label");

            workbench.toggle_pinned_item(key, &command(0, Some("100")), false);
            let (_, shown) = format_pinned(vec![Entry::Item(command(0, Some("100")))], &mut vec![()], &workbench.pinned_items(key));
            let Entry::Item(pinned) = &shown[1] else { panic!("the pinned copy") };
            workbench.toggle_pinned_item(key, pinned, true);
            assert_eq!(workbench.workspace_storage.lock().unwrap().get(key), Some(r#"[{"label":"ls","description":"~"}]"#), "the Pinned button removes the session command's pin only");
        });
    }
}