use std::borrow::Cow;
use std::collections::HashMap;
use std::ops::Range;
use std::rc::Rc;
use std::time::Instant;
use gpui::{
AnyElement, AnyView, App, Context, Div, ElementId, Entity, FontWeight, InteractiveElement,
KeyDownEvent, MouseButton, MouseDownEvent, Point, Render, Rgba, ScrollHandle, SharedString,
StyledText, Window, deferred, div, point, prelude::*, px,
};
use crate::controls::{WidgetContext, search_field};
use crate::easing::{ease_out_cubic, progress};
use crate::keyboard::{self, Dismiss, Key, Orientation};
use crate::lighting;
use crate::palette::Palette;
use crate::state::{
COMBO_REVEAL, ComboId, ControlHost, ControlState, ListChange, MOVE, SWITCH_SLIDE, Tag,
};
use crate::text_input::{self as text, TextInput};
pub struct Tooltip {
text: SharedString,
shortcut: Option<SharedString>,
palette: Palette,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Hint {
pub text: SharedString,
pub shortcut: Option<SharedString>,
}
impl Hint {
pub fn new(text: impl Into<SharedString>) -> Self {
Self {
text: text.into(),
shortcut: None,
}
}
pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
self.shortcut = Some(shortcut.into());
self
}
pub fn tooltip(self, palette: Palette) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static {
move |_window, cx| {
let hint = self.clone();
cx.new(move |_cx| Tooltip {
text: hint.text,
shortcut: hint.shortcut,
palette,
})
.into()
}
}
}
impl From<&str> for Hint {
fn from(text: &str) -> Self {
Hint::new(text.to_string())
}
}
impl From<String> for Hint {
fn from(text: String) -> Self {
Hint::new(text)
}
}
impl From<SharedString> for Hint {
fn from(text: SharedString) -> Self {
Hint::new(text)
}
}
impl Tooltip {
pub fn text(
text: impl Into<SharedString>,
palette: Palette,
) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static {
Hint::new(text).tooltip(palette)
}
pub fn with_shortcut(
text: impl Into<SharedString>,
shortcut: impl Into<SharedString>,
palette: Palette,
) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static {
Hint::new(text).shortcut(shortcut).tooltip(palette)
}
}
impl Render for Tooltip {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let palette = self.palette;
let dark = palette.is_dark;
let fill = if dark {
palette.soft_fill
} else {
palette.field_surface
};
div()
.px(px(8.0))
.py(px(4.0))
.flex()
.items_center()
.gap(px(8.0))
.rounded(px(5.0))
.bg(fill)
.border_1()
.border_color(lighting::rim(fill, dark))
.shadow(lighting::panel(dark))
.text_size(px(11.5))
.text_color(palette.text_primary)
.whitespace_nowrap()
.child(self.text.clone())
.children(
self.shortcut
.clone()
.map(|shortcut| div().text_color(palette.text_secondary).child(shortcut)),
)
}
}
#[derive(Clone, Debug)]
pub struct Command {
pub id: SharedString,
pub label: SharedString,
pub group: Option<SharedString>,
pub shortcut: Option<SharedString>,
}
impl Command {
pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
group: None,
shortcut: None,
}
}
pub fn group(mut self, group: impl Into<SharedString>) -> Self {
self.group = Some(group.into());
self
}
pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
self.shortcut = Some(shortcut.into());
self
}
}
#[derive(Clone, Debug)]
pub struct SearchResult {
pub id: SharedString,
pub label: SharedString,
pub detail: Option<SharedString>,
pub section: Option<SharedString>,
pub shortcut: Option<SharedString>,
leading: Option<Leading>,
group: Option<SharedString>,
}
#[derive(Clone)]
struct Leading(Rc<dyn Fn(Palette) -> AnyElement>);
impl std::fmt::Debug for Leading {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Leading(..)")
}
}
impl SearchResult {
pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
detail: None,
section: None,
shortcut: None,
leading: None,
group: None,
}
}
pub fn detail(mut self, detail: impl Into<SharedString>) -> Self {
self.detail = Some(detail.into());
self
}
pub fn section(mut self, section: impl Into<SharedString>) -> Self {
self.section = Some(section.into());
self
}
pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
self.shortcut = Some(shortcut.into());
self
}
pub fn leading<E: IntoElement + 'static>(
mut self,
render: impl Fn(Palette) -> E + 'static,
) -> Self {
self.leading = Some(Leading(Rc::new(move |palette| {
render(palette).into_any_element()
})));
self
}
}
fn command_result(command: &Command) -> SearchResult {
SearchResult {
id: command.id.clone(),
label: command.label.clone(),
detail: None,
section: None,
shortcut: command.shortcut.clone(),
leading: None,
group: command.group.clone(),
}
}
pub fn fuzzy_score(query: &str, candidate: &str) -> Option<i32> {
if query.chars().all(char::is_whitespace) {
return Some(0);
}
fuzzy_score_normalized(&query.to_lowercase(), candidate)
}
fn fuzzy_score_normalized(query: &str, candidate: &str) -> Option<i32> {
if query.chars().all(char::is_whitespace) {
return Some(0);
}
let candidate_lower = candidate.to_lowercase();
let mut haystack = candidate_lower.chars().enumerate();
let mut score = 0i32;
let mut last_index: Option<usize> = None;
let mut previous = None;
for needle in query.chars() {
if needle.is_whitespace() {
continue;
}
loop {
let (index, ch) = haystack.next()?;
let starts_word = previous.is_none_or(|previous: char| {
previous.is_whitespace() || previous == '-' || previous == '_'
});
previous = Some(ch);
if ch != needle {
continue;
}
score += if starts_word { 12 } else { 2 };
if last_index == Some(index.saturating_sub(1)) {
score += 6;
}
last_index = Some(index);
break;
}
}
Some(score - (candidate.chars().count() as i32 / 8))
}
pub fn fuzzy_filter(query: &str, commands: &[Command]) -> Vec<Command> {
matching_commands(query, commands)
.map(Clone::clone)
.collect()
}
fn matching_commands<'a>(
query: &str,
commands: &'a [Command],
) -> impl Iterator<Item = &'a Command> {
let empty = query.chars().all(char::is_whitespace);
let mut scored: Vec<(i32, usize, &Command)> = if empty {
Vec::new()
} else {
let query = query.to_lowercase();
commands
.iter()
.enumerate()
.filter_map(|(index, command)| {
let haystack = match &command.group {
Some(group) => Cow::Owned(format!("{group} {}", command.label)),
None => Cow::Borrowed(command.label.as_ref()),
};
fuzzy_score_normalized(&query, &haystack).map(|score| (score, index, command))
})
.collect()
};
scored.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
let original = if empty { commands } else { &[] };
original
.iter()
.chain(scored.into_iter().map(|(_, _, command)| command))
}
pub(crate) fn command_results(query: &str, commands: &[Command]) -> Vec<SearchResult> {
matching_commands(query, commands)
.map(command_result)
.collect()
}
pub fn rank_results(query: &str, results: &[SearchResult]) -> Vec<SearchResult> {
let empty = query.chars().all(char::is_whitespace);
let query = query.to_lowercase();
let mut searchable = String::new();
let mut rank = |result: &SearchResult| -> Option<Option<i32>> {
if let Some(score) = fuzzy_score_normalized(&query, &result.label) {
return Some(Some(score));
}
if result.detail.is_none() && result.section.is_none() {
return None;
}
let capacity = result.label.len()
+ [&result.detail, &result.section]
.into_iter()
.flatten()
.map(|part| part.len() + 1)
.sum::<usize>();
searchable.clear();
searchable.reserve(capacity);
searchable.push_str(&result.label);
for part in [&result.detail, &result.section].into_iter().flatten() {
searchable.push(' ');
searchable.push_str(part);
}
fuzzy_score_normalized(&query, &searchable).map(|_| None)
};
type Run<'a> = Vec<(Option<i32>, &'a SearchResult)>;
let mut sections: Vec<(Option<&str>, Run)> = Vec::new();
let mut positions: HashMap<Option<&str>, usize> = HashMap::new();
for result in results {
let Some(rank) = (if empty { Some(Some(0)) } else { rank(result) }) else {
continue;
};
let section = result.section.as_deref();
let index = *positions.entry(section).or_insert_with(|| {
let index = sections.len();
sections.push((section, Vec::new()));
index
});
sections[index].1.push((rank, result));
}
if !empty {
for (_, run) in &mut sections {
run.sort_by_key(|(rank, _)| std::cmp::Reverse(*rank));
}
sections.sort_by_key(|(_, run)| std::cmp::Reverse(run[0].0));
}
sections
.into_iter()
.flat_map(|(_, run)| run)
.map(|(_, result)| result.clone())
.collect()
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Line {
Label,
Detail,
}
fn matched_ranges(text: &str, query: &str, line: Line) -> Vec<Range<usize>> {
if query.trim().is_empty() {
return Vec::new();
}
let chars: Vec<(usize, char)> = text.char_indices().collect();
let same = |a: char, b: char| a.to_lowercase().eq(b.to_lowercase());
let mut ranges: Vec<Range<usize>> = Vec::new();
let byte_at = |index: usize| chars.get(index).map_or(text.len(), |ch| ch.0);
for word in query.split_whitespace() {
let needle: Vec<char> = word.chars().collect();
let starts_word = |start: usize| start == 0 || !chars[start - 1].1.is_alphanumeric();
let whole = (0..=chars.len().saturating_sub(needle.len())).find(|&start| {
start + needle.len() <= chars.len()
&& (line == Line::Label || starts_word(start))
&& needle
.iter()
.enumerate()
.all(|(offset, &ch)| same(chars[start + offset].1, ch))
});
if let Some(start) = whole {
ranges.push(byte_at(start)..byte_at(start + needle.len()));
} else if line == Line::Label {
let checkpoint = ranges.len();
let mut from = 0;
for &ch in &needle {
let Some(index) = (from..chars.len()).find(|&i| same(chars[i].1, ch)) else {
ranges.truncate(checkpoint);
break;
};
ranges.push(byte_at(index)..byte_at(index + 1));
from = index + 1;
}
}
}
ranges.sort_unstable_by_key(|range| range.start);
let mut merged = 0;
for index in 0..ranges.len() {
let range = ranges[index].clone();
if merged > 0 && range.start <= ranges[merged - 1].end {
ranges[merged - 1].end = ranges[merged - 1].end.max(range.end);
} else {
ranges[merged] = range;
merged += 1;
}
}
ranges.truncate(merged);
ranges
}
fn emphasised(text: &SharedString, query: &str, line: Line) -> StyledText {
StyledText::new(text.clone()).with_highlights(
matched_ranges(text, query, line)
.into_iter()
.map(|range| (range, FontWeight::SEMIBOLD.into())),
)
}
pub const COMMAND_ROW_HEIGHT: f32 = 30.0;
const DETAIL_ROW_HEIGHT: f32 = 44.0;
const SECTION_HEIGHT: f32 = 20.0;
const ROW_GAP: f32 = 1.0;
const ROW_INSET: f32 = 9.0;
const LEADING_SIZE: f32 = 20.0;
const ROW_SPACING: f32 = 8.0;
const INLINE_RESULT_MAX_HEIGHT: f32 = 300.0;
pub(crate) const PALETTE_RESULT_MAX_HEIGHT: f32 = 340.0;
struct RowPlacement {
heading: bool,
heading_run: usize,
top: f32,
height: f32,
}
fn row_layout(results: &[SearchResult]) -> Vec<RowPlacement> {
let mut previous: Option<&str> = None;
let mut runs: HashMap<&str, usize> = HashMap::new();
let mut top = 0.0;
results
.iter()
.map(|result| {
let section = result.section.as_deref();
let heading = section.is_some() && section != previous;
previous = section;
let heading_run = if heading {
let count = runs
.entry(section.expect("a heading has a section"))
.or_default();
let run = *count;
*count += 1;
run
} else {
0
};
if heading {
top += SECTION_HEIGHT + ROW_GAP;
}
let height = if result.detail.is_some() {
DETAIL_ROW_HEIGHT
} else {
COMMAND_ROW_HEIGHT
};
let placement = RowPlacement {
heading,
heading_run,
top,
height,
};
top += height + ROW_GAP;
placement
})
.collect()
}
fn arrival(state: &ControlState, key: Tag, fresh: bool) -> f32 {
if fresh {
state.tween(key, 1.0, SWITCH_SLIDE)
} else {
state.tween_from(key, 0.0, 1.0, SWITCH_SLIDE)
}
}
fn result_rows<V: ControlHost>(
id: &'static str,
emphasis: &str,
results: &[SearchResult],
highlighted: usize,
ctx: WidgetContext<'_, '_, '_, V>,
on_activate: &Activate<V>,
) -> (Vec<AnyElement>, Vec<Range<f32>>) {
let WidgetContext { palette, view, cx } = ctx;
let state = view.control_state();
let fresh = !state.present(id);
let has_leading = results.iter().any(|result| result.leading.is_some());
let mut elements: Vec<AnyElement> = Vec::with_capacity(results.len());
let mut extents = Vec::with_capacity(results.len());
for (index, (result, placement)) in results.iter().zip(row_layout(results)).enumerate() {
if placement.heading
&& let Some(section) = &result.section
{
let key = |part: &'static str| Tag::new((id, part, section, placement.heading_run));
let shown = arrival(state, key("section-shown"), fresh);
let top = placement.top - SECTION_HEIGHT - ROW_GAP;
let offset = state.tween(key("section-place"), top, MOVE) - top;
elements.push(section_heading(
section,
has_leading,
shown,
offset,
palette,
));
}
let cx: &mut Context<V> = &mut *cx;
let look = RowLook {
active: index == highlighted,
has_leading,
fresh,
palette,
};
elements.push(result_row(
id,
result,
emphasis,
&placement,
look,
state,
cx,
on_activate.clone(),
));
extents.push(placement.top..placement.top + placement.height);
}
(elements, extents)
}
fn visible_result_range(placements: &[RowPlacement], offset: f32, viewport: f32) -> Range<usize> {
let viewport = viewport.max(1.0);
let scroll_top = (-offset).max(0.0);
let start = scroll_top - viewport - SECTION_HEIGHT;
let end = scroll_top + 2.0 * viewport + SECTION_HEIGHT;
placements.partition_point(|row| row.top + row.height < start)
..placements.partition_point(|row| row.top <= end)
}
#[allow(clippy::too_many_arguments)]
fn visible_result_rows<V: ControlHost>(
id: &'static str,
emphasis: &str,
results: &[SearchResult],
placements: &[RowPlacement],
visible: Range<usize>,
highlighted: usize,
ctx: WidgetContext<'_, '_, '_, V>,
on_activate: &Activate<V>,
) -> Vec<AnyElement> {
let WidgetContext { palette, view, cx } = ctx;
let state = view.control_state();
let fresh = !state.present(id);
let has_leading = results.iter().any(|result| result.leading.is_some());
let mut elements = Vec::with_capacity(2 * visible.len());
for index in visible {
let (result, placement) = (&results[index], &placements[index]);
if placement.heading
&& let Some(section) = &result.section
{
let key = |part: &'static str| Tag::new((id, part, section, placement.heading_run));
let shown = arrival(state, key("section-shown"), fresh);
let top = placement.top - SECTION_HEIGHT - ROW_GAP;
let offset = state.tween(key("section-place"), top, MOVE) - top;
elements.push(
div()
.absolute()
.top(px(top))
.left_0()
.right_0()
.child(section_heading(
section,
has_leading,
shown,
offset,
palette,
))
.into_any_element(),
);
}
let look = RowLook {
active: index == highlighted,
has_leading,
fresh,
palette,
};
elements.push(
div()
.absolute()
.top(px(placement.top))
.left_0()
.right_0()
.child(result_row(
id,
result,
emphasis,
placement,
look,
state,
cx,
on_activate.clone(),
))
.into_any_element(),
);
}
elements
}
fn section_heading(
section: &SharedString,
has_leading: bool,
shown: f32,
offset: f32,
palette: Palette,
) -> AnyElement {
let inset = if has_leading {
ROW_INSET + LEADING_SIZE + ROW_SPACING
} else {
ROW_INSET
};
div()
.relative()
.top(px(offset))
.h(px(SECTION_HEIGHT))
.flex_none()
.px(px(inset))
.flex()
.items_center()
.opacity(shown)
.text_size(px(11.5))
.font_weight(FontWeight::MEDIUM)
.text_color(palette.text_secondary)
.child(section.clone())
.into_any_element()
}
#[derive(Clone, Copy)]
struct RowLook {
active: bool,
has_leading: bool,
fresh: bool,
palette: Palette,
}
#[allow(clippy::too_many_arguments)]
fn result_row<V: ControlHost>(
id: &'static str,
result: &SearchResult,
emphasis: &str,
placement: &RowPlacement,
look: RowLook,
state: &ControlState,
cx: &mut Context<V>,
on_activate: Activate<V>,
) -> AnyElement {
let RowLook {
active,
has_leading,
fresh,
palette,
} = look;
let key = |part: &'static str| Tag::new((id, part, &result.id));
let on = state.blend(key("lit"), active, SWITCH_SLIDE);
let secondary = crate::color::lerp(palette.text_secondary, palette.soft_label, on);
let shown = arrival(state, key("shown"), fresh);
let offset = state.tween(key("place"), placement.top, MOVE) - placement.top;
let picked = result.id.clone();
div()
.id(ElementId::Name(format!("{id}-result-{}", result.id).into()))
.relative()
.top(px(offset))
.opacity(shown)
.h(px(placement.height))
.flex_none()
.w_full()
.px(px(ROW_INSET))
.flex()
.items_center()
.gap(px(ROW_SPACING))
.rounded(px(5.0))
.cursor_pointer()
.text_size(px(12.5))
.text_color(crate::color::lerp(
palette.text_primary,
palette.soft_label,
on,
))
.when(on > 0.01, |el| {
el.bg(lighting::lit_at(palette.soft_fill, 0.08, on))
})
.when(!active, |el| {
el.hover(move |style| style.bg(palette.row_hover))
})
.on_click(cx.listener(move |this, _event, window, cx| {
on_activate(this, picked.clone(), window, cx);
cx.notify();
}))
.when(has_leading, |el| {
el.child(
div()
.size(px(LEADING_SIZE))
.flex_none()
.flex()
.items_center()
.justify_center()
.children(result.leading.as_ref().map(|leading| (leading.0)(palette))),
)
})
.children(
result
.group
.clone()
.map(|group| div().flex_none().text_color(secondary).child(group)),
)
.child(
div()
.flex_1()
.min_w(px(0.0))
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.truncate()
.child(emphasised(&result.label, emphasis, Line::Label)),
)
.children(result.detail.as_ref().map(|detail| {
div()
.truncate()
.text_size(px(11.5))
.text_color(secondary)
.child(emphasised(detail, emphasis, Line::Detail))
})),
)
.children(result.shortcut.clone().map(|shortcut| {
div()
.flex_none()
.text_size(px(11.5))
.text_color(secondary)
.child(shortcut)
}))
.into_any_element()
}
pub fn command_list<V: ControlHost>(
id: &'static str,
matches: &[Command],
highlighted: usize,
ctx: WidgetContext<'_, '_, '_, V>,
on_activate: impl Fn(&mut V, SharedString, &mut Window, &mut Context<V>) + 'static,
) -> Div {
let results: Vec<SearchResult> = matches.iter().map(command_result).collect();
let on_activate: Activate<V> = Rc::new(on_activate);
let (rows, _) = result_rows(id, "", &results, highlighted, ctx, &on_activate);
div()
.flex()
.flex_col()
.gap(px(ROW_GAP))
.overflow_hidden()
.children(rows)
}
pub(crate) type Dismissed<V> = Rc<dyn Fn(&mut V, &mut Window, &mut Context<V>)>;
pub(crate) type Activate<V> = Rc<dyn Fn(&mut V, SharedString, &mut Window, &mut Context<V>)>;
#[allow(clippy::too_many_arguments)]
pub fn search_list<V: ControlHost>(
id: &'static str,
query: &Entity<TextInput>,
items: &[Command],
mut ctx: WidgetContext<'_, '_, '_, V>,
window: &Window,
on_activate: impl Fn(&mut V, SharedString, &mut Window, &mut Context<V>) + 'static,
) -> Div {
let palette = ctx.palette;
let on_activate: Activate<V> = Rc::new(on_activate);
let text = query.read(ctx.cx).shared_text();
let matches = fuzzy_filter(&text, items);
let ids: Rc<[SharedString]> = matches.iter().map(|command| command.id.clone()).collect();
let (highlighted, _) = ctx.view.control_state().follow_list(id, &text, &ids);
let rows = {
let on_activate = on_activate.clone();
command_list(
id,
&matches,
highlighted,
ctx.reborrow(),
move |view, id, window, cx| on_activate(view, id, window, cx),
)
};
let cx: &mut Context<V> = &mut *ctx.cx;
let list = div()
.flex()
.flex_col()
.gap(px(6.0))
.child(search_field(id, query, palette, window, cx))
.child(rows);
list_keys(list, id, ids, None, cx, on_activate)
}
#[allow(clippy::too_many_arguments)]
pub fn ranked_search_list<V: ControlHost>(
id: &'static str,
query: &Entity<TextInput>,
results: &[SearchResult],
start: Rgba,
end: Rgba,
mut ctx: WidgetContext<'_, '_, '_, V>,
window: &Window,
on_activate: impl Fn(&mut V, SharedString, &mut Window, &mut Context<V>) + 'static,
) -> Div {
let palette = ctx.palette;
let text = query.read(ctx.cx).shared_text();
let on_activate: Activate<V> = Rc::new(on_activate);
let list = result_list(
id,
&text,
&text,
results,
INLINE_RESULT_MAX_HEIGHT,
ctx.reborrow(),
on_activate.clone(),
);
let state = ctx.view.control_state();
let cx: &mut Context<V> = &mut *ctx.cx;
let element = div()
.flex()
.flex_col()
.gap(px(6.0))
.child(search_field(id, query, palette, window, cx))
.child(result_viewport(
id,
list.elements,
&list.navigation,
"No results",
(start, end),
palette,
state,
));
list_keys(
element,
id,
list.ids,
Some(list.navigation),
cx,
on_activate,
)
}
pub(crate) struct ResultList {
elements: Vec<AnyElement>,
ids: Rc<[SharedString]>,
navigation: Rc<ResultNavigation>,
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn result_list<V: ControlHost>(
id: &'static str,
query: &str,
emphasis: &str,
results: &[SearchResult],
max_height: f32,
ctx: WidgetContext<'_, '_, '_, V>,
on_activate: Activate<V>,
) -> ResultList {
let ids: Rc<[SharedString]> = results.iter().map(|result| result.id.clone()).collect();
let state = ctx.view.control_state();
let (highlighted, change) = state.follow_list(id, query, &ids);
let scroll = state.scroll((id, "list"));
let placements = row_layout(results);
let rows = placements
.iter()
.map(|placement| placement.top..placement.top + placement.height)
.collect();
let navigation = Rc::new(ResultNavigation {
scroll,
rows,
max_height,
});
match change {
ListChange::Reset => navigation.scroll.set_offset(Point::default()),
ListChange::Moved => navigation.reveal(highlighted),
ListChange::Same => {}
}
let painted_height = f32::from(navigation.scroll.bounds().size.height);
let viewport = if painted_height > 0.0 {
painted_height
} else {
max_height
};
let visible = visible_result_range(
&placements,
f32::from(navigation.scroll.offset().y),
viewport,
);
let elements = visible_result_rows(
id,
emphasis,
results,
&placements,
visible,
highlighted,
ctx,
&on_activate,
);
ResultList {
elements,
ids,
navigation,
}
}
fn result_viewport(
id: &'static str,
rows: Vec<AnyElement>,
navigation: &ResultNavigation,
empty_message: &'static str,
(start, end): (Rgba, Rgba),
palette: Palette,
state: &ControlState,
) -> Div {
let empty = navigation.rows.is_empty();
div()
.relative()
.child(
div()
.id(ElementId::Name(format!("{id}-list").into()))
.max_h(px(navigation.max_height))
.flex()
.flex_col()
.overflow_y_scroll()
.restrict_scroll_to_axis()
.track_scroll(&navigation.scroll)
.child(
div()
.relative()
.flex_none()
.w_full()
.h(px(navigation.content_height()))
.children(rows),
)
.when(empty, |el| {
el.child(
div()
.h(px(COMMAND_ROW_HEIGHT))
.px(px(ROW_INSET))
.flex()
.items_center()
.text_size(px(12.5))
.font_weight(FontWeight::NORMAL)
.text_color(palette.text_secondary)
.child(empty_message),
)
}),
)
.children(crate::scroll::scroll_fades(
state,
id,
&navigation.scroll,
crate::scroll::ScrollAxis::Vertical,
start,
end,
))
}
struct ResultNavigation {
scroll: ScrollHandle,
rows: Vec<Range<f32>>,
max_height: f32,
}
impl ResultNavigation {
fn content_height(&self) -> f32 {
self.rows.last().map_or(0.0, |row| row.end)
}
fn viewport_height(&self) -> f32 {
self.content_height().min(self.max_height)
}
fn reveal(&self, index: usize) {
let Some(row) = self.rows.get(index) else {
return;
};
let viewport = self.viewport_height();
let offset = self.scroll.offset();
let next = revealed_offset(
f32::from(offset.y),
self.content_height() - viewport,
0.0..viewport,
row.clone(),
);
self.scroll.set_offset(point(offset.x, px(next)));
}
}
fn page_target(key: Key, current: usize, rows: &[Range<f32>], viewport: f32) -> Option<usize> {
let last = rows.len().checked_sub(1)?;
let current = current.min(last);
let page = viewport.max(1.0);
match key {
Key::PageDown => {
let threshold = rows[current].start + page;
Some(
((current + 1)..=last)
.find(|&index| rows[index].start >= threshold)
.unwrap_or(last),
)
}
Key::PageUp => {
let threshold = rows[current].start - page;
Some(
(0..current)
.rev()
.find(|&index| rows[index].start <= threshold)
.unwrap_or(0),
)
}
_ => None,
}
}
fn revealed_offset(offset: f32, max_offset: f32, viewport: Range<f32>, item: Range<f32>) -> f32 {
let margin = crate::scroll::SCROLL_FADE.min((viewport.end - viewport.start) / 4.0);
let wanted = if item.start + offset < viewport.start + margin {
viewport.start + margin - item.start
} else if item.end + offset > viewport.end - margin {
viewport.end - margin - item.end
} else {
offset
};
wanted.clamp(-max_offset.max(0.0), 0.0)
}
fn navigate_list<V: ControlHost>(
this: &mut V,
id: &'static str,
ids: &[SharedString],
key: Key,
navigation: Option<&ResultNavigation>,
cx: &mut Context<V>,
) {
let count = ids.len();
let state = this.control_state();
let here = state.list_position(id).min(count.saturating_sub(1));
let moved = match (key, navigation) {
(Key::PageUp | Key::PageDown, Some(navigation)) => {
page_target(key, here, &navigation.rows, navigation.viewport_height())
}
(Key::PageUp, None) => count.checked_sub(1).map(|_| here.saturating_sub(10)),
(Key::PageDown, None) => count.checked_sub(1).map(|last| (here + 10).min(last)),
_ => keyboard::step(key, Orientation::Vertical, here, count),
};
if let Some(moved) = moved
&& let Some(picked) = ids.get(moved)
{
state.highlight_list_item(id, moved, picked);
if let Some(navigation) = navigation {
navigation.reveal(moved);
}
cx.notify();
}
}
fn list_keys<V: ControlHost, E: InteractiveElement>(
element: E,
id: &'static str,
ids: Rc<[SharedString]>,
navigation: Option<Rc<ResultNavigation>>,
cx: &mut Context<V>,
on_activate: Activate<V>,
) -> E {
let step = {
let ids = ids.clone();
Rc::new(move |this: &mut V, key: Key, cx: &mut Context<V>| {
navigate_list(this, id, &ids, key, navigation.as_deref(), cx);
})
};
let step_down = step.clone();
let step_page = step.clone();
element
.on_action(cx.listener(move |this, _: &text::Up, _window, cx| {
step(this, Key::Up, cx);
}))
.on_action(cx.listener(move |this, _: &text::Down, _window, cx| {
step_down(this, Key::Down, cx);
}))
.on_key_down(cx.listener(move |this, event: &KeyDownEvent, _window, cx| {
if let Some(key @ (Key::PageUp | Key::PageDown)) = keyboard::key(event) {
cx.stop_propagation();
step_page(this, key, cx);
}
}))
.on_action(cx.listener(move |this, _: &text::Enter, window, cx| {
let here = this
.control_state()
.list_position(id)
.min(ids.len().saturating_sub(1));
if let Some(picked) = ids.get(here) {
on_activate(this, picked.clone(), window, cx);
cx.notify();
}
}))
}
pub(crate) fn palette_opened_at(state: &ControlState, id: ComboId) -> Option<Instant> {
state
.palette_overlay
.as_ref()
.filter(|open| open.id == id)
.map(|open| open.opened_at)
}
fn closing_palette<V: ControlHost>(
on_activate: impl Fn(&mut V, SharedString, &mut Window, &mut Context<V>) + 'static,
) -> Activate<V> {
Rc::new(move |view: &mut V, picked, window, cx| {
view.control_state_mut().close_palette(window, cx);
on_activate(view, picked, window, cx);
})
}
#[allow(clippy::too_many_arguments)]
pub fn command_palette<V: ControlHost>(
id: ComboId,
query: &Entity<TextInput>,
commands: &[Command],
mut ctx: WidgetContext<'_, '_, '_, V>,
window: &Window,
on_activate: impl Fn(&mut V, SharedString, &mut Window, &mut Context<V>) + 'static,
) -> Option<impl IntoElement> {
let opened_at = palette_opened_at(ctx.view.control_state(), id)?;
let text = query.read(ctx.cx).shared_text();
let matches = command_results(&text, commands);
let on_activate = closing_palette(on_activate);
let list = result_list(
id,
&text,
"",
&matches,
PALETTE_RESULT_MAX_HEIGHT,
ctx.reborrow(),
on_activate.clone(),
);
Some(palette_with_results(
id,
opened_at,
query,
list,
"No matching commands",
ctx,
window,
on_activate,
))
}
#[allow(clippy::too_many_arguments)]
pub fn ranked_command_palette<V: ControlHost>(
id: ComboId,
query: &Entity<TextInput>,
results: &[SearchResult],
mut ctx: WidgetContext<'_, '_, '_, V>,
window: &Window,
on_activate: impl Fn(&mut V, SharedString, &mut Window, &mut Context<V>) + 'static,
) -> Option<impl IntoElement> {
let opened_at = palette_opened_at(ctx.view.control_state(), id)?;
let text = query.read(ctx.cx).shared_text();
let on_activate = closing_palette(on_activate);
let list = result_list(
id,
&text,
&text,
results,
PALETTE_RESULT_MAX_HEIGHT,
ctx.reborrow(),
on_activate.clone(),
);
Some(palette_with_results(
id,
opened_at,
query,
list,
"No results",
ctx,
window,
on_activate,
))
}
#[allow(clippy::too_many_arguments)]
fn palette_with_results<V: ControlHost>(
id: ComboId,
opened_at: Instant,
query: &Entity<TextInput>,
list: ResultList,
empty_message: &'static str,
ctx: WidgetContext<'_, '_, '_, V>,
window: &Window,
on_activate: Activate<V>,
) -> impl IntoElement {
let WidgetContext { palette, view, cx } = ctx;
let reveal = ease_out_cubic(progress(
opened_at,
view.control_state().scaled(COMBO_REVEAL),
));
let panel = palette_panel(
id,
query,
list,
empty_message,
WidgetContext { palette, view, cx },
window,
on_activate,
Rc::new(|this: &mut V, window: &mut Window, cx: &mut Context<V>| {
this.control_state_mut().close_palette(window, cx);
}),
)
.mt(gpui::relative(0.16))
.relative()
.top(px(-6.0 * (1.0 - reveal)))
.opacity(reveal)
.w(px(PALETTE_WIDTH))
.max_w(gpui::relative(0.9))
.rounded(px(10.0))
.border_1()
.border_color(lighting::rim(palette_fill(palette), palette.is_dark))
.shadow(lighting::panel(palette.is_dark));
deferred(
div()
.id(ElementId::Name(format!("{id}-scrim").into()))
.absolute()
.inset_0()
.flex()
.flex_col()
.items_center()
.bg(crate::color::with_alpha(
palette.scrim(),
palette.scrim().alpha * reveal,
))
.occlude()
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, _event: &MouseDownEvent, window, cx| {
this.control_state_mut().close_palette(window, cx);
cx.notify();
}),
)
.child(panel),
)
.priority(180)
}
pub(crate) const PALETTE_WIDTH: f32 = 520.0;
pub(crate) const PALETTE_PADDING: f32 = 8.0;
const PALETTE_GAP: f32 = 6.0;
pub(crate) fn palette_fill(palette: Palette) -> Rgba {
if palette.is_dark {
palette.soft_fill
} else {
palette.field_surface
}
}
#[cfg(feature = "command-bar-window")]
pub(crate) fn palette_panel_height(list: &ResultList) -> f32 {
let rows = if list.navigation.rows.is_empty() {
COMMAND_ROW_HEIGHT
} else {
list.navigation.viewport_height()
};
2.0 * PALETTE_PADDING + crate::controls::CONTROL_HEIGHT + PALETTE_GAP + rows
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn palette_panel<V: ControlHost>(
id: ComboId,
query: &Entity<TextInput>,
list: ResultList,
empty_message: &'static str,
ctx: WidgetContext<'_, '_, '_, V>,
window: &Window,
on_activate: Activate<V>,
on_dismiss: Dismissed<V>,
) -> Div {
let WidgetContext { palette, view, cx } = ctx;
let state = view.control_state();
let fill = palette_fill(palette);
let panel = div()
.flex()
.flex_col()
.gap(px(PALETTE_GAP))
.p(px(PALETTE_PADDING))
.bg(fill)
.occlude()
.on_action(cx.listener(move |this, _: &Dismiss, window, cx| {
on_dismiss(this, window, cx);
cx.notify();
}))
.child(search_field(id, query, palette, window, cx))
.child(result_viewport(
id,
list.elements,
&list.navigation,
empty_message,
(fill, fill),
palette,
state,
));
list_keys(panel, id, list.ids, Some(list.navigation), cx, on_activate)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn word_starts_outrank_scattered_letters() {
let open_file = fuzzy_score("opf", "Open File").expect("matches");
let scattered = fuzzy_score("opf", "Optional Prefix").expect("matches");
assert!(
open_file > scattered,
"expected Open File ({open_file}) above Optional Prefix ({scattered})"
);
}
#[test]
fn a_query_that_is_not_a_subsequence_does_not_match() {
assert!(fuzzy_score("zzz", "Open File").is_none());
assert!(fuzzy_score("elif", "Open File").is_none());
}
#[test]
fn an_empty_query_keeps_everything_in_its_original_order() {
let commands = vec![
Command::new("b", "Much longer first command"),
Command::new("a", "First"),
];
for query in ["", " \t\n"] {
let filtered = fuzzy_filter(query, &commands);
let ids: Vec<&str> = filtered.iter().map(|command| command.id.as_ref()).collect();
assert_eq!(ids, vec!["b", "a"]);
}
}
#[test]
fn consecutive_unicode_characters_get_the_same_bonus_as_ascii() {
assert_eq!(fuzzy_score("été", "été"), fuzzy_score("ete", "ete"));
assert_eq!(fuzzy_score("b", "a\tb"), fuzzy_score("b", "a b"));
}
#[test]
fn the_group_is_searched_along_with_the_label() {
let commands = vec![Command::new("save", "Save").group("File")];
assert_eq!(fuzzy_filter("file sa", &commands).len(), 1);
}
#[test]
fn emphasis_prefers_a_whole_match_and_merges_overlapping_words() {
assert_eq!(
matched_ranges("Design system", "sign des", Line::Label),
vec![0..6]
);
assert_eq!(
matched_ranges("Open File", "opf", Line::Label),
vec![0..2, 5..6]
);
}
#[test]
fn emphasis_uses_valid_unicode_byte_boundaries() {
assert_eq!(
matched_ranges("Café résumé", "fé su", Line::Label),
vec![2..5, 9..11]
);
assert!(matched_ranges("Café", "", Line::Label).is_empty());
}
#[test]
fn a_detail_line_emphasises_only_runs_that_start_a_word() {
let detail = "Project board · 2 minutes ago";
assert!(matched_ranges(detail, "de", Line::Detail).is_empty());
assert_eq!(matched_ranges(detail, "boa", Line::Detail), vec![8..11]);
assert!(matched_ranges("Visited this morning", "in", Line::Detail).is_empty());
assert_eq!(
matched_ranges("Visited this morning", "mor", Line::Detail),
vec![13..16]
);
assert_eq!(
matched_ranges("Design review", "de", Line::Label),
vec![0..2]
);
assert_eq!(matched_ranges("Morning", "in", Line::Label), vec![4..6]);
}
fn sources() -> Vec<SearchResult> {
[
(
"tab-design",
"Design review",
"Project board · 2 minutes ago",
"Open tabs",
),
(
"tab-release",
"Release checklist",
"Draft · Current window",
"Open tabs",
),
(
"tab-insights",
"Traffic insights",
"Analytics · Current window",
"Open tabs",
),
("tab-issues", "Issue tracker", "42 open tasks", "Open tabs"),
(
"bookmark-system",
"Design system",
"Components and colour recipes",
"Bookmarks",
),
(
"bookmark-keys",
"Keyboard shortcuts",
"Reference · Documentation",
"Bookmarks",
),
(
"bookmark-api",
"API reference",
"Framework documentation",
"Bookmarks",
),
(
"bookmark-roadmap",
"Project roadmap",
"Milestones and plans",
"Bookmarks",
),
(
"file-budget",
"Quarterly budget",
"Shared documents · Updated today",
"Files",
),
(
"file-summary",
"Meeting summary",
"Notes · Updated yesterday",
"Files",
),
(
"history-notes",
"Design notes",
"Visited this morning",
"History",
),
(
"history-changelog",
"Release notes",
"Visited yesterday",
"History",
),
(
"action-invite",
"Invite teammate",
"Share this workspace",
"Actions",
),
(
"action-export",
"Export report",
"Save a local copy",
"Actions",
),
]
.into_iter()
.map(|(id, label, detail, section)| {
SearchResult::new(id, label).detail(detail).section(section)
})
.collect()
}
#[test]
fn ranking_keeps_each_section_together() {
let sources = sources();
for query in ["", "de", "re", "design", "no", "book"] {
let ranked = rank_results(query, &sources);
let mut seen: Vec<&str> = Vec::new();
for result in &ranked {
let section = result
.section
.as_deref()
.expect("every source has a section");
if seen.last() != Some(§ion) {
assert!(
!seen.contains(§ion),
"{section} heads two runs for {query:?}"
);
seen.push(section);
}
}
}
let ids = |query: &str| -> Vec<SharedString> {
rank_results(query, &sources)
.into_iter()
.map(|result| result.id)
.collect()
};
let all: Vec<SharedString> = sources.iter().map(|result| result.id.clone()).collect();
assert_eq!(ids(""), all);
assert_eq!(
ids("design"),
["tab-design", "bookmark-system", "history-notes"]
);
assert_eq!(
ids("book"),
[
"bookmark-system",
"bookmark-keys",
"bookmark-api",
"bookmark-roadmap"
]
);
assert!(ids("zzz").is_empty());
}
#[test]
fn many_distinct_sections_keep_source_order() {
let results: Vec<_> = (0..2_000)
.map(|index| {
SearchResult::new(format!("item-{index}"), "Entry")
.section(format!("Section {index}"))
})
.collect();
let ranked = rank_results("", &results);
assert_eq!(ranked.len(), results.len());
assert!(ranked.iter().zip(&results).all(|(a, b)| a.id == b.id));
}
#[test]
fn ranking_scores_the_label_not_the_length_of_the_detail() {
let results = [
SearchResult::new("long", "Design review")
.detail("A detail line long enough to cost several points of length"),
SearchResult::new("short", "Design notes").detail("Brief"),
SearchResult::new("detail-only", "Weekly sync").detail("Design"),
];
let ranked: Vec<SharedString> = rank_results("design", &results)
.into_iter()
.map(|result| result.id)
.collect();
assert_eq!(ranked, ["long", "short", "detail-only"]);
}
#[test]
fn section_headings_take_room_but_no_keyboard_step() {
let results = [
SearchResult::new("a", "First")
.section("Tabs")
.detail("Detail"),
SearchResult::new("b", "Second").section("Tabs"),
SearchResult::new("c", "Third"),
SearchResult::new("d", "Fourth")
.section("Bookmarks")
.detail("Detail"),
];
let layout = row_layout(&results);
assert_eq!(
layout.iter().map(|row| row.heading).collect::<Vec<_>>(),
[true, false, false, true]
);
assert_eq!(
layout.iter().map(|row| row.top).collect::<Vec<_>>(),
[21.0, 66.0, 97.0, 149.0]
);
assert_eq!(
layout.iter().map(|row| row.height).collect::<Vec<_>>(),
[
DETAIL_ROW_HEIGHT,
COMMAND_ROW_HEIGHT,
COMMAND_ROW_HEIGHT,
DETAIL_ROW_HEIGHT
]
);
}
#[test]
fn a_long_result_list_builds_only_the_window_around_its_scroll() {
let results: Vec<_> = (0..10_000)
.map(|index| SearchResult::new(format!("item-{index}"), "Entry"))
.collect();
let layout = row_layout(&results);
let target = 5_000;
let visible = visible_result_range(&layout, -layout[target].top, 300.0);
assert!(visible.contains(&target));
assert!(visible.len() < 40, "offscreen rows must stay unbuilt");
assert_eq!(visible_result_range(&layout, 0.0, 300.0).start, 0);
}
#[test]
fn page_navigation_moves_by_viewport_and_stops_at_edges() {
let rows: Vec<Range<f32>> = [21.0, 66.0, 99.0, 153.0, 198.0, 243.0]
.into_iter()
.map(|top| top..top + 30.0)
.collect();
assert_eq!(page_target(Key::PageDown, 0, &rows, 100.0), Some(3));
assert_eq!(page_target(Key::PageUp, 3, &rows, 100.0), Some(0));
assert_eq!(page_target(Key::PageDown, 3, &rows, 100.0), Some(5));
assert_eq!(page_target(Key::PageUp, 0, &rows, 100.0), Some(0));
assert_eq!(page_target(Key::PageDown, 0, &[], 100.0), None);
}
#[test]
fn highlighted_result_clears_scroll_edge_fades() {
assert_eq!(revealed_offset(0.0, 300.0, 0.0..100.0, 90.0..110.0), -35.0);
assert_eq!(
revealed_offset(-130.0, 300.0, 0.0..100.0, 120.0..140.0),
-95.0
);
assert_eq!(revealed_offset(0.0, 300.0, 0.0..100.0, 0.0..20.0), 0.0);
assert_eq!(
revealed_offset(-295.0, 300.0, 0.0..100.0, 380.0..400.0),
-300.0
);
}
#[test]
fn long_inline_results_page_to_a_row_inside_their_own_viewport() {
let results: Vec<_> = (0..14)
.map(|index| {
SearchResult::new(format!("result-{index}"), format!("Result {index}"))
.section(if index < 7 { "Tabs" } else { "Files" })
.detail("A second line")
})
.collect();
let navigation = ResultNavigation {
scroll: ScrollHandle::new(),
rows: row_layout(&results)
.iter()
.map(|row| row.top..row.top + row.height)
.collect(),
max_height: INLINE_RESULT_MAX_HEIGHT,
};
let viewport = navigation.viewport_height();
assert_eq!(viewport, INLINE_RESULT_MAX_HEIGHT);
let target = page_target(Key::PageDown, 0, &navigation.rows, viewport)
.expect("page down reaches a result");
let row = navigation.rows[target].clone();
assert!(row.start >= viewport);
let offset = revealed_offset(
0.0,
navigation.content_height() - viewport,
0.0..viewport,
row.clone(),
);
assert!(offset < 0.0);
assert!(row.end + offset <= viewport - crate::scroll::SCROLL_FADE);
}
#[test]
fn a_short_list_is_its_own_viewport() {
let results: Vec<_> = (0..3)
.map(|index| SearchResult::new(format!("r{index}"), "Result"))
.collect();
let navigation = ResultNavigation {
scroll: ScrollHandle::new(),
rows: row_layout(&results)
.iter()
.map(|row| row.top..row.top + row.height)
.collect(),
max_height: PALETTE_RESULT_MAX_HEIGHT,
};
assert_eq!(navigation.content_height(), 3.0 * COMMAND_ROW_HEIGHT + 2.0);
assert_eq!(navigation.viewport_height(), navigation.content_height());
assert_eq!(
page_target(
Key::PageDown,
0,
&navigation.rows,
navigation.viewport_height()
),
Some(2)
);
}
}
#[cfg(test)]
#[path = "emphasis_bench.rs"]
mod emphasis_bench;
#[cfg(test)]
#[path = "search_bench.rs"]
mod search_bench;