refactor: consolidate shared ui helpers and prune unused code

This commit is contained in:
2026-11-22 18:23:21 +07:00
parent 4a72f2b4a0
commit 9daee9d54d
82 changed files with 3607 additions and 7184 deletions
+2 -7
View File
@@ -269,7 +269,7 @@ impl RenderOnce for Alert {
/// One pushed alert, with its identity in the stack.
#[derive(Clone)]
pub struct AlertEntry {
struct AlertEntry {
/// The id [`Alerts::push`] returned.
pub id: usize,
/// The alert as pushed.
@@ -338,14 +338,9 @@ impl Alerts {
}
/// The stacked alerts, oldest first.
pub fn entries(&self) -> &[AlertEntry] {
fn entries(&self) -> &[AlertEntry] {
&self.entries
}
/// How many alerts are stacked.
pub fn count(&self) -> usize {
self.entries.len()
}
}
/// The floating stack of pushed alerts, topmost right.
+95 -22
View File
@@ -14,6 +14,7 @@
use std::collections::HashMap;
use std::fmt::Display;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, div,
@@ -140,6 +141,78 @@ impl RenderOnce for Avatar {
}
}
/// An avatar with the display name beside it.
#[derive(IntoElement)]
#[must_use]
pub struct IdentityRow {
id: SharedString,
name: SharedString,
picture: Option<SharedString>,
size: Size,
truncate: bool,
style: StyleRefinement,
}
impl IdentityRow {
/// Creates the row for `id` (the pixel-fallback seed) showing `name`.
pub fn new<ID, N>(id: ID, name: N, picture: Option<SharedString>) -> Self
where
ID: Into<SharedString>,
N: Into<SharedString>,
{
Self {
id: id.into(),
name: name.into(),
picture,
size: Size::default(),
truncate: false,
style: StyleRefinement::default(),
}
}
/// Truncates the name to one line inside the available width.
pub fn truncate(mut self) -> Self {
self.truncate = true;
self
}
}
impl Sizable for IdentityRow {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl gpui::Styled for IdentityRow {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for IdentityRow {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
h_flex()
.refine_style(&self.style)
.child(
Avatar::new(self.id.clone())
.name(self.name.clone())
.picture(self.picture)
.with_size(self.size),
)
.child(
div()
.when(self.truncate, |name| {
name.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
})
.child(self.name),
)
}
}
/// A deterministic, offline pixel-art avatar.
#[derive(IntoElement)]
struct PixelAvatar {
@@ -218,6 +291,28 @@ thread_local! {
std::cell::RefCell::new(HashMap::new());
}
/// Tiny xorshift64* PRNG for deriving the pattern from the seed.
struct PixelRng(u64);
impl PixelRng {
fn new(seed: u64) -> Self {
Self(seed.max(1))
}
fn next(&mut self) -> u64 {
let mut x = self.0;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.0 = x;
x.wrapping_mul(0x2545_f491_4f6c_dd1d)
}
fn chance(&mut self, probability: f32) -> bool {
self.next() as f32 / (u64::MAX as f32) < probability
}
}
fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] {
let cached = PATTERN_CACHE.with(|cache| cache.borrow().get(&seed).copied());
if let Some(cached) = cached {
@@ -284,25 +379,3 @@ fn fnv1a(bytes: &[u8]) -> u64 {
}
hash
}
/// Tiny xorshift64* PRNG for deriving the pattern from the seed.
struct PixelRng(u64);
impl PixelRng {
fn new(seed: u64) -> Self {
Self(seed.max(1))
}
fn next(&mut self) -> u64 {
let mut x = self.0;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.0 = x;
x.wrapping_mul(0x2545_f491_4f6c_dd1d)
}
fn chance(&mut self, probability: f32) -> bool {
self.next() as f32 / (u64::MAX as f32) < probability
}
}
+12 -12
View File
@@ -46,18 +46,6 @@ pub enum ButtonVariant {
Destructive,
}
/// The variant colors a button paints with, resolved from the active theme.
pub struct ButtonChrome {
/// The resting background, `None` for unpainted variants like `Ghost`.
pub background: Option<Hsla>,
pub foreground: Hsla,
pub hover: Hsla,
pub pressed: Hsla,
pub border: Hsla,
pub hover_border: Hsla,
pub pressed_border: Hsla,
}
impl ButtonVariant {
/// The variant's colors from the active theme.
pub fn chrome(&self, cx: &App) -> ButtonChrome {
@@ -117,6 +105,18 @@ pub enum ButtonSide {
Right,
}
/// The variant colors a button paints with, resolved from the active theme.
pub struct ButtonChrome {
/// The resting background, `None` for unpainted variants like `Ghost`.
pub background: Option<Hsla>,
pub foreground: Hsla,
pub hover: Hsla,
pub pressed: Hsla,
pub border: Hsla,
pub hover_border: Hsla,
pub pressed_border: Hsla,
}
/// A push button that renders a label, an icon, or both, and fires
/// [`Button::on_click`] on click, Enter, or Space.
#[derive(IntoElement)]
+70 -6
View File
@@ -15,21 +15,20 @@ use std::time::Duration;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyView, App, ClipboardItem, ElementId, Entity, IntoElement, RenderOnce, SharedString,
StyleRefinement, Task, Window,
AnyView, App, ClipboardItem, ElementId, Entity, IntoElement, ParentElement as _, RenderOnce,
SharedString, StyleRefinement, Styled as _, Task, Window, div,
};
use crate::components::button::{Button, ButtonVariant};
use crate::components::common::{ResultLogErr as _, Sizable, StyledExt as _};
use crate::components::common::{ResultLogErr as _, Sizable, StyledExt as _, h_flex};
use crate::icons::IconRole;
use crate::theme::Size;
use crate::theme::{ActiveTheme as _, Size};
/// How long the check mark shows before reverting to the copy icon.
pub const COPIED_DURATION: Duration = Duration::from_secs(1);
const COPIED_DURATION: Duration = Duration::from_secs(1);
/// The tooltip view builder gpui's `.tooltip(...)` expects.
type TooltipBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyView>;
/// Runs after the value lands on the clipboard.
type CopiedHandler = Box<dyn Fn(&mut App)>;
@@ -184,3 +183,68 @@ impl RenderOnce for ClipboardButton {
})
}
}
/// A copyable value shown as a boxed row with a trailing copy button.
#[derive(IntoElement)]
#[must_use]
pub struct CopyRow {
id: SharedString,
value: SharedString,
large_text: bool,
}
impl CopyRow {
/// Monospace `value` in a secondary-background row (the clone-command look).
pub fn new<ID, V>(id: ID, value: V) -> Self
where
ID: Into<SharedString>,
V: Into<SharedString>,
{
Self {
id: id.into(),
value: value.into(),
large_text: false,
}
}
/// Base-size label and default-size copy button (the about-dialog list look).
pub fn text_base(mut self) -> Self {
self.large_text = true;
self
}
}
impl RenderOnce for CopyRow {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
h_flex()
.h_8()
.px_2()
.gap_2()
.min_w_0()
.bg(theme.colors.secondary)
.rounded(theme.radius.control)
.text_color(theme.colors.secondary_foreground)
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.when(self.large_text, |text| text.text_base())
.when(!self.large_text, |text| {
text.font_family(theme.mono_font).text_xs()
})
.child(self.value.clone()),
)
.child(if self.large_text {
ClipboardButton::new(self.id, self.value).into_any_element()
} else {
ClipboardButton::new(self.id, self.value)
.xsmall()
.into_any_element()
})
}
}
+145 -161
View File
@@ -47,34 +47,13 @@ actions!(code_view, [Copy]);
/// The key context the code view declares while it holds focus.
pub const CODE_VIEW_CONTEXT: &str = "CodeView";
/// Binds the code view's copy chord: cmd-c on macOS, ctrl-c elsewhere.
///
/// Call once at startup. Without it, selection copy has no key.
pub fn bind_code_view_keys(cx: &mut App) {
let context = match KeyBindingContextPredicate::parse(CODE_VIEW_CONTEXT) {
Ok(context) => Some(Rc::new(context)),
Err(error) => {
log::error!("failed to parse code view key context: {error}");
return;
}
};
let binding = match KeyBinding::load("secondary-c", Box::new(Copy), context, false, None, cx) {
Ok(binding) => binding,
Err(error) => {
log::error!("failed to parse code view copy keystroke: {error}");
return;
}
};
cx.bind_keys([binding]);
}
/// A point in the source, in lines and characters (not bytes).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SelectionPoint {
struct SelectionPoint {
/// The zero-based line index.
pub row: usize,
row: usize,
/// The zero-based character offset within the line.
pub col: usize,
col: usize,
}
impl SelectionPoint {
@@ -235,24 +214,8 @@ impl CodeViewState {
self.active_line
}
/// Selects a range, endpoints in lines and characters.
pub fn select_range(
&mut self,
start: SelectionPoint,
end: SelectionPoint,
cx: &mut Context<Self>,
) {
self.selection = if start.earlier_than(&end) {
Some((start, end))
} else {
Some((end, start))
};
self.selecting = false;
cx.notify();
}
/// The selected range, endpoints in document order, when there is one.
pub fn selection(&self) -> Option<(SelectionPoint, SelectionPoint)> {
fn selection(&self) -> Option<(SelectionPoint, SelectionPoint)> {
self.selection.map(|(anchor, head)| {
if anchor.earlier_than(&head) {
(anchor, head)
@@ -263,7 +226,7 @@ impl CodeViewState {
}
/// The selected text, or `None` when nothing is selected.
pub fn selected_text(&self) -> Option<String> {
fn selected_text(&self) -> Option<String> {
let (start, end) = self.selection()?;
let lines: Vec<&str> = self.source.split('\n').collect();
@@ -325,6 +288,128 @@ impl CodeViewState {
SelectionPoint { row, col }
}
#[allow(clippy::too_many_arguments)]
fn render_row(
&self,
id: &ElementId,
line_ix: usize,
active: bool,
selection: Option<(SelectionPoint, SelectionPoint)>,
mono_font: &'static str,
colors: ColorTokens,
ramps: Ramps,
text_size: Pixels,
line_height: Pixels,
cx: &App,
) -> gpui::AnyElement {
let layout = self.line_layouts.get(line_ix);
let text = layout.map_or("", |layout| layout.text.as_str());
let roles = layout.map_or(&[][..], |layout| layout.roles.as_slice());
let char_count = text.chars().count();
let mut selected = vec![false; char_count];
if let Some((start, end)) = selection
&& line_ix >= start.row
&& line_ix <= end.row
{
let start_col = if line_ix == start.row {
start.col.min(char_count)
} else {
0
};
let end_col = if line_ix == end.row {
end.col.min(char_count)
} else {
char_count
};
for slot in &mut selected[start_col..end_col] {
*slot = true;
}
}
let mut highlights: Vec<(std::ops::Range<usize>, HighlightStyle)> = Vec::new();
let mut run_start = 0usize;
let mut run_end = 0usize;
let mut run_role = Role::Text;
let mut run_selected = false;
for (char_ix, (byte_ix, character)) in text.char_indices().enumerate() {
let fresh =
char_ix == 0 || roles[char_ix] != run_role || selected[char_ix] != run_selected;
if fresh {
if char_ix > 0 {
highlights.push((
run_start..run_end,
run_role.run_style(run_selected, colors, ramps),
));
}
run_start = byte_ix;
run_role = roles[char_ix];
run_selected = selected[char_ix];
}
run_end = byte_ix + character.len_utf8();
}
if run_end > run_start || !text.is_empty() {
highlights.push((
run_start..run_end,
run_role.run_style(run_selected, colors, ramps),
));
}
let style = TextStyle {
color: colors.foreground,
font_family: SharedString::from(mono_font),
font_size: text_size.into(),
line_height: line_height.into(),
white_space: gpui::WhiteSpace::Nowrap,
..Default::default()
};
div()
.debug_selector(move || format!("{id}-row-{line_ix}"))
.id(("code-row", line_ix))
.w_full()
.text_xs()
.h(line_height)
.flex()
.items_center()
.overflow_hidden()
.when(active, |row| {
row.bg(Hsla {
a: colors.muted.a * WASH_ALPHA_SOFT,
..colors.muted
})
})
.child(
gutter_cell(
cx,
if active {
colors.foreground
} else {
colors.muted_foreground
},
format!("{}", line_ix + 1),
)
.justify_end()
.pr_2()
.whitespace_nowrap(),
)
.child(
div()
.flex_1()
.min_w_0()
.ml_4()
.overflow_hidden()
.whitespace_nowrap()
.child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)),
)
.into_any_element()
}
}
impl gpui::Focusable for CodeViewState {
@@ -362,8 +447,7 @@ impl Render for CodeViewState {
range
.map(|line_ix| {
render_row(
code,
code.render_row(
&id,
line_ix,
active_line == Some(line_ix),
@@ -523,123 +607,23 @@ impl Render for CodeViewState {
}
}
#[allow(clippy::too_many_arguments)]
fn render_row(
code: &CodeViewState,
id: &ElementId,
line_ix: usize,
active: bool,
selection: Option<(SelectionPoint, SelectionPoint)>,
mono_font: &'static str,
colors: ColorTokens,
ramps: Ramps,
text_size: Pixels,
line_height: Pixels,
cx: &App,
) -> gpui::AnyElement {
let layout = code.line_layouts.get(line_ix);
let text = layout.map_or("", |layout| layout.text.as_str());
let roles = layout.map_or(&[][..], |layout| layout.roles.as_slice());
let char_count = text.chars().count();
let mut selected = vec![false; char_count];
if let Some((start, end)) = selection
&& line_ix >= start.row
&& line_ix <= end.row
{
let start_col = if line_ix == start.row {
start.col.min(char_count)
} else {
0
};
let end_col = if line_ix == end.row {
end.col.min(char_count)
} else {
char_count
};
for slot in &mut selected[start_col..end_col] {
*slot = true;
/// Binds the code view's copy chord: cmd-c on macOS, ctrl-c elsewhere.
///
/// Call once at startup. Without it, selection copy has no key.
pub fn bind_code_view_keys(cx: &mut App) {
let context = match KeyBindingContextPredicate::parse(CODE_VIEW_CONTEXT) {
Ok(context) => Some(Rc::new(context)),
Err(error) => {
log::error!("failed to parse code view key context: {error}");
return;
}
}
let mut highlights: Vec<(std::ops::Range<usize>, HighlightStyle)> = Vec::new();
let mut run_start = 0usize;
let mut run_end = 0usize;
let mut run_role = Role::Text;
let mut run_selected = false;
for (char_ix, (byte_ix, character)) in text.char_indices().enumerate() {
let fresh = char_ix == 0 || roles[char_ix] != run_role || selected[char_ix] != run_selected;
if fresh {
if char_ix > 0 {
highlights.push((
run_start..run_end,
run_role.run_style(run_selected, colors, ramps),
));
}
run_start = byte_ix;
run_role = roles[char_ix];
run_selected = selected[char_ix];
}
run_end = byte_ix + character.len_utf8();
}
if run_end > run_start || !text.is_empty() {
highlights.push((
run_start..run_end,
run_role.run_style(run_selected, colors, ramps),
));
}
let style = TextStyle {
color: colors.foreground,
font_family: SharedString::from(mono_font),
font_size: text_size.into(),
line_height: line_height.into(),
white_space: gpui::WhiteSpace::Nowrap,
..Default::default()
};
div()
.debug_selector(move || format!("{id}-row-{line_ix}"))
.id(("code-row", line_ix))
.w_full()
.text_xs()
.h(line_height)
.flex()
.items_center()
.overflow_hidden()
.when(active, |row| {
row.bg(Hsla {
a: colors.muted.a * WASH_ALPHA_SOFT,
..colors.muted
})
})
.child(
gutter_cell(
cx,
if active {
colors.foreground
} else {
colors.muted_foreground
},
format!("{}", line_ix + 1),
)
.justify_end()
.pr_2()
.whitespace_nowrap(),
)
.child(
div()
.flex_1()
.min_w_0()
.ml_4()
.overflow_hidden()
.whitespace_nowrap()
.child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)),
)
.into_any_element()
let binding = match KeyBinding::load("secondary-c", Box::new(Copy), context, false, None, cx) {
Ok(binding) => binding,
Err(error) => {
log::error!("failed to parse code view copy keystroke: {error}");
return;
}
};
cx.bind_keys([binding]);
}
+32 -124
View File
@@ -2,9 +2,8 @@
//!
//! The state is the view: [`ComboboxState`] owns the query field and the
//! options, and the owner renders the entity itself. Typing filters, the
//! arrow keys move a highlight, Enter commits, and what happens to unmatched
//! text when the field loses focus is decided by [`UnmatchedText`], which
//! reverts by default.
//! arrow keys move a highlight, Enter commits, and unmatched text reverts to
//! the chosen option's label (or empties the field) when focus is lost.
//!
//! # Examples
//!
@@ -33,13 +32,12 @@ use gpui::{
App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding,
MouseButton, MouseDownEvent, ParentElement as _, Pixels, Render, Role, SharedString,
StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Task,
UniformListScrollHandle, Window, actions, anchored, canvas, deferred, div, point, px,
uniform_list,
UniformListScrollHandle, Window, actions, canvas, div, uniform_list,
};
use crate::components::common::{
ControlSizing, OVERLAY_LAYER, ResultLogErr as _, Sizable, StyledExt as _, floating_panel,
h_flex, paint_highlighted_row, v_flex, wrapping_adjacent_selectable,
ControlSizing, ResultLogErr as _, Sizable, StyledExt as _, floating_panel, h_flex,
paint_highlighted_row, v_flex, wrapping_adjacent_selectable,
};
use crate::components::empty_state::EmptyState;
use crate::components::input::{Input, InputState, InputStateEvent};
@@ -54,41 +52,10 @@ actions!(
/// The key context the combobox's wrapper declares.
pub const COMBOBOX_CONTEXT: &str = "Combobox";
/// Binds the combobox's four keys: down, up, enter, and escape.
pub fn bind_combobox_keys(cx: &mut App) {
let under_input = Some("Combobox > Input");
cx.bind_keys([
KeyBinding::new("down", HighlightNext, under_input),
KeyBinding::new("up", HighlightPrevious, under_input),
KeyBinding::new("enter", Choose, under_input),
KeyBinding::new("escape", Dismiss, under_input),
KeyBinding::new("down", HighlightNext, Some(COMBOBOX_CONTEXT)),
KeyBinding::new("up", HighlightPrevious, Some(COMBOBOX_CONTEXT)),
KeyBinding::new("enter", Choose, Some(COMBOBOX_CONTEXT)),
KeyBinding::new("escape", Dismiss, Some(COMBOBOX_CONTEXT)),
]);
}
/// What happens to text that matches no option when the field loses focus.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum UnmatchedText {
/// Restore the chosen option's label, or empty the field.
#[default]
Revert,
/// Leave the text and leave the value cleared.
Keep,
/// Hand the text to the `on_create` handler.
Create,
}
/// An option for a [`Combobox`]: a value and the label the filter matches on.
pub type ComboboxOption<T> = (T, SharedString);
/// Reports the value whenever it changes.
pub type ComboboxHandler<T> = Rc<dyn Fn(Option<T>, &mut Window, &mut App)>;
/// Receives unmatched text when the field loses focus in create mode.
pub type ComboboxCreateHandler = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
/// Decides which options survive a query: the query, the value, the label.
pub type ComboboxFilter<T> = Rc<dyn Fn(&str, &T, &SharedString) -> bool>;
/// Builder for a combobox, consumed by [`ComboboxState::new`].
#[must_use]
@@ -102,9 +69,6 @@ where
selected: Option<T>,
placeholder: SharedString,
on_change: Option<ComboboxHandler<T>>,
on_create: Option<ComboboxCreateHandler>,
filter: Option<ComboboxFilter<T>>,
unmatched: UnmatchedText,
size: Size,
/// Icon shown at the field's leading edge while a value is selected.
selected_icon: Option<Icon>,
@@ -127,9 +91,6 @@ where
selected: None,
placeholder: SharedString::from("Select..."),
on_change: None,
on_create: None,
filter: None,
unmatched: UnmatchedText::default(),
size: Size::default(),
selected_icon: None,
style: StyleRefinement::default(),
@@ -169,31 +130,6 @@ where
self
}
/// Hands unmatched text to `handler` when the field loses focus.
pub fn on_create<F>(mut self, handler: F) -> Self
where
F: Fn(SharedString, &mut Window, &mut App) + 'static,
{
self.on_create = Some(Rc::new(handler));
self.unmatched = UnmatchedText::Create;
self
}
/// Sets the matcher that decides which options survive a query.
pub fn filter<F>(mut self, filter: F) -> Self
where
F: Fn(&str, &T, &SharedString) -> bool + 'static,
{
self.filter = Some(Rc::new(filter));
self
}
/// Leaves unmatched text in the field on blur.
pub fn keep_unmatched_text(mut self) -> Self {
self.unmatched = UnmatchedText::Keep;
self
}
/// Overrides the accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
@@ -250,9 +186,6 @@ where
/// The highlighted popup *row*, when the popup is open.
highlight: Option<usize>,
on_change: Option<ComboboxHandler<T>>,
on_create: Option<ComboboxCreateHandler>,
filter: ComboboxFilter<T>,
unmatched: UnmatchedText,
size: Size,
/// Width refinements from the builder, applied to the wrapper each render.
style: StyleRefinement,
@@ -312,11 +245,6 @@ where
visible,
highlight: None,
on_change: combobox.on_change,
on_create: combobox.on_create,
filter: combobox.filter.unwrap_or_else(|| {
Rc::new(|query, _value, label| label.to_lowercase().contains(&query.to_lowercase()))
}),
unmatched: combobox.unmatched,
size: combobox.size,
style: combobox.style,
selected_icon: combobox.selected_icon,
@@ -326,21 +254,6 @@ where
}
}
/// The text currently in the field.
pub fn text(&self, cx: &App) -> String {
self.query.read(cx).value().to_string()
}
/// Focuses the query field.
pub fn focus(&self, window: &mut Window, cx: &mut App) {
window.focus(&self.query.read(cx).focus_handle(), cx);
}
/// Whether the option list is showing.
pub fn is_open(&self) -> bool {
self.highlight.is_some()
}
/// The chosen value.
pub fn selected(&self) -> Option<&T> {
self.selected.as_ref()
@@ -367,11 +280,6 @@ where
cx.notify();
}
/// A copy of the current choice list.
pub fn options_snapshot(&self) -> Vec<ComboboxOption<T>> {
self.options.clone()
}
/// The label of the chosen option, if there is one.
fn selected_label(&self) -> Option<SharedString> {
let selected = self.selected.as_ref()?;
@@ -383,12 +291,12 @@ where
/// Recomputes `visible` for `query` and clamps the highlight onto it.
fn refilter(&mut self, query: &str) {
let filter = self.filter.clone();
let needle = query.to_lowercase();
self.visible = self
.options
.iter()
.enumerate()
.filter(|(_, (value, label))| filter(query, value, label))
.filter(|(_, (_, label))| label.to_lowercase().contains(&needle))
.map(|(index, _)| index)
.collect();
self.highlight = self.highlight.filter(|row| *row < self.visible.len());
@@ -452,7 +360,7 @@ where
cx.notify();
}
/// Losing focus. [`UnmatchedText`] decides what the text becomes.
/// Losing focus: unmatched text reverts to the chosen option's label.
fn blurred(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.highlight = None;
let text = self.query_text(cx);
@@ -462,26 +370,10 @@ where
return;
}
match self.unmatched {
UnmatchedText::Revert => {
let restored = self.selected_label().unwrap_or_default().to_string();
self.query
.update(cx, |query, cx| query.set_value_silent(restored, window, cx));
}
UnmatchedText::Keep => {}
UnmatchedText::Create => {
if !text.is_empty()
&& let Some(on_create) = self.on_create.clone()
{
let text = SharedString::from(text);
let task = window.spawn(cx, async move |cx| {
cx.update(|window, cx| on_create(text, window, cx))
.log_err();
});
self.task.replace(task);
}
}
}
let restored = self.selected_label().unwrap_or_default().to_string();
self.query.update(cx, |query, cx| {
query.set_value_silent(restored, window, cx);
});
cx.notify();
}
@@ -798,10 +690,26 @@ where
.inset_0(),
);
wrapper.child(
deferred(anchored().offset(point(px(0.), px(4.))).child(panel))
.with_priority(OVERLAY_LAYER),
)
wrapper.child(crate::components::menu::anchored_overlay(
None,
panel.into_any_element(),
None,
))
})
}
}
/// Binds the combobox's four keys: down, up, enter, and escape.
pub fn bind_combobox_keys(cx: &mut App) {
let under_input = Some("Combobox > Input");
cx.bind_keys([
KeyBinding::new("down", HighlightNext, under_input),
KeyBinding::new("up", HighlightPrevious, under_input),
KeyBinding::new("enter", Choose, under_input),
KeyBinding::new("escape", Dismiss, under_input),
KeyBinding::new("down", HighlightNext, Some(COMBOBOX_CONTEXT)),
KeyBinding::new("up", HighlightPrevious, Some(COMBOBOX_CONTEXT)),
KeyBinding::new("enter", Choose, Some(COMBOBOX_CONTEXT)),
KeyBinding::new("escape", Dismiss, Some(COMBOBOX_CONTEXT)),
]);
}
+24 -32
View File
@@ -30,7 +30,7 @@ use gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, App, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding,
MouseButton, ParentElement as _, Render, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Subscription, UniformListScrollHandle, Window, actions, canvas,
StyleRefinement, Styled as _, Subscription, UniformListScrollHandle, Window, actions,
deferred, div, relative, rems, uniform_list,
};
@@ -51,20 +51,10 @@ actions!(
/// The key context the palette's panel declares.
pub const COMMAND_PALETTE_CONTEXT: &str = "CommandPalette";
/// Binds the palette's four keys: down, up, enter, and escape.
pub fn bind_command_palette_keys(cx: &mut App) {
let under_input = Some("CommandPalette > Input");
cx.bind_keys([
KeyBinding::new("down", HighlightNext, under_input),
KeyBinding::new("up", HighlightPrevious, under_input),
KeyBinding::new("enter", Choose, under_input),
KeyBinding::new("escape", Dismiss, under_input),
KeyBinding::new("down", HighlightNext, Some(COMMAND_PALETTE_CONTEXT)),
KeyBinding::new("up", HighlightPrevious, Some(COMMAND_PALETTE_CONTEXT)),
KeyBinding::new("enter", Choose, Some(COMMAND_PALETTE_CONTEXT)),
KeyBinding::new("escape", Dismiss, Some(COMMAND_PALETTE_CONTEXT)),
]);
}
/// Filters and ranks the commands for a query.
pub type CommandMatcher = Rc<dyn Fn(&str, &[Command]) -> Vec<Command>>;
/// Runs the chosen command.
pub type CommandHandler = Rc<dyn Fn(&Command, &mut Window, &mut App)>;
/// A command the palette can run: a stable id and the label the matcher sees.
#[derive(Clone)]
@@ -117,11 +107,6 @@ impl Command {
// Command is a data builder, not an element, adopt the combinators explicitly.
impl FluentBuilder for Command {}
/// Filters and ranks the commands for a query.
pub type CommandMatcher = Rc<dyn Fn(&str, &[Command]) -> Vec<Command>>;
/// Runs the chosen command.
pub type CommandHandler = Rc<dyn Fn(&Command, &mut Window, &mut App)>;
/// Builder for a command palette, consumed by [`CommandPaletteState::new`].
#[must_use]
pub struct CommandPalette {
@@ -525,18 +510,10 @@ impl Render for CommandPaletteState {
.placeholder(self.placeholder.clone()),
)
.child(rows)
.child(
canvas(|_, _, _| {}, {
let focus = query_focus.clone();
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
.child(crate::components::menu::focus_capture(
query_focus.clone(),
move |window, cx| !query_focus.contains_focused(window, cx),
));
let scrim = div()
.absolute()
@@ -566,3 +543,18 @@ impl Render for CommandPaletteState {
.into_any_element()
}
}
/// Binds the palette's four keys: down, up, enter, and escape.
pub fn bind_command_palette_keys(cx: &mut App) {
let under_input = Some("CommandPalette > Input");
cx.bind_keys([
KeyBinding::new("down", HighlightNext, under_input),
KeyBinding::new("up", HighlightPrevious, under_input),
KeyBinding::new("enter", Choose, under_input),
KeyBinding::new("escape", Dismiss, under_input),
KeyBinding::new("down", HighlightNext, Some(COMMAND_PALETTE_CONTEXT)),
KeyBinding::new("up", HighlightPrevious, Some(COMMAND_PALETTE_CONTEXT)),
KeyBinding::new("enter", Choose, Some(COMMAND_PALETTE_CONTEXT)),
KeyBinding::new("escape", Dismiss, Some(COMMAND_PALETTE_CONTEXT)),
]);
}
+27 -29
View File
@@ -19,8 +19,33 @@ use gpui::{
WindowId, div, px, rems,
};
pub use crate::theme::Size;
use crate::theme::{ActiveTheme as _, FOCUS_RING_ALPHA, FOCUS_RING_SPREAD};
use crate::theme::{ActiveTheme as _, FOCUS_RING_ALPHA, FOCUS_RING_SPREAD, Size};
/// Deferred draw priority of window-modal surfaces; default layer 0 stays for in-flow chrome like resize handles.
pub const DIALOG_LAYER: usize = 1;
/// Deferred draw priority of floating panels, so controls inside a dialog open above it.
pub const OVERLAY_LAYER: usize = 2;
/// Deferred draw priority of passive notifications, so they stay visible over dialogs.
pub const TOAST_LAYER: usize = 3;
/// A handler told to clean up after a dismissed surface.
pub type DismissHandler = std::rc::Rc<dyn Fn(&mut gpui::App)>;
/// The painted bounds of elements that tooltips anchor to, per window and element id.
#[derive(Default)]
struct AnchorBoundsRegistry(HashMap<(WindowId, ElementId), Bounds<Pixels>>);
impl Global for AnchorBoundsRegistry {}
impl AnchorBoundsRegistry {
fn record(&mut self, window: WindowId, id: ElementId, bounds: Bounds<Pixels>) {
self.0.insert((window, id), bounds);
}
fn get(&self, window: WindowId, id: &ElementId) -> Option<Bounds<Pixels>> {
self.0.get(&(window, id.clone())).copied()
}
}
/// A row whose children center on the cross axis.
#[must_use]
@@ -87,23 +112,6 @@ pub fn focus_handle(id: &ElementId, window: &mut Window, cx: &mut App) -> FocusH
.clone()
}
/// The painted bounds of elements that tooltips anchor to, per window and element id.
/// Entries are never evicted: bounds are bounded by live windows, though long-lived processes minting dynamic per-item ids could accumulate.
#[derive(Default)]
struct AnchorBoundsRegistry(HashMap<(WindowId, ElementId), Bounds<Pixels>>);
impl Global for AnchorBoundsRegistry {}
impl AnchorBoundsRegistry {
fn record(&mut self, window: WindowId, id: ElementId, bounds: Bounds<Pixels>) {
self.0.insert((window, id), bounds);
}
fn get(&self, window: WindowId, id: &ElementId) -> Option<Bounds<Pixels>> {
self.0.get(&(window, id.clone())).copied()
}
}
/// The last bounds an element painted at, in the given window.
pub fn anchor_bounds(window: WindowId, id: &ElementId, cx: &App) -> Option<Bounds<Pixels>> {
cx.try_global::<AnchorBoundsRegistry>()
@@ -250,16 +258,6 @@ where
})
}
/// A handler told to clean up after a dismissed surface.
pub type DismissHandler = std::rc::Rc<dyn Fn(&mut gpui::App)>;
/// Deferred draw priority of window-modal surfaces; default layer 0 stays for in-flow chrome like resize handles.
pub const DIALOG_LAYER: usize = 1;
/// Deferred draw priority of floating panels, so controls inside a dialog open above it.
pub const OVERLAY_LAYER: usize = 2;
/// Deferred draw priority of passive notifications, so they stay visible over dialogs.
pub const TOAST_LAYER: usize = 3;
/// A component that can be told which size to render at.
pub trait Sizable: Sized {
/// Sets the size.
-145
View File
@@ -1,145 +0,0 @@
//! Renders a menu at the pointer when its target element is right-clicked.
//!
//! # Examples
//!
//! ```no_run
//! use gpui::{IntoElement as _, ParentElement as _, SharedString, div};
//! use ui::context_menu::ContextMenu;
//! use ui::menu::MenuItem;
//!
//! let context = ContextMenu::new("project-context")
//! .target(|_window, _cx| {
//! div()
//! .child(SharedString::from("project.el"))
//! .into_any_element()
//! })
//! .items(|_window, _cx| vec![MenuItem::new("Delete").handler(|_window, _cx| {})]);
//! ```
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, ElementId, InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent,
ParentElement as _, RenderOnce, SharedString, StyleRefinement, Window, div,
};
use crate::components::common::StyledExt as _;
use crate::components::menu::{Menu, MenuItem};
/// Builds the element that opens the menu on right-click.
type TargetFn = Box<dyn Fn(&mut Window, &mut App) -> gpui::AnyElement>;
/// Builds the menu's items fresh each render.
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<MenuItem>>;
/// A menu that opens at the pointer when its target is right-clicked.
///
/// Open state is owned internally by design, unlike the controlled [`Menu`].
#[derive(IntoElement)]
#[must_use]
pub struct ContextMenu {
id: ElementId,
target: Option<TargetFn>,
items: Option<ItemsFn>,
a11y_label: Option<SharedString>,
style: StyleRefinement,
}
impl ContextMenu {
/// Creates a context menu over a target set with [`ContextMenu::target`].
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
target: None,
items: None,
a11y_label: None,
style: StyleRefinement::default(),
}
}
/// Sets the element that opens the menu on right-click.
pub fn target<F>(mut self, target: F) -> Self
where
F: Fn(&mut Window, &mut App) -> gpui::AnyElement + 'static,
{
self.target = Some(Box::new(target));
self
}
/// Sets the menu's items, built fresh each render.
pub fn items<F>(mut self, items: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<MenuItem> + 'static,
{
self.items = Some(Box::new(items));
self
}
/// Overrides the menu's accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl RenderOnce for ContextMenu {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let open = window.with_element_namespace(self.id.clone(), |window| {
window
.use_keyed_state("context-open", cx, |_, _| false)
.clone()
});
let at = window.with_element_namespace(self.id.clone(), |window| {
window
.use_keyed_state("context-position", cx, |_, _| None)
.clone()
});
let is_open = *open.read(cx);
let position = *at.read(cx);
let target = self.target;
let at_for_target = at.clone();
let trigger = move |window: &mut Window, cx: &mut App| {
let base = target
.as_ref()
.map(|build| build(window, cx))
.unwrap_or_else(|| div().into_any_element());
div()
.on_mouse_down(MouseButton::Right, {
let at = at_for_target.clone();
move |event: &MouseDownEvent, _window, cx| {
at.update(cx, |at, _| *at = Some(event.position));
}
})
.child(base)
.into_any_element()
};
let items = move |window: &mut Window, cx: &mut App| {
self.items
.as_ref()
.map(|build| build(window, cx))
.unwrap_or_default()
};
Menu::new(self.id)
.open(is_open)
.on_change(move |next, _window, cx| open.update(cx, |open, _| *open = next))
.open_at(position)
.trigger_button(MouseButton::Right)
.trigger(trigger)
.items(items)
.refine_style(&self.style)
.when_some(self.a11y_label.clone(), |menu, label| {
menu.accessibility_label(label)
})
}
}
+1 -1
View File
@@ -42,7 +42,7 @@ use crate::icons::IconRole;
use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH};
/// Requests the dialog's close: `false` closes.
pub type ChangeHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
type ChangeHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
type ContentFn = Box<dyn Fn(&mut Window, &mut App) -> AnyElement>;
type ActionsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<AnyElement>>;
-720
View File
@@ -1,720 +0,0 @@
//! Renders a unified, syntax-highlighted diff of two versions of a file:
//! change bars or `+`/`-` markers, tinted number gutters, word-level
//! intra-line highlights, and collapsed hunk separators.
//!
//! Rows reuse the code view's highlighting. Consumers that already hold a
//! git diff can build [`DiffRow`]s themselves instead of calling
//! [`DiffViewState::diff_rows`].
//!
//! # Examples
//!
//! ```no_run
//! use gpui::{App, AppContext as _};
//! use ui::diff::{DiffIndicators, DiffViewState};
//! use ui::highlight::Language;
//!
//! fn patch(cx: &mut App) -> gpui::Entity<DiffViewState> {
//! let state = DiffViewState::new(
//! "patch",
//! "# gpui\nA UI kit for gpui.",
//! "# gpui\nA UI toolkit for gpui.",
//! Language::Rust,
//! )
//! .indicators(DiffIndicators::Bars);
//!
//! cx.new(|_| state)
//! }
//! ```
use std::ops::Range;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, Context, ElementId, HighlightStyle, InteractiveElement as _, IntoElement,
ListHorizontalSizingBehavior, ParentElement as _, Pixels, Render, ScrollStrategy, SharedString,
StatefulInteractiveElement as _, Styled as _, TextStyle, UniformListScrollHandle, Window, div,
point, px, rems, uniform_list,
};
use similar::{Change, ChangeTag, TextDiff};
use crate::components::highlight::{HighlightedCode, Language, Line, Role, highlight};
use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility};
use crate::components::utils::{gutter_cell, wash, wash_gutter, wash_strong};
use crate::theme::{ActiveTheme as _, CODE_GUTTER_WIDTH, CODE_LINE_HEIGHT, MONO_ADVANCE_RATIO};
/// The left change-indicator bar's width, four hairlines.
const CHANGE_BAR_WIDTH: Pixels = px(4.0);
/// What a diff row did to the file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DiffRowKind {
/// Present in both versions.
Context,
/// Only in the new version.
Added,
/// Only in the old version.
Removed,
/// A hunk separator introducing the rows after it.
Hunk,
}
/// One row of a unified diff: a diff line or a hunk separator.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DiffRow {
pub kind: DiffRowKind,
/// The highlighted line content; empty for hunk separators.
pub content: Line,
/// 1-based line number in the old version, when the row exists there.
pub old_number: Option<usize>,
/// 1-based line number in the new version, when the row exists there.
pub new_number: Option<usize>,
/// Byte ranges of intra-line word changes, tinted on changed rows.
pub changed_ranges: Vec<Range<usize>>,
/// The `@@ -a,b +c,d @@` header, for hunk separator rows.
pub header: SharedString,
/// Unchanged lines collapsed into this separator row; zero elsewhere.
pub hidden_lines: usize,
}
/// How changed rows are marked.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DiffIndicators {
/// A two-pixel bar on the row's left edge.
#[default]
Bars,
/// Classic `+`/`-` glyphs in a marker column.
Classic,
/// Only the background washes.
None,
}
/// How collapsed regions between hunks render.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum HunkSeparator {
/// The collapsed unchanged line count, centered.
#[default]
LineInfo,
/// The patch-style `@@ -a,b +c,d @@` header.
Metadata,
/// A minimal `···` bar.
Simple,
}
/// Presentation options for the diff view.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DiffViewOptions {
/// How changed rows are marked.
pub indicators: DiffIndicators,
/// How collapsed regions between hunks render.
pub separator: HunkSeparator,
/// Whether the line-number gutter renders.
pub line_numbers: bool,
}
impl Default for DiffViewOptions {
fn default() -> Self {
Self {
indicators: DiffIndicators::Bars,
separator: HunkSeparator::LineInfo,
line_numbers: true,
}
}
}
impl DiffRow {
/// Assembles a diff line row from a `similar` change.
pub(crate) fn from_change(
change: &Change<&str>,
code: &HighlightedCode,
changed_ranges: Vec<Range<usize>>,
) -> DiffRow {
let content = match change.tag() {
ChangeTag::Equal => change
.new_index()
.and_then(|ix| code.lines.get(ix))
.cloned()
.unwrap_or_default(),
ChangeTag::Delete => change
.old_index()
.and_then(|ix| code.lines.get(ix))
.cloned()
.unwrap_or_default(),
ChangeTag::Insert => change
.new_index()
.and_then(|ix| code.lines.get(ix))
.cloned()
.unwrap_or_default(),
};
let (old_number, new_number) = match change.tag() {
ChangeTag::Equal => (
change.old_index().map(|ix| ix + 1),
change.new_index().map(|ix| ix + 1),
),
ChangeTag::Delete => (change.old_index().map(|ix| ix + 1), None),
ChangeTag::Insert => (None, change.new_index().map(|ix| ix + 1)),
};
DiffRow {
kind: match change.tag() {
ChangeTag::Equal => DiffRowKind::Context,
ChangeTag::Delete => DiffRowKind::Removed,
ChangeTag::Insert => DiffRowKind::Added,
},
content,
old_number,
new_number,
changed_ranges,
header: Default::default(),
hidden_lines: 0,
}
}
/// The row's text length, in characters.
fn char_count(&self) -> usize {
self.content.text().chars().count()
}
/// Stable element id: the kind and line numbers packed into one integer.
fn element_id(&self, hunk_ordinal: usize) -> ElementId {
let kind = match self.kind {
DiffRowKind::Context => 0u64,
DiffRowKind::Added => 1,
DiffRowKind::Removed => 2,
DiffRowKind::Hunk => {
return ElementId::named_usize("diff-hunk", hunk_ordinal);
}
};
// Line numbers saturate at 2^31 so the two fields never overlap.
let old = self.old_number.unwrap_or(0).min((1 << 31) - 1) as u64;
let new = self.new_number.unwrap_or(0).min((1 << 31) - 1) as u64;
ElementId::named_usize("diff-row", ((kind << 62) | (old << 31) | new) as usize)
}
}
/// Retained state for a diff view.
///
/// Build one in a [`gpui::Entity`], render the entity, and call its setters
/// to update the rendered view.
pub struct DiffViewState {
id: ElementId,
rows: Vec<DiffRow>,
/// Cached per-row id and text length, parallel to `rows`.
row_layouts: Vec<RowLayout>,
/// The row whose width drives horizontal scroll extent, `rows`-derived.
widest_row: Option<usize>,
options: DiffViewOptions,
/// Drives both scroll axes of the virtualized row list.
handle: UniformListScrollHandle,
a11y_label: Option<SharedString>,
}
/// Cached per-row render data, computed once when the rows are set.
struct RowLayout {
id: ElementId,
char_count: usize,
}
impl DiffViewState {
/// Builds the state, diffing `old` against `new`.
pub fn new<I, O, N>(id: I, old: O, new: N, language: Language) -> Self
where
I: Into<ElementId>,
O: AsRef<str>,
N: AsRef<str>,
{
let mut state = Self {
id: id.into(),
rows: Vec::new(),
row_layouts: Vec::new(),
widest_row: None,
options: DiffViewOptions::default(),
handle: UniformListScrollHandle::new(),
a11y_label: None,
};
state.set_rows(old, new, language);
state
}
/// Replaces the rows, recomputing the per-row layout cache with them.
fn set_rows<O, N>(&mut self, old: O, new: N, language: Language)
where
O: AsRef<str>,
N: AsRef<str>,
{
self.rows = Self::diff_rows(old.as_ref(), new.as_ref(), language);
let mut hunk_ordinal = 0usize;
self.row_layouts = self
.rows
.iter()
.map(|row| {
let ordinal = if row.kind == DiffRowKind::Hunk {
hunk_ordinal += 1;
hunk_ordinal
} else {
0
};
RowLayout {
id: row.element_id(ordinal),
char_count: row.char_count(),
}
})
.collect();
self.widest_row = self
.rows
.iter()
.zip(&self.row_layouts)
.enumerate()
.filter(|(_, (row, _))| row.kind != DiffRowKind::Hunk)
.max_by_key(|(_, (_, layout))| layout.char_count)
.map(|(widest, _)| widest);
}
/// Computes unified rows between two texts, highlighting every line with
/// `language`. Rows include [`DiffRowKind::Hunk`] separators between
/// hunks.
pub fn diff_rows(old: &str, new: &str, language: Language) -> Vec<DiffRow> {
let old_code = highlight(old, language);
let new_code = highlight(new, language);
let diff = TextDiff::from_lines(old, new);
let mut rows = Vec::new();
let mut collapsed_before = 0usize;
for group in diff.grouped_ops(3) {
let (Some(first), Some(last)) = (group.first(), group.last()) else {
continue;
};
let old_range = first.old_range().start..last.old_range().end;
let new_range = first.new_range().start..last.new_range().end;
// git prints the line before a pure insertion when the count is zero.
let old_start = if old_range.is_empty() {
old_range.start
} else {
old_range.start + 1
};
let new_start = if new_range.is_empty() {
new_range.start
} else {
new_range.start + 1
};
let collapsed = first.old_range().start.saturating_sub(collapsed_before);
if collapsed > 0 {
rows.push(DiffRow {
kind: DiffRowKind::Hunk,
content: Line::default(),
old_number: None,
new_number: None,
changed_ranges: Vec::new(),
header: format!(
"@@ -{},{} +{},{} @@",
old_start,
old_range.len(),
new_start,
new_range.len()
)
.into(),
hidden_lines: collapsed,
});
}
collapsed_before = last.old_range().end;
for op in &group {
let changes: Vec<_> = diff.iter_changes(op).collect();
let mut index = 0;
while index < changes.len() {
if changes[index].tag() == ChangeTag::Equal {
rows.push(DiffRow::from_change(&changes[index], &new_code, Vec::new()));
index += 1;
continue;
}
let deletions = changes[index..]
.iter()
.take_while(|change| change.tag() == ChangeTag::Delete)
.count();
let insertions = changes[index + deletions..]
.iter()
.take_while(|change| change.tag() == ChangeTag::Insert)
.count();
let mut deletion_ranges = vec![Vec::new(); deletions];
let mut insertion_ranges = vec![Vec::new(); insertions];
for pair in 0..deletions.min(insertions) {
let old_text = changes[index + pair].value().trim_end_matches('\n');
let new_text = changes[index + deletions + pair]
.value()
.trim_end_matches('\n');
let words = TextDiff::from_words(old_text, new_text);
let (mut old_offset, mut new_offset) = (0usize, 0usize);
for word in words.iter_all_changes() {
let len = word.value().len();
match word.tag() {
ChangeTag::Delete => {
deletion_ranges[pair].push(old_offset..old_offset + len);
old_offset += len;
}
ChangeTag::Insert => {
insertion_ranges[pair].push(new_offset..new_offset + len);
new_offset += len;
}
ChangeTag::Equal => {
old_offset += len;
new_offset += len;
}
}
}
}
for pair in 0..deletions {
rows.push(DiffRow::from_change(
&changes[index + pair],
&old_code,
deletion_ranges[pair].clone(),
));
}
for pair in 0..insertions {
rows.push(DiffRow::from_change(
&changes[index + deletions + pair],
&new_code,
insertion_ranges[pair].clone(),
));
}
index += deletions + insertions;
}
}
}
rows
}
/// Sets how changed rows are marked.
pub fn indicators(mut self, indicators: DiffIndicators) -> Self {
self.options.indicators = indicators;
self
}
/// Sets how collapsed regions between hunks render.
pub fn hunk_separator(mut self, separator: HunkSeparator) -> Self {
self.options.separator = separator;
self
}
/// Shows or hides the line-number gutter.
pub fn line_numbers(mut self, show: bool) -> Self {
self.options.line_numbers = show;
self
}
/// Replaces the versions and re-diffs them.
pub fn set_versions<O, N>(&mut self, old: O, new: N, language: Language, cx: &mut Context<Self>)
where
O: AsRef<str>,
N: AsRef<str>,
{
self.set_rows(old, new, language);
self.handle.scroll_to_item(0, ScrollStrategy::Top);
// The replaced versions rarely share the old width; start at the left.
let offset = ScrollbarHandle::offset(&self.handle);
ScrollbarHandle::set_offset(&self.handle, point(Pixels::ZERO, offset.y));
cx.notify();
}
/// The diff rows.
pub fn rows(&self) -> &[DiffRow] {
&self.rows
}
/// Scrolls the first added or removed row to the top of the view.
pub fn scroll_to_first_change(&self) {
let Some(row) = self
.rows
.iter()
.position(|row| matches!(row.kind, DiffRowKind::Added | DiffRowKind::Removed))
else {
return;
};
self.handle.scroll_to_item(row, ScrollStrategy::Top);
}
/// Overrides the accessibility label of the view.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl Render for DiffViewState {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let text_size = rems(0.75).to_pixels(window.rem_size());
let id = self.id.clone();
let state = cx.entity();
let row_count = self.rows.len();
let options = self.options;
let widest_row = self.widest_row;
let mut rows = uniform_list((id.clone(), "rows"), row_count, {
move |range, _window, cx| {
let diff = state.read(cx);
range
.map(|row_index| {
render_row(
&diff.rows[row_index],
&diff.row_layouts[row_index],
row_index,
options,
text_size,
cx,
)
})
.collect()
}
})
.with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
.with_width_from_item(widest_row)
.track_scroll(&self.handle)
.h_full();
// Lock each gesture to its initial axis
rows.interactivity().base_style.restrict_scroll_to_axis = Some(true);
div()
.id((id.clone(), "view"))
.relative()
.size_full()
.text_xs()
.when_some(self.a11y_label.clone(), |view, label| {
view.aria_label(label)
})
.child(rows)
.child(
Scrollbar::vertical((self.id.clone(), "v-scrollbar"), self.handle.clone())
.visibility(ScrollbarVisibility::Platform),
)
.child(
Scrollbar::horizontal((self.id.clone(), "h-scrollbar"), self.handle.clone())
.visibility(ScrollbarVisibility::Platform),
)
}
}
fn render_row(
row: &DiffRow,
layout: &RowLayout,
row_index: usize,
options: DiffViewOptions,
text_size: Pixels,
cx: &App,
) -> gpui::AnyElement {
let theme = cx.theme();
let mono_font = theme.mono_font;
let colors = theme.colors;
let ramps = theme.ramps;
let line_height = text_size * CODE_LINE_HEIGHT;
let char_width = text_size * MONO_ADVANCE_RATIO;
let frame = div()
.debug_selector(move || format!("diff-row-{row_index}"))
.id(layout.id.clone())
.w_full()
.h(line_height)
.font_family(mono_font)
.text_xs()
.overflow_hidden();
if row.kind == DiffRowKind::Hunk {
let content = match options.separator {
HunkSeparator::LineInfo => {
SharedString::from(format!("{} unchanged lines", row.hidden_lines))
}
HunkSeparator::Metadata => row.header.clone(),
HunkSeparator::Simple => SharedString::from("···"),
};
return frame
.flex()
.items_center()
.text_color(colors.muted_foreground)
.when(
options.indicators == DiffIndicators::Classic,
|row_element| row_element.child(div().w(CODE_GUTTER_WIDTH).flex_none()),
)
.when(options.line_numbers, |row_element| {
row_element.child(div().w(CODE_GUTTER_WIDTH).flex_none())
})
.when(
options.indicators == DiffIndicators::Bars && !options.line_numbers,
|row_element| {
row_element.child(
div()
.flex_none()
.border_l(CHANGE_BAR_WIDTH)
.border_color(gpui::transparent_black()),
)
},
)
.child(div().flex_none().ml_2().child(content))
.into_any_element();
}
let change_color = match row.kind {
DiffRowKind::Added => ramps.success.base,
DiffRowKind::Removed => ramps.destructive.base,
DiffRowKind::Context | DiffRowKind::Hunk => gpui::transparent_black(),
};
let wash = match row.kind {
DiffRowKind::Added => Some(wash(ramps.success.base)),
DiffRowKind::Removed => Some(wash(ramps.destructive.base)),
DiffRowKind::Context | DiffRowKind::Hunk => None,
};
let mut text = String::new();
let mut spans: Vec<(Range<usize>, Role)> = Vec::new();
for span in &row.content.spans {
let start = text.len();
text.push_str(&span.text);
if span.role != Role::Text {
spans.push((start..text.len(), span.role));
}
}
let mut boundaries: Vec<usize> = spans
.iter()
.flat_map(|(range, _)| [range.start, range.end])
.chain(
row.changed_ranges
.iter()
.flat_map(|range| [range.start, range.end]),
)
.collect();
boundaries.sort_unstable();
boundaries.dedup();
let mut highlights: Vec<(std::ops::Range<usize>, HighlightStyle)> = Vec::new();
let mut span_ix = 0;
for window in boundaries.windows(2) {
let (start, end) = (window[0], window[1]);
while span_ix < spans.len() && spans[span_ix].0.end <= start {
span_ix += 1;
}
let mut segment = HighlightStyle::default();
if let Some((range, role)) = spans.get(span_ix)
&& range.contains(&start)
&& *role != Role::Text
{
segment = segment.highlight(HighlightStyle {
color: Some(role.color(colors, ramps)),
..Default::default()
});
}
if row
.changed_ranges
.iter()
.any(|range| range.contains(&start))
{
segment = segment.highlight(HighlightStyle {
background_color: Some(wash_strong(change_color)),
..Default::default()
});
}
highlights.push((start..end, segment));
}
let style = TextStyle {
color: colors.foreground,
font_family: SharedString::from(mono_font),
font_size: text_size.into(),
line_height: line_height.into(),
..Default::default()
};
frame
.flex()
.items_center()
.when_some(wash, |row_element, tint| row_element.bg(tint))
.when(
options.indicators == DiffIndicators::Classic,
|row_element| {
row_element.child(gutter_cell(
cx,
if row.kind == DiffRowKind::Context {
gpui::transparent_black()
} else {
change_color
},
match row.kind {
DiffRowKind::Added => "+",
DiffRowKind::Removed => "-",
_ => "",
},
))
},
)
.when(options.line_numbers, |row_element| {
row_element.child(
gutter_cell(
cx,
colors.muted_foreground,
row.new_number
.or(row.old_number)
.map(|number| number.to_string())
.unwrap_or_default(),
)
.w(CODE_GUTTER_WIDTH)
.whitespace_nowrap()
.bg(match row.kind {
DiffRowKind::Context => wash_gutter(&colors),
_ => wash_strong(change_color),
})
.when(options.indicators == DiffIndicators::Bars, |number| {
number.border_l(CHANGE_BAR_WIDTH).border_color(change_color)
}),
)
})
.when(
options.indicators == DiffIndicators::Bars && !options.line_numbers,
|row_element| {
row_element.child(
div()
.h_full()
.flex_none()
.border_l(CHANGE_BAR_WIDTH)
.border_color(change_color),
)
},
)
.child(
div()
.flex_none()
.ml_2()
.w(char_width * layout.char_count as f32)
.whitespace_nowrap()
.child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)),
)
.into_any_element()
}
+15 -2
View File
@@ -11,8 +11,8 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, IntoElement, ParentElement as _, RenderOnce, SharedString, StyleRefinement, Styled as _,
Window, div, rems,
AnyElement, App, IntoElement, ParentElement as _, RenderOnce, SharedString, StyleRefinement,
Styled as _, Window, div, rems,
};
use crate::components::common::{StyledExt, v_flex};
@@ -45,6 +45,19 @@ impl EmptyState {
}
}
/// The empty state centered in the full available space.
pub fn centered<L>(message: L) -> AnyElement
where
L: Into<SharedString>,
{
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Self::new(message))
.into_any_element()
}
/// Sets a large muted icon above the headline.
pub fn icon<I>(mut self, icon: I) -> Self
where
+5 -5
View File
@@ -29,11 +29,6 @@ const TILE_PX: u32 = 256;
#[must_use]
pub struct Grain;
/// Creates a grain overlay.
pub fn grain() -> Grain {
Grain
}
impl RenderOnce for Grain {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
let texture = texture();
@@ -74,6 +69,11 @@ impl RenderOnce for Grain {
}
}
/// Creates a grain overlay.
pub fn grain() -> Grain {
Grain
}
/// Returns the shared noise tile so every tile reuses one atlas entry.
fn texture() -> Arc<RenderImage> {
static TEXTURE: OnceLock<Arc<RenderImage>> = OnceLock::new();
+8 -8
View File
@@ -28,14 +28,6 @@ thread_local! {
RefCell::new(HashMap::new());
}
/// A grammar's parser and compiled highlight query.
#[cfg(not(target_arch = "wasm32"))]
struct Highlighter {
parser: tree_sitter::Parser,
query: tree_sitter::Query,
roles: Vec<Option<Role>>,
}
/// A language source can highlight as.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Language {
@@ -64,6 +56,14 @@ pub enum Role {
Escape,
}
/// A grammar's parser and compiled highlight query.
#[cfg(not(target_arch = "wasm32"))]
struct Highlighter {
parser: tree_sitter::Parser,
query: tree_sitter::Query,
roles: Vec<Option<Role>>,
}
/// A run of text sharing one role.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Span {
+56 -100
View File
@@ -12,7 +12,7 @@
//! use ui::input::{Input, InputState, bind_input_keys};
//!
//! # let mut cx: gpui::App = unimplemented!();
//! bind_input_keys(&mut cx, None);
//! bind_input_keys(&mut cx);
//!
//! let state = InputState::builder()
//! .text("Ada Lovelace")
@@ -131,10 +131,9 @@ actions!(
/// The keybindings [`bind_input_keys`] registers on the application.
///
/// A `None` field leaves its action unbound. Start from [`InputBindings::default`]
/// to rebind one action and keep the platform defaults, or from
/// [`InputBindings::empty`] to bind only what you set.
/// to rebind one action and keep the platform defaults.
#[derive(Clone, Debug)]
pub struct InputBindings {
pub(crate) struct InputBindings {
pub escape: Option<KeyBinding>,
pub submit: Option<KeyBinding>,
pub secondary_submit: Option<KeyBinding>,
@@ -260,43 +259,6 @@ impl Default for InputBindings {
}
impl InputBindings {
/// A table with every key unbound, for building custom bindings.
pub fn empty() -> Self {
Self {
escape: None,
submit: None,
secondary_submit: None,
insert_newline: None,
backspace: None,
delete: None,
delete_word_left: None,
delete_word_right: None,
delete_to_beginning_of_line: None,
left: None,
right: None,
up: None,
down: None,
select_left: None,
select_right: None,
select_up: None,
select_down: None,
word_left: None,
word_right: None,
select_word_left: None,
select_word_right: None,
home: None,
end: None,
select_home: None,
select_end: None,
select_all: None,
copy: None,
cut: None,
paste: None,
undo: None,
redo: None,
}
}
/// Collects the table into keybindings.
pub(crate) fn into_bindings(self) -> Vec<KeyBinding> {
let mut bindings: Vec<KeyBinding> = [
@@ -508,55 +470,6 @@ impl HistoryEntry {
}
}
/// The application-owned state of a text field that [`Input`] renders.
pub struct InputState {
text: String,
/// The caret's byte offset.
cursor: usize,
/// The byte offset the selection extends from.
anchor: usize,
/// The byte range of in-progress IME composition, if any.
marked_range: Option<Range<usize>>,
/// Whether the field had focus at the last paint, for focus transitions.
focused: bool,
focus_handle: gpui::FocusHandle,
/// The key-down handler, bound to this entity with `cx.listener`.
key_down_handler: KeyDownHandler,
/// The mouse-down handler, bound to this entity with `cx.listener`.
mouse_down_handler: MouseDownHandler,
/// Whether a drag-select is in progress.
dragging: bool,
/// Patch history. `redo_stack` holds undone entries awaiting redo.
undo_stack: Vec<HistoryEntry>,
redo_stack: Vec<HistoryEntry>,
/// Consecutive edits within this interval merge into one undo entry.
group_interval: Duration,
/// When set, user edits are refused; focus, movement, selection, and copy still work.
read_only: bool,
/// When set, the field is a password field.
password: bool,
/// Whether a password field currently shows its content.
revealed: bool,
/// Whether the field holds multiple lines of text.
multiline: bool,
/// Which keystroke submits a multiline field.
submit_on: SubmitOn,
/// The x the caret keeps across vertical movement, reset on any other move.
goal_x: Option<Pixels>,
/// Content scroll inside the field: x for single-line, y for multiline, clamped at paint.
scroll_offset: gpui::Point<Pixels>,
/// Set by every caret-affecting change.
scroll_to_caret_pending: bool,
/// Bumped on every edit.
caret_epoch: usize,
/// When the current caret epoch started.
caret_epoch_started: Instant,
/// The shaped line and element bounds, recorded during each paint.
layout: Option<InputLayout>,
/// The last shaped buffer, reused while no shaping input changed.
shaped_cache: std::cell::RefCell<Option<(ShapeCacheKey, ShapedText)>>,
}
/// Everything `shape_text` consumes, for cache reuse between frames.
#[derive(Clone, PartialEq)]
struct ShapeCacheKey {
@@ -567,8 +480,6 @@ struct ShapeCacheKey {
color: gpui::Hsla,
}
impl EventEmitter<InputStateEvent> for InputState {}
/// Builder for [`InputState`] settings that are fixed at creation.
#[derive(Default)]
pub struct InputStateBuilder {
@@ -628,6 +539,57 @@ impl InputStateBuilder {
}
}
/// The application-owned state of a text field that [`Input`] renders.
pub struct InputState {
text: String,
/// The caret's byte offset.
cursor: usize,
/// The byte offset the selection extends from.
anchor: usize,
/// The byte range of in-progress IME composition, if any.
marked_range: Option<Range<usize>>,
/// Whether the field had focus at the last paint, for focus transitions.
focused: bool,
focus_handle: gpui::FocusHandle,
/// The key-down handler, bound to this entity with `cx.listener`.
key_down_handler: KeyDownHandler,
/// The mouse-down handler, bound to this entity with `cx.listener`.
mouse_down_handler: MouseDownHandler,
/// Whether a drag-select is in progress.
dragging: bool,
/// Patch history. `redo_stack` holds undone entries awaiting redo.
undo_stack: Vec<HistoryEntry>,
redo_stack: Vec<HistoryEntry>,
/// Consecutive edits within this interval merge into one undo entry.
group_interval: Duration,
/// When set, user edits are refused; focus, movement, selection, and copy still work.
read_only: bool,
/// When set, the field is a password field.
password: bool,
/// Whether a password field currently shows its content.
revealed: bool,
/// Whether the field holds multiple lines of text.
multiline: bool,
/// Which keystroke submits a multiline field.
submit_on: SubmitOn,
/// The x the caret keeps across vertical movement, reset on any other move.
goal_x: Option<Pixels>,
/// Content scroll inside the field: x for single-line, y for multiline, clamped at paint.
scroll_offset: gpui::Point<Pixels>,
/// Set by every caret-affecting change.
scroll_to_caret_pending: bool,
/// Bumped on every edit.
caret_epoch: usize,
/// When the current caret epoch started.
caret_epoch_started: Instant,
/// The shaped line and element bounds, recorded during each paint.
layout: Option<InputLayout>,
/// The last shaped buffer, reused while no shaping input changed.
shaped_cache: std::cell::RefCell<Option<(ShapeCacheKey, ShapedText)>>,
}
impl EventEmitter<InputStateEvent> for InputState {}
impl InputState {
fn new_inner(cx: &mut Context<Self>) -> Self {
Self {
@@ -2517,14 +2479,8 @@ impl RenderOnce for Input {
}
/// Registers the input keybindings on the application, once at startup.
///
/// Pass `None` for the platform defaults or an [`InputBindings`] table for
/// custom ones.
pub fn bind_input_keys<B>(cx: &mut App, bindings: B)
where
B: Into<Option<InputBindings>>,
{
cx.bind_keys(bindings.into().unwrap_or_default().into_bindings());
pub fn bind_input_keys(cx: &mut App) {
cx.bind_keys(InputBindings::default().into_bindings());
}
/// The row holding `display`.
+17 -88
View File
@@ -3,23 +3,19 @@
//! # Examples
//!
//! ```no_run
//! use gpui::{Keystroke, ParentElement as _};
//! use ui::kbd::{Kbd, KbdGroup};
//! use gpui::Keystroke;
//! use ui::kbd::Kbd;
//!
//! let save = Kbd::new(Keystroke::parse("cmd-s").unwrap());
//! let combo = KbdGroup::new()
//! .child(Kbd::new(Keystroke::parse("ctrl-b").unwrap()))
//! .child(Kbd::new(Keystroke::parse("ctrl-k").unwrap()));
//! ```
use gpui::prelude::FluentBuilder as _;
use gpui::{
Action, AnyElement, App, FocusHandle, InteractiveElement as _, IntoElement, KeyBinding,
KeyContext, Keystroke, OperatingSystem, ParentElement as _, RenderOnce, SharedString,
StyleRefinement, Styled as _, Window, div, relative,
Action, App, InteractiveElement as _, IntoElement, KeyBinding, KeyContext, Keystroke,
OperatingSystem, ParentElement as _, RenderOnce, SharedString, StyleRefinement, Styled as _,
Window, div, relative,
};
use crate::components::common::{StyledExt as _, h_flex};
use crate::components::common::StyledExt as _;
use crate::theme::ActiveTheme as _;
/// A key or shortcut shown as a small key cap, like `⌘S` or `Ctrl+S`.
@@ -27,7 +23,6 @@ use crate::theme::ActiveTheme as _;
#[must_use]
pub struct Kbd {
stroke: Keystroke,
appearance: bool,
style: StyleRefinement,
}
@@ -42,7 +37,6 @@ impl Kbd {
pub fn new(stroke: Keystroke) -> Self {
Self {
stroke,
appearance: true,
style: StyleRefinement::default(),
}
}
@@ -52,12 +46,6 @@ impl Kbd {
&self.stroke
}
/// When false, paints the formatted shortcut as plain text without the key cap.
pub fn appearance(mut self, appearance: bool) -> Self {
self.appearance = appearance;
self
}
/// Returns a key cap for the highest-precedence binding of `action`.
pub fn binding_for_action(
action: &dyn Action,
@@ -73,23 +61,6 @@ impl Kbd {
Self::from_binding(&binding)
}
/// Returns a key cap for the binding of `action`.
pub fn binding_for_action_in(
action: &dyn Action,
focus_handle: &FocusHandle,
window: &Window,
) -> Option<Self> {
let binding = window.highest_precedence_binding_for_action_in(action, focus_handle)?;
Self::from_binding(&binding)
}
/// Returns a key cap for the binding of `action` registered without a key context.
pub fn global_binding_for_action(action: &dyn Action, window: &Window) -> Option<Self> {
let binding = window
.highest_precedence_binding_for_action_in_context(action, KeyContext::default())?;
Self::from_binding(&binding)
}
/// Shows the binding's keystroke as the keymap holds it.
fn from_binding(binding: &KeyBinding) -> Option<Self> {
binding.keystrokes().first().map(|stroke| {
@@ -102,7 +73,7 @@ impl Kbd {
}
/// Formats `stroke` for `os`: modifier symbols on macOS, `Ctrl+` words elsewhere.
pub fn format(stroke: &Keystroke, os: OperatingSystem) -> String {
fn format(stroke: &Keystroke, os: OperatingSystem) -> String {
let mac = os == OperatingSystem::Mac;
let separator = if mac { "" } else { "+" };
let mut parts: Vec<&str> = Vec::new();
@@ -253,60 +224,18 @@ impl RenderOnce for Kbd {
let label = SharedString::from(Self::format(&self.stroke, os));
div()
// Lets a test ask whether this shortcut hint was painted this frame.
.debug_selector(move || selector)
.when(self.appearance, |key| {
key.flex_none()
.border_1()
.border_color(theme.colors.border)
.bg(theme.colors.muted)
.text_color(theme.colors.muted_foreground)
.py_0p5()
.px_1()
.min_w_5()
.rounded(theme.radius.sm)
.text_center()
.line_height(relative(1.))
.text_xs()
})
.flex_none()
.bg(theme.colors.muted)
.text_color(theme.colors.muted_foreground)
.py_0p5()
.px_1()
.min_w_5()
.rounded(theme.radius.sm)
.text_center()
.line_height(relative(1.))
.text_xs()
.refine_style(&self.style)
.child(label)
}
}
/// A row of key caps, grouping the keys of a multi-key hint.
#[derive(IntoElement, Default)]
#[must_use]
pub struct KbdGroup {
style: StyleRefinement,
children: Vec<AnyElement>,
}
impl KbdGroup {
/// Creates an empty group.
pub fn new() -> Self {
Self::default()
}
}
impl gpui::ParentElement for KbdGroup {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl gpui::Styled for KbdGroup {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for KbdGroup {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
h_flex()
.flex_none()
.gap_1()
.refine_style(&self.style)
.children(self.children)
}
}
-154
View File
@@ -1,154 +0,0 @@
//! Renders a link that opens a URL or fires a click handler.
//!
//! # Examples
//!
//! ```no_run
//! use ui::link::Link;
//!
//! let docs = Link::new("docs-link")
//! .label("Documentation")
//! .href("https://example.com/docs");
//!
//! let settings = Link::new("settings-link")
//! .label("Open settings")
//! .on_click(|_event, _window, _cx| println!("open settings"));
//! ```
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, ClickEvent, ElementId, InteractiveElement as _, IntoElement, ParentElement as _,
RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
Window,
};
use crate::components::common::{ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex};
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
/// The handler called with the [`gpui::ClickEvent`], replacing the default `href` opening.
type ClickHandler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
/// A hyperlink that opens a URL or fires a click handler.
#[derive(IntoElement)]
#[must_use]
pub struct Link {
id: ElementId,
label: Option<SharedString>,
href: Option<SharedString>,
size: Size,
disabled: bool,
a11y_label: Option<SharedString>,
on_click: Option<ClickHandler>,
style: StyleRefinement,
}
impl Link {
/// Creates a link without a label or target.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
label: None,
href: None,
size: Size::default(),
disabled: false,
a11y_label: None,
on_click: None,
style: StyleRefinement::default(),
}
}
/// Sets the visible label.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Sets the URL the link opens through the platform.
pub fn href<U>(mut self, href: U) -> Self
where
U: Into<SharedString>,
{
self.href = Some(href.into());
self
}
/// Renders the link inert, unfocusable, and dimmed; disabled always wins.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Replaces the default `href` opening with this handler.
pub fn on_click<F>(mut self, handler: F) -> Self
where
F: Fn(&ClickEvent, &mut Window, &mut App) + 'static,
{
self.on_click = Some(Box::new(handler));
self
}
}
impl gpui::Styled for Link {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Link {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Link {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let size = self.size;
let on_click = self.on_click;
let href = self.href;
let a11y_label = self.a11y_label.or_else(|| self.label.clone());
h_flex()
.id(self.id)
.control_text(size)
.text_color(ramps.primary.base)
.underline()
.refine_style(&self.style)
.role(Role::Link)
.when_some(a11y_label, |link, label| link.aria_label(label))
.when(self.disabled, |link| link.opacity(DISABLED_OPACITY))
.when(!self.disabled, |link| {
link.cursor_pointer()
.focusable()
.tab_stop(true)
.hover(move |style| style.text_color(ramps.primary.hover))
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.on_click(move |event, window, cx| match on_click.as_ref() {
Some(on_click) => on_click(event, window, cx),
None => {
if let Some(href) = href.as_ref() {
cx.open_url(href);
}
}
})
})
.when_some(self.label, |link, label| link.child(label))
}
}
-290
View File
@@ -1,290 +0,0 @@
//! Renders a single-selection list of [`ListItem`] rows with keyboard navigation.
//!
//! # Examples
//!
//! ```no_run
//! use ui::list::{List, ListItem};
//!
//! let folders = List::new("folders")
//! .selected(Some(0))
//! .items(|_, _| {
//! vec![
//! ListItem::new("documents", "Documents").detail("24 files"),
//! ListItem::new("downloads", "Downloads"),
//! ]
//! })
//! .on_change(|_selected, _window, _cx| println!("selection changed"));
//! ```
use std::rc::Rc;
use gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent,
ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Window, div, rems,
};
use crate::common::focus_handle;
use crate::components::common::{
StyledExt as _, nav_key, paint_selectable_row, selectable_label_color, v_flex,
};
use crate::icons::Icon;
use crate::theme::ActiveTheme as _;
/// The change reporter, fired with the next selection by pointer and keys.
type ChangeHandler = Rc<dyn Fn(Option<usize>, &mut Window, &mut App)>;
/// The row builder, run during render.
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<ListItem>>;
/// One row of a [`List`].
#[must_use]
pub struct ListItem {
key: ElementId,
label: SharedString,
icon: Option<Icon>,
detail: Option<SharedString>,
disabled: bool,
}
impl ListItem {
/// Creates a row shown as `label`, identified by `key`.
pub fn new<K, L>(key: K, label: L) -> Self
where
K: Into<ElementId>,
L: Into<SharedString>,
{
Self {
key: key.into(),
label: label.into(),
icon: None,
detail: None,
disabled: false,
}
}
/// Shows an icon leading the label, a role or any custom [`crate::icons::IconNamed`].
pub fn icon<I>(mut self, icon: I) -> Self
where
I: Into<Icon>,
{
self.icon = Some(icon.into());
self
}
/// Shows muted trailing text.
pub fn detail<D>(mut self, detail: D) -> Self
where
D: Into<SharedString>,
{
self.detail = Some(detail.into());
self
}
/// Renders the row dimmed; clicks and keyboard skip it.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
// ListItem is a data builder, not an element, adopt the combinators explicitly.
impl FluentBuilder for ListItem {}
/// A single-selection list of [`ListItem`] rows.
#[derive(IntoElement)]
#[must_use]
pub struct List {
id: ElementId,
selected: Option<usize>,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
items: Option<ItemsFn>,
style: StyleRefinement,
}
impl List {
/// Creates a list with nothing selected.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
selected: None,
a11y_label: None,
on_change: None,
items: None,
style: StyleRefinement::default(),
}
}
/// Sets the current selection.
pub fn selected(mut self, selected: Option<usize>) -> Self {
self.selected = selected;
self
}
/// Reports the next selection, from clicks and keys alike.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(Option<usize>, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
/// Sets the rows; the closure runs during render and must not mutate entities or notify.
pub fn items<F>(mut self, items: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<ListItem> + 'static,
{
self.items = Some(Box::new(items));
self
}
/// Overrides the accessibility label, which defaults to the id.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl gpui::Styled for List {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for List {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let items = match self.items {
Some(build) => build(window, cx),
None => Vec::new(),
};
let selectable: Vec<usize> = items
.iter()
.enumerate()
.filter(|(_, item)| !item.disabled)
.map(|(index, _)| index)
.collect();
let focus = focus_handle(&self.id, window, cx);
let label = self
.a11y_label
.clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
let rows: Vec<AnyElement> = items
.iter()
.enumerate()
.map(|(index, item)| {
item.render_row(
cx,
index,
items.len(),
self.selected == Some(index),
&self.on_change,
&focus,
)
})
.collect();
v_flex()
.id(self.id)
.gap_0p5()
.text_sm()
.refine_style(&self.style)
.track_focus(&focus)
.focusable()
.tab_stop(true)
.role(Role::List)
.aria_label(label)
.on_key_down({
let selected = self.selected;
let on_change = self.on_change.clone();
move |event: &KeyDownEvent, window, cx| {
if nav_key(&selectable, selected, &event.keystroke.key, |next| {
if let Some(on_change) = &on_change {
on_change(next, window, cx);
}
}) {
cx.stop_propagation();
}
}
})
.children(rows)
}
}
impl ListItem {
fn render_row(
&self,
cx: &App,
index: usize,
count: usize,
selected: bool,
on_change: &Option<ChangeHandler>,
focus: &FocusHandle,
) -> AnyElement {
let theme = cx.theme();
let label_color = selectable_label_color(cx, selected, self.disabled);
let disabled = self.disabled;
div()
.id((self.key.clone(), "list-item"))
.flex()
.items_center()
.gap_2()
.px_2()
.py_1()
.min_h_8()
.rounded(theme.radius.sm)
.role(Role::ListItem)
.aria_selected(selected)
.aria_position_in_set(index + 1)
.aria_size_of_set(count)
.map(|row| paint_selectable_row(cx, row, selected, disabled))
.when(!disabled, |row| {
row.cursor_pointer().on_click({
let on_change = on_change.clone();
let focus = focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if let Some(on_change) = &on_change {
on_change(Some(index), window, cx);
}
}
})
})
.when_some(self.icon.clone(), |row, icon| {
row.child(icon.size(rems(1.0)).color(label_color))
})
.child(
div()
.flex_1()
.text_color(label_color)
.child(self.label.clone()),
)
.when_some(self.detail.clone(), |row, detail| {
row.child(
div()
.flex_none()
.text_sm()
.text_color(if selected {
theme.colors.primary_foreground
} else {
theme.colors.muted_foreground
})
.child(detail),
)
})
.into_any_element()
}
}
+99 -191
View File
@@ -19,8 +19,6 @@
//! fn notes(cx: &mut App) -> TextView {
//! let state = cx.new(|_| MarkdownViewState::new("notes", "# Notes\n- [x] shipped"));
//! TextView::new(&state)
//! .on_link_click(|destination, _window, _cx| println!("{destination}"))
//! .on_task_toggle(|index, checked, _window, _cx| println!("{index}: {checked}"))
//! }
//! ```
@@ -29,7 +27,6 @@ use std::collections::HashMap;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::ops::Range;
use std::rc::Rc;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
@@ -56,11 +53,6 @@ const BODY_LINE_HEIGHT: f32 = 1.6;
/// The key context the text view declares while it holds focus.
pub const TEXT_VIEW_CONTEXT: &str = "TextView";
/// The callback a view invokes when the user clicks a markdown link.
pub type LinkClickHandler = Arc<dyn Fn(&SharedString, &mut Window, &mut App)>;
/// The callback a view invokes when the user toggles a task checkbox.
pub type TaskToggleHandler = Arc<dyn Fn(usize, bool, &mut Window, &mut App)>;
actions!(text_view, [Copy]);
/// A heading level, 1 to 6.
@@ -191,6 +183,94 @@ impl MarkdownBlock {
self.hash(&mut hasher);
hasher.finish()
}
/// The block's selectable text units, in render order.
fn block_text_units(&self) -> Vec<String> {
match self {
MarkdownBlock::Heading { spans, .. } => vec![spans_text_of(spans)],
MarkdownBlock::Paragraph { items, .. } | MarkdownBlock::ListItem { items, .. } => {
let mut units: Vec<String> = Vec::new();
for item in items {
match item {
InlineItem::Text(span) => match units.last_mut() {
// Consecutive text items share the unit between images.
Some(unit) => unit.push_str(&span.text),
None => units.push(span.text.as_ref().to_string()),
},
// An image starts the next unit; the render emits no
// element for it.
InlineItem::Image { .. } => units.push(String::new()),
}
}
units
}
MarkdownBlock::Code { lines, .. } => {
lines.lines.iter().map(|line| line.text()).collect()
}
MarkdownBlock::Table { table, .. } => table
.rows
.iter()
.flat_map(|row| row.cells.iter())
.map(|cell| spans_text_of(&cell.spans))
.collect(),
MarkdownBlock::Image { .. } | MarkdownBlock::ThematicBreak { .. } => Vec::new(),
}
}
/// Renders one parsed block as a list row.
fn render_block(&self, block_index: usize, ctx: &BlockContext, cx: &App) -> AnyElement {
let gap = rems(0.75);
match self {
MarkdownBlock::Heading {
level,
spans,
indent,
quote,
} => heading_row(
*level,
spans,
*indent,
*quote,
if block_index == 0 {
Rems::ZERO
} else {
rems(0.375)
},
ctx,
cx,
),
MarkdownBlock::Paragraph {
items,
indent,
quote,
} => text_row(items, *indent, *quote, gap, None, ctx, cx),
MarkdownBlock::ListItem {
marker,
items,
indent,
quote,
} => text_row(items, *indent, *quote, rems(0.2), Some(*marker), ctx, cx),
MarkdownBlock::Image {
source,
alt,
indent,
quote,
} => image_row(source, alt, *indent, *quote, ctx, cx),
MarkdownBlock::Code {
language,
lines,
indent,
quote,
} => code_row(lines, language.as_ref(), *indent, *quote, ctx, cx),
MarkdownBlock::ThematicBreak { indent, quote } => rule_row(*indent, *quote, ctx, cx),
MarkdownBlock::Table {
table,
indent,
quote,
} => table_row(table, *indent, *quote, ctx, cx),
}
}
}
/// One run of inline text sharing a style.
@@ -235,8 +315,6 @@ pub struct MarkdownViewState {
/// Drives the vertical scroll of the virtualized block list.
handle: ListState,
a11y_label: Option<SharedString>,
link_handler: Option<LinkClickHandler>,
task_toggle_handler: Option<TaskToggleHandler>,
/// `(anchor, head)` in the order they were set, over the rendered text.
selection: Option<(usize, usize)>,
/// Whether a drag is still extending the selection.
@@ -265,8 +343,6 @@ impl MarkdownViewState {
highlight_code: true,
handle: ListState::new(count, ListAlignment::Top, CODE_OVERSCROLL_MAX),
a11y_label: None,
link_handler: None,
task_toggle_handler: None,
selection: None,
selecting: false,
focus_handle: None,
@@ -360,34 +436,6 @@ impl MarkdownViewState {
self
}
/// Invokes `handler` when the user clicks a link, instead of opening it.
pub fn on_link_click<F>(mut self, handler: F) -> Self
where
F: Fn(&SharedString, &mut Window, &mut App) + 'static,
{
self.link_handler = Some(Arc::new(handler));
self
}
/// Replaces the link click handler.
pub fn set_link_handler(&mut self, handler: LinkClickHandler) {
self.link_handler = Some(handler);
}
/// Invokes `handler(block, checked)` when the user toggles a task checkbox.
pub fn on_task_toggle<F>(mut self, handler: F) -> Self
where
F: Fn(usize, bool, &mut Window, &mut App) + 'static,
{
self.task_toggle_handler = Some(Arc::new(handler));
self
}
/// Replaces the task toggle handler.
pub fn set_task_toggle_handler(&mut self, handler: TaskToggleHandler) {
self.task_toggle_handler = Some(handler);
}
/// Selects a range over the rendered text, endpoints in byte offsets.
pub fn select_range(&mut self, start: usize, end: usize, cx: &mut Context<Self>) {
self.selection = Some((start, end));
@@ -430,8 +478,6 @@ impl Render for MarkdownViewState {
let focus_handle = self.focus_handle(cx);
let frame = std::rc::Rc::new(ViewFrame {
state: state.clone(),
link_handler: self.link_handler.clone(),
task_toggle: self.task_toggle_handler.clone(),
selection: self.selection(),
focus_handle,
pressed_on_piece: std::rc::Rc::new(std::cell::Cell::new(false)),
@@ -455,7 +501,7 @@ impl Render for MarkdownViewState {
block_index,
block_id,
};
render_block(block, block_index, &ctx, cx)
block.render_block(block_index, &ctx, cx)
}
None => div().into_any_element(),
}
@@ -481,8 +527,6 @@ impl Render for MarkdownViewState {
/// The per-frame context the view's renderers wire themselves from.
struct ViewFrame {
state: Entity<MarkdownViewState>,
link_handler: Option<LinkClickHandler>,
task_toggle: Option<TaskToggleHandler>,
/// The selection over the rendered text, endpoints in document order.
selection: Option<(usize, usize)>,
focus_handle: gpui::FocusHandle,
@@ -525,7 +569,6 @@ impl BlockContext<'_> {
Some(PieceContext {
state: self.frame.state.clone(),
link_handler: self.frame.link_handler.clone(),
doc_range: piece.range.clone(),
selected,
pressed_on_piece: self.frame.pressed_on_piece.clone(),
@@ -536,7 +579,6 @@ impl BlockContext<'_> {
/// What one selectable text element wires itself from.
struct PieceContext {
state: Entity<MarkdownViewState>,
link_handler: Option<LinkClickHandler>,
/// The piece's byte range in the rendered text.
doc_range: Range<usize>,
/// The selection overlap, in piece-local bytes.
@@ -579,7 +621,7 @@ impl TextDocument {
.iter()
.position(|piece| piece.block_index != block_index)
.map_or(self.pieces.len(), |offset| piece_ix + offset);
let units = block_text_units(block);
let units = block.block_text_units();
for piece in &self.pieces[piece_ix..block_end] {
let Some(unit) = units.get(piece.sub_index).filter(|unit| !unit.is_empty()) else {
@@ -602,8 +644,6 @@ pub struct TextView {
id: ElementId,
source: Option<SharedString>,
state: Option<Entity<MarkdownViewState>>,
link_handler: Option<LinkClickHandler>,
task_toggle_handler: Option<TaskToggleHandler>,
style: StyleRefinement,
}
@@ -618,8 +658,6 @@ impl TextView {
id: id.into(),
source: Some(source.into()),
state: None,
link_handler: None,
task_toggle_handler: None,
style: StyleRefinement::default(),
}
}
@@ -630,29 +668,9 @@ impl TextView {
id: ElementId::from(SharedString::from(format!("{}", state.entity_id()))),
source: None,
state: Some(state.clone()),
link_handler: None,
task_toggle_handler: None,
style: StyleRefinement::default(),
}
}
/// Invokes `handler` when the user clicks a link, instead of opening it.
pub fn on_link_click<F>(mut self, handler: F) -> Self
where
F: Fn(&SharedString, &mut Window, &mut App) + 'static,
{
self.link_handler = Some(Arc::new(handler));
self
}
/// Invokes `handler(block, checked)` when the user toggles a task checkbox.
pub fn on_task_toggle<F>(mut self, handler: F) -> Self
where
F: Fn(usize, bool, &mut Window, &mut App) + 'static,
{
self.task_toggle_handler = Some(Arc::new(handler));
self
}
}
impl Styled for TextView {
@@ -693,8 +711,6 @@ impl Element for TextView {
};
let source = self.source.clone();
let link_handler = self.link_handler.clone();
let task_toggle = self.task_toggle_handler.clone();
let (selection, focus_handle) =
state.update(cx, |view, cx| (view.selection(), view.focus_handle(cx)));
@@ -703,19 +719,11 @@ impl Element for TextView {
if let Some(source) = source {
view.set_source(source, cx);
}
if let Some(link_handler) = link_handler {
view.set_link_handler(link_handler);
}
if let Some(task_toggle) = task_toggle {
view.set_task_toggle_handler(task_toggle);
}
});
let view = state.read(cx);
let frame = ViewFrame {
state: state.clone(),
link_handler: view.link_handler.clone(),
task_toggle: view.task_toggle_handler.clone(),
selection,
focus_handle,
pressed_on_piece: std::rc::Rc::new(std::cell::Cell::new(false)),
@@ -908,7 +916,7 @@ fn render_blocks(
block_index,
block_id,
};
render_block(block, block_index, &ctx, cx)
block.render_block(block_index, &ctx, cx)
},
))
}
@@ -917,37 +925,6 @@ fn spans_text_of(spans: &[InlineSpan]) -> String {
spans.iter().map(|span| span.text.as_ref()).collect()
}
/// The selectable text units of a block.
fn block_text_units(block: &MarkdownBlock) -> Vec<String> {
match block {
MarkdownBlock::Heading { spans, .. } => vec![spans_text_of(spans)],
MarkdownBlock::Paragraph { items, .. } | MarkdownBlock::ListItem { items, .. } => {
let mut units: Vec<String> = Vec::new();
for item in items {
match item {
InlineItem::Text(span) => match units.last_mut() {
// Consecutive text items share the unit between images.
Some(unit) => unit.push_str(&span.text),
None => units.push(span.text.as_ref().to_string()),
},
// An image starts the next unit; the render emits no
// element for it.
InlineItem::Image { .. } => units.push(String::new()),
}
}
units
}
MarkdownBlock::Code { lines, .. } => lines.lines.iter().map(|line| line.text()).collect(),
MarkdownBlock::Table { table, .. } => table
.rows
.iter()
.flat_map(|row| row.cells.iter())
.map(|cell| spans_text_of(&cell.spans))
.collect(),
MarkdownBlock::Image { .. } | MarkdownBlock::ThematicBreak { .. } => Vec::new(),
}
}
/// Enumerates the selectable text pieces of `blocks`, in render order.
fn text_document(blocks: &[MarkdownBlock]) -> TextDocument {
let mut pieces = Vec::new();
@@ -960,7 +937,7 @@ fn text_document(blocks: &[MarkdownBlock]) -> TextDocument {
MarkdownBlock::Paragraph { .. } | MarkdownBlock::ListItem { .. }
);
for (sub_index, unit) in block_text_units(block).into_iter().enumerate() {
for (sub_index, unit) in block.block_text_units().into_iter().enumerate() {
if unit.is_empty() && skip_empty {
continue;
}
@@ -1405,66 +1382,6 @@ fn flush_item_inline(
});
}
/// Renders one parsed block as a list row.
fn render_block(
block: &MarkdownBlock,
block_index: usize,
ctx: &BlockContext,
cx: &App,
) -> AnyElement {
let gap = rems(0.75);
match block {
MarkdownBlock::Heading {
level,
spans,
indent,
quote,
} => heading_row(
*level,
spans,
*indent,
*quote,
if block_index == 0 {
Rems::ZERO
} else {
rems(0.375)
},
ctx,
cx,
),
MarkdownBlock::Paragraph {
items,
indent,
quote,
} => text_row(items, *indent, *quote, gap, None, ctx, cx),
MarkdownBlock::ListItem {
marker,
items,
indent,
quote,
} => text_row(items, *indent, *quote, rems(0.2), Some(*marker), ctx, cx),
MarkdownBlock::Image {
source,
alt,
indent,
quote,
} => image_row(source, alt, *indent, *quote, ctx, cx),
MarkdownBlock::Code {
language,
lines,
indent,
quote,
} => code_row(lines, language.as_ref(), *indent, *quote, ctx, cx),
MarkdownBlock::ThematicBreak { indent, quote } => rule_row(*indent, *quote, ctx, cx),
MarkdownBlock::Table {
table,
indent,
quote,
} => table_row(table, *indent, *quote, ctx, cx),
}
}
/// The shared block frame: ambient text style, spacing, quote bar.
fn block_frame(quote: bool, top: Rems, bottom: Rems, id: &ElementId, cx: &App) -> Div {
let theme = cx.theme();
@@ -1579,22 +1496,17 @@ fn text_row(
.into_any_element()
}
/// The task marker: a checkbox that reports toggles when a handler is set.
/// The task marker: a checkbox that renders the state without toggling.
fn task_toggle(checked: bool, label: SharedString, ctx: &BlockContext) -> AnyElement {
let block_index = ctx.block_index;
let selector = SharedString::from(format!("task-toggle-{block_index}"));
let checkbox = Checkbox::new((ctx.block_id.clone(), "task"))
Checkbox::new((ctx.block_id.clone(), "task"))
.debug_selector(move || selector.to_string())
.checked(checked)
.with_size(Size::Small)
.accessibility_label(label);
match ctx.frame.task_toggle.clone() {
Some(handler) => checkbox
.on_change(move |next, window, cx| handler(block_index, next, window, cx))
.into_any_element(),
None => checkbox.disabled(true).into_any_element(),
}
.accessibility_label(label)
.disabled(true)
.into_any_element()
}
/// The item's plain text, for the checkbox's accessibility label.
@@ -2016,16 +1928,12 @@ where
let inner = if destinations.is_empty() {
styled.into_any_element()
} else {
let link_handler = piece.as_ref().and_then(|piece| piece.link_handler.clone());
InteractiveText::new(id.clone(), styled)
.on_click(link_ranges, move |range_ix, window, cx| {
.on_click(link_ranges, move |range_ix, _window, cx| {
let Some(destination) = destinations.get(range_ix) else {
return;
};
match link_handler.as_ref() {
Some(handler) => handler(destination, window, cx),
None => cx.open_url(destination.as_ref()),
}
cx.open_url(destination.as_ref());
})
.into_any_element()
};
+344 -334
View File
@@ -54,6 +54,14 @@ type TriggerFn = Box<dyn Fn(&mut Window, &mut App) -> AnyElement>;
/// The menu's rows, rebuilt on each render while open.
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<MenuItem>>;
/// One row of a [`Menu`]: an action, a checkable action, a submenu, or a separator.
#[derive(Clone)]
enum MenuItemKind {
Action,
Separator,
Submenu(Rc<[MenuItem]>),
}
/// One row of a [`Menu`]: an action, a checkable action, a submenu, or a separator.
#[derive(Clone)]
#[must_use]
@@ -62,20 +70,12 @@ pub struct MenuItem {
kind: MenuItemKind,
label: SharedString,
icon: Option<Icon>,
shortcut: Option<SharedString>,
handler: Option<ItemHandler>,
disabled: bool,
destructive: bool,
checked: bool,
}
#[derive(Clone)]
enum MenuItemKind {
Action,
Separator,
Submenu(Rc<[MenuItem]>),
}
impl MenuItem {
/// Creates an action row with this label.
pub fn new<L>(label: L) -> Self
@@ -87,7 +87,6 @@ impl MenuItem {
kind: MenuItemKind::Action,
label: label.into(),
icon: None,
shortcut: None,
handler: None,
disabled: false,
destructive: false,
@@ -102,7 +101,6 @@ impl MenuItem {
kind: MenuItemKind::Separator,
label: SharedString::default(),
icon: None,
shortcut: None,
handler: None,
disabled: false,
destructive: false,
@@ -137,15 +135,6 @@ impl MenuItem {
self
}
/// Shows a shortcut hint after the label.
pub fn shortcut<S>(mut self, shortcut: S) -> Self
where
S: Into<SharedString>,
{
self.shortcut = Some(shortcut.into());
self
}
/// Marks the item non-selectable and non-activatable.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
@@ -185,6 +174,226 @@ impl MenuItem {
fn selectable(&self) -> bool {
matches!(self.kind, MenuItemKind::Action | MenuItemKind::Submenu(_)) && !self.disabled
}
/// Renders one menu row.
fn render_item(
&self,
window: &mut Window,
cx: &mut App,
index: usize,
selected: bool,
env: &RowEnv,
) -> AnyElement {
match &self.kind {
MenuItemKind::Separator => div()
.h_px()
.debug_selector(move || format!("{}-separator-{index}", env.debug_prefix))
.mx_2()
.my_1()
.bg(env.chrome.border)
.into_any_element(),
MenuItemKind::Action => {
let label_color = self.row_color(selected, false, env.chrome);
let disabled = self.disabled;
let checked = self.checked;
let icon = self.icon.clone();
self.row_shell(cx, index, selected, env)
.on_click({
let handler = self.handler.clone();
let on_activate = env.on_activate.clone();
move |_, window, cx| {
if disabled {
return;
}
if let Some(on_activate) = &on_activate {
on_activate(false, window, cx);
}
if let Some(handler) = &handler {
handler(window, cx);
}
}
})
.when_some(icon, |row, icon| {
row.child(icon.size(rems(1.0)).color(label_color))
})
.child(
div()
.flex_1()
.text_color(label_color)
.child(self.label.clone()),
)
.when(checked, |row| {
row.child(
icon_glyph(IconRole::Check)
.size(rems(0.75))
.color(label_color),
)
})
.into_any_element()
}
MenuItemKind::Submenu(items) => {
let chrome = env.chrome;
let flyout = env.flyout;
let disabled = self.disabled;
let open = *flyout.open.read(cx) == Some(index);
let label_color = self.row_color(selected, open, chrome);
let row_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None));
self.row_shell(cx, index, selected, env)
.on_click({
let set_flyout = flyout.set_flyout.clone();
move |_, _window, cx| {
if disabled {
return;
}
// Hover already opens the flyout; a click never closes it.
set_flyout(Some(index), false, cx);
}
})
.child(
div()
.flex_1()
.text_color(label_color)
.child(self.label.clone()),
)
.child(
icon_glyph(IconRole::ChevronRight)
.size(rems(0.75))
.color(label_color),
)
.aria_expanded(open)
.when(open, |row| {
row.child(
canvas(
{
let cell = row_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
.child(
deferred(div().absolute().left_full().top_0().child(menu_panel(
window,
cx,
flyout.state,
MenuPanelParams {
id: &flyout.id,
items: items.clone(),
initial_selection: None,
preselect: *flyout.preselect.read(cx),
min_width: flyout.min_width,
label: self.label.clone(),
dismiss_bounds: &row_bounds,
bounds_sink: Some(flyout.bounds),
outer_stack: Some(flyout.stack),
on_dismiss: Some(flyout.dismiss.clone()),
on_activate: flyout.on_activate.clone(),
is_flyout: true,
chrome,
enter_duration: flyout.enter_duration,
debug_prefix: "submenu",
},
)))
.with_priority(OVERLAY_LAYER),
)
})
.into_any_element()
}
}
}
/// The shared row shell: dimensions, highlight, and hover-selection.
fn row_shell(
&self,
cx: &App,
index: usize,
selected: bool,
env: &RowEnv,
) -> gpui::Stateful<gpui::Div> {
let chrome = env.chrome;
let selectable = self.selectable();
let opens_submenu = self.submenu_items().is_some();
let flyout_open = *env.flyout.open.read(cx) == Some(index);
let row_id = self
.id
.clone()
.unwrap_or_else(|| ("menu-item", index).into());
div()
.id(row_id)
.role(Role::MenuItem)
.debug_selector(move || format!("{}-item-{index}", env.debug_prefix))
.flex()
.items_center()
.gap_2()
.min_h_8()
.px_4()
.text_sm()
.line_height(relative(1.0))
.rounded(chrome.radius_full)
.map(|row| {
if self.disabled {
row
} else if selected && flyout_open {
row.bg(chrome.muted_hover)
} else if selected {
let highlight = if self.destructive {
chrome.destructive
} else {
chrome.primary
};
row.bg(highlight)
} else {
row.hover(|row| row.bg(chrome.muted_hover))
}
})
.on_mouse_move({
let selection = env.selection.clone();
let flyout_open = env.flyout.open.clone();
let set_flyout = env.flyout.set_flyout.clone();
let dismiss = env.flyout.dismiss.clone();
move |_, window, cx| {
if !selectable {
return;
}
if *selection.read(cx) != Some(index) {
selection.update(cx, |selection, _| *selection = Some(index));
}
if opens_submenu {
set_flyout(Some(index), false, cx);
} else if flyout_open.read(cx).is_some() {
dismiss(false, window, cx);
}
}
})
}
/// The row's label/icon color.
fn row_color(&self, selected: bool, flyout_open: bool, chrome: &MenuChrome) -> gpui::Hsla {
if self.disabled {
return chrome.muted_foreground;
}
if self.destructive {
return if selected && !flyout_open {
chrome.destructive_foreground
} else {
chrome.destructive
};
}
if selected && !flyout_open {
chrome.primary_foreground
} else {
chrome.foreground
}
}
}
// MenuItem is a data builder, not an element, adopt the combinators explicitly.
@@ -378,49 +587,12 @@ impl RenderOnce for Menu {
div()
.relative()
.refine_style(&self.style)
.child(
canvas(
{
let cell = trigger_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
{
let on_change = on_change;
let open = self.open;
let trigger_button = self.trigger_button;
let cell = trigger_bounds.clone();
move |_, _, window, _cx| {
let trigger_bounds = cell;
window.on_mouse_event({
let on_change = on_change.clone();
move |event: &MouseDownEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble
|| event.button != trigger_button
{
return;
}
let on_trigger = trigger_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position));
if !on_trigger {
return;
}
if let Some(on_change) = &on_change {
on_change(!open, window, cx);
}
cx.stop_propagation();
}
});
}
},
)
.absolute()
.inset_0(),
)
.child(trigger_toggle(
&trigger_bounds,
self.open,
on_change.clone(),
self.trigger_button,
))
.when_some(self.trigger, |wrapper, trigger| {
wrapper.child(trigger(window, cx))
})
@@ -455,15 +627,6 @@ struct MenuPanelState {
selection: Entity<Option<usize>>,
}
fn create_menu_panel_state(id: &ElementId, window: &mut Window, cx: &mut App) -> MenuPanelState {
MenuPanelState {
focus: focus_handle(&(id.clone(), "panel").into(), window, cx),
was_open: window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false),
scroll: window.use_keyed_state((id.clone(), "menu-scroll"), cx, |_, _| ScrollHandle::new()),
selection: window.use_keyed_state((id.clone(), "menu-selection"), cx, |_, _| None),
}
}
struct MenuPanelParams<'a> {
id: &'a ElementId,
items: Rc<[MenuItem]>,
@@ -513,6 +676,104 @@ struct RowEnv<'a> {
debug_prefix: &'static str,
}
/// Everything key navigation needs from the panel.
struct MenuKeyEnv<'a> {
items: &'a [MenuItem],
selection: &'a Entity<Option<usize>>,
set_flyout: &'a FlyoutSetter,
on_dismiss: &'a Option<ChangeHandler>,
on_activate: &'a Option<ChangeHandler>,
left_dismisses: bool,
}
/// Canvas that records the trigger's painted bounds and toggles `open` on click.
pub(crate) fn trigger_toggle(
bounds: &TriggerBoundsCell,
open: bool,
on_change: Option<ChangeHandler>,
button: MouseButton,
) -> AnyElement {
let painted = bounds.clone();
canvas(
{
let cell = bounds.clone();
move |painted, _window, _cx| *cell.borrow_mut() = Some(painted)
},
move |_, _, window, _cx| {
let cell = painted.clone();
window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble || event.button != button {
return;
}
let on_trigger = cell
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position));
if !on_trigger {
return;
}
if let Some(on_change) = &on_change {
on_change(!open, window, cx);
}
cx.stop_propagation();
});
},
)
.absolute()
.inset_0()
.into_any_element()
}
/// Deferred anchored overlay on OVERLAY_LAYER, optionally fading in.
pub(crate) fn anchored_overlay(
position: Option<Point<Pixels>>,
panel: AnyElement,
fade: Option<(&'static str, std::time::Duration)>,
) -> AnyElement {
let anchored = match position {
Some(position) => anchored().position(position),
None => anchored(),
}
.offset(point(px(0.), px(4.)));
// AnyElement lacks `Styled`, so the opacity animation rides a wrapper.
let panel = match fade {
Some((id, duration)) => div()
.child(panel)
.with_animation(
id,
Animation::new(duration).with_easing(ease_out_quint()),
|panel, delta| panel.opacity(delta),
)
.into_any_element(),
None => panel,
};
deferred(anchored.child(panel))
.with_priority(OVERLAY_LAYER)
.into_any_element()
}
/// Canvas that grabs focus when `should_grab` holds.
pub(crate) fn focus_capture(
focus: FocusHandle,
should_grab: impl Fn(&mut Window, &mut App) -> bool + 'static,
) -> AnyElement {
canvas(
|_, _, _| {},
move |_, _, window, cx| {
if should_grab(window, cx) {
window.focus(&focus, cx);
}
},
)
.absolute()
.inset_0()
.into_any_element()
}
/// Assembles the floating menu panel anchored to its trigger.
pub(crate) fn anchored_menu_panel(
window: &mut Window,
@@ -524,8 +785,6 @@ pub(crate) fn anchored_menu_panel(
) -> Option<AnyElement> {
let was_open = window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false);
// Render-phase residue: trigger-toggle and owner-driven closes bypass every
// dismissal handler, so this closed frame is the only universal close hook.
if !spec.open {
was_open.update(cx, |was_open, _| *was_open = false);
// A closed menu drops any open flyout; fresh state on the next open.
@@ -562,17 +821,7 @@ pub(crate) fn anchored_menu_panel(
},
);
let anchored = match spec.position {
Some(position) => anchored().position(position),
None => anchored(),
}
.offset(point(px(0.), px(4.)));
Some(
deferred(anchored.child(panel))
.with_priority(OVERLAY_LAYER)
.into_any_element(),
)
Some(anchored_overlay(spec.position, panel, None))
}
/// Builds one menu panel: chrome, rows, focus, navigation, and dismissals.
@@ -668,10 +917,9 @@ fn menu_panel(
.iter()
.enumerate()
.map(|(index, item)| {
render_item(
item.render_item(
window,
cx,
item,
index,
selected == Some(index),
&RowEnv {
@@ -791,254 +1039,6 @@ fn menu_panel(
.into_any_element()
}
/// Renders one menu row.
fn render_item(
window: &mut Window,
cx: &mut App,
item: &MenuItem,
index: usize,
selected: bool,
env: &RowEnv,
) -> AnyElement {
match &item.kind {
MenuItemKind::Separator => div()
.h_px()
.debug_selector(move || format!("{}-separator-{index}", env.debug_prefix))
.mx_2()
.my_1()
.bg(env.chrome.border)
.into_any_element(),
MenuItemKind::Action => {
let label_color = row_color(item, selected, false, env.chrome);
let disabled = item.disabled;
let destructive = item.destructive;
let checked = item.checked;
let shortcut = item.shortcut.clone();
let icon = item.icon.clone();
row_shell(cx, item, index, selected, env)
.on_click({
let handler = item.handler.clone();
let on_activate = env.on_activate.clone();
move |_, window, cx| {
if disabled {
return;
}
if let Some(on_activate) = &on_activate {
on_activate(false, window, cx);
}
if let Some(handler) = &handler {
handler(window, cx);
}
}
})
.when_some(icon, |row, icon| {
row.child(icon.size(rems(1.0)).color(label_color))
})
.child(
div()
.flex_1()
.text_color(label_color)
.child(item.label.clone()),
)
.when_some(shortcut, |row, shortcut| {
row.child(
div()
.text_color(if selected && !destructive && !disabled {
env.chrome.primary_foreground
} else {
env.chrome.muted_foreground
})
.child(shortcut),
)
})
.when(checked, |row| {
row.child(
icon_glyph(IconRole::Check)
.size(rems(0.75))
.color(label_color),
)
})
.into_any_element()
}
MenuItemKind::Submenu(items) => {
let chrome = env.chrome;
let flyout = env.flyout;
let disabled = item.disabled;
let open = *flyout.open.read(cx) == Some(index);
let label_color = row_color(item, selected, open, chrome);
let row_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None));
row_shell(cx, item, index, selected, env)
.on_click({
let set_flyout = flyout.set_flyout.clone();
move |_, _window, cx| {
if disabled {
return;
}
// Hover already opens the flyout; a click never closes it.
set_flyout(Some(index), false, cx);
}
})
.child(
div()
.flex_1()
.text_color(label_color)
.child(item.label.clone()),
)
.child(
icon_glyph(IconRole::ChevronRight)
.size(rems(0.75))
.color(label_color),
)
.aria_expanded(open)
.when(open, |row| {
row.child(
canvas(
{
let cell = row_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
.child(
deferred(div().absolute().left_full().top_0().child(menu_panel(
window,
cx,
flyout.state,
MenuPanelParams {
id: &flyout.id,
items: items.clone(),
initial_selection: None,
preselect: *flyout.preselect.read(cx),
min_width: flyout.min_width,
label: item.label.clone(),
dismiss_bounds: &row_bounds,
bounds_sink: Some(flyout.bounds),
outer_stack: Some(flyout.stack),
on_dismiss: Some(flyout.dismiss.clone()),
on_activate: flyout.on_activate.clone(),
is_flyout: true,
chrome,
enter_duration: flyout.enter_duration,
debug_prefix: "submenu",
},
)))
.with_priority(OVERLAY_LAYER),
)
})
.into_any_element()
}
}
}
/// The shared row shell: dimensions, highlight, and hover-selection.
fn row_shell(
cx: &App,
item: &MenuItem,
index: usize,
selected: bool,
env: &RowEnv,
) -> gpui::Stateful<gpui::Div> {
let chrome = env.chrome;
let selectable = item.selectable();
let opens_submenu = item.submenu_items().is_some();
let flyout_open = *env.flyout.open.read(cx) == Some(index);
let row_id = item
.id
.clone()
.unwrap_or_else(|| ("menu-item", index).into());
div()
.id(row_id)
.role(Role::MenuItem)
.debug_selector(move || format!("{}-item-{index}", env.debug_prefix))
.flex()
.items_center()
.gap_2()
.min_h_8()
.px_4()
.text_sm()
.line_height(relative(1.0))
.rounded(chrome.radius_full)
.map(|row| {
if item.disabled {
row
} else if selected && flyout_open {
row.bg(chrome.muted_hover)
} else if selected {
let highlight = if item.destructive {
chrome.destructive
} else {
chrome.primary
};
row.bg(highlight)
} else {
row.hover(|row| row.bg(chrome.muted_hover))
}
})
.on_mouse_move({
let selection = env.selection.clone();
let flyout_open = env.flyout.open.clone();
let set_flyout = env.flyout.set_flyout.clone();
let dismiss = env.flyout.dismiss.clone();
move |_, window, cx| {
if !selectable {
return;
}
if *selection.read(cx) != Some(index) {
selection.update(cx, |selection, _| *selection = Some(index));
}
if opens_submenu {
set_flyout(Some(index), false, cx);
} else if flyout_open.read(cx).is_some() {
dismiss(false, window, cx);
}
}
})
}
/// The row's label/icon color.
fn row_color(
item: &MenuItem,
selected: bool,
flyout_open: bool,
chrome: &MenuChrome,
) -> gpui::Hsla {
if item.disabled {
return chrome.muted_foreground;
}
if item.destructive {
return if selected && !flyout_open {
chrome.destructive_foreground
} else {
chrome.destructive
};
}
if selected && !flyout_open {
chrome.primary_foreground
} else {
chrome.foreground
}
}
/// Everything key navigation needs from the panel.
struct MenuKeyEnv<'a> {
items: &'a [MenuItem],
selection: &'a Entity<Option<usize>>,
set_flyout: &'a FlyoutSetter,
on_dismiss: &'a Option<ChangeHandler>,
on_activate: &'a Option<ChangeHandler>,
left_dismisses: bool,
}
/// Handles the panel's navigation keys.
fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, cx: &mut App) {
let selectable: Vec<usize> = env
@@ -1111,3 +1111,13 @@ fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, c
cx.stop_propagation();
}
/// Creates one panel's keyed state: focus, open tracking, scroll, and selection.
fn create_menu_panel_state(id: &ElementId, window: &mut Window, cx: &mut App) -> MenuPanelState {
MenuPanelState {
focus: focus_handle(&(id.clone(), "panel").into(), window, cx),
was_open: window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false),
scroll: window.use_keyed_state((id.clone(), "menu-scroll"), cx, |_, _| ScrollHandle::new()),
selection: window.use_keyed_state((id.clone(), "menu-selection"), cx, |_, _| None),
}
}
-8
View File
@@ -10,9 +10,7 @@ pub mod code;
pub mod combobox;
pub mod command_palette;
pub mod common;
pub mod context_menu;
pub mod dialog;
pub mod diff;
pub mod dropdown_menu;
pub mod empty_state;
pub mod field;
@@ -20,21 +18,15 @@ pub mod grain;
pub mod highlight;
pub mod input;
pub mod kbd;
pub mod link;
pub mod list;
pub mod markdown;
pub mod menu;
pub mod popover;
pub mod progress;
pub mod radio;
pub mod scroll_area;
pub mod scrollbar;
pub mod segmented;
pub mod select;
pub mod separator;
pub mod sidebar;
pub mod slider;
pub mod speech;
pub mod spinner;
pub mod status_dot;
pub mod switch;
+23 -76
View File
@@ -24,24 +24,21 @@ use std::rc::Rc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
Animation, AnimationExt as _, AnyElement, App, Bounds, DispatchPhase, ElementId,
InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent,
ParentElement as _, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Window, anchored, canvas, deferred, div, ease_out_quint, point,
px,
AnyElement, App, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton,
ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Window, div,
};
use crate::components::common::{OVERLAY_LAYER, StyledExt as _, floating_panel, v_flex};
use crate::components::menu::{
ChangeHandler, TriggerBoundsCell, anchored_overlay, focus_capture, trigger_toggle,
};
use crate::components::common::{StyledExt as _, floating_panel, v_flex};
use crate::theme::{ActiveTheme as _, POPOVER_MIN_WIDTH};
/// Reports the next open state of a [`Popover`]: `true` to open, `false` to close.
type ChangeHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
/// The element the panel anchors below, built during render.
type TriggerFn = Box<dyn FnOnce(&mut Window, &mut App) -> AnyElement>;
/// The panel's contents, built when it opens.
type ContentFn = Box<dyn FnOnce(&mut Window, &mut App) -> AnyElement>;
/// Bounds captured during the last paint, shared with the dismissal listener.
type BoundsCell = Rc<RefCell<Option<Bounds<Pixels>>>>;
/// A floating panel anchored below its trigger.
#[derive(IntoElement)]
@@ -134,7 +131,7 @@ impl RenderOnce for Popover {
)
};
let trigger_bounds: BoundsCell = Rc::new(RefCell::new(None));
let trigger_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None));
let fallback_label = self
.a11y_label
@@ -144,49 +141,12 @@ impl RenderOnce for Popover {
div()
.relative()
.refine_style(&self.style)
.child(
canvas(
{
let cell = trigger_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
{
let on_change = self.on_change.clone();
let open = self.open;
let cell = trigger_bounds.clone();
move |_, _, window, _cx| {
window.on_mouse_event({
let on_change = on_change.clone();
let trigger_bounds = cell;
move |event: &MouseDownEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble
|| event.button != MouseButton::Left
{
return;
}
let on_trigger = trigger_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position));
if !on_trigger {
return;
}
if let Some(on_change) = &on_change {
on_change(!open, window, cx);
}
cx.stop_propagation();
}
});
}
},
)
.absolute()
.inset_0(),
)
.child(trigger_toggle(
&trigger_bounds,
self.open,
self.on_change.clone(),
MouseButton::Left,
))
.when_some(self.trigger, |wrapper, trigger| {
wrapper.child(trigger(window, cx))
})
@@ -238,29 +198,16 @@ impl RenderOnce for Popover {
}
})
.when_some(content, |panel, content| panel.child(content))
.child(
canvas(|_, _, _| {}, {
let focus = focus;
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
.child(focus_capture(
focus.clone(),
move |window, cx| !focus.contains_focused(window, cx),
));
wrapper.child(
deferred(anchored().offset(point(Pixels::ZERO, px(4.))).child(
panel.with_animation(
"popover-enter",
Animation::new(enter_duration).with_easing(ease_out_quint()),
|panel, delta| panel.opacity(delta),
),
))
.with_priority(OVERLAY_LAYER),
)
wrapper.child(anchored_overlay(
None,
panel.into_any_element(),
Some(("popover-enter", enter_duration)),
))
})
}
}
-132
View File
@@ -1,132 +0,0 @@
//! Renders a progress bar with a determinate fill or an indeterminate sweep.
//!
//! # Examples
//!
//! ```no_run
//! use ui::progress::Progress;
//!
//! let upload = Progress::new("upload", 0.4);
//! let loading = Progress::new("loading", 0.0).indeterminate(true);
//! ```
use gpui::prelude::FluentBuilder as _;
use gpui::{
Animation, AnimationExt as _, App, ElementId, InteractiveElement as _, IntoElement,
ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
StyleRefinement, Styled as _, Window, div, relative,
};
use crate::components::common::{Sizable, StyledExt as _};
use crate::theme::{ActiveTheme as _, PROGRESS_ANIMATION_PERIOD, Size};
/// A bar that paints a determinate fill from its `value`, or an indeterminate sweep.
#[derive(IntoElement)]
#[must_use]
pub struct Progress {
id: ElementId,
value: f32,
indeterminate: bool,
size: Size,
a11y_label: Option<SharedString>,
style: StyleRefinement,
}
impl Progress {
/// Creates a determinate progress bar at `value` (`0..=1`).
pub fn new<I>(id: I, value: f32) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
value,
indeterminate: false,
size: Size::default(),
a11y_label: None,
style: StyleRefinement::default(),
}
}
/// Sweeps instead of painting a fill, for work of unknown length.
pub fn indeterminate(mut self, indeterminate: bool) -> Self {
self.indeterminate = indeterminate;
self
}
/// Sets the accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
impl gpui::Styled for Progress {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Progress {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Progress {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let radius = theme.radius;
let size = self.size;
let value = self.value.clamp(0.0, 1.0);
let track = div().w_full().rounded(radius.full).bg(colors.border);
let track = match size {
Size::XSmall => track.h_0p5(),
Size::Small | Size::Medium => track.h_1(),
Size::Large => track.h_1p5(),
};
div()
.id(self.id)
.w_full()
.refine_style(&self.style)
.role(Role::ProgressIndicator)
.when_some(self.a11y_label, |progress, label| {
progress.aria_label(label)
})
.when(!self.indeterminate, |progress| {
progress
.aria_numeric_value(f64::from(value))
.aria_min_numeric_value(0.0)
.aria_max_numeric_value(1.0)
})
.child(track.child(if self.indeterminate {
div()
.h_full()
.w(relative(0.3))
.rounded(radius.full)
.bg(ramps.primary.base)
.with_animation(
"indeterminate",
Animation::new(PROGRESS_ANIMATION_PERIOD)
.repeat()
.with_max_fps(30.),
|pill, delta| pill.ml(relative(delta * 0.7)),
)
.into_any_element()
} else {
div()
.h_full()
.w(relative(value))
.rounded(radius.full)
.bg(ramps.primary.base)
.into_any_element()
}))
}
}
-259
View File
@@ -1,259 +0,0 @@
//! Renders a group of radio buttons that reports the clicked choice.
//!
//! # Examples
//!
//! ```no_run
//! use ui::radio::{Radio, RadioGroup};
//!
//! let plan = RadioGroup::new("plan")
//! .selected(Some("monthly"))
//! .child(Radio::new("monthly", "monthly").label("Monthly"))
//! .child(Radio::new("yearly", "yearly").label("Yearly"))
//! .on_change(|value, _window, _cx| println!("selected: {value}"));
//! ```
use gpui::prelude::FluentBuilder;
use gpui::{
App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window,
div,
};
use crate::components::common::{
ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex, v_flex,
};
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
/// The group's change reporter, fired with the clicked radio's value.
type ChangeHandler<V> = std::rc::Rc<dyn Fn(V, &mut Window, &mut App)>;
/// A single choice in a [`RadioGroup`].
///
/// Each radio is its own tab stop; the full ARIA radiogroup pattern (single
/// stop plus arrow-key roving focus) needs a group owner that does not exist yet.
#[must_use]
pub struct Radio<V> {
id: ElementId,
value: V,
label: Option<SharedString>,
disabled: bool,
a11y_label: Option<SharedString>,
}
impl<V> Radio<V>
where
V: Clone + PartialEq + 'static,
{
/// Creates a radio representing `value`.
pub fn new<I>(id: I, value: V) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
value,
label: None,
disabled: false,
a11y_label: None,
}
}
/// Sets the visible label; clicking it selects the radio too.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Renders the radio inert, unfocusable, and dimmed.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
// Radio is a data builder, not an element, adopt the combinators explicitly.
impl<V> FluentBuilder for Radio<V> {}
/// A set of [`Radio`] choices that reports clicks through [`RadioGroup::on_change`].
#[derive(IntoElement)]
#[must_use]
pub struct RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
id: ElementId,
selected: Option<V>,
children: Vec<Radio<V>>,
size: Size,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler<V>>,
style: StyleRefinement,
}
impl<V> RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
/// Creates an empty group with nothing selected.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
selected: None,
children: Vec::new(),
size: Size::default(),
a11y_label: None,
on_change: None,
style: StyleRefinement::default(),
}
}
/// Sets the currently selected value.
pub fn selected(mut self, selected: Option<V>) -> Self {
self.selected = selected;
self
}
/// Adds a radio to the group.
pub fn child(mut self, radio: Radio<V>) -> Self {
self.children.push(radio);
self
}
/// Sets the group's accessibility label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Sets the handler fired with the clicked radio's value.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(V, &mut Window, &mut App) + 'static,
{
self.on_change = Some(std::rc::Rc::new(handler));
self
}
}
impl<V> Sizable for RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl<V> gpui::Styled for RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl<V> RenderOnce for RadioGroup<V>
where
V: Clone + PartialEq + 'static,
{
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let radius = theme.radius;
let size = self.size;
let selected = self.selected;
let on_change = self.on_change;
let group_label = self.a11y_label;
v_flex()
.id(self.id)
.gap_2()
.control_text(size)
.refine_style(&self.style)
.role(Role::RadioGroup)
.when_some(group_label.clone(), |group, label| group.aria_label(label))
.children(self.children.into_iter().map(move |radio| {
let is_selected = selected.as_ref() == Some(&radio.value);
let disabled = radio.disabled;
let row_on_change = on_change.clone();
let a11y_label = radio
.a11y_label
.or(radio.label.clone())
.or_else(|| group_label.clone());
h_flex()
.id(radio.id)
.gap_2()
.role(Role::RadioButton)
.when_some(a11y_label, |row, label| row.aria_label(label))
.aria_toggled(Toggled::from(is_selected))
.when(disabled, |row| row.opacity(DISABLED_OPACITY))
.when(!disabled, move |row| {
let value = radio.value.clone();
row.cursor_pointer()
.focusable()
.tab_stop(true)
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.when_some(row_on_change, |row, on_change| {
row.on_click(move |_, window, cx| {
on_change(value.clone(), window, cx)
})
})
})
.child(
h_flex()
.justify_center()
.flex_none()
.control_indicator(size)
.rounded(radius.full)
.border_1()
.when(is_selected, |indicator| {
indicator
.bg(ramps.primary.base)
.border_color(ramps.primary.base)
.hover(|style| {
style
.bg(ramps.primary.hover)
.border_color(ramps.primary.hover)
})
.child({
let dot = match size {
Size::XSmall => div().size_1p5(),
Size::Small | Size::Medium => div().size_2(),
Size::Large => div().size_2p5(),
};
dot.rounded(radius.full).bg(colors.primary_foreground)
})
})
.when(!is_selected, |indicator| {
indicator
.bg(colors.input)
.border_color(colors.border)
.hover(|style| style.border_color(colors.muted_foreground))
}),
)
.when_some(radio.label, |row, label| row.child(label))
}))
}
}
+47 -49
View File
@@ -42,6 +42,39 @@ pub enum ScrollbarVisibility {
/// How often the autohide fade repaints while it runs.
const FADE_STEP: Duration = Duration::from_millis(50);
/// The drag state shared between the scrollbar's mouse handlers.
type Drag = Option<(Pixels, Pixels)>;
/// Which direction the scrollbar lies along.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Axis {
Vertical,
Horizontal,
}
impl Axis {
fn along(self, position: Point<Pixels>) -> Pixels {
match self {
Axis::Vertical => position.y,
Axis::Horizontal => position.x,
}
}
fn with_along(self, position: Point<Pixels>, along: Pixels) -> Point<Pixels> {
match self {
Axis::Vertical => point(position.x, along),
Axis::Horizontal => point(along, position.y),
}
}
fn viewport_along(self, viewport: &Bounds<Pixels>) -> Pixels {
match self {
Axis::Vertical => viewport.size.height,
Axis::Horizontal => viewport.size.width,
}
}
}
/// The shared autohide timeline for an overlay scrollbar.
#[derive(Clone)]
struct Autohide {
@@ -199,36 +232,6 @@ impl ScrollbarHandle for ListState {
}
}
/// Which direction the scrollbar lies along.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Axis {
Vertical,
Horizontal,
}
impl Axis {
fn along(self, position: Point<Pixels>) -> Pixels {
match self {
Axis::Vertical => position.y,
Axis::Horizontal => position.x,
}
}
fn with_along(self, position: Point<Pixels>, along: Pixels) -> Point<Pixels> {
match self {
Axis::Vertical => point(position.x, along),
Axis::Horizontal => point(along, position.y),
}
}
fn viewport_along(self, viewport: &Bounds<Pixels>) -> Pixels {
match self {
Axis::Vertical => viewport.size.height,
Axis::Horizontal => viewport.size.width,
}
}
}
/// An overlay scrollbar, rendered over the scrolled surface.
#[derive(IntoElement)]
#[must_use]
@@ -239,6 +242,20 @@ pub struct Scrollbar {
id: ElementId,
}
impl RenderOnce for Scrollbar {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
canvas(|_, _, _| {}, {
let handle = self.handle;
let axis = self.axis;
let visibility = self.visibility;
let id = self.id;
move |_, _, window, cx| Self::paint(&handle, axis, visibility, &id, window, cx)
})
.absolute()
.inset_0()
}
}
impl Scrollbar {
/// Creates a vertical scrollbar named by `id`, driven by `handle`.
pub fn vertical<I, H>(id: I, handle: H) -> Self
@@ -304,26 +321,7 @@ impl Scrollbar {
..color
})
}
}
impl RenderOnce for Scrollbar {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
canvas(|_, _, _| {}, {
let handle = self.handle;
let axis = self.axis;
let visibility = self.visibility;
let id = self.id;
move |_, _, window, cx| Self::paint(&handle, axis, visibility, &id, window, cx)
})
.absolute()
.inset_0()
}
}
/// The drag state shared between the scrollbar's mouse handlers.
type Drag = Option<(Pixels, Pixels)>;
impl Scrollbar {
fn paint(
handle: &Rc<dyn ScrollbarHandle>,
axis: Axis,
+1 -1
View File
@@ -29,7 +29,7 @@ use crate::icons::{Icon, IconRole, icon};
use crate::theme::{ActiveTheme as _, Size};
/// Reports the value the user chose. `None` means the select holds no value.
pub type SelectHandler<T> = Rc<dyn Fn(Option<T>, &mut Window, &mut App)>;
type SelectHandler<T> = Rc<dyn Fn(Option<T>, &mut Window, &mut App)>;
/// Select option for a [`Select`] control.
#[derive(Clone)]
+123 -161
View File
@@ -143,6 +143,129 @@ impl SidebarEntry {
}
self
}
#[allow(clippy::too_many_arguments)]
fn render_entry(
self,
cx: &App,
index: usize,
position_in_set: usize,
size_of_set: usize,
selected: bool,
material: bool,
on_change: &Option<ChangeHandler>,
focus: &FocusHandle,
) -> AnyElement {
let theme = cx.theme();
match self {
SidebarEntry::Header {
label,
prefix,
suffix,
} => {
// The id is required for the role to surface in the a11y tree.
div()
.id(("sidebar-header".into(), label.clone()))
.flex()
.items_center()
.gap_2()
.px_2()
.pt_2()
.pb_1()
.text_sm()
.font_semibold()
.text_color(theme.colors.muted_foreground)
.role(Role::Heading)
.when_some(prefix, |header, prefix| header.child(prefix))
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label),
)
.when_some(suffix, |header, suffix| header.child(suffix))
.into_any_element()
}
SidebarEntry::Custom(element) => element,
SidebarEntry::Row {
key,
label,
detail,
prefix,
suffix,
disabled: row_disabled,
} => {
let label_color = selectable_label_color(cx, selected, row_disabled);
div()
.id((key.clone(), "sidebar-row"))
.flex()
.items_center()
.gap_2()
.px_2()
.py_1()
.min_h_8()
.rounded(theme.radius.sm)
.text_color(label_color)
.role(Role::ListItem)
.aria_selected(selected)
.aria_position_in_set(position_in_set)
.aria_size_of_set(size_of_set)
.map(|row| {
if material && !row_disabled {
if selected {
row.bg(theme.material.selection)
} else {
row.hover(|row| row.bg(theme.material.hover))
}
} else {
paint_selectable_row(cx, row, selected, row_disabled)
}
})
.when(!row_disabled, |row| {
row.cursor_pointer().on_click({
let on_change = on_change.clone();
let focus = focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if let Some(on_change) = &on_change {
on_change(Some(index), window, cx);
}
}
})
})
.when_some(prefix, |row, prefix| row.child(prefix))
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label),
)
.when_some(detail, |row, detail| {
row.child(
div()
.flex_none()
.text_sm()
.text_color(if selected {
theme.colors.primary_foreground
} else {
theme.colors.muted_foreground
})
.child(detail),
)
})
.when_some(suffix, |row, suffix| row.child(suffix))
.into_any_element()
}
}
}
}
// SidebarEntry is a data builder, not an element, adopt the combinators explicitly.
@@ -198,48 +321,12 @@ impl Sidebar {
self
}
/// Whether translucent material fills are painted.
pub fn is_transparent(&self) -> bool {
self.transparent
}
/// Textures the sidebar with a film-grain overlay.
pub fn grain(mut self, grain: bool) -> Self {
self.grain = grain;
self
}
/// Paints a hairline border on the sidebar's right edge.
pub fn border_right(mut self, border_right: bool) -> Self {
self.border_right = border_right;
self
}
/// Whether the right-edge border is painted.
pub fn has_border_right(&self) -> bool {
self.border_right
}
/// Insets the entry list from the sidebar's edges; the scrollbar stays on the edge.
pub fn padded(mut self, padded: bool) -> Self {
self.padded = padded;
self
}
/// Whether the entry list is inset from the sidebar's edges.
pub fn is_padded(&self) -> bool {
self.padded
}
/// Sets the sidebar's width, overriding the default.
pub fn width<W>(mut self, width: W) -> Self
where
W: Into<Pixels>,
{
self.width = width.into();
self
}
/// Reports the next selected row, from clicks and keys alike.
pub fn on_change<F>(mut self, handler: F) -> Self
where
@@ -404,128 +491,3 @@ impl RenderOnce for Sidebar {
.when(material && grain, |sidebar| sidebar.child(grain_overlay()))
}
}
impl SidebarEntry {
#[allow(clippy::too_many_arguments)]
fn render_entry(
self,
cx: &App,
index: usize,
position_in_set: usize,
size_of_set: usize,
selected: bool,
material: bool,
on_change: &Option<ChangeHandler>,
focus: &FocusHandle,
) -> AnyElement {
let theme = cx.theme();
match self {
SidebarEntry::Header {
label,
prefix,
suffix,
} => {
// The id is required for the role to surface in the a11y tree.
div()
.id(("sidebar-header".into(), label.clone()))
.flex()
.items_center()
.gap_2()
.px_2()
.pt_2()
.pb_1()
.text_sm()
.font_semibold()
.text_color(theme.colors.muted_foreground)
.role(Role::Heading)
.when_some(prefix, |header, prefix| header.child(prefix))
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label),
)
.when_some(suffix, |header, suffix| header.child(suffix))
.into_any_element()
}
SidebarEntry::Custom(element) => element,
SidebarEntry::Row {
key,
label,
detail,
prefix,
suffix,
disabled: row_disabled,
} => {
let label_color = selectable_label_color(cx, selected, row_disabled);
div()
.id((key.clone(), "sidebar-row"))
.flex()
.items_center()
.gap_2()
.px_2()
.py_1()
.min_h_8()
.rounded(theme.radius.sm)
.text_color(label_color)
.role(Role::ListItem)
.aria_selected(selected)
.aria_position_in_set(position_in_set)
.aria_size_of_set(size_of_set)
.map(|row| {
if material && !row_disabled {
if selected {
row.bg(theme.material.selection)
} else {
row.hover(|row| row.bg(theme.material.hover))
}
} else {
paint_selectable_row(cx, row, selected, row_disabled)
}
})
.when(!row_disabled, |row| {
row.cursor_pointer().on_click({
let on_change = on_change.clone();
let focus = focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if let Some(on_change) = &on_change {
on_change(Some(index), window, cx);
}
}
})
})
.when_some(prefix, |row, prefix| row.child(prefix))
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label),
)
.when_some(detail, |row, detail| {
row.child(
div()
.flex_none()
.text_sm()
.text_color(if selected {
theme.colors.primary_foreground
} else {
theme.colors.muted_foreground
})
.child(detail),
)
})
.when_some(suffix, |row, suffix| row.child(suffix))
.into_any_element()
}
}
}
}
-341
View File
@@ -1,341 +0,0 @@
//! Renders a controlled slider that reports its next value on click, drag, and arrow keys.
//!
//! # Examples
//!
//! ```no_run
//! use ui::slider::Slider;
//!
//! let opacity = Slider::new("opacity", 1.0)
//! .step(0.25)
//! .on_change(|value, _window, _cx| println!("opacity: {value}"));
//! ```
use std::cell::Cell;
use std::rc::Rc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, Bounds, DispatchPhase, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent,
MouseButton, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, RenderOnce, Role,
SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas,
div, relative,
};
use crate::components::common::{Sizable, StyledExt as _, focus_ring, h_flex};
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size};
/// The change reporter, fired with the next value by click, drag, and arrows.
type ChangeHandler = Rc<dyn Fn(f32, &mut Window, &mut App)>;
/// The pointer→value setter shared by the click and drag listeners.
type ValueSetter = Rc<dyn Fn(Pixels, &mut Window, &mut App)>;
/// The arrow-key stride as a share of the range when the slider is continuous.
const FALLBACK_STEP_FRACTION: f32 = 0.05;
impl Slider {
/// Clamps `value` into `[min, max]` and snaps it to `step` when stepped.
fn constrain(min: f32, max: f32, step: f32, value: f32) -> f32 {
let clamped = value.clamp(min, max);
if step > 0.0 {
(min + ((clamped - min) / step).round() * step).clamp(min, max)
} else {
clamped
}
}
}
/// A controlled slider over `[min, max]`.
#[derive(IntoElement)]
#[must_use]
pub struct Slider {
id: ElementId,
min: f32,
max: f32,
step: f32,
value: f32,
size: Size,
disabled: bool,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
style: StyleRefinement,
}
impl Slider {
/// Creates a slider over `0..=1` with no stepping, at `value`.
pub fn new<I>(id: I, value: f32) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
min: 0.0,
max: 1.0,
step: 0.0,
value,
size: Size::default(),
disabled: false,
a11y_label: None,
on_change: None,
style: StyleRefinement::default(),
}
}
/// Sets the range's lower bound.
pub fn min(mut self, min: f32) -> Self {
self.min = min;
self
}
/// Sets the range's upper bound.
pub fn max(mut self, max: f32) -> Self {
self.max = max;
self
}
/// Sets the step; values snap to `min + n * step`. `0` is continuous.
pub fn step(mut self, step: f32) -> Self {
self.step = step;
self
}
/// Renders the slider inert, unfocusable, and dimmed; disabled always wins.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Sets the accessibility label, required for an unlabeled slider.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// Sets the change handler, fired with the next value by click, drag, and arrows.
pub fn on_change<F>(mut self, handler: F) -> Self
where
F: Fn(f32, &mut Window, &mut App) + 'static,
{
self.on_change = Some(Rc::new(handler));
self
}
}
impl gpui::Styled for Slider {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl Sizable for Slider {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for Slider {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let radius = theme.radius;
let rem = window.rem_size();
let row_height = self.size.slider_row_rems() * rem;
let track_height = self.size.slider_track_rems() * rem;
let knob = self.size.indicator_rems() * rem;
let value = self.value.clamp(self.min, self.max);
let fraction = if self.max > self.min {
(value - self.min) / (self.max - self.min)
} else {
0.0
};
let bounds_cell = Rc::new(Cell::new(None::<Bounds<Pixels>>));
let focus_handle = crate::components::common::focus_handle(&self.id, window, cx);
let dragging =
window.use_keyed_state((self.id.clone(), "slider-dragging"), cx, |_, _| false);
let set_value: ValueSetter = {
let bounds_cell = bounds_cell.clone();
let on_change = self.on_change.clone();
let (min, max, step) = (self.min, self.max, self.step);
Rc::new(move |x: Pixels, window: &mut Window, cx: &mut App| {
if let (Some(bounds), Some(on_change)) = (bounds_cell.get(), on_change.as_ref())
&& bounds.size.width > Pixels::ZERO
{
let fraction = ((x - bounds.origin.x) / bounds.size.width).clamp(0.0, 1.0);
on_change(
Self::constrain(min, max, step, min + fraction * (max - min)),
window,
cx,
);
}
})
};
let down_dragging = dragging.clone();
let down_set_value = set_value.clone();
let disabled = self.disabled;
h_flex()
.id(self.id)
.relative()
.w_full()
.map(|slider| match self.size {
Size::XSmall => slider.h_6(),
Size::Small => slider.h_9(),
Size::Medium => slider.h_10(),
Size::Large => slider.h_12(),
})
.refine_style(&self.style)
.role(Role::Slider)
.when_some(self.a11y_label.clone(), |slider, label| {
slider.aria_label(label)
})
.aria_numeric_value(f64::from(value))
.aria_min_numeric_value(f64::from(self.min))
.aria_max_numeric_value(f64::from(self.max))
.when(self.disabled, |slider| slider.opacity(DISABLED_OPACITY))
.when(!self.disabled, |slider| {
slider
.track_focus(&focus_handle)
.tab_stop(true)
.focus_visible(|style| style.shadow(focus_ring(colors.ring)))
.on_mouse_down(MouseButton::Left, move |event, window, cx| {
down_dragging.update(cx, |dragging, _| *dragging = true);
down_set_value(event.position.x, window, cx);
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if !focus_handle.contains_focused(window, cx) {
return;
}
let single_step = if self.step > 0.0 {
self.step
} else {
(self.max - self.min) * FALLBACK_STEP_FRACTION
};
let next = match event.keystroke.key.as_str() {
"left" | "down" => Some(value - single_step),
"right" | "up" => Some(value + single_step),
"home" => Some(self.min),
"end" => Some(self.max),
_ => None,
};
if let Some(next) = next
&& let Some(on_change) = self.on_change.as_ref()
{
on_change(
Self::constrain(self.min, self.max, self.step, next),
window,
cx,
);
cx.stop_propagation();
}
})
})
.child(
canvas(
{
let bounds_cell = bounds_cell.clone();
move |bounds, _, _| bounds_cell.set(Some(bounds))
},
{
let dragging = dragging.clone();
let set_value = set_value.clone();
move |_, _, window, _cx| {
if disabled {
return;
}
window.on_mouse_event({
let dragging = dragging.clone();
let set_value = set_value.clone();
move |event: &MouseMoveEvent, phase, window, cx| {
if phase == DispatchPhase::Bubble
&& *dragging.read(cx)
&& event.pressed_button == Some(MouseButton::Left)
{
set_value(event.position.x, window, cx);
}
}
});
window.on_mouse_event({
let dragging = dragging.clone();
move |event: &MouseUpEvent, phase, _window, cx| {
if phase == DispatchPhase::Bubble
&& event.button == MouseButton::Left
{
dragging.update(cx, |dragging, _| *dragging = false);
}
}
});
}
},
)
.absolute()
.inset_0(),
)
.child(
div()
.absolute()
.left_0()
.top((row_height - track_height) / 2.0)
.map(|track| match self.size {
Size::XSmall => track.h_0p5(),
Size::Small | Size::Medium => track.h_1(),
Size::Large => track.h_1p5(),
})
.w_full()
.rounded(radius.full)
.bg(colors.border),
)
.child(
div()
.absolute()
.left_0()
.top((row_height - track_height) / 2.0)
.map(|track| match self.size {
Size::XSmall => track.h_0p5(),
Size::Small | Size::Medium => track.h_1(),
Size::Large => track.h_1p5(),
})
.w(relative(fraction))
.rounded(radius.full)
.bg(ramps.primary.base),
)
.child(
h_flex()
.absolute()
.left_0()
.top_0()
.h_full()
.w(relative(fraction))
.justify_end()
.items_center()
.child(
div()
.map(|dot| match self.size {
Size::XSmall => dot.size_2p5(),
Size::Small => dot.size_3p5(),
Size::Medium => dot.size_4(),
Size::Large => dot.size_5(),
})
.flex_none()
.rounded(radius.full)
.bg(colors.primary_foreground)
.border_1()
.border_color(colors.border)
.mr(-knob / 2.0),
),
)
}
}
File diff suppressed because it is too large Load Diff
+17 -3
View File
@@ -10,11 +10,12 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce,
Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, div,
AnyElement, App, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _,
RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
Window, div,
};
use crate::components::common::{Sizable, StyledExt as _};
use crate::components::common::{Sizable, StyledExt as _, v_flex};
use crate::icons::{IconRole, icon};
use crate::theme::{ActiveTheme as _, SPINNER_PERIOD, Size};
@@ -44,6 +45,19 @@ impl Spinner {
}
}
/// The spinner centered in the full available space.
pub fn centered<I>(id: I) -> AnyElement
where
I: Into<ElementId>,
{
v_flex()
.size_full()
.items_center()
.justify_center()
.child(Self::new(id))
.into_any_element()
}
/// Overrides the icon color, for accent-filled surfaces.
pub fn color(mut self, color: Hsla) -> Self {
self.color = Some(color);
+286 -287
View File
@@ -388,6 +388,292 @@ impl Tab {
self.wrap = Some(Box::new(wrap));
self
}
fn render_tab(mut self, ctx: &StripCtx, cx: &App, index: usize) -> AnyElement {
let selected = index == ctx.selected;
// A pinned tab always wears the active treatment, selected or not.
let active = selected || self.pinned;
let theme = cx.theme();
let label_color = tab_label_color(ctx.variant, active, self.disabled, cx);
let titlebar = ctx.variant == TabsVariant::Titlebar;
let group = SharedString::from(format!("{}-tab-{}", ctx.id, self.key));
let close = (self.closeable && ctx.on_close.is_some() && !self.disabled)
.then(|| self.render_tab_close(&ctx.id, index, &ctx.on_close));
let label = div()
.flex_grow(1.0)
.when(titlebar, |label| {
let fade = if active {
theme.colors.background
} else {
theme.colors.muted
};
let hover_fade = if active {
theme.colors.background
} else {
theme.colors.muted_hover
};
let fade_width = rems(0.75);
let hover_fade_width = rems(1.5);
label
.min_w_0()
.relative()
.overflow_hidden()
.child(
div()
.w_full()
.whitespace_nowrap()
.text_overflow(TextOverflow::Truncate(SharedString::default()))
.child(self.label.clone()),
)
.child(
div()
.absolute()
.top_0()
.right_0()
.bottom_0()
.w(fade_width)
.bg(linear_gradient(
90.,
linear_color_stop(fade.opacity(0.), 0.),
linear_color_stop(fade, 1.),
)),
)
.child(
div()
.absolute()
.top_0()
.right_0()
.bottom_0()
.w(hover_fade_width)
.bg(linear_gradient(
90.,
linear_color_stop(hover_fade.opacity(0.), 0.),
linear_color_stop(hover_fade, 1.),
))
.invisible()
.group_hover(group.clone(), |style| style.visible()),
)
})
.when(!titlebar, |label| label.child(self.label.clone()));
let strip_tab = div()
.id((self.key.clone(), "tab"))
.debug_selector({
let tabs_id = ctx.id.clone();
let label = self.label.clone();
move || format!("{tabs_id}-tab-{}", label)
})
.flex()
.items_center()
.gap_2()
.role(Role::Tab)
.aria_selected(selected)
.text_color(label_color)
.when(titlebar, |strip_tab| strip_tab.group(group.clone()))
.when(!self.disabled && !active, |strip_tab| {
strip_tab.hover(|strip_tab| {
strip_tab.bg(match ctx.variant {
TabsVariant::Titlebar => theme.colors.muted_hover,
_ => theme.colors.muted,
})
})
})
.map(|strip_tab| {
apply_tab_chrome(strip_tab, ctx.variant, active, cx).when(titlebar, |strip_tab| {
strip_tab.min_w(TAB_MIN_WIDTH).max_w(TAB_MAX_WIDTH)
})
})
.when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead))
.child(label)
.when(ctx.variant == TabsVariant::Pill, |strip_tab| {
strip_tab.child(div().flex_none().w_4())
})
.when(self.busy && !self.disabled, |strip_tab| {
strip_tab.child(
Spinner::new((self.key.clone(), "tab-busy"))
.small()
.accessibility_label("Loading"),
)
})
.when_some(close, |strip_tab, close| {
if titlebar {
strip_tab.child(
div()
.flex_none()
.invisible()
.group_hover(group, |style| style.visible())
.child(close),
)
} else {
strip_tab.child(close)
}
})
.when(
{
let drop = ctx.drop_at.read(cx);
drop.onto == Some(index) && !drop.canceled()
},
|strip_tab| {
strip_tab.child(
div()
.absolute()
.left_0()
.top_0p5()
.bottom_0p5()
.w_0p5()
.rounded(theme.radius.sm)
.bg(theme.ramps.primary.base),
)
},
)
.when_some(ctx.measure.clone(), |strip_tab, measure| {
let key = measure.key.clone();
let root_bounds = measure.root_bounds.clone();
let tab_key = self.key.to_string();
strip_tab.child(
canvas(
move |bounds, _, cx| {
let root = root_bounds.borrow();
if let Some(root) = root.as_ref() {
cx.default_global::<TabsMeasurements>().record_tab(
&key,
tab_key,
TabMeasure {
left: bounds.origin.x - root.origin.x,
width: bounds.size.width,
},
);
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
})
.when(!self.disabled, |strip_tab| {
strip_tab.cursor_pointer().on_click({
let selected = ctx.selected;
let on_change = ctx.on_change.clone();
let focus = ctx.focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if index != selected
&& let Some(on_change) = &on_change
{
on_change(index, window, cx);
}
}
})
})
.when(ctx.draggable && !self.disabled, |strip_tab| {
strip_tab
.on_mouse_down(MouseButton::Left, {
let drop_at = ctx.drop_at.clone();
move |event, _, cx| {
cx.stop_propagation();
drop_at.update(cx, |drop, cx| {
let fresh = TabDrop {
origin: Some(event.position),
..TabDrop::default()
};
if *drop != fresh {
*drop = fresh;
cx.notify();
}
});
}
})
.on_drag(TabDrag { index }, {
let label = self.label.clone();
move |_, _, _, cx| {
cx.new(|_| TabDragPreview {
label: label.clone(),
})
}
})
.drag_over::<TabDrag>({
let drop_at = ctx.drop_at.clone();
move |style, drag, _, cx| {
let drop = *drop_at.read(cx);
let hovered = drag.index != index && !drop.canceled();
drop_at.update(cx, |drop, cx| match (hovered, drop.onto) {
(true, current) if current != Some(index) => {
drop.onto = Some(index);
cx.notify();
}
(false, Some(_)) => {
drop.onto = None;
cx.notify();
}
_ => {}
});
style
}
})
.on_drop::<TabDrag>({
let on_reorder = ctx.on_reorder.clone();
let drop_at = ctx.drop_at.clone();
move |drag, window, cx| {
let canceled = drop_at.read(cx).canceled();
drop_at.update(cx, |drop, cx| {
if drop.onto.is_some() {
drop.onto = None;
cx.notify();
}
});
let target = (!canceled)
.then(|| reorder_target(drag.index, index))
.flatten();
if let (Some(to), Some(on_reorder)) = (target, on_reorder.as_ref()) {
on_reorder(drag.index, to, window, cx);
}
}
})
});
match self.wrap {
Some(wrap) => wrap(strip_tab),
None => strip_tab.into_any_element(),
}
}
fn render_tab_close(
&self,
tabs_id: &ElementId,
index: usize,
on_close: &Option<CloseHandler>,
) -> AnyElement {
Button::new((self.key.clone(), "tab-close"))
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.xsmall()
.fully_rounded(true)
.tab_stop(false)
.debug_selector({
let tabs_id = tabs_id.clone();
let label = self.label.clone();
move || format!("{tabs_id}-close-{}", label)
})
.tooltip(Tooltip::text("Close"))
.accessibility_label(SharedString::from(format!("Close {}", self.label)))
.on_click({
let on_close = on_close.clone();
move |_, window, cx| {
cx.stop_propagation();
if let Some(on_close) = &on_close {
on_close(index, window, cx);
}
}
})
.into_any_element()
}
}
// Tab is a data builder, not an element, adopt the combinators explicitly.
@@ -1060,290 +1346,3 @@ impl RenderOnce for Tabs {
}
}
impl Tab {
fn render_tab(mut self, ctx: &StripCtx, cx: &App, index: usize) -> AnyElement {
let selected = index == ctx.selected;
// A pinned tab always wears the active treatment, selected or not.
let active = selected || self.pinned;
let theme = cx.theme();
let label_color = tab_label_color(ctx.variant, active, self.disabled, cx);
let titlebar = ctx.variant == TabsVariant::Titlebar;
let group = SharedString::from(format!("{}-tab-{}", ctx.id, self.key));
let close = (self.closeable && ctx.on_close.is_some() && !self.disabled)
.then(|| self.render_tab_close(&ctx.id, index, &ctx.on_close));
let label = div()
.flex_grow(1.0)
.when(titlebar, |label| {
let fade = if active {
theme.colors.background
} else {
theme.colors.muted
};
let hover_fade = if active {
theme.colors.background
} else {
theme.colors.muted_hover
};
let fade_width = rems(0.75);
let hover_fade_width = rems(1.5);
label
.min_w_0()
.relative()
.overflow_hidden()
.child(
div()
.w_full()
.whitespace_nowrap()
.text_overflow(TextOverflow::Truncate(SharedString::default()))
.child(self.label.clone()),
)
.child(
div()
.absolute()
.top_0()
.right_0()
.bottom_0()
.w(fade_width)
.bg(linear_gradient(
90.,
linear_color_stop(fade.opacity(0.), 0.),
linear_color_stop(fade, 1.),
)),
)
.child(
div()
.absolute()
.top_0()
.right_0()
.bottom_0()
.w(hover_fade_width)
.bg(linear_gradient(
90.,
linear_color_stop(hover_fade.opacity(0.), 0.),
linear_color_stop(hover_fade, 1.),
))
.invisible()
.group_hover(group.clone(), |style| style.visible()),
)
})
.when(!titlebar, |label| label.child(self.label.clone()));
let strip_tab = div()
.id((self.key.clone(), "tab"))
.debug_selector({
let tabs_id = ctx.id.clone();
let label = self.label.clone();
move || format!("{tabs_id}-tab-{}", label)
})
.flex()
.items_center()
.gap_2()
.role(Role::Tab)
.aria_selected(selected)
.text_color(label_color)
.when(titlebar, |strip_tab| strip_tab.group(group.clone()))
.when(!self.disabled && !active, |strip_tab| {
strip_tab.hover(|strip_tab| {
strip_tab.bg(match ctx.variant {
TabsVariant::Titlebar => theme.colors.muted_hover,
_ => theme.colors.muted,
})
})
})
.map(|strip_tab| {
apply_tab_chrome(strip_tab, ctx.variant, active, cx).when(titlebar, |strip_tab| {
strip_tab.min_w(TAB_MIN_WIDTH).max_w(TAB_MAX_WIDTH)
})
})
.when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead))
.child(label)
.when(ctx.variant == TabsVariant::Pill, |strip_tab| {
strip_tab.child(div().flex_none().w_4())
})
.when(self.busy && !self.disabled, |strip_tab| {
strip_tab.child(
Spinner::new((self.key.clone(), "tab-busy"))
.small()
.accessibility_label("Loading"),
)
})
.when_some(close, |strip_tab, close| {
if titlebar {
strip_tab.child(
div()
.flex_none()
.invisible()
.group_hover(group, |style| style.visible())
.child(close),
)
} else {
strip_tab.child(close)
}
})
.when(
{
let drop = ctx.drop_at.read(cx);
drop.onto == Some(index) && !drop.canceled()
},
|strip_tab| {
strip_tab.child(
div()
.absolute()
.left_0()
.top_0p5()
.bottom_0p5()
.w_0p5()
.rounded(theme.radius.sm)
.bg(theme.ramps.primary.base),
)
},
)
.when_some(ctx.measure.clone(), |strip_tab, measure| {
let key = measure.key.clone();
let root_bounds = measure.root_bounds.clone();
let tab_key = self.key.to_string();
strip_tab.child(
canvas(
move |bounds, _, cx| {
let root = root_bounds.borrow();
if let Some(root) = root.as_ref() {
cx.default_global::<TabsMeasurements>().record_tab(
&key,
tab_key,
TabMeasure {
left: bounds.origin.x - root.origin.x,
width: bounds.size.width,
},
);
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
})
.when(!self.disabled, |strip_tab| {
strip_tab.cursor_pointer().on_click({
let selected = ctx.selected;
let on_change = ctx.on_change.clone();
let focus = ctx.focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if index != selected
&& let Some(on_change) = &on_change
{
on_change(index, window, cx);
}
}
})
})
.when(ctx.draggable && !self.disabled, |strip_tab| {
strip_tab
.on_mouse_down(MouseButton::Left, {
let drop_at = ctx.drop_at.clone();
move |event, _, cx| {
cx.stop_propagation();
drop_at.update(cx, |drop, cx| {
let fresh = TabDrop {
origin: Some(event.position),
..TabDrop::default()
};
if *drop != fresh {
*drop = fresh;
cx.notify();
}
});
}
})
.on_drag(TabDrag { index }, {
let label = self.label.clone();
move |_, _, _, cx| {
cx.new(|_| TabDragPreview {
label: label.clone(),
})
}
})
.drag_over::<TabDrag>({
let drop_at = ctx.drop_at.clone();
move |style, drag, _, cx| {
let drop = *drop_at.read(cx);
let hovered = drag.index != index && !drop.canceled();
drop_at.update(cx, |drop, cx| match (hovered, drop.onto) {
(true, current) if current != Some(index) => {
drop.onto = Some(index);
cx.notify();
}
(false, Some(_)) => {
drop.onto = None;
cx.notify();
}
_ => {}
});
style
}
})
.on_drop::<TabDrag>({
let on_reorder = ctx.on_reorder.clone();
let drop_at = ctx.drop_at.clone();
move |drag, window, cx| {
let canceled = drop_at.read(cx).canceled();
drop_at.update(cx, |drop, cx| {
if drop.onto.is_some() {
drop.onto = None;
cx.notify();
}
});
let target = (!canceled)
.then(|| reorder_target(drag.index, index))
.flatten();
if let (Some(to), Some(on_reorder)) = (target, on_reorder.as_ref()) {
on_reorder(drag.index, to, window, cx);
}
}
})
});
match self.wrap {
Some(wrap) => wrap(strip_tab),
None => strip_tab.into_any_element(),
}
}
fn render_tab_close(
&self,
tabs_id: &ElementId,
index: usize,
on_close: &Option<CloseHandler>,
) -> AnyElement {
Button::new((self.key.clone(), "tab-close"))
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.xsmall()
.fully_rounded(true)
.tab_stop(false)
.debug_selector({
let tabs_id = tabs_id.clone();
let label = self.label.clone();
move || format!("{tabs_id}-close-{}", label)
})
.tooltip(Tooltip::text("Close"))
.accessibility_label(SharedString::from(format!("Close {}", self.label)))
.on_click({
let on_close = on_close.clone();
move |_, window, cx| {
cx.stop_propagation();
if let Some(on_close) = &on_close {
on_close(index, window, cx);
}
}
})
.into_any_element()
}
}
+64 -164
View File
@@ -2,17 +2,7 @@
//!
//! A [`Toasts`] entity holds the raised toast, and a [`ToastsView`] renders
//! it; mount the view at the window root.
//!
//! # Examples
//!
//! ```no_run
//! use ui::toast::{Toast, ToastAction};
//!
//! let toast = Toast::new("Copied to clipboard")
//! .action(ToastAction::new("Undo", |_cx| println!("undo")));
//! ```
use std::rc::Rc;
use std::time::Duration;
use gpui::prelude::FluentBuilder;
@@ -25,45 +15,18 @@ use gpui::{
use crate::components::button::{Button, ButtonVariant};
use crate::components::common::{
DismissHandler, ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, floating_panel,
v_flex,
ResultLogErr as _, Sizable as _, StyledExt as _, TOAST_LAYER, floating_panel, v_flex,
};
use crate::icons::{Icon, IconRole};
use crate::theme::{ActiveTheme as _, TOAST_MAX_WIDTH};
/// The action handler of a [`Toast`].
pub type ActionHandler = Rc<dyn Fn(&mut App)>;
/// One user action offered by a toast.
#[derive(Clone)]
pub struct ToastAction {
label: SharedString,
handler: ActionHandler,
}
impl ToastAction {
/// Creates an action with this label.
pub fn new<L, F>(label: L, handler: F) -> Self
where
L: Into<SharedString>,
F: Fn(&mut App) + 'static,
{
Self {
label: label.into(),
handler: Rc::new(handler),
}
}
}
/// A toast notification.
#[derive(Clone)]
#[must_use]
pub struct Toast {
message: SharedString,
icon: Option<Icon>,
action: Option<ToastAction>,
duration: Option<Duration>,
on_dismiss: Option<DismissHandler>,
style: StyleRefinement,
}
@@ -79,9 +42,7 @@ impl Toast {
Self {
message: message.into(),
icon: None,
action: None,
duration: Some(Self::DURATION),
on_dismiss: None,
style: StyleRefinement::default(),
}
}
@@ -94,27 +55,6 @@ impl Toast {
self.icon = Some(icon.into());
self
}
/// Offers the user this action.
pub fn action(mut self, action: ToastAction) -> Self {
self.action = Some(action);
self
}
/// Sets the time before the toast dismisses itself.
pub fn duration(mut self, duration: Duration) -> Self {
self.duration = Some(duration);
self
}
/// Runs when the toast is dismissed by any means, once it is fully gone.
pub fn on_dismiss<F>(mut self, handler: F) -> Self
where
F: Fn(&mut App) + 'static,
{
self.on_dismiss = Some(Rc::new(handler));
self
}
}
// Toast is a data builder, not an element, adopt the combinators explicitly.
@@ -127,6 +67,68 @@ pub struct ToastEntry {
pub toast: Toast,
}
impl ToastEntry {
/// The rendered pill for this toast.
fn pill(&self, toasts: &Entity<Toasts>, cx: &App) -> gpui::Stateful<gpui::Div> {
let theme = cx.theme();
let foreground = theme.colors.foreground;
let radius = theme.radius.full;
let toast = &self.toast;
let toasts = toasts.clone();
let id = self.id;
floating_panel(
cx,
radius,
div()
.id(("toast", id))
.debug_selector(|| "toast-pill".to_string())
.role(Role::Alert)
.aria_label(toast.message.clone())
.max_w(TOAST_MAX_WIDTH)
.flex()
.items_center()
.gap_2()
.py_1p5()
.px_3(),
theme.elevations.popover.shadows(),
)
.refine_style(&toast.style)
.when_some(toast.icon.clone(), |pill, icon| {
pill.child(
div()
.flex_none()
.flex()
.items_center()
.child(icon.size(rems(1.0)).color(foreground)),
)
})
.child(
div()
.flex_1()
.min_w(px(0.))
.truncate()
.text_sm()
.text_color(foreground)
.child(toast.message.clone()),
)
.child(
div().flex_none().child(
Button::new(("toast-close", id))
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.small()
.accessibility_label("Dismiss")
.on_click(move |_, _window, cx| {
toasts.update(cx, |toasts, cx| {
toasts.dismiss(id, cx);
});
}),
),
)
}
}
/// The store of raised toasts.
#[derive(Default)]
pub struct Toasts {
@@ -177,33 +179,13 @@ impl Toasts {
}
}
/// Dismisses the toast on screen.
pub fn clear(&mut self, cx: &mut Context<Self>) {
if let Some(entry) = self.current.take() {
self.start_exit(entry, cx);
} else {
self.finish_exit(cx);
}
}
/// The toast now showing, if any.
pub fn current(&self) -> Option<&ToastEntry> {
self.current.as_ref()
}
/// How many toasts are on screen, including one fading out.
pub fn count(&self) -> usize {
usize::from(self.current.is_some()) + usize::from(self.exiting.is_some())
}
/// Moves a toast into the fade-out phase.
fn start_exit(&mut self, entry: ToastEntry, cx: &mut Context<Self>) {
if let Some(previous) = self.exiting.take()
&& let Some(on_dismiss) = &previous.toast.on_dismiss
{
on_dismiss(cx);
}
self.exiting = Some(entry);
cx.notify();
@@ -217,11 +199,8 @@ impl Toasts {
}
fn finish_exit(&mut self, cx: &mut Context<Self>) {
if let Some(entry) = self.exiting.take() {
if self.exiting.take().is_some() {
cx.notify();
if let Some(on_dismiss) = &entry.toast.on_dismiss {
on_dismiss(cx);
}
}
}
}
@@ -282,82 +261,3 @@ impl RenderOnce for ToastsView {
.with_priority(TOAST_LAYER)
}
}
impl ToastEntry {
/// The rendered pill for this toast.
fn pill(&self, toasts: &Entity<Toasts>, cx: &App) -> gpui::Stateful<gpui::Div> {
let theme = cx.theme();
let foreground = theme.colors.foreground;
let radius = theme.radius.full;
let toast = &self.toast;
let toasts = toasts.clone();
let id = self.id;
floating_panel(
cx,
radius,
div()
.id(("toast", id))
.debug_selector(|| "toast-pill".to_string())
.role(Role::Alert)
.aria_label(toast.message.clone())
.max_w(TOAST_MAX_WIDTH)
.flex()
.items_center()
.gap_2()
.py_1p5()
.px_3(),
theme.elevations.popover.shadows(),
)
.refine_style(&toast.style)
.when_some(toast.icon.clone(), |pill, icon| {
pill.child(
div()
.flex_none()
.flex()
.items_center()
.child(icon.size(rems(1.0)).color(foreground)),
)
})
.child(
div()
.flex_1()
.min_w(px(0.))
.truncate()
.text_sm()
.text_color(foreground)
.child(toast.message.clone()),
)
.when_some(toast.action.clone(), |pill, action| {
let toasts = toasts.clone();
pill.child(
div().flex_none().child(
Button::new(("toast-action", id))
.label(action.label.clone())
.variant(ButtonVariant::Primary)
.small()
.on_click(move |_, _window, cx| {
(action.handler)(cx);
toasts.update(cx, |toasts, cx| {
toasts.dismiss(id, cx);
});
}),
),
)
})
.child(
div().flex_none().child(
Button::new(("toast-close", id))
.icon(IconRole::Close)
.variant(ButtonVariant::Ghost)
.small()
.accessibility_label("Dismiss")
.on_click(move |_, _window, cx| {
toasts.update(cx, |toasts, cx| {
toasts.dismiss(id, cx);
});
}),
),
)
}
}
+300 -113
View File
@@ -15,6 +15,8 @@
//! .on_change(|_selected, _window, _cx| println!("selection changed"));
//! ```
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::rc::Rc;
use gpui::prelude::FluentBuilder;
@@ -71,6 +73,16 @@ impl TreeItem {
}
}
/// The row's key: the path-like id its builder passed.
pub fn key(&self) -> &ElementId {
&self.key
}
/// Whether the row has children and paints a chevron.
pub fn is_expandable(&self) -> bool {
self.expandable
}
/// Shows a custom icon leading the label.
pub fn icon<I>(mut self, icon: I) -> Self
where
@@ -103,11 +115,299 @@ impl TreeItem {
self.disabled = disabled;
self
}
#[allow(clippy::too_many_arguments)]
fn render_row(
&self,
cx: &App,
index: usize,
position_in_set: usize,
size_of_set: usize,
selected: bool,
on_change: &Option<ChangeHandler>,
on_disclosure: &Option<DisclosureHandler>,
focus: &FocusHandle,
) -> AnyElement {
let theme = cx.theme();
let label_color = selectable_label_color(cx, selected, self.disabled);
let disabled = self.disabled;
let depth = self.depth.min(TREE_MAX_DEPTH) as f32;
let indent = rems(0.75 * if self.depth == 0 { 0.5 } else { depth + 1.0 });
div()
.id((self.key.clone(), "tree-item"))
.relative()
.flex()
.items_center()
.gap_2()
.pl(indent)
.pr_2()
.py_1()
.min_h_8()
.rounded(theme.radius.sm)
.role(Role::TreeItem)
.aria_selected(selected)
.aria_level(self.depth + 1)
.aria_position_in_set(position_in_set)
.aria_size_of_set(size_of_set)
.when(self.expandable, |row| row.aria_expanded(self.expanded))
.map(|row| paint_selectable_row(cx, row, selected, disabled))
.when(!disabled, |row| {
row.cursor_pointer().on_click({
let on_change = on_change.clone();
let on_disclosure = on_disclosure.clone();
let expandable = self.expandable;
let focus = focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if let Some(on_change) = &on_change {
on_change(Some(index), window, cx);
}
// A folder row toggles with its own click, not just its chevron.
if expandable && let Some(on_disclosure) = &on_disclosure {
on_disclosure(index, window, cx);
}
}
})
})
.children((0..self.depth.min(TREE_MAX_DEPTH)).map(|level| {
let step = level as f32;
div()
.absolute()
.left(rems(0.75 * (step + 0.5)))
.top_0()
.bottom_0()
.border_l_1()
.border_color(theme.colors.border)
}))
.child(self.render_disclosure(cx, selected))
.when_some(
self.icon
.clone()
.or_else(|| (!self.expandable).then(|| icon(IconRole::File))),
|row, icon| row.child(icon.size(rems(1.0)).color(label_color)),
)
.child(
div()
.flex_1()
.text_color(label_color)
.child(self.label.clone()),
)
.into_any_element()
}
fn render_disclosure(&self, cx: &App, selected: bool) -> AnyElement {
let theme = cx.theme();
let glyph_color = if self.disabled || !selected {
theme.colors.muted_foreground
} else {
theme.colors.primary_foreground
};
// Only expandable rows draw a chevron; the empty cell keeps labels aligned with folders.
div()
.flex_none()
.size_4()
.flex()
.items_center()
.justify_center()
.when(self.expandable, |cell| {
cell.child(
icon(if self.expanded {
IconRole::ChevronDown
} else {
IconRole::ChevronRight
})
.size(rems(0.75))
.color(glyph_color),
)
})
.into_any_element()
}
}
// TreeItem is a data builder, not an element, adopt the combinators explicitly.
impl FluentBuilder for TreeItem {}
/// A nested path node; `flatten_all` turns a forest of these into rows.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TreeItemSeed {
/// Path of the node, relative to the worktree root.
pub id: String,
pub label: String,
pub children: Vec<TreeItemSeed>,
}
impl TreeItemSeed {
/// Flattens the seeds into the rows a flat tree renders, honoring `expanded`.
///
/// Expandable rows carry the folder icon; leaves fall back to the file icon
/// the tree paints by default.
pub fn flatten_all(seeds: &[TreeItemSeed], expanded: &HashSet<String>) -> Vec<TreeItem> {
fn push(
seed: &TreeItemSeed,
depth: usize,
expanded: &HashSet<String>,
rows: &mut Vec<TreeItem>,
) {
let is_expanded = expanded.contains(&seed.id);
let mut item = TreeItem::new(seed.id.clone(), seed.label.clone())
.depth(depth)
.expandable(!seed.children.is_empty())
.expanded(is_expanded);
if !seed.children.is_empty() {
item = item.icon(Icon::named(IconRole::Folder));
}
rows.push(item);
if is_expanded {
for child in &seed.children {
push(child, depth + 1, expanded, rows);
}
}
}
let mut rows = Vec::new();
for seed in seeds {
push(seed, 0, expanded, &mut rows);
}
rows
}
/// Every folder id, for starting with the tree fully expanded.
pub fn collect_expanded(seeds: &[TreeItemSeed]) -> HashSet<String> {
fn push(seed: &TreeItemSeed, expanded: &mut HashSet<String>) {
if !seed.children.is_empty() {
expanded.insert(seed.id.clone());
for child in &seed.children {
push(child, expanded);
}
}
}
let mut expanded = HashSet::new();
for seed in seeds {
push(seed, &mut expanded);
}
expanded
}
/// Builds nested tree items from a flat entry list sorted dirs-first.
pub fn from_paths(paths: &[PathBuf]) -> Vec<TreeItemSeed> {
// Node indices by full path, so parents resolve in constant time while inserting.
let mut index: HashMap<String, usize> = HashMap::new();
let mut nodes: Vec<(String, String, Vec<usize>)> = Vec::new();
let mut roots: Vec<usize> = Vec::new();
for entry in paths {
let mut parent: Option<usize> = None;
let mut path = String::new();
for part in entry.components() {
let label = part.as_os_str().to_string_lossy().into_owned();
path = if path.is_empty() {
label.clone()
} else {
format!("{path}/{label}")
};
let ix = *index.entry(path.clone()).or_insert_with(|| {
let ix = nodes.len();
nodes.push((path.clone(), label.clone(), Vec::new()));
match parent {
Some(parent) => nodes[parent].2.push(ix),
None => roots.push(ix),
}
ix
});
parent = Some(ix);
}
}
fn assemble(ix: usize, nodes: &[(String, String, Vec<usize>)]) -> TreeItemSeed {
let (id, label, children) = &nodes[ix];
TreeItemSeed {
id: id.clone(),
label: label.clone(),
children: children
.iter()
.map(|child| assemble(*child, nodes))
.collect(),
}
}
roots.iter().map(|root| assemble(*root, &nodes)).collect()
}
}
#[cfg(test)]
mod seed_tests {
use super::*;
fn ids(rows: &[TreeItem]) -> Vec<(String, usize)> {
rows.iter()
.map(|row| (row.key().to_string(), row.depth))
.collect()
}
#[test]
fn collapsed_folders_hide_children() {
let seeds = TreeItemSeed::from_paths(&[
PathBuf::from("src"),
PathBuf::from("src/lib.rs"),
PathBuf::from("README.md"),
]);
let rows = TreeItemSeed::flatten_all(&seeds, &HashSet::new());
assert_eq!(
ids(&rows),
vec![("src".to_owned(), 0), ("README.md".to_owned(), 0)]
);
assert!(rows[0].expandable);
assert!(!rows[0].expanded);
}
#[test]
fn expanding_a_folder_shows_children_in_order() {
let seeds = TreeItemSeed::from_paths(&[
PathBuf::from("src"),
PathBuf::from("src/lib.rs"),
PathBuf::from("src/views/mod.rs"),
PathBuf::from("README.md"),
]);
let expanded = HashSet::from(["src".to_owned(), "src/views".to_owned()]);
let rows = TreeItemSeed::flatten_all(&seeds, &expanded);
assert_eq!(
ids(&rows),
vec![
("src".to_owned(), 0),
("src/lib.rs".to_owned(), 1),
("src/views".to_owned(), 1),
("src/views/mod.rs".to_owned(), 2),
("README.md".to_owned(), 0),
]
);
}
#[test]
fn indices_map_to_row_ids() {
let seeds = TreeItemSeed::from_paths(&[
PathBuf::from("docs"),
PathBuf::from("docs/guide.md"),
PathBuf::from("README.md"),
]);
let expanded = HashSet::from(["docs".to_owned()]);
let rows = TreeItemSeed::flatten_all(&seeds, &expanded);
assert_eq!(rows[0].key().to_string(), "docs");
assert_eq!(rows[1].key().to_string(), "docs/guide.md");
assert_eq!(rows[2].key().to_string(), "README.md");
}
}
/// A tree of [`TreeItem`] rows with single selection and disclosure handling.
#[derive(IntoElement)]
#[must_use]
@@ -345,116 +645,3 @@ impl RenderOnce for Tree {
.children(rows)
}
}
impl TreeItem {
#[allow(clippy::too_many_arguments)]
fn render_row(
&self,
cx: &App,
index: usize,
position_in_set: usize,
size_of_set: usize,
selected: bool,
on_change: &Option<ChangeHandler>,
on_disclosure: &Option<DisclosureHandler>,
focus: &FocusHandle,
) -> AnyElement {
let theme = cx.theme();
let label_color = selectable_label_color(cx, selected, self.disabled);
let disabled = self.disabled;
let depth = self.depth.min(TREE_MAX_DEPTH) as f32;
let indent = rems(0.75 * if self.depth == 0 { 0.5 } else { depth + 1.0 });
div()
.id((self.key.clone(), "tree-item"))
.relative()
.flex()
.items_center()
.gap_2()
.pl(indent)
.pr_2()
.py_1()
.min_h_8()
.rounded(theme.radius.sm)
.role(Role::TreeItem)
.aria_selected(selected)
.aria_level(self.depth + 1)
.aria_position_in_set(position_in_set)
.aria_size_of_set(size_of_set)
.when(self.expandable, |row| row.aria_expanded(self.expanded))
.map(|row| paint_selectable_row(cx, row, selected, disabled))
.when(!disabled, |row| {
row.cursor_pointer().on_click({
let on_change = on_change.clone();
let on_disclosure = on_disclosure.clone();
let expandable = self.expandable;
let focus = focus.clone();
move |_, window, cx| {
window.focus(&focus, cx);
if let Some(on_change) = &on_change {
on_change(Some(index), window, cx);
}
// A folder row toggles with its own click, not just its chevron.
if expandable && let Some(on_disclosure) = &on_disclosure {
on_disclosure(index, window, cx);
}
}
})
})
.children((0..self.depth.min(TREE_MAX_DEPTH)).map(|level| {
let step = level as f32;
div()
.absolute()
.left(rems(0.75 * (step + 0.5)))
.top_0()
.bottom_0()
.border_l_1()
.border_color(theme.colors.border)
}))
.child(self.render_disclosure(cx, selected))
.when_some(
self.icon
.clone()
.or_else(|| (!self.expandable).then(|| icon(IconRole::File))),
|row, icon| row.child(icon.size(rems(1.0)).color(label_color)),
)
.child(
div()
.flex_1()
.text_color(label_color)
.child(self.label.clone()),
)
.into_any_element()
}
fn render_disclosure(&self, cx: &App, selected: bool) -> AnyElement {
let theme = cx.theme();
let glyph_color = if self.disabled || !selected {
theme.colors.muted_foreground
} else {
theme.colors.primary_foreground
};
// Only expandable rows draw a chevron; the empty cell keeps labels aligned with folders.
div()
.flex_none()
.size_4()
.flex()
.items_center()
.justify_center()
.when(self.expandable, |cell| {
cell.child(
icon(if self.expanded {
IconRole::ChevronDown
} else {
IconRole::ChevronRight
})
.size(rems(0.75))
.color(glyph_color),
)
})
.into_any_element()
}
}
+2 -29
View File
@@ -1,5 +1,5 @@
//! Shared helpers for the editor's views: gutter cells, role colors and run
//! styles, code line text, language mapping and change washes.
//! styles, code line text and language mapping.
use std::ops::Range;
@@ -8,10 +8,7 @@ use gpui::{
};
use crate::components::highlight::{Language, Line, Role};
use crate::theme::{
ActiveTheme as _, CODE_GUTTER_WIDTH, ColorTokens, Ramps, WASH_ALPHA, WASH_ALPHA_GUTTER,
WASH_ALPHA_STRONG,
};
use crate::theme::{ActiveTheme as _, CODE_GUTTER_WIDTH, ColorTokens, Ramps};
impl Role {
/// Maps the role to the theme's semantic palette.
@@ -78,30 +75,6 @@ where
.child(content)
}
/// A change wash: the ramp color at the alpha rows tint with.
pub(crate) fn wash(color: Hsla) -> Hsla {
Hsla {
a: color.a * WASH_ALPHA,
..color
}
}
/// The stronger wash under number gutters and intra-line word changes.
pub(crate) fn wash_strong(color: Hsla) -> Hsla {
Hsla {
a: color.a * WASH_ALPHA_STRONG,
..color
}
}
/// The subtle wash that sets the number gutter off from the code.
pub(crate) fn wash_gutter(colors: &ColorTokens) -> Hsla {
Hsla {
a: colors.muted.a * WASH_ALPHA_GUTTER,
..colors.muted
}
}
/// One highlighted code line as styled text, roles resolved from the theme.
pub(crate) fn code_line(line: &Line, colors: ColorTokens, ramps: Ramps) -> StyledText {
let mut highlights: Vec<(Range<usize>, HighlightStyle)> = Vec::new();