use std::{cell::RefCell, rc::Rc};
use arc_motion::{
ArcPresence, BlurFallback, arc_spring_with_options, is_reduced_motion, spring::SpringOptions,
};
use arc_tokens::{
ActiveArcTheme as _, CommandPaletteTokens, ControlHeights, Radii, Shadows, Spacing, Typography,
};
use gpui_kit::{
App, Context, ElementId, Entity, FocusHandle, Focusable as _, IntoElement, KeyDownEvent,
MouseMoveEvent, ParentElement, RenderOnce, Role, ScrollHandle, SharedString, Styled,
Subscription, TestSupportExt as _, Window,
assets::IconName,
base::{ElementExt as _, StyledExt as _},
canvas,
component::{
Icon,
input::{Input as KitInput, InputState, MoveEnd, MoveHome},
},
div, point,
prelude::*,
px,
};
#[derive(Clone, Debug, PartialEq)]
pub struct CommandItem {
pub id: SharedString,
pub label: SharedString,
pub description: Option<SharedString>,
pub group: Option<SharedString>,
pub keywords: Vec<SharedString>,
pub icon: Option<IconName>,
pub shortcut: Option<SharedString>,
}
impl CommandItem {
pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
description: None,
group: None,
keywords: Vec::new(),
icon: None,
shortcut: None,
}
}
pub fn description(mut self, value: impl Into<SharedString>) -> Self {
self.description = Some(value.into());
self
}
pub fn group(mut self, value: impl Into<SharedString>) -> Self {
self.group = Some(value.into());
self
}
pub fn keywords<I, S>(mut self, values: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<SharedString>,
{
self.keywords = values.into_iter().map(Into::into).collect();
self
}
pub fn icon(mut self, value: IconName) -> Self {
self.icon = Some(value);
self
}
pub fn shortcut(mut self, value: impl Into<SharedString>) -> Self {
self.shortcut = Some(value.into());
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct MatchRange {
start: usize,
end: usize,
}
#[derive(Clone, Debug)]
struct RankedCommand {
item: CommandItem,
score: usize,
ranges: Vec<MatchRange>,
order: usize,
}
fn word_start(text: &str, word: &str) -> Option<usize> {
if word.is_empty() {
return None;
}
let mut offset = 0;
while let Some(found) = text[offset..].find(word) {
let at = offset + found;
if at == 0
|| !text[..at]
.chars()
.next_back()
.is_some_and(|c| c.is_alphanumeric())
{
return Some(at);
}
offset = at
+ text[at..]
.chars()
.next()
.expect("nonempty match")
.len_utf8();
}
None
}
fn subsequence(text: &str, word: &str) -> Option<Vec<MatchRange>> {
let mut chars = word.chars();
let first = chars.next()?;
if word.chars().count() < 2 {
return None;
}
for (start, _) in text.match_indices(first) {
if start > 0
&& text[..start]
.chars()
.next_back()
.is_some_and(|c| c.is_alphanumeric())
{
continue;
}
let mut ranges = vec![MatchRange {
start,
end: start + first.len_utf8(),
}];
let mut cursor = start + first.len_utf8();
let mut matched = true;
for next in chars.clone() {
let Some(relative) = text[cursor..].find(next) else {
matched = false;
break;
};
let at = cursor + relative;
let end = at + next.len_utf8();
if ranges.last().is_some_and(|range| range.end == at) {
ranges.last_mut().expect("range exists").end = end;
} else {
ranges.push(MatchRange { start: at, end });
}
cursor = end;
}
if matched && text[start..cursor].chars().count() <= word.chars().count() * 3 {
return Some(ranges);
}
}
None
}
fn score_word(item: &CommandItem, label: &str, word: &str) -> Option<(usize, Vec<MatchRange>)> {
if let Some(at) = word_start(label, word) {
if at == 0 {
return Some((
100,
vec![MatchRange {
start: 0,
end: word.len(),
}],
));
}
return Some((
80,
vec![MatchRange {
start: at,
end: at + word.len(),
}],
));
}
if word.chars().count() >= 3
&& let Some(at) = label.find(word).filter(|at| *at > 0)
{
return Some((
50,
vec![MatchRange {
start: at,
end: at + word.len(),
}],
));
}
if item
.keywords
.iter()
.any(|keyword| word_start(&keyword.to_lowercase(), word).is_some())
{
return Some((40, Vec::new()));
}
if item
.description
.as_ref()
.is_some_and(|description| word_start(&description.to_lowercase(), word).is_some())
{
return Some((25, Vec::new()));
}
subsequence(label, word).map(|ranges| (10, ranges))
}
pub fn command_palette_rank(items: &[CommandItem], query: &str) -> Vec<CommandItem> {
command_palette_ranked(items, query)
.into_iter()
.map(|entry| entry.item)
.collect()
}
fn command_palette_ranked(items: &[CommandItem], query: &str) -> Vec<RankedCommand> {
let words: Vec<String> = query
.trim()
.to_lowercase()
.split_whitespace()
.map(str::to_owned)
.collect();
let mut ranked = Vec::new();
for (order, item) in items.iter().enumerate() {
if words.is_empty() {
ranked.push(RankedCommand {
item: item.clone(),
score: 0,
ranges: Vec::new(),
order,
});
continue;
}
let label = item.label.to_lowercase();
let mut score = 0;
let mut ranges = Vec::new();
let mut matched = true;
for word in &words {
let Some((word_score, word_ranges)) = score_word(item, &label, word) else {
matched = false;
break;
};
score += word_score;
ranges.extend(word_ranges);
}
if matched {
ranked.push(RankedCommand {
item: item.clone(),
score,
ranges,
order,
});
}
}
ranked.sort_by_key(|entry| (std::cmp::Reverse(entry.score), entry.order));
ranked
}
pub fn command_palette_group_by(ranked: &[CommandItem]) -> Vec<(SharedString, Vec<CommandItem>)> {
let mut groups: Vec<(SharedString, Vec<CommandItem>)> = Vec::new();
for item in ranked {
let group = item.group.clone().unwrap_or_else(|| "Actions".into());
if let Some((_, entries)) = groups.iter_mut().find(|(name, _)| *name == group) {
entries.push(item.clone());
} else {
groups.push((group, vec![item.clone()]));
}
}
groups
}
pub fn command_palette_shortcut_keys(shortcut: &str) -> Vec<SharedString> {
let mut keys = Vec::new();
let mut start = 0;
for (at, ch) in shortcut.char_indices() {
if ch.is_whitespace() || (ch == '+' && at + 1 < shortcut.len()) {
if start < at {
keys.push(shortcut[start..at].into());
}
start = at + ch.len_utf8();
}
}
if start < shortcut.len() {
keys.push(shortcut[start..].into());
}
keys
}
fn highlight_ranges(label: &str, ranges: &[MatchRange]) -> Vec<std::ops::Range<usize>> {
let mut folded_at = 0;
let mut result: Vec<std::ops::Range<usize>> = Vec::new();
for (at, character) in label.char_indices() {
let folded_end = folded_at + character.to_lowercase().map(char::len_utf8).sum::<usize>();
if ranges
.iter()
.any(|range| range.start < folded_end && range.end > folded_at)
{
let end = at + character.len_utf8();
if let Some(last) = result.last_mut().filter(|last| last.end == at) {
last.end = end;
} else {
result.push(at..end);
}
}
folded_at = folded_end;
}
result
}
fn label_with_highlight(label: &str, ranges: &[MatchRange]) -> gpui_kit::StyledText {
gpui_kit::StyledText::new(label.to_owned()).with_highlights(
highlight_ranges(label, ranges).into_iter().map(|range| {
(
range,
gpui_kit::HighlightStyle {
font_weight: Some(gpui_kit::FontWeight::MEDIUM),
..Default::default()
},
)
}),
)
}
#[derive(Clone)]
struct RetainedCommandRow {
item: CommandItem,
ranges: Vec<MatchRange>,
top: f32,
}
#[derive(Clone)]
struct RetainedCommandGroup {
name: SharedString,
top: f32,
rows: Vec<RetainedCommandRow>,
}
fn command_row_content(
palette_id: &ElementId,
item: &CommandItem,
ranges: &[MatchRange],
narrow: bool,
cx: &App,
) -> gpui_kit::Div {
let colors = cx.arc_theme().colors;
let mut copy = div()
.flex()
.items_center()
.gap(Spacing::S2)
.min_w_0()
.flex_1()
.child(
div()
.min_w_0()
.truncate()
.text_size(Typography::TEXT_SM)
.child(label_with_highlight(item.label.as_ref(), ranges)),
);
if let Some(description) = &item.description {
copy = copy.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.truncate()
.child(description.clone()),
);
}
div()
.flex()
.items_center()
.w_full()
.gap(Spacing::S2)
.child(
Icon::new(item.icon.unwrap_or(IconName::Command))
.text_size(CommandPaletteTokens::ICON)
.text_color(if item.icon.is_some() {
colors.text_secondary
} else {
colors.text_muted
}),
)
.child(copy)
.when_some(
item.shortcut.as_ref().filter(|_| !narrow),
|row, shortcut| {
row.child(
div()
.id(ElementId::NamedChild(
palette_id.clone().into(),
format!("shortcut-{}", item.id).into(),
))
.test_support()
.flex()
.gap(Spacing::S1)
.children(
command_palette_shortcut_keys(shortcut)
.into_iter()
.map(|key| {
div()
.min_w(CommandPaletteTokens::KEYCAP)
.h(CommandPaletteTokens::KEYCAP)
.px(Spacing::S1)
.rounded(Radii::CONTROL)
.bg(colors.surface_muted)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.flex()
.items_center()
.justify_center()
.child(key)
}),
),
)
},
)
}
type CommandSelectHandler = Rc<dyn Fn(&CommandItem, &mut Window, &mut App)>;
type CommandCloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;
#[derive(Clone)]
struct CommandPaletteInternal {
query_input: Entity<InputState>,
keyboard_scope: FocusHandle,
focus_handle: FocusHandle,
last_query: SharedString,
placeholder: SharedString,
active_index: i64,
pointer_item: Option<SharedString>,
pointer_navigation: bool,
highlight_top: f32,
last_pointer: Rc<RefCell<Option<(f32, f32)>>>,
scroll: ScrollHandle,
width: Rc<RefCell<f32>>,
previous_positions: std::collections::HashMap<SharedString, f32>,
previous_active: Option<SharedString>,
group_positions: std::collections::HashMap<SharedString, f32>,
content_origin: Rc<std::cell::Cell<f32>>,
displayed_results: Option<bool>,
rendered_ranked: Vec<RankedCommand>,
retained_rows: Vec<RetainedCommandRow>,
retained_groups: Vec<RetainedCommandGroup>,
glide: bool,
empty_query: SharedString,
_subscriptions: Rc<Vec<Subscription>>,
}
impl CommandPaletteInternal {
fn new(
placeholder: SharedString,
auto_focus: bool,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let query_input = cx.new(|cx| InputState::new(window, cx).placeholder(placeholder.clone()));
let focus_handle = query_input.read(cx).focus_handle(cx);
let observer = cx.observe(&query_input, |_, _, cx| cx.notify());
let input = query_input.clone();
let window_id = window.window_handle().window_id();
let shortcut = cx.intercept_keystrokes(move |event, window, cx| {
let stroke = &event.keystroke;
if window.window_handle().window_id() == window_id
&& (stroke.modifiers.control || stroke.modifiers.platform)
&& stroke.key.eq_ignore_ascii_case("k")
{
input.update(cx, |input, cx| input.focus(window, cx));
cx.stop_propagation();
window.refresh();
}
});
if auto_focus {
let input = query_input.clone();
window.on_next_frame(move |window, cx| {
input.update(cx, |input, cx| input.focus(window, cx));
});
}
Self {
query_input,
keyboard_scope: cx.focus_handle(),
focus_handle,
last_query: "".into(),
placeholder,
active_index: 0,
pointer_item: None,
pointer_navigation: false,
highlight_top: 0.0,
last_pointer: Rc::new(RefCell::new(None)),
scroll: ScrollHandle::new(),
width: Rc::new(RefCell::new(f32::from(CommandPaletteTokens::MAX_WIDTH))),
previous_positions: Default::default(),
previous_active: None,
group_positions: Default::default(),
content_origin: Rc::new(std::cell::Cell::new(0.0)),
displayed_results: None,
rendered_ranked: Vec::new(),
retained_rows: Vec::new(),
retained_groups: Vec::new(),
glide: true,
empty_query: "".into(),
_subscriptions: Rc::new(vec![observer, shortcut]),
}
}
}
#[derive(IntoElement)]
pub struct CommandPalette {
id: ElementId,
items: Vec<CommandItem>,
placeholder: SharedString,
label: SharedString,
auto_focus: bool,
animate_entry: bool,
on_select: Option<CommandSelectHandler>,
on_close: Option<CommandCloseHandler>,
}
impl CommandPalette {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
items: Vec::new(),
placeholder: "Search commands".into(),
label: "Command palette".into(),
auto_focus: false,
animate_entry: true,
on_select: None,
on_close: None,
}
}
pub fn items<I>(mut self, items: I) -> Self
where
I: IntoIterator<Item = CommandItem>,
{
self.items = items.into_iter().collect();
self
}
pub fn placeholder(mut self, value: impl Into<SharedString>) -> Self {
self.placeholder = value.into();
self
}
pub fn label(mut self, value: impl Into<SharedString>) -> Self {
self.label = value.into();
self
}
pub fn auto_focus(mut self, value: bool) -> Self {
self.auto_focus = value;
self
}
pub fn animate_entry(mut self, value: bool) -> Self {
self.animate_entry = value;
self
}
pub fn on_select<F>(mut self, callback: F) -> Self
where
F: Fn(&CommandItem, &mut Window, &mut App) + 'static,
{
self.on_select = Some(Rc::new(callback));
self
}
pub fn on_close<F>(mut self, callback: F) -> Self
where
F: Fn(&mut Window, &mut App) + 'static,
{
self.on_close = Some(Rc::new(callback));
self
}
}
impl RenderOnce for CommandPalette {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let colors = cx.arc_theme().colors;
let reduced = is_reduced_motion(cx);
let state_id = ElementId::NamedChild(self.id.clone().into(), "state".into());
let internal = window.use_keyed_state(state_id, cx, |window, cx| {
CommandPaletteInternal::new(self.placeholder.clone(), self.auto_focus, window, cx)
});
let snapshot = internal.read(cx).clone();
let motion = cx.arc_theme().motion;
let raw_query = snapshot.query_input.read(cx).value();
let query = raw_query.trim().to_owned();
if snapshot.placeholder != self.placeholder {
internal.update(cx, |state, _| state.placeholder = self.placeholder.clone());
snapshot.query_input.update(cx, |input, cx| {
input.set_placeholder(self.placeholder.clone(), window, cx);
});
}
let ranked = command_palette_ranked(&self.items, &query);
let ranked_items: Vec<CommandItem> =
ranked.iter().map(|entry| entry.item.clone()).collect();
let groups = command_palette_group_by(&ranked_items);
let visual_items: Vec<CommandItem> = groups
.iter()
.flat_map(|(_, items)| items.iter().cloned())
.collect();
let query_changed = raw_query != snapshot.last_query;
let active_index = if visual_items.is_empty() {
-1
} else if query_changed {
0
} else {
snapshot
.active_index
.clamp(0, visual_items.len() as i64 - 1)
};
internal.update(cx, |state, _| {
state.last_query = raw_query.clone();
state.active_index = active_index;
if query_changed {
state.pointer_navigation = false;
state.pointer_item = None;
}
});
let narrow = *snapshot.width.borrow() < f32::from(CommandPaletteTokens::NARROW_WIDTH);
let row_h = f32::from(CommandPaletteTokens::ROW);
let heading_h = f32::from(CommandPaletteTokens::HEADING);
let mut positions = std::collections::HashMap::new();
let mut content_height = 0.0;
for (_, items) in &groups {
content_height += heading_h;
for item in items {
positions.insert(item.id.clone(), content_height);
content_height += row_h;
}
}
let previous_items: Vec<_> = command_palette_group_by(
&snapshot
.rendered_ranked
.iter()
.map(|e| e.item.clone())
.collect::<Vec<_>>(),
)
.into_iter()
.flat_map(|(_, items)| items)
.collect();
let list_changed = previous_items != visual_items;
let glide = !reduced
&& if list_changed {
visual_items.iter().enumerate().all(|(index, item)| {
previous_items
.iter()
.position(|old| old.id == item.id)
.is_none_or(|before| {
before.abs_diff(index) <= CommandPaletteTokens::GLIDE_ROWS
})
})
} else {
snapshot.glide
};
internal.update(cx, |state, _| state.glide = glide);
let pointer_navigation = snapshot.pointer_navigation && !query_changed;
let active_id = if pointer_navigation {
snapshot
.pointer_item
.clone()
.filter(|id| positions.contains_key(id))
} else {
(active_index >= 0).then(|| visual_items[active_index as usize].id.clone())
};
if !pointer_navigation && (query_changed || active_id != snapshot.previous_active) {
let scroll = snapshot.scroll.clone();
let target = active_id.as_ref().map(|id| positions[id]);
let viewport = content_height.min(f32::from(
CommandPaletteTokens::MAX_RESULTS - CommandPaletteTokens::RESULTS_INSET * 2.0,
));
window.on_next_frame(move |window, _| {
let offset = scroll.offset();
let mut y = f32::from(offset.y);
if let Some(top) = target {
if top + y < 0.0 {
y = -top;
}
if top + row_h + y > viewport {
y = viewport - top - row_h;
}
} else {
y = 0.0;
}
scroll.set_offset(point(offset.x, px(y.min(0.0))));
window.refresh();
});
}
internal.update(cx, |state, _| {
state.previous_active = active_id.clone();
});
let query_input = KitInput::new(&snapshot.query_input)
.id(ElementId::NamedChild(
self.id.clone().into(),
"input".into(),
))
.appearance(false)
.h(ControlHeights::MD)
.w_full()
.text_size(Typography::TEXT_SM)
.role(Role::ComboBox)
.aria_label(self.label.clone());
let click_select_handler = self.on_select.clone();
let select = self.on_select.clone();
let close = self.on_close.clone();
let key_state = internal.clone();
let key_items = visual_items.clone();
let key_input = snapshot.query_input.clone();
let key_close = close.clone();
let home_state = internal.clone();
let end_state = internal.clone();
let end_index = key_items.len() as i64 - 1;
let home_listener = move |_: &MoveHome, window: &mut Window, cx: &mut App| {
home_state.update(cx, |state, _| {
state.active_index = 0;
state.pointer_navigation = false;
state.pointer_item = None;
});
cx.stop_propagation();
window.refresh();
};
let end_listener = move |_: &MoveEnd, window: &mut Window, cx: &mut App| {
end_state.update(cx, |state, _| {
state.active_index = end_index;
state.pointer_navigation = false;
state.pointer_item = None;
});
cx.stop_propagation();
window.refresh();
};
let key_listener = move |event: &KeyDownEvent, window: &mut Window, cx: &mut App| {
let key = event.keystroke.key.as_str();
let modifiers = event.keystroke.modifiers;
if (modifiers.control || modifiers.platform) && key.eq_ignore_ascii_case("k") {
key_input.update(cx, |state, cx| state.focus(window, cx));
window.refresh();
return;
}
let len = key_items.len() as i64;
if matches!(
key,
"down" | "arrowdown" | "up" | "arrowup" | "home" | "end"
) {
key_state.update(cx, |state, _| {
state.pointer_navigation = false;
state.pointer_item = None;
});
}
match key {
"down" | "arrowdown" | "up" | "arrowup" | "home" | "end" | "enter" if len == 0 => {}
"down" | "arrowdown" if len > 0 => {
key_state.update(cx, |state, _| {
state.active_index = (state.active_index + 1).min(len - 1);
});
}
"up" | "arrowup" if len > 0 => {
key_state.update(cx, |state, _| {
state.active_index = (state.active_index - 1).max(0);
});
}
"home" if len > 0 => key_state.update(cx, |state, _| {
state.active_index = 0;
}),
"end" if len > 0 => key_state.update(cx, |state, _| {
state.active_index = len - 1;
}),
"enter" if len > 0 => {
let state = key_state.read(cx);
let target = if state.pointer_navigation {
state
.pointer_item
.as_ref()
.and_then(|id| key_items.iter().find(|item| &item.id == id))
} else {
key_items.get(state.active_index.clamp(0, len - 1) as usize)
};
if let Some(item) = target {
if let Some(handler) = &select {
handler(item, window, cx);
}
key_input.update(cx, |state, cx| {
state.set_value("", window, cx);
state.focus(window, cx);
});
key_state.update(cx, |state, _| {
state.last_query = "".into();
state.active_index = 0;
state.pointer_navigation = false;
state.pointer_item = None;
});
}
}
"escape" => {
if !key_input.read(cx).value().is_empty() {
key_input.update(cx, |state, cx| state.set_value("", window, cx));
key_state.update(cx, |state, _| {
state.last_query = "".into();
state.active_index = 0;
state.pointer_navigation = false;
state.pointer_item = None;
});
} else if let Some(handler) = &key_close {
handler(window, cx);
}
}
_ => return,
}
cx.stop_propagation();
window.refresh();
};
let highlight_target = active_id
.as_ref()
.map(|id| positions[id])
.unwrap_or(snapshot.highlight_top);
let highlight_y = arc_spring_with_options(
(self.id.clone(), "highlight-y"),
highlight_target,
SpringOptions::new(motion.spring.snappy)
.with_initial_value(highlight_target)
.with_travel(!reduced && active_id.is_some() && snapshot.previous_active.is_some()),
window,
cx,
)
.value;
internal.update(cx, |state, _| state.highlight_top = highlight_y);
let highlight_opacity =
ArcPresence::new((self.id.clone(), "highlight-opacity"), active_id.is_some())
.enter(CommandPaletteTokens::HIGHLIGHT_ENTER, motion.ease.enter)
.exit(CommandPaletteTokens::HIGHLIGHT_EXIT, motion.ease.standard)
.sample(window, cx)
.progress;
let wants_results = !visual_items.is_empty();
let mut showing_results = snapshot.displayed_results.unwrap_or(wants_results);
let mut content_presence = ArcPresence::new(
(self.id.clone(), "content-presence"),
showing_results == wants_results,
)
.animate_initial(false)
.enter(motion.duration.standard, motion.ease.enter)
.exit(motion.duration.instant, motion.ease.standard)
.sample(window, cx);
if !content_presence.should_render() {
showing_results = wants_results;
internal.update(cx, |state, _| {
state.displayed_results = Some(showing_results)
});
content_presence = ArcPresence::new((self.id.clone(), "content-presence"), true)
.enter(motion.duration.standard, motion.ease.enter)
.exit(motion.duration.instant, motion.ease.standard)
.sample(window, cx);
}
let displayed_ranked = if showing_results && wants_results {
ranked.clone()
} else {
snapshot.rendered_ranked.clone()
};
internal.update(cx, |state, _| {
state.displayed_results = Some(showing_results);
if showing_results && wants_results {
state.rendered_ranked = ranked.clone();
}
if !showing_results && !wants_results {
state.empty_query = query.clone().into();
}
});
let displayed_items: Vec<_> = displayed_ranked.iter().map(|e| e.item.clone()).collect();
let displayed_groups = if showing_results {
command_palette_group_by(&displayed_items)
} else {
Vec::new()
};
let mut displayed_positions = std::collections::HashMap::new();
let mut displayed_height = 0.0;
for (_, items) in &displayed_groups {
displayed_height += heading_h;
for item in items {
displayed_positions.insert(item.id.clone(), displayed_height);
displayed_height += row_h;
}
}
let interactive_results = showing_results && wants_results;
let mut retained_groups = snapshot.retained_groups.clone();
for (name, entries) in command_palette_group_by(&previous_items) {
if interactive_results
&& !displayed_groups.iter().any(|(next, _)| *next == name)
&& !retained_groups.iter().any(|group| group.name == name)
&& let Some(top) = snapshot.group_positions.get(&name)
{
retained_groups.push(RetainedCommandGroup {
name,
top: *top,
rows: entries
.into_iter()
.filter_map(|item| {
snapshot.previous_positions.get(&item.id).map(|top| {
RetainedCommandRow {
ranges: snapshot
.rendered_ranked
.iter()
.find(|r| r.item.id == item.id)
.map(|r| r.ranges.clone())
.unwrap_or_default(),
item,
top: *top,
}
})
})
.collect(),
});
}
}
let mut active_groups = Vec::new();
let mut exit_groups = Vec::new();
for group in retained_groups {
if !interactive_results || displayed_groups.iter().any(|(name, _)| *name == group.name)
{
continue;
}
let sample = ArcPresence::new(
(
ElementId::NamedChild(
self.id.clone().into(),
format!("group-{}", group.name).into(),
),
"group-presence",
),
false,
)
.animate_initial(false)
.enter(motion.duration.standard, motion.ease.enter)
.exit(
if glide {
motion.duration.instant
} else {
std::time::Duration::ZERO
},
motion.ease.standard,
)
.sample(window, cx);
if sample.should_render() {
let mut layer = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
format!("exit-group-{}", group.name).into(),
))
.test_support()
.absolute()
.top(px(group.top))
.left_0()
.right_0()
.opacity(sample.progress)
.child(
div()
.h(px(heading_h))
.px(Spacing::S3)
.flex()
.items_center()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.font_medium()
.child(group.name.clone()),
);
for row in &group.rows {
layer = layer.child(
div()
.absolute()
.top(px(row.top - group.top))
.left_0()
.right_0()
.h(px(row_h))
.px(Spacing::S3)
.flex()
.items_center()
.child(command_row_content(
&ElementId::NamedChild(self.id.clone().into(), "exit".into()),
&row.item,
&row.ranges,
narrow,
cx,
)),
);
}
exit_groups.push(layer.into_any_element());
active_groups.push(group);
}
}
internal.update(cx, |state, _| state.retained_groups = active_groups.clone());
let mut retained_rows = snapshot.retained_rows.clone();
for previous in &snapshot.rendered_ranked {
if interactive_results
&& !displayed_positions.contains_key(&previous.item.id)
&& !retained_rows
.iter()
.any(|row| row.item.id == previous.item.id)
&& let Some(top) = snapshot.previous_positions.get(&previous.item.id)
{
retained_rows.push(RetainedCommandRow {
item: previous.item.clone(),
ranges: previous.ranges.clone(),
top: *top,
});
}
}
let mut active_retained = Vec::new();
let mut exit_rows = Vec::new();
for row in retained_rows {
if !interactive_results
|| displayed_positions.contains_key(&row.item.id)
|| active_groups
.iter()
.any(|group| group.rows.iter().any(|r| r.item.id == row.item.id))
{
continue;
}
let sample = ArcPresence::new(
(
ElementId::NamedChild(self.id.clone().into(), row.item.id.clone()),
"row-presence",
),
false,
)
.animate_initial(false)
.enter(motion.duration.standard, motion.ease.enter)
.exit(
if glide {
motion.duration.instant
} else {
std::time::Duration::ZERO
},
motion.ease.standard,
)
.sample(window, cx);
if sample.should_render() {
exit_rows.push(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
format!("exit-{}", row.item.id).into(),
))
.test_support()
.absolute()
.top(px(row.top))
.left_0()
.right_0()
.h(px(row_h))
.px(Spacing::S3)
.flex()
.items_center()
.opacity(sample.progress)
.child(command_row_content(
&ElementId::NamedChild(self.id.clone().into(), "exit".into()),
&row.item,
&row.ranges,
narrow,
cx,
))
.into_any_element(),
);
active_retained.push(row);
}
}
internal.update(cx, |state, _| state.retained_rows = active_retained);
let mut result_rows: Vec<gpui_kit::AnyElement> = Vec::new();
let mut flat_index = 0usize;
let mut group_top = 0.0;
for (group_name, entries) in displayed_groups {
let group_id =
ElementId::NamedChild(self.id.clone().into(), format!("group-{group_name}").into());
let group_presence = ArcPresence::new((group_id.clone(), "group-presence"), true)
.animate_initial(snapshot.displayed_results.is_some())
.enter(motion.duration.standard, motion.ease.enter)
.exit(motion.duration.instant, motion.ease.standard)
.sample(window, cx);
let group_y = arc_spring_with_options(
(group_id.clone(), "group-y"),
group_top,
SpringOptions::new(motion.spring.smooth)
.with_initial_value(group_top)
.with_travel(glide),
window,
cx,
)
.value
- group_top;
let group_base = group_top;
group_top += heading_h + entries.len() as f32 * row_h;
let measured_state = internal.clone();
let measured_origin = snapshot.content_origin.clone();
let measured_group = group_name.clone();
let heading = div()
.h(px(heading_h))
.px(Spacing::S3)
.flex()
.items_center()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.font_medium()
.child(group_name.clone());
let mut rows = vec![heading.into_any_element()];
for entry in entries {
let row_index = flat_index;
flat_index += 1;
let active = interactive_results && active_id.as_ref() == Some(&entry.id);
let item_id = entry.id.clone();
let pointer_state = internal.clone();
let leave_state = internal.clone();
let pointer_id = entry.id.clone();
let leave_id = entry.id.clone();
let item_for_click = entry.clone();
let click_select = click_select_handler.clone();
let click_state = internal.clone();
let click_input = snapshot.query_input.clone();
let row_target = displayed_positions[&entry.id];
let row_y = arc_spring_with_options(
(
ElementId::NamedChild(self.id.clone().into(), entry.id.clone()),
"row-y",
),
row_target - group_base,
SpringOptions::new(motion.spring.smooth)
.with_initial_value(row_target - group_base)
.with_travel(glide),
window,
cx,
)
.value
- (row_target - group_base);
let ranges = displayed_ranked
.iter()
.find(|candidate| candidate.item.id == entry.id)
.map(|candidate| candidate.ranges.clone())
.unwrap_or_default();
let row_presence = ArcPresence::new(
(
ElementId::NamedChild(self.id.clone().into(), entry.id.clone()),
"row-presence",
),
true,
)
.animate_initial(snapshot.displayed_results.is_some())
.enter(motion.duration.standard, motion.ease.enter)
.exit(motion.duration.instant, motion.ease.standard)
.sample(window, cx);
let measured_row_state = internal.clone();
let measured_row_origin = snapshot.content_origin.clone();
let measured_item = entry.id.clone();
let row = div()
.on_prepaint(move |bounds, _, cx| {
measured_row_state.update(cx, |s, _| {
s.previous_positions.insert(
measured_item.clone(),
f32::from(bounds.origin.y) - measured_row_origin.get(),
);
});
})
.opacity(row_presence.progress)
.id(ElementId::NamedChild(
self.id.clone().into(),
format!("item-{item_id}").into(),
))
.test_support()
.w_full()
.h(px(row_h))
.flex_shrink_0()
.top(px(row_y))
.px(Spacing::S3)
.gap(Spacing::S2)
.rounded(Radii::CONTROL)
.flex()
.flex_row()
.items_center()
.relative()
.cursor_pointer()
.role(Role::ListBoxOption)
.aria_label(entry.label.clone())
.aria_selected(active)
.when(active, |d| d.aria_active_descendant())
.aria_position_in_set(row_index + 1)
.aria_size_of_set(visual_items.len())
.on_mouse_move(move |event: &MouseMoveEvent, window, cx| {
if !interactive_results {
return;
}
let point = event.position;
let current = (f32::from(point.x), f32::from(point.y));
let pointer = pointer_state.read(cx).last_pointer.clone();
if *pointer.borrow() == Some(current) {
return;
}
*pointer.borrow_mut() = Some(current);
pointer_state.update(cx, |state, _| {
state.pointer_navigation = true;
state.pointer_item = Some(pointer_id.clone());
});
window.refresh();
})
.on_hover(move |hovered, window, cx| {
if !*hovered {
leave_state.update(cx, |state, _| {
if state.pointer_item.as_ref() == Some(&leave_id) {
state.pointer_item = None;
*state.last_pointer.borrow_mut() = None;
}
});
window.refresh();
}
})
.on_mouse_down(gpui_kit::MouseButton::Left, |_, window, _| {
window.prevent_default()
})
.on_click(move |_, window, cx| {
if !interactive_results {
return;
}
if let Some(handler) = &click_select {
handler(&item_for_click, window, cx);
}
click_input.update(cx, |input, cx| {
input.set_value("", window, cx);
input.focus(window, cx);
});
click_state.update(cx, |state, _| {
state.last_query = "".into();
state.active_index = 0;
state.pointer_navigation = false;
state.pointer_item = None;
});
window.refresh();
});
rows.push(
row.child(command_row_content(&self.id, &entry, &ranges, narrow, cx))
.into_any_element(),
);
}
result_rows.push(
div()
.id(group_id)
.test_support()
.on_prepaint(move |bounds, _, cx| {
measured_state.update(cx, |s, _| {
s.group_positions.insert(
measured_group.clone(),
f32::from(bounds.origin.y) - measured_origin.get(),
);
});
})
.relative()
.top(px(group_y))
.opacity(group_presence.progress)
.role(Role::Group)
.aria_label(group_name)
.flex()
.flex_col()
.children(rows)
.into_any_element(),
);
}
internal.update(cx, |state, _| {
state
.previous_positions
.retain(|id, _| displayed_positions.contains_key(id));
state.group_positions.retain(|name, _| {
displayed_items.iter().any(|item| {
item.group
.as_ref()
.map_or("Actions", |group| group.as_ref())
== name.as_ref()
})
});
});
if !showing_results {
let empty_presence = content_presence;
let blur = BlurFallback::evaluate(
motion.blur.subtle * (1.0 - empty_presence.progress),
reduced,
);
result_rows.push(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"empty".into(),
))
.test_support()
.relative()
.top(if reduced {
px(0.0)
} else {
(if empty_presence.is_exiting() {
CommandPaletteTokens::EXIT_Y
} else {
CommandPaletteTokens::ENTER_Y
}) * (1.0 - empty_presence.progress)
})
.opacity(empty_presence.progress * blur.opacity_multiplier)
.h(CommandPaletteTokens::EMPTY_HEIGHT)
.flex()
.flex_col()
.items_center()
.justify_center()
.gap(Spacing::S1)
.text_color(colors.text_muted)
.child(Icon::new(IconName::Search).text_size(px(18.0)))
.child(if !wants_results && query.is_empty() {
"No commands".to_owned()
} else {
format!(
"No results for “{}”",
if wants_results {
snapshot.empty_query.as_ref()
} else {
&query
}
)
})
.child(
div()
.text_size(Typography::TEXT_XS)
.child(if query.is_empty() {
"Add commands to this palette."
} else {
"Try a different word or clear the search."
}),
)
.into_any_element(),
);
}
let target_height = if showing_results {
displayed_height.min(f32::from(
CommandPaletteTokens::MAX_RESULTS - CommandPaletteTokens::RESULTS_INSET * 2.0,
))
} else {
f32::from(CommandPaletteTokens::EMPTY_HEIGHT)
};
let list_height = arc_spring_with_options(
(self.id.clone(), "results-height"),
target_height,
SpringOptions::new(motion.spring.smooth)
.with_initial_value(target_height)
.with_travel(!reduced),
window,
cx,
)
.value;
let presence = ArcPresence::new((self.id.clone(), "presence"), true)
.animate_initial(self.animate_entry)
.enter(motion.duration.fast, motion.ease.enter)
.sample(window, cx);
let panel_opacity = presence.progress;
let panel_y = if reduced {
px(0.0)
} else {
CommandPaletteTokens::ENTER_Y * (1.0 - presence.progress)
};
let clear_presence =
ArcPresence::new((self.id.clone(), "clear-presence"), !raw_query.is_empty())
.animate_initial(false)
.enter(motion.duration.instant, motion.ease.enter)
.exit(motion.duration.instant, motion.ease.standard)
.sample(window, cx);
let clear_scale = arc_spring_with_options(
(self.id.clone(), "clear-scale"),
if raw_query.is_empty() {
CommandPaletteTokens::CLEAR_SCALE
} else {
1.0
},
SpringOptions::new(motion.spring.snappy).with_travel(!reduced),
window,
cx,
)
.value;
let clear_blur = BlurFallback::evaluate(
motion.blur.subtle * (1.0 - clear_presence.progress),
reduced,
);
let width_ref = snapshot.width.clone();
let width_probe = canvas(
move |bounds, window, _| {
let measured = f32::from(bounds.size.width);
let was_narrow =
*width_ref.borrow() < f32::from(CommandPaletteTokens::NARROW_WIDTH);
let is_narrow = measured < f32::from(CommandPaletteTokens::NARROW_WIDTH);
*width_ref.borrow_mut() = measured;
if was_narrow != is_narrow {
window.on_next_frame(|window, _| window.refresh());
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let content_origin = snapshot.content_origin.clone();
let clear_state = internal.clone();
let clear_input = snapshot.query_input.clone();
let shell_id = ElementId::NamedChild(self.id.clone().into(), "shell".into());
let list_id = ElementId::NamedChild(self.id.clone().into(), "results".into());
let clear_button = if !clear_presence.should_render() {
None
} else {
Some(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"clear".into(),
))
.test_support()
.size(Spacing::S6)
.flex_shrink_0()
.role(Role::Button)
.opacity(clear_presence.progress * clear_blur.opacity_multiplier)
.rounded(Radii::CONTROL)
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.text_color(colors.text_muted)
.hover(|d| d.bg(colors.surface_muted))
.aria_label("Clear search")
.on_click(move |_, window, cx| {
clear_input.update(cx, |state, cx| {
state.set_value("", window, cx);
state.focus(window, cx);
});
clear_state.update(cx, |state, _| {
state.last_query = "".into();
state.active_index = 0;
state.pointer_navigation = false;
state.pointer_item = None;
});
window.refresh();
})
.child(Icon::new(IconName::X).text_size(Typography::TEXT_SM * clear_scale)),
)
};
let search_focused = snapshot.focus_handle.is_focused(window);
div()
.w_full()
.max_w(CommandPaletteTokens::MAX_WIDTH)
.relative()
.child(
div()
.id(self.id.clone())
.test_support()
.relative()
.w_full()
.top(panel_y)
.rounded(CommandPaletteTokens::PANEL_RADIUS)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.shadow(Shadows::floating(cx.arc_theme().mode))
.overflow_hidden()
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.flex()
.flex_col()
.track_focus(&snapshot.keyboard_scope)
.capture_action(home_listener)
.capture_action(end_listener)
.capture_key_down(key_listener)
.child(width_probe)
.opacity(panel_opacity)
.role(Role::Group)
.aria_label(self.label)
.child(
div()
.id(shell_id)
.test_support()
.relative()
.h(ControlHeights::MD)
.w_full()
.border_b_1()
.border_color(colors.border_subtle)
.when(search_focused, |row| {
row.rounded_tl(CommandPaletteTokens::PANEL_RADIUS)
.rounded_tr(CommandPaletteTokens::PANEL_RADIUS)
.bg(colors.surface_muted)
})
.flex()
.flex_row()
.items_center()
.gap(Spacing::S2)
.px(Spacing::S3)
.child(
Icon::new(IconName::Search)
.text_size(CommandPaletteTokens::ICON)
.text_color(colors.text_muted),
)
.child(query_input)
.when_some(clear_button, |d, button| d.child(button))
.when_some(close, |d, handler| {
d.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"close".into(),
))
.test_support()
.role(Role::Button)
.aria_label("Close command palette")
.h(Spacing::S6)
.px(Spacing::S1)
.rounded(Radii::CONTROL)
.cursor_pointer()
.flex_shrink_0()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.on_click(move |_, window, cx| handler(window, cx))
.child("Esc"),
)
})
.when(!narrow, |d| {
d.child(
div()
.flex_shrink_0()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(if cfg!(target_os = "macos") {
"⌘ K"
} else {
"Ctrl K"
}),
)
}),
)
.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"results-frame".into(),
))
.test_support()
.p(CommandPaletteTokens::RESULTS_INSET)
.child(
div()
.id(list_id)
.test_support()
.relative()
.h(px(list_height))
.flex_shrink_0()
.track_scroll(&snapshot.scroll)
.max_h(
CommandPaletteTokens::MAX_RESULTS
- CommandPaletteTokens::RESULTS_INSET * 2.0,
)
.overflow_y_scroll()
.role(Role::ListBox)
.aria_label("Command results")
.child(
div()
.on_prepaint(move |bounds, _, _| {
content_origin.set(f32::from(bounds.origin.y))
})
.relative()
.h(px(if showing_results {
displayed_height
} else {
f32::from(CommandPaletteTokens::EMPTY_HEIGHT)
}))
.opacity(if showing_results {
content_presence.progress
} else {
1.0
})
.when(showing_results && highlight_opacity > 0.0, |d| {
d.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"highlight".into(),
))
.test_support()
.absolute()
.left_0()
.right_0()
.top(px(highlight_y))
.h(px(row_h))
.rounded(Radii::CONTROL)
.bg(colors.surface_muted)
.opacity(highlight_opacity),
)
})
.children(result_rows)
.children(exit_rows)
.children(exit_groups),
),
),
)
.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"status".into(),
))
.role(Role::Status)
.test_support()
.aria_label(if query.is_empty() {
String::new()
} else if visual_items.is_empty() {
"No results".to_owned()
} else if visual_items.len() == 1 {
"1 result".to_owned()
} else {
format!("{} results", visual_items.len())
})
.absolute()
.size(px(1.0))
.overflow_hidden()
.child(" "),
),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn items() -> Vec<CommandItem> {
vec![
CommandItem::new("a", "Open project")
.group("Workspace")
.keywords(["launch"]),
CommandItem::new("b", "Project settings")
.group("Settings")
.description("Configure the workspace"),
CommandItem::new("c", "Duplicate project").group("Workspace"),
]
}
#[test]
fn ranks_prefix_boundary_substring_keyword_and_description() {
let ranked = command_palette_rank(&items(), "project");
assert_eq!(
ranked
.iter()
.map(|item| item.id.as_ref())
.collect::<Vec<_>>(),
vec!["b", "a", "c"]
);
assert_eq!(command_palette_rank(&items(), "launch")[0].id.as_ref(), "a");
assert_eq!(
command_palette_rank(&items(), "configure")[0].id.as_ref(),
"b"
);
}
#[test]
fn all_words_must_match_and_ties_keep_input_order() {
let ranked = command_palette_rank(&items(), "project settings");
assert_eq!(ranked.len(), 1);
assert_eq!(ranked[0].id.as_ref(), "b");
let tied = vec![
CommandItem::new("a", "Alpha"),
CommandItem::new("b", "Alpha copy"),
];
assert_eq!(
command_palette_rank(&tied, "alpha")
.iter()
.map(|item| item.id.as_ref())
.collect::<Vec<_>>(),
vec!["a", "b"]
);
}
#[test]
fn groups_default_to_actions_and_follow_rank_order() {
let ranked = command_palette_rank(&items(), "");
let groups = command_palette_group_by(&ranked);
assert_eq!(groups[0].0.as_ref(), "Workspace");
assert_eq!(groups[1].0.as_ref(), "Settings");
let plain = vec![CommandItem::new("x", "Action")];
assert_eq!(command_palette_group_by(&plain)[0].0.as_ref(), "Actions");
}
#[test]
fn shortcut_parser_splits_modifiers_and_spaces() {
assert_eq!(command_palette_shortcut_keys("⌘ K").len(), 2);
assert_eq!(command_palette_shortcut_keys("Shift+N").len(), 2);
assert_eq!(
command_palette_shortcut_keys("Ctrl++"),
vec![SharedString::from("Ctrl"), SharedString::from("+")]
);
}
#[test]
fn score_weights_match_upstream_and_extra_words_are_boundary_only() {
let candidates = [
CommandItem::new("substring", "Latest"),
CommandItem::new("prefix", "Test command"),
CommandItem::new("word", "Run test"),
CommandItem::new("keyword", "Other").keywords(["test"]),
CommandItem::new("description", "More").description("test the system"),
CommandItem::new("not-keyword", "Unrelated").keywords(["latest"]),
CommandItem::new("not-description", "Nothing").description("latest"),
];
let ranked = command_palette_ranked(&candidates, "test");
assert_eq!(
ranked
.iter()
.map(|entry| (entry.item.id.as_ref(), entry.score))
.collect::<Vec<_>>(),
vec![
("prefix", 100),
("word", 80),
("substring", 50),
("keyword", 40),
("description", 25)
]
);
assert!(command_palette_rank(&candidates, "test absent").is_empty());
}
#[test]
fn subsequences_are_word_anchored_and_span_limited() {
let candidate = CommandItem::new("share", "Share project");
let ranked = command_palette_ranked(&[candidate], "shpr");
assert_eq!(ranked[0].score, 10);
assert!(subsequence("xxshare project", "shpr").is_none());
assert!(subsequence("s...........p", "sp").is_none());
assert_eq!(command_palette_rank(&items(), "dup pr")[0].id.as_ref(), "c");
}
#[test]
fn unicode_highlights_keep_original_utf8_boundaries_and_merge_overlaps() {
let candidates = [
CommandItem::new("cn", "打开项目"),
CommandItem::new("unicode", "İstanbul"),
];
let ranked = command_palette_ranked(&candidates, "打开");
assert_eq!(highlight_ranges("打开项目", &ranked[0].ranges), vec![0..6]);
let ranked = command_palette_ranked(&candidates, "i");
assert_eq!(highlight_ranges("İstanbul", &ranked[0].ranges), vec![0..2]);
assert_eq!(
highlight_ranges(
"Open",
&[
MatchRange { start: 0, end: 3 },
MatchRange { start: 0, end: 2 }
]
),
vec![0..3]
);
assert_eq!(command_palette_rank(&items(), " \t ").len(), 3);
}
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{Render, TestAppContext, test::TestWindowExt as _};
struct PaletteHost {
selected: Rc<RefCell<Vec<String>>>,
closed: Rc<RefCell<usize>>,
commands: Vec<CommandItem>,
show: bool,
width: f32,
auto_focus: bool,
}
impl Render for PaletteHost {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
let selected = self.selected.clone();
let closed = self.closed.clone();
div().w(px(self.width)).p(Spacing::S4).when(self.show, |d| {
d.child(
CommandPalette::new("palette-test")
.items(self.commands.clone())
.auto_focus(self.auto_focus)
.on_select(move |item, _, _| {
selected.borrow_mut().push(item.id.to_string())
})
.on_close(move |_, _| *closed.borrow_mut() += 1),
)
})
}
}
fn element(name: &str) -> ElementId {
ElementId::NamedChild(
ElementId::Name("palette-test".into()).into(),
name.to_owned().into(),
)
}
fn setup(cx: &mut TestAppContext, mode: ThemeMode) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(mode, Accent::Violet, cx);
arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
});
}
#[gpui_kit::test]
fn pointer_leave_clears_only_pointer_target_and_keyboard_restores_selection(
cx: &mut TestAppContext,
) {
use gpui_kit::test::TestEventExt as _;
setup(cx, ThemeMode::Dark);
let events = Rc::new(RefCell::new(Vec::new()));
let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
selected: events.clone(),
closed: Rc::new(RefCell::new(0)),
commands: items(),
show: true,
width: 560.0,
auto_focus: false,
});
cx.update(|w, cx| {
w.render_frame(cx);
w.press("ctrl-k", cx);
w.press("down", cx);
assert_eq!(w.find(element("item-c")).selected(), Some(true));
let last = w.find(element("item-b")).bounds().center();
w.pointer_move(last, None, cx);
w.render_frame(cx);
assert_eq!(w.find(element("item-b")).selected(), Some(true));
let panel = w.find("palette-test").bounds();
w.pointer_move(point(panel.center().x, panel.bottom() + px(10.0)), None, cx);
w.render_frame(cx);
for id in ["a", "b", "c"] {
assert_eq!(
w.find(element(&format!("item-{id}"))).selected(),
Some(false)
);
}
assert!(w.try_find(element("highlight")).is_none());
w.press("enter", cx);
assert!(events.borrow().is_empty(), "不得执行已经不可见的鼠标目标");
w.press("down", cx);
assert_eq!(w.find(element("item-b")).selected(), Some(true));
w.pointer_move(point(px(1.0), px(1.0)), None, cx);
w.render_frame(cx);
assert_eq!(w.find(element("item-b")).selected(), Some(true));
w.press("enter", cx);
assert_eq!(events.borrow().as_slice(), &["b"]);
});
}
#[gpui_kit::test]
fn pointer_highlight_fades_in_place_and_reentry_reverses(cx: &mut TestAppContext) {
use gpui_kit::test::TestEventExt as _;
setup(cx, ThemeMode::Dark);
cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx));
let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
selected: Rc::new(RefCell::new(Vec::new())),
closed: Rc::new(RefCell::new(0)),
commands: items(),
show: true,
width: 560.0,
auto_focus: false,
});
cx.update(|w, cx| w.render_frame(cx));
cx.executor()
.advance_clock(std::time::Duration::from_millis(500));
cx.update(|w, cx| {
w.render_frame(cx);
let p = w.find(element("item-b")).bounds().center();
w.pointer_move(p, None, cx);
w.render_frame(cx);
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(500));
let before = cx.update(|w, cx| {
w.render_frame(cx);
let before = w.find(element("highlight")).bounds();
let p = w.find("palette-test").bounds();
w.pointer_move(point(p.center().x, p.bottom() + px(10.0)), None, cx);
w.render_frame(cx);
assert_eq!(w.find(element("highlight")).bounds(), before);
before
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(40));
cx.update(|w, cx| {
w.render_frame(cx);
assert_eq!(
w.find(element("highlight")).bounds(),
before,
"淡出中不得回滑"
);
let p = w.find(element("item-b")).bounds().center();
w.pointer_move(p, None, cx);
w.render_frame(cx);
assert_eq!(w.find(element("item-b")).selected(), Some(true));
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(120));
cx.update(|w, cx| {
w.render_frame(cx);
assert!(w.try_find(element("highlight")).is_some());
let p = w.find("palette-test").bounds();
w.pointer_move(point(p.center().x, p.bottom() + px(10.0)), None, cx);
w.render_frame(cx);
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(120));
cx.update(|w, cx| {
w.render_frame(cx);
assert!(w.try_find(element("highlight")).is_none());
});
}
#[gpui_kit::test]
fn results_clip_rectangle_stays_inside_panel_corners_even_when_scrolled(
cx: &mut TestAppContext,
) {
use gpui_kit::{
InputEvent as _, ScrollDelta, ScrollEvent, TouchPhase, test::TestEventExt as _,
};
setup(cx, ThemeMode::Light);
let (view, cx) = cx.add_window_view(|_, _| PaletteHost {
selected: Rc::new(RefCell::new(Vec::new())),
closed: Rc::new(RefCell::new(0)),
commands: (0..30)
.map(|i| CommandItem::new(format!("r{i}"), format!("Row {i}")))
.collect(),
show: true,
width: 560.0,
auto_focus: false,
});
cx.update(|w, cx| {
for mode in [ThemeMode::Light, ThemeMode::Dark] {
install_arc_theme(mode, Accent::Violet, cx);
for width in [560.0, 360.0] {
view.update(cx, |host, cx| {
host.width = width;
cx.notify();
});
w.render_frame(cx);
let panel = w.find("palette-test").bounds();
let list = w.find(element("results")).bounds();
let radius = f32::from(CommandPaletteTokens::PANEL_RADIUS);
let dx = f32::from(list.left() - panel.left());
let dy = f32::from(panel.bottom() - list.bottom());
assert!(
(radius - dx).powi(2) + (radius - dy).powi(2) <= radius.powi(2),
"矩形裁剪角须位于面板圆角内"
);
assert!(list.right() < panel.right());
assert!(list.size.height <= CommandPaletteTokens::MAX_RESULTS);
w.press("ctrl-k", cx);
w.press("end", cx);
w.simulate_next_frame(cx);
w.render_frame(cx);
let row = w.find(element("item-r29")).bounds();
assert!(row.bottom() <= list.bottom());
let hi = w.find(element("highlight")).bounds();
assert!(hi.left() >= list.left() && hi.right() <= list.right());
w.pointer_move(list.center(), None, cx);
for delta in [60.0, 60.0, -30.0, -2000.0] {
w.dispatch_event(
ScrollEvent {
position: list.center(),
delta: ScrollDelta::Pixels(point(px(0.0), px(delta))),
modifiers: Default::default(),
touch_phase: TouchPhase::Moved,
source: Default::default(),
}
.to_platform_input(),
cx,
);
w.render_frame(cx);
assert_eq!(w.find(element("results")).bounds(), list);
}
}
}
});
}
#[gpui_kit::test]
fn keyboard_scope_does_not_reuse_the_search_input_focus(cx: &mut TestAppContext) {
setup(cx, ThemeMode::Light);
let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
selected: Rc::new(RefCell::new(Vec::new())),
closed: Rc::new(RefCell::new(0)),
commands: items(),
show: true,
width: 560.0,
auto_focus: false,
});
cx.update(|w, cx| {
w.render_frame(cx);
w.press("ctrl-k", cx);
w.press("down", cx);
assert_eq!(w.find(element("item-c")).selected(), Some(true));
w.input("settings", cx);
w.press("enter", cx);
let state = cx.new(|cx| CommandPaletteInternal::new("Search".into(), false, w, cx));
let state = state.read(cx);
assert_ne!(
state.keyboard_scope, state.focus_handle,
"父级事件作用域不能重复声明输入焦点"
);
assert_eq!(
state.query_input.read(cx).focus_handle(cx),
state.focus_handle
);
});
}
#[gpui_kit::test]
fn filtered_rows_pop_out_without_stale_selection_and_expire(cx: &mut TestAppContext) {
setup(cx, ThemeMode::Light);
cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx));
let selected = Rc::new(RefCell::new(Vec::new()));
let events = selected.clone();
let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
selected,
closed: Rc::new(RefCell::new(0)),
commands: items(),
show: true,
width: 560.0,
auto_focus: false,
});
cx.update(|window, cx| window.render_frame(cx));
cx.executor()
.advance_clock(std::time::Duration::from_millis(500));
cx.update(|window, cx| {
window.render_frame(cx);
window.press("ctrl-k", cx);
window.input("dup", cx);
assert!(window.try_find(element("item-a")).is_none());
assert!(window.try_find(element("exit-a")).is_some());
assert!(window.try_find(element("item-c")).is_some());
assert_eq!(window.find(element("item-c")).selected(), Some(true));
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(180));
cx.update(|window, cx| {
window.render_frame(cx);
assert!(window.try_find(element("exit-a")).is_none());
window.press("enter", cx);
});
assert_eq!(events.borrow().as_slice(), &["c"]);
}
#[gpui_kit::test]
fn whole_group_exit_keeps_heading_copy_and_shortcuts_then_reverses(cx: &mut TestAppContext) {
setup(cx, ThemeMode::Dark);
cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx));
let (view, cx) = cx.add_window_view(|_, _| PaletteHost {
selected: Rc::new(RefCell::new(Vec::new())),
closed: Rc::new(RefCell::new(0)),
commands: vec![
CommandItem::new("a", "Alpha").group("First"),
CommandItem::new("b", "Beta")
.group("Second")
.description("Details")
.shortcut("Ctrl+B"),
],
show: true,
width: 560.0,
auto_focus: false,
});
cx.update(|w, cx| w.render_frame(cx));
cx.executor()
.advance_clock(std::time::Duration::from_millis(700));
cx.update(|w, cx| w.render_frame(cx));
cx.executor()
.advance_clock(std::time::Duration::from_millis(700));
let before = cx.update(|w, cx| {
w.render_frame(cx);
let before = w.find(element("group-Second")).bounds();
w.press("ctrl-k", cx);
w.input("alpha", cx);
let exit = w.find(element("exit-group-Second"));
assert_eq!(exit.bounds().origin.y, before.origin.y);
assert!(w.try_find(element("exit-b")).is_none());
let shortcut = ElementId::NamedChild(element("exit").into(), "shortcut-b".into());
assert!(w.try_find(shortcut).is_some());
assert_eq!(exit.role(), None);
before
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(40));
cx.update(|w, cx| {
w.render_frame(cx);
w.press("escape", cx);
assert!(w.try_find(element("exit-group-Second")).is_none());
assert!(w.try_find(element("group-Second")).is_some());
view.update(cx, |_, cx| cx.notify());
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(700));
cx.update(|w, cx| {
w.render_frame(cx);
assert_eq!(
w.find(element("group-Second")).bounds().origin.y,
before.origin.y
);
w.input("alpha", cx);
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(180));
cx.update(|w, cx| {
w.render_frame(cx);
assert!(w.try_find(element("exit-group-Second")).is_none());
});
}
#[gpui_kit::test]
fn row_exit_retains_shortcut_and_mid_glide_position(cx: &mut TestAppContext) {
setup(cx, ThemeMode::Light);
cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx));
let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
selected: Rc::new(RefCell::new(Vec::new())),
closed: Rc::new(RefCell::new(0)),
commands: vec![
CommandItem::new("a", "Alpha").group("Actions"),
CommandItem::new("b", "Beta")
.group("Actions")
.description("Details")
.shortcut("Ctrl+B"),
CommandItem::new("c", "Gamma").group("Actions"),
],
show: true,
width: 560.0,
auto_focus: false,
});
cx.update(|w, cx| w.render_frame(cx));
cx.executor()
.advance_clock(std::time::Duration::from_millis(700));
cx.update(|w, cx| {
w.render_frame(cx);
w.press("ctrl-k", cx);
w.input("beta", cx);
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(40));
cx.update(|w, cx| {
w.render_frame(cx);
let before = w.find(element("item-b")).bounds().origin.y;
w.press("escape", cx);
w.input("gamma", cx);
assert!((f32::from(w.find(element("exit-b")).bounds().origin.y - before)).abs() < 0.1);
let shortcut = ElementId::NamedChild(element("exit").into(), "shortcut-b".into());
assert!(w.try_find(shortcut).is_some());
});
}
#[gpui_kit::test]
fn long_reorder_snaps_exits_and_does_not_resume_glide(cx: &mut TestAppContext) {
setup(cx, ThemeMode::Light);
cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx));
let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
selected: Rc::new(RefCell::new(Vec::new())),
closed: Rc::new(RefCell::new(0)),
commands: (0..12)
.map(|i| CommandItem::new(format!("n{i}"), format!("Command {i}")))
.collect(),
show: true,
width: 560.0,
auto_focus: false,
});
cx.update(|w, cx| w.render_frame(cx));
cx.executor()
.advance_clock(std::time::Duration::from_millis(700));
cx.update(|w, cx| {
w.render_frame(cx);
w.press("ctrl-k", cx);
w.input("command 11", cx);
assert!(w.try_find(element("exit-n0")).is_none());
let before = w.find(element("item-n11")).bounds().origin.y;
w.render_frame(cx);
assert_eq!(w.find(element("item-n11")).bounds().origin.y, before);
});
}
#[gpui_kit::test]
fn entry_keeps_final_layout_size_without_trailing_growth(cx: &mut TestAppContext) {
setup(cx, ThemeMode::Light);
cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx));
let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
selected: Rc::new(RefCell::new(Vec::new())),
closed: Rc::new(RefCell::new(0)),
commands: items(),
show: true,
width: 560.0,
auto_focus: false,
});
let first = cx.update(|w, cx| {
w.render_frame(cx);
(
w.find("palette-test").bounds(),
w.find(element("item-a")).bounds(),
)
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(700));
cx.update(|w, cx| {
w.render_frame(cx);
let settled = w.find("palette-test").bounds();
assert_eq!(first.0.size, settled.size, "入场不得改变面板布局尺寸");
assert!((f32::from(first.0.center().x - settled.center().x)).abs() < 0.1);
assert!(
(f32::from(first.0.origin.y - settled.origin.y)
- f32::from(CommandPaletteTokens::ENTER_Y))
.abs()
< 0.1
);
assert_eq!(first.1.size, w.find(element("item-a")).bounds().size);
});
}
#[gpui_kit::test]
fn reduced_motion_skips_group_exits_and_entry_motion(cx: &mut TestAppContext) {
setup(cx, ThemeMode::Dark);
let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
selected: Rc::new(RefCell::new(Vec::new())),
closed: Rc::new(RefCell::new(0)),
commands: items(),
show: true,
width: 560.0,
auto_focus: false,
});
cx.update(|w, cx| {
w.render_frame(cx);
assert_eq!(
w.find(element("item-a")).bounds().size.height,
CommandPaletteTokens::ROW
);
let width = w.find("palette-test").bounds().size.width;
w.press("ctrl-k", cx);
w.input("dup", cx);
assert!(w.try_find(element("exit-group-Settings")).is_none());
assert!(w.try_find(element("exit-a")).is_none());
assert_eq!(w.find("palette-test").bounds().size.width, width);
});
}
#[gpui_kit::test]
fn result_empty_wait_sequence_preserves_exit_and_reverses(cx: &mut TestAppContext) {
setup(cx, ThemeMode::Dark);
cx.update(|cx| arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx));
let selected = Rc::new(RefCell::new(Vec::new()));
let events = selected.clone();
let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
selected,
closed: Rc::new(RefCell::new(0)),
commands: items(),
show: true,
width: 560.0,
auto_focus: false,
});
cx.update(|window, cx| window.render_frame(cx));
cx.executor()
.advance_clock(std::time::Duration::from_millis(500));
cx.update(|window, cx| {
window.render_frame(cx);
window.press("ctrl-k", cx);
window.input("zzzz", cx);
assert!(window.try_find(element("item-a")).is_some());
assert!(window.try_find(element("empty")).is_none());
window.click(element("item-a"), cx);
window.press("enter", cx);
});
assert!(events.borrow().is_empty());
cx.executor()
.advance_clock(std::time::Duration::from_millis(180));
cx.update(|window, cx| {
window.render_frame(cx);
assert!(window.try_find(element("empty")).is_some());
assert!(window.try_find(element("item-a")).is_none());
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(300));
cx.update(|window, cx| {
window.render_frame(cx);
window.press("escape", cx);
assert!(window.try_find(element("empty")).is_some());
assert!(window.try_find(element("item-a")).is_none());
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(60));
cx.update(|window, cx| {
window.render_frame(cx);
window.input("zzzz", cx);
assert!(window.try_find(element("empty")).is_some());
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(300));
cx.update(|window, cx| {
window.render_frame(cx);
assert!(window.try_find(element("empty")).is_some());
window.press("escape", cx);
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(180));
cx.update(|window, cx| {
window.render_frame(cx);
assert!(window.try_find(element("item-a")).is_some());
assert!(window.try_find(element("empty")).is_none());
});
}
#[gpui_kit::test]
fn keyboard_walks_visual_groups_without_wrapping_and_selects(cx: &mut TestAppContext) {
setup(cx, ThemeMode::Light);
let selected = Rc::new(RefCell::new(Vec::new()));
let events = selected.clone();
let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
selected,
closed: Rc::new(RefCell::new(0)),
commands: items(),
show: true,
width: 560.0,
auto_focus: false,
});
cx.update(|window, cx| {
window.render_frame(cx);
assert_eq!(window.find(element("results")).role(), Some(Role::ListBox));
assert_eq!(window.find(element("item-a")).selected(), Some(true));
window.press("ctrl-k", cx);
window.press("up", cx);
assert_eq!(window.find(element("item-a")).selected(), Some(true));
window.press("down", cx);
assert_eq!(window.find(element("item-c")).selected(), Some(true));
window.press("end", cx);
window.press("down", cx);
assert_eq!(window.find(element("item-b")).selected(), Some(true));
window.press("home", cx);
window.press("enter", cx);
});
assert_eq!(events.borrow().as_slice(), &["a"]);
}
#[gpui_kit::test]
fn search_clear_escape_pointer_select_and_close_are_reachable(cx: &mut TestAppContext) {
setup(cx, ThemeMode::Dark);
let selected = Rc::new(RefCell::new(Vec::new()));
let closed = Rc::new(RefCell::new(0));
let selection_events = selected.clone();
let close_events = closed.clone();
let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
selected,
closed,
commands: items(),
show: true,
width: 560.0,
auto_focus: false,
});
cx.update(|window, cx| {
window.render_frame(cx);
window.press("ctrl-k", cx);
window.input("dup pr", cx);
window.render_frame(cx);
assert!(window.try_find(element("item-a")).is_none());
assert_eq!(window.find(element("item-c")).selected(), Some(true));
window.click(element("item-c"), cx);
assert_eq!(selection_events.borrow().as_slice(), &["c"]);
assert!(window.try_find(element("item-a")).is_some());
window.input("zzzzzz", cx);
window.render_frame(cx);
assert!(window.try_find(element("empty")).is_some());
window.press("enter", cx);
assert_eq!(selection_events.borrow().len(), 1);
window.press("escape", cx);
assert_eq!(*close_events.borrow(), 0);
assert!(window.try_find(element("item-a")).is_some());
window.input("project", cx);
window.render_frame(cx);
window.click(element("clear"), cx);
assert!(window.try_find(element("item-a")).is_some());
window.press("escape", cx);
assert_eq!(*close_events.borrow(), 1);
window.click(element("close"), cx);
assert_eq!(*close_events.borrow(), 2);
});
}
#[gpui_kit::test]
fn whitespace_escape_clears_before_closing(cx: &mut TestAppContext) {
setup(cx, ThemeMode::Light);
let closed = Rc::new(RefCell::new(0));
let events = closed.clone();
let (_, cx) = cx.add_window_view(|_, _| PaletteHost {
selected: Rc::new(RefCell::new(Vec::new())),
closed,
commands: items(),
show: true,
width: 560.0,
auto_focus: false,
});
cx.update(|window, cx| {
window.render_frame(cx);
window.press("ctrl-k", cx);
window.input(" ", cx);
window.press("escape", cx);
assert_eq!(*events.borrow(), 0);
assert!(window.try_find(element("clear")).is_none());
window.press("escape", cx);
assert_eq!(*events.borrow(), 1);
});
}
#[gpui_kit::test]
fn shortcuts_follow_width_breakpoints_and_end_scrolls_into_view(cx: &mut TestAppContext) {
setup(cx, ThemeMode::Dark);
let commands = (0..30)
.map(|index| {
CommandItem::new(format!("row-{index}"), format!("Command {index}"))
.shortcut("Ctrl+K")
})
.collect();
let (view, cx) = cx.add_window_view(|_, _| PaletteHost {
selected: Rc::new(RefCell::new(Vec::new())),
closed: Rc::new(RefCell::new(0)),
commands,
show: true,
width: 560.0,
auto_focus: false,
});
cx.update(|window, cx| {
window.render_frame(cx);
assert!(window.try_find(element("shortcut-row-0")).is_some());
view.update(cx, |host, cx| {
host.width = 360.0;
cx.notify();
});
window.render_frame(cx);
window.render_frame(cx);
assert!(window.try_find(element("shortcut-row-0")).is_none());
view.update(cx, |host, cx| {
host.width = 560.0;
cx.notify();
});
window.render_frame(cx);
window.render_frame(cx);
assert!(window.try_find(element("shortcut-row-0")).is_some());
window.press("ctrl-k", cx);
window.press("end", cx);
window.simulate_next_frame(cx);
window.render_frame(cx);
let row = window.find(element("item-row-29"));
let frame = window.find(element("results")).bounds();
assert_eq!(row.selected(), Some(true));
assert!(row.bounds().origin.y >= frame.origin.y);
assert!(row.bounds().bottom() <= frame.bottom());
window.press("home", cx);
window.simulate_next_frame(cx);
window.render_frame(cx);
assert!(window.find(element("item-row-0")).bounds().origin.y >= frame.origin.y);
});
}
#[gpui_kit::test]
fn autofocus_does_not_steal_focus_on_rerender_and_shortcut_unsubscribes(
cx: &mut TestAppContext,
) {
setup(cx, ThemeMode::Light);
let (view, cx) = cx.add_window_view(|_, _| PaletteHost {
selected: Rc::new(RefCell::new(Vec::new())),
closed: Rc::new(RefCell::new(0)),
commands: items(),
show: true,
width: 560.0,
auto_focus: true,
});
cx.update(|window, cx| {
window.render_frame(cx);
window.simulate_next_frame(cx);
window.render_frame(cx);
assert!(window.focused(cx).is_some());
window.blur(cx);
view.update(cx, |_, cx| cx.notify());
window.render_frame(cx);
window.render_frame(cx);
assert!(window.focused(cx).is_none());
window.press("ctrl-k", cx);
assert!(window.focused(cx).is_some());
window.blur(cx);
view.update(cx, |host, cx| {
host.show = false;
cx.notify();
});
window.render_frame(cx);
window.render_frame(cx);
});
cx.run_until_parked();
cx.update(|window, cx| {
window.press("ctrl-k", cx);
assert!(window.focused(cx).is_none());
});
}
#[gpui_kit::test]
fn empty_palette_and_dynamic_items_do_not_select_stale_commands(cx: &mut TestAppContext) {
setup(cx, ThemeMode::Light);
let events = Rc::new(RefCell::new(Vec::new()));
let (view, cx) = cx.add_window_view(|_, _| PaletteHost {
selected: events.clone(),
closed: Rc::new(RefCell::new(0)),
commands: Vec::new(),
show: true,
width: 560.0,
auto_focus: false,
});
cx.update(|window, cx| {
window.render_frame(cx);
window.press("ctrl-k", cx);
for key in ["down", "end", "up", "home", "enter"] {
window.press(key, cx);
}
assert!(events.borrow().is_empty());
assert!(window.try_find(element("empty")).is_some());
view.update(cx, |host, cx| {
host.commands = items();
cx.notify();
});
window.render_frame(cx);
window.press("enter", cx);
assert_eq!(events.borrow().as_slice(), &["a"]);
view.update(cx, |host, cx| {
host.show = false;
cx.notify();
});
window.render_frame(cx);
assert!(window.try_find(element("results")).is_none());
});
}
}