restructure

This commit is contained in:
2026-09-01 10:55:44 +07:00
parent 05ab543fa0
commit 3cdc623583
32 changed files with 886 additions and 834 deletions
+67
View File
@@ -0,0 +1,67 @@
use gpui::prelude::*;
use gpui::{App, ClipboardItem, Div, ElementId, SharedString, div};
use gpui_component::clipboard::Clipboard;
use gpui_component::menu::PopupMenuItem;
use gpui_component::{ActiveTheme, StyledExt, h_flex};
/// A muted command row with a copy button: the value in a mono-friendly,
/// truncated line, with a [`Clipboard`] button copying the full value.
pub fn copy_row<E>(copy_id: E, command: &SharedString, cx: &App) -> Div
where
E: Into<ElementId>,
{
h_flex()
.h_8()
.w_full()
.px_2()
.gap_2()
.items_center()
.bg(cx.theme().muted)
.rounded(cx.theme().radius)
.child(
h_flex()
.flex_1()
.min_w_0()
.truncate()
.text_ellipsis()
.text_xs()
.child(command.clone()),
)
.child(
Clipboard::new(copy_id)
.tooltip("Copy")
.value(command.clone()),
)
}
/// One row of a copy menu: a small title above the compact label, with
/// a copy button that flips to a check while the value is on the clipboard.
/// Clicking the row copies and dismisses the menu; the copy button stops
/// propagation so the menu stays open. Both copy `copy`, never the label.
pub fn menu_copy_row(
id: &'static str,
title: &'static str,
label: String,
copy: String,
) -> PopupMenuItem {
let row_copy = copy.clone();
PopupMenuItem::element(move |_window, _cx| {
let button_copy = copy.clone();
h_flex()
.flex_1()
.gap_2()
.items_end()
.child(
h_flex()
.flex_1()
.gap_1()
.text_xs()
.child(div().flex_shrink_0().w_20().font_semibold().child(title))
.child(div().flex_1().text_ellipsis().child(label.clone())),
)
.child(Clipboard::new(id).tooltip("Copy").value(button_copy))
})
.on_click(move |_, _, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(row_copy.clone()));
})
}
+185
View File
@@ -0,0 +1,185 @@
use gpui::prelude::*;
use gpui::{
Anchor, AnyElement, App, DismissEvent, ElementId, Entity, Focusable, SharedString,
StyleRefinement, Window, px,
};
use gpui_base::{Button as BaseButton, Popover, Selectable, StyledExt};
use gpui_component::menu::PopupMenu;
use gpui_component::{ActiveTheme, Icon, IconName, Sizable, h_flex};
/// A split dropdown button built on `gpui_base::Popover`: an action element
/// with a separate caret trigger that opens a [`PopupMenu`].
///
/// The action and the caret are caller-supplied elements, so the look stays
/// in the application; this component only owns the popover wiring.
#[derive(IntoElement)]
pub struct DropdownButton {
id: ElementId,
style: StyleRefinement,
anchor: Anchor,
action: Option<AnyElement>,
caret: Option<CaretBuilder>,
menu: Option<MenuBuilder>,
}
type MenuBuilder =
Box<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static>;
type CaretBuilder = Box<dyn FnOnce(bool, &Window, &App) -> AnyElement>;
impl DropdownButton {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
style: StyleRefinement::default(),
anchor: Anchor::TopRight,
action: None,
caret: None,
menu: None,
}
}
/// The action half of the button. It keeps its own icon, label, tooltip
/// and click handler.
pub fn action(mut self, action: impl IntoElement + 'static) -> Self {
self.action = Some(action.into_any_element());
self
}
/// The menu built by `builder` — the same signature as gpui-component's
/// `DropdownButton::dropdown_menu`, so existing menu code keeps working.
pub fn dropdown_menu(
mut self,
builder: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
) -> Self {
self.menu = Some(Box::new(builder));
self
}
/// Which corner of the caret the menu anchors to. Defaults to
/// [`Anchor::TopRight`], so the menu's right edge lines up with the
/// caret's.
#[allow(dead_code)] // API knob; current call sites use the default anchor.
pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
self.anchor = anchor.into();
self
}
}
impl Styled for DropdownButton {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
/// Holds the [`PopupMenu`] entity of one popover between renders. Dismissal
/// drops it, so the menu is rebuilt with fresh items on the next open.
#[derive(Default)]
struct DropdownMenuState {
menu: Option<Entity<PopupMenu>>,
}
impl RenderOnce for DropdownButton {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
debug_assert!(
self.menu.is_some(),
"a DropdownButton needs a `dropdown_menu`"
);
// The popover needs its own id: both the container and the popover register keyed state on this window.
let popover_id = SharedString::from(format!("{}-popover", self.id));
let anchor = self.anchor;
let menu_state =
window.use_keyed_state(popover_id.clone(), cx, |_, _| DropdownMenuState::default());
let caret = self.caret.unwrap_or_else(|| {
let id = popover_id.clone();
Box::new(move |is_open, _, cx| {
let caret = default_caret(id.clone(), cx);
let selected = caret.is_selected();
caret.selected(selected || is_open).into_any_element()
})
});
h_flex()
.id(self.id)
.refine_style(&self.style)
.gap_0p5()
.when_some(self.action, |this, action| this.child(action))
.when_some(self.menu, |this, builder| {
this.child(
Popover::new(popover_id)
.anchor(anchor)
// The menu dismisses itself on outside click or Escape;
// the subscription below closes the popover along with it.
.overlay_closable(false)
.trigger_with(caret)
.content(
move |_, window, cx| match menu_state.read(cx).menu.clone() {
Some(menu) => menu,
None => {
let menu = PopupMenu::build(window, cx, |menu, window, cx| {
builder(menu, window, cx)
});
menu_state
.update(cx, |state, _| state.menu = Some(menu.clone()));
menu.focus_handle(cx).focus(window, cx);
let popover_state = cx.entity();
window
.subscribe(&menu, cx, {
let menu_state = menu_state.clone();
move |_, _: &DismissEvent, window, cx| {
popover_state.update(cx, |state, cx| {
state.dismiss(window, cx);
});
menu_state.update(cx, |state, _| {
state.menu = None;
});
}
})
.detach();
menu.clone()
}
},
),
)
})
}
}
/// The default caret: a chevron button the height of a medium button, tinted
/// by the theme, with hover and menu-open states.
fn default_caret(id: impl Into<ElementId>, cx: &App) -> BaseButton {
BaseButton::new(id)
.h(px(32.))
.px_1p5()
.text_color(cx.theme().muted_foreground)
.hover(|style| style.bg(cx.theme().secondary_hover))
.styles(|this| {
this.selected(|style| style.bg(cx.theme().secondary_active))
.disabled(|style| style.opacity(0.5))
})
.child(Icon::new(IconName::ChevronDown).xsmall())
}
#[cfg(test)]
mod tests {
use gpui::div;
use super::*;
#[test]
fn dropdown_button_builder_state() {
let button = DropdownButton::new("issues")
.action(div())
.anchor(Anchor::BottomLeft)
.dropdown_menu(|menu, _, _| menu);
assert!(button.action.is_some());
// The caret is `None` until render, which falls back to the default.
assert!(button.caret.is_none());
assert!(button.menu.is_some());
assert_eq!(button.anchor, Anchor::BottomLeft);
}
}
+139
View File
@@ -0,0 +1,139 @@
use std::collections::{HashMap, VecDeque};
use std::mem::take;
use futures::FutureExt;
use gpui::{
App, AppContext, Asset, AssetLogger, ElementId, Entity, ImageAssetLoader, ImageCache,
ImageCacheItem, ImageCacheProvider, ImageSource, Resource, hash,
};
/// Default number of images each view's cache retains. Loading a new image
/// evicts the least recently used entry once this is reached.
pub const MAX_IMAGES: usize = 128;
pub fn image_cache(id: impl Into<ElementId>, max_items: usize) -> AppImageCacheProvider {
AppImageCacheProvider {
id: id.into(),
max_items,
}
}
pub struct AppImageCacheProvider {
id: ElementId,
max_items: usize,
}
impl ImageCacheProvider for AppImageCacheProvider {
fn provide(&mut self, window: &mut gpui::Window, cx: &mut App) -> gpui::AnyImageCache {
window
.with_global_id(self.id.clone(), |id, window| {
window.with_element_state(id, |cache, _| {
let cache = cache.unwrap_or_else(|| AppImageCache::new(self.max_items, cx));
(cache.clone(), cache)
})
})
.into()
}
}
pub struct AppImageCache {
max_items: usize,
usage_list: VecDeque<u64>,
cache: HashMap<u64, (ImageCacheItem, Resource)>,
}
impl AppImageCache {
pub fn new(max_items: usize, cx: &mut App) -> Entity<Self> {
cx.new(|cx| {
log::info!("Creating AppImageCacheProvider");
cx.on_release(|this: &mut Self, cx| {
for (ix, (mut image, resource)) in take(&mut this.cache) {
if let Some(Ok(image)) = image.get() {
log::info!("Dropping image {ix}");
cx.drop_image(image, None);
}
ImageSource::Resource(resource).remove_asset(cx);
}
})
.detach();
AppImageCache {
max_items,
usage_list: VecDeque::with_capacity(max_items),
cache: HashMap::with_capacity(max_items),
}
})
}
}
impl ImageCache for AppImageCache {
fn load(
&mut self,
resource: &Resource,
window: &mut gpui::Window,
cx: &mut gpui::App,
) -> Option<Result<std::sync::Arc<gpui::RenderImage>, gpui::ImageCacheError>> {
let hash = hash(resource);
if let Some(item) = self.cache.get_mut(&hash) {
let current_idx = self
.usage_list
.iter()
.position(|item| *item == hash)
.expect("cache has an item usage_list doesn't");
self.usage_list.remove(current_idx);
self.usage_list.push_front(hash);
return item.0.get();
}
let load_future = AssetLogger::<ImageAssetLoader>::load(resource.clone(), cx);
let task = cx.background_executor().spawn(load_future).shared();
if self.usage_list.len() >= self.max_items {
log::info!("Image cache is full, evicting oldest item");
if let Some(oldest) = self.usage_list.pop_back() {
let mut image = self
.cache
.remove(&oldest)
.expect("usage_list has an item cache doesn't");
if let Some(Ok(image)) = image.0.get() {
log::info!("requesting image to be dropped");
cx.drop_image(image, Some(window));
}
ImageSource::Resource(image.1).remove_asset(cx);
}
}
self.cache.insert(
hash,
(
gpui::ImageCacheItem::Loading(task.clone()),
resource.clone(),
),
);
self.usage_list.push_front(hash);
let entity = window.current_view();
window
.spawn(cx, async move |cx| {
let result = task.await;
if let Err(err) = result {
log::error!("error loading image into cache: {:?}", err);
}
cx.on_next_frame(move |_, cx| {
cx.notify(entity);
});
})
.detach();
None
}
}
+49
View File
@@ -0,0 +1,49 @@
//! Reusable UI components and elements for Signed.
//!
//! Everything here is presentation-only: the components read theme tokens
//! through [`gpui_component::ActiveTheme`] and render with plain GPUI
//! elements, so any view in the app can use them without depending on app
//! state. They are built on the unstyled `gpui-base` primitives and the
//! styled `gpui-component` library.
//!
//! The crate is organized by component:
//!
//! - [`PixelAvatar`] — deterministic, offline "pixel art" avatar
//! - [`NavItem`] — sidebar navigation row (leading element + label + suffix)
//! - [`DropdownButton`] — split button: an action plus a caret that opens a
//! [`PopupMenu`], wired through `gpui_base::Popover`
//! - [`SegmentButton`] / [`CountBadge`] — segmented filter/tab button with an
//! optional count badge
//! - [`status_badge`] — NIP-34 issue/PR status badge
//! - [`placeholder`] — centered muted placeholder message
//! - [`copy_row`] / [`menu_copy_row`] — rows with a copy-to-clipboard button
//! - [`tree_row`] — one row of a file tree
//! - [`title_bar_drag_handlers`] — make an element behave like a window
//! title bar (drag moves the window, double-click zooms)
//! - [`image_cache`] — per-view LRU image cache provider
//! - [`middle_truncate`] — `[head]...[tail]` string truncation
mod dropdown_button;
mod nav_item;
mod pixel_avatar;
mod placeholder;
mod segment_button;
mod status_badge;
mod title_bar;
mod tree_row;
pub mod copy_row;
pub mod image_cache;
pub mod util;
pub use copy_row::{copy_row, menu_copy_row};
pub use dropdown_button::DropdownButton;
pub use image_cache::{MAX_IMAGES, image_cache};
pub use nav_item::NavItem;
pub use pixel_avatar::PixelAvatar;
pub use placeholder::placeholder;
pub use segment_button::{CountBadge, SegmentButton};
pub use status_badge::status_badge;
pub use title_bar::title_bar_drag_handlers;
pub use tree_row::tree_row;
pub use util::middle_truncate;
+78
View File
@@ -0,0 +1,78 @@
use gpui::prelude::*;
use gpui::{App, ClickEvent, ElementId, SharedString, StyleRefinement, Window, div};
use gpui_component::{ActiveTheme, StyledExt, h_flex};
/// A single navigation entry in a sidebar: an arbitrary leading element
/// (an icon, avatar, ...) and a text label with a hover highlight,
/// an optional trailing suffix (e.g. a status icon) and an optional click handler.
#[allow(clippy::type_complexity)]
#[derive(IntoElement)]
pub struct NavItem {
id: ElementId,
style: StyleRefinement,
icon: gpui::AnyElement,
label: SharedString,
/// Trailing element rendered at the right edge of the row, after the (ellipsized) label.
suffix: Option<gpui::AnyElement>,
on_click: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>,
}
impl NavItem {
pub fn new<I, L, N>(id: I, label: L, icon: N) -> Self
where
I: Into<ElementId>,
L: Into<SharedString>,
N: IntoElement,
{
Self {
id: id.into(),
icon: icon.into_any_element(),
label: label.into(),
style: StyleRefinement::default(),
suffix: None,
on_click: None,
}
}
/// A trailing element rendered at the right edge of the row
pub fn suffix(mut self, suffix: impl IntoElement) -> Self {
self.suffix = Some(suffix.into_any_element());
self
}
pub fn on_click(
mut self,
listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.on_click = Some(Box::new(listener));
self
}
}
impl RenderOnce for NavItem {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
h_flex()
.id(self.id)
.refine_style(&self.style)
.px_2()
.py_1()
.w_full()
.gap_2()
.rounded(cx.theme().radius)
.child(self.icon)
.child(
div()
.flex_1()
.min_w_0()
.text_sm()
.whitespace_nowrap()
.text_ellipsis()
.child(self.label),
)
.when_some(self.suffix, |this, suffix| {
this.child(div().flex_shrink_0().child(suffix))
})
.hover(|this| this.bg(cx.theme().list_hover))
.when_some(self.on_click, |this, listener| this.on_click(listener))
}
}
+214
View File
@@ -0,0 +1,214 @@
use gpui::prelude::*;
use gpui::{App, Pixels, StyleRefinement, Window, div, px};
use gpui_base::StyledExt;
use gpui_component::{ActiveTheme, Colorize};
/// Number of rows and columns in the pixel grid.
const GRID_SIZE: usize = 8;
/// Probability that a cell in the left half is filled.
const FILL_PROBABILITY: f32 = 0.42;
/// Probability that a filled cell uses the accent shade instead of the main color.
const ACCENT_PROBABILITY: f32 = 0.25;
/// Minimum number of filled left-half cells, so a sparse roll still yields a
/// recognizable shape (each left-half cell is mirrored to a right-half one).
const MIN_FILLED: usize = 5;
/// A deterministic, offline "pixel art" avatar: an 8×8 grid with horizontal
/// mirror symmetry, seeded from a stable string such as the repository id and
/// owner public key. The same seed always renders the same avatar.
#[derive(IntoElement)]
pub struct PixelAvatar {
seed: u64,
size: Pixels,
style: StyleRefinement,
}
impl PixelAvatar {
/// Create an avatar seeded from `seed`. The seed should be a stable string
/// unique to the entity the avatar represents.
pub fn new(seed: impl AsRef<str>) -> Self {
Self {
seed: fnv1a(seed.as_ref().as_bytes()),
size: px(16.),
style: StyleRefinement::default(),
}
}
}
impl Styled for PixelAvatar {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for PixelAvatar {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let pattern = pattern(self.seed);
let hue = self.seed as f32 / u64::MAX as f32;
let main = theme.blue.hue(hue);
let shade = if theme.is_dark() {
main.lightness((main.l * 1.6).min(0.95))
} else {
main.lightness((main.l * 0.45).max(0.18))
};
let mut cells = Vec::new();
for row in 0..GRID_SIZE {
for col in 0..GRID_SIZE {
let value = pattern[row * GRID_SIZE + col];
if value != 0 {
let color = if value == 2 { shade } else { main };
cells.push(
div()
.row_start(row as i16 + 1)
.row_end(row as i16 + 2)
.col_start(col as i16 + 1)
.col_end(col as i16 + 2)
.bg(color),
);
}
}
}
div()
.refine_style(&self.style)
.grid()
.grid_cols(GRID_SIZE as u16)
.grid_rows(GRID_SIZE as u16)
.size(self.size)
.flex_shrink_0()
.overflow_hidden()
.bg(main.opacity(0.16))
.children(cells)
}
}
/// Generate the 8×8 cell pattern for `seed`. Cells are `0` (empty), `1`
/// (main color) or `2` (accent shade); the right half mirrors the left half.
fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] {
let mut rng = PixelRng::new(seed);
let mut pattern = [0u8; GRID_SIZE * GRID_SIZE];
let mut filled = 0usize;
for row in 0..GRID_SIZE {
for col in 0..GRID_SIZE / 2 {
if rng.chance(FILL_PROBABILITY) {
let accent = rng.chance(ACCENT_PROBABILITY);
set_cell(&mut pattern, row, col, if accent { 2 } else { 1 });
filled += 1;
}
}
}
// Sparse rolls can come out nearly empty; top the pattern up to the
// minimum fill, scanning from a seeded starting cell.
if filled < MIN_FILLED {
let half = GRID_SIZE * GRID_SIZE / 2;
let start = (rng.next() % half as u64) as usize;
for offset in 0..half {
if filled >= MIN_FILLED {
break;
}
let ix = (start + offset) % half;
let row = ix / (GRID_SIZE / 2);
let col = ix % (GRID_SIZE / 2);
if pattern[row * GRID_SIZE + col] == 0 {
set_cell(&mut pattern, row, col, 1);
filled += 1;
}
}
}
pattern
}
/// Fill `cell (row, col)` and its horizontal mirror.
fn set_cell(pattern: &mut [u8; GRID_SIZE * GRID_SIZE], row: usize, col: usize, value: u8) {
pattern[row * GRID_SIZE + col] = value;
pattern[row * GRID_SIZE + (GRID_SIZE - 1 - col)] = value;
}
/// FNV-1a 64-bit hash; stable across platforms and runs.
fn fnv1a(bytes: &[u8]) -> u64 {
let mut hash = 0xcbf2_9ce4_8422_2325u64;
for &byte in bytes {
hash ^= byte as u64;
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
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
}
}
#[cfg(test)]
mod tests {
use super::*;
fn count_filled(pattern: &[u8; GRID_SIZE * GRID_SIZE]) -> usize {
pattern.iter().filter(|&&cell| cell != 0).count()
}
#[test]
fn pattern_is_mirror_symmetric() {
for seed in 0..50 {
let pattern = pattern(seed);
for row in 0..GRID_SIZE {
for col in 0..GRID_SIZE {
assert_eq!(
pattern[row * GRID_SIZE + col],
pattern[row * GRID_SIZE + (GRID_SIZE - 1 - col)],
"asymmetric pattern for seed {seed} at ({row}, {col})"
);
}
}
}
}
#[test]
fn pattern_has_minimum_fill() {
for seed in 0..50 {
let pattern = pattern(seed);
assert!(
count_filled(&pattern) >= MIN_FILLED * 2,
"pattern too sparse for seed {seed}"
);
}
}
#[test]
fn pattern_is_deterministic() {
for seed in [0, 1, 42, u64::MAX] {
assert_eq!(pattern(seed), pattern(seed));
}
assert_ne!(pattern(42), pattern(43));
}
#[test]
fn fnv1a_is_stable_and_distinct() {
assert_eq!(fnv1a(b""), 0xcbf2_9ce4_8422_2325);
assert_eq!(fnv1a(b"repo"), fnv1a(b"repo"));
assert_ne!(fnv1a(b"repo:a"), fnv1a(b"repo:b"));
}
}
+19
View File
@@ -0,0 +1,19 @@
use gpui::prelude::*;
use gpui::{AnyElement, App, div};
use gpui_component::{ActiveTheme, v_flex};
/// A centered muted placeholder message, filling its parent.
pub fn placeholder(message: &str, cx: &App) -> AnyElement {
v_flex()
.size_full()
.items_center()
.justify_center()
.p_4()
.child(
div()
.text_sm()
.text_color(cx.theme().muted_foreground)
.child(message.to_string()),
)
.into_any_element()
}
+179
View File
@@ -0,0 +1,179 @@
use gpui::prelude::*;
use gpui::{App, ClickEvent, ElementId, SharedString, StyleRefinement, Window, div, px, relative};
use gpui_base::{Button as BaseButton, StyledExt};
use gpui_component::ActiveTheme;
/// A small count badge shown after a label, e.g. on a segmented filter
/// button ("All 12") or a tab. Rendered from theme tokens; sized for the
/// compact header buttons it lives on.
#[derive(IntoElement)]
pub struct CountBadge {
count: usize,
style: StyleRefinement,
}
impl CountBadge {
pub fn new(count: usize) -> Self {
Self {
count,
style: StyleRefinement::default(),
}
}
}
impl Styled for CountBadge {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for CountBadge {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
div()
.refine_style(&self.style)
.h_flex()
.justify_center()
.ml_2()
.px_1()
.py_0p5()
.min_w_4()
.text_size(px(8.))
.bg(cx.theme().muted)
.text_color(cx.theme().muted_foreground)
.rounded(cx.theme().radius)
.line_height(relative(1.))
.child(SharedString::from(self.count.to_string()))
}
}
/// A segmented filter/tab button: an icon, a label, an optional [`CountBadge`]
/// and a selected (pressed) state, styled from the theme's button tokens.
///
/// Built on the unstyled `gpui_base::Button`, like the app's other custom
/// controls; the `primary` variant uses the primary button tokens for
/// call-to-action buttons ("New issue", "New PR").
#[allow(clippy::type_complexity)]
#[derive(IntoElement)]
pub struct SegmentButton {
id: ElementId,
style: StyleRefinement,
icon: Option<gpui::AnyElement>,
label: SharedString,
count: Option<usize>,
selected: bool,
primary: bool,
on_click: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>,
}
impl SegmentButton {
pub fn new<I, L>(id: I, label: L) -> Self
where
I: Into<ElementId>,
L: Into<SharedString>,
{
Self {
id: id.into(),
label: label.into(),
style: StyleRefinement::default(),
icon: None,
count: None,
selected: false,
primary: false,
on_click: None,
}
}
/// The leading icon, e.g. `Icon::new(CustomIconName::GitIssueDone)`.
pub fn icon(mut self, icon: impl IntoElement) -> Self {
self.icon = Some(icon.into_any_element());
self
}
/// A count shown in a badge after the label.
pub fn count(mut self, count: usize) -> Self {
self.count = Some(count);
self
}
/// Whether the button reflects an active filter/tab.
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
/// Use the primary button tokens (for call-to-action buttons).
pub fn primary(mut self) -> Self {
self.primary = true;
self
}
pub fn on_click(
mut self,
listener: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.on_click = Some(Box::new(listener));
self
}
}
impl Styled for SegmentButton {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for SegmentButton {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let Self {
id,
style,
icon,
label,
count,
selected,
primary,
on_click,
} = self;
let theme = cx.theme();
let fg = if primary {
theme.button_primary_foreground
} else {
theme.button_foreground
};
let base = if primary {
theme.button_primary
} else {
theme.button_active
};
let hover = if primary {
theme.button_primary_hover
} else {
theme.button_hover
};
let active = if primary {
theme.button_primary_active
} else {
theme.button_active
};
BaseButton::new(id)
.refine_style(&style)
.flex()
.items_center()
.h_7()
.px_2()
.gap_1()
.when_some(icon, |this, icon| this.child(icon))
.child(div().text_sm().child(label))
.when_some(count, |this, count| this.child(CountBadge::new(count)))
.text_color(fg)
.rounded(theme.radius)
.hover(move |this| this.bg(hover))
.active(move |this| this.bg(active))
.selected(selected)
.when(primary, |this| this.bg(base))
.when(selected, |this| this.bg(active))
.when_some(on_click, |this, listener| this.on_click(listener))
}
}
+53
View File
@@ -0,0 +1,53 @@
use assets::CustomIconName;
use gpui::prelude::*;
use gpui::{AnyElement, App};
use gpui_component::tooltip::Tooltip;
use gpui_component::{ActiveTheme, Icon, Sizable, v_flex};
use signed_core::RepoStatus;
/// The status badge shown next to an issue or pull request: icon + colored square,
/// with a tooltip describing the status.
pub fn status_badge(status: RepoStatus, cx: &App) -> AnyElement {
let (icon, label, tooltip, bg, fg) = match status {
RepoStatus::Open => (
CustomIconName::GitIssueDone,
"open",
"Issue is open",
cx.theme().primary,
cx.theme().primary_foreground,
),
RepoStatus::Closed => (
CustomIconName::GitIssueClosed,
"closed",
"Issue is closed",
cx.theme().danger,
cx.theme().danger_foreground,
),
RepoStatus::Draft => (
CustomIconName::GitIssueOngoing,
"draft",
"Issue is draft",
cx.theme().accent,
cx.theme().accent_foreground,
),
RepoStatus::Applied => (
CustomIconName::GitIssueOpen,
"applied",
"Issue is completed",
cx.theme().secondary,
cx.theme().secondary_foreground,
),
};
v_flex()
.id(label)
.flex_shrink_0()
.size_7()
.items_center()
.justify_center()
.rounded(cx.theme().radius)
.bg(bg)
.child(Icon::new(icon).small().text_color(fg))
.tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx))
.into_any_element()
}
+55
View File
@@ -0,0 +1,55 @@
use gpui::{
App, Div, InteractiveElement as _, MouseButton, Stateful, StatefulInteractiveElement as _,
Window, WindowControlArea,
};
/// State used to move the window when the title bar area is dragged.
struct WindowDragState {
should_move: bool,
}
/// Make an element behave like a window title bar: dragging it moves the
/// window, and double-clicking zooms the window (or performs the platform's
/// default title-bar double-click action on macOS).
///
/// Only the bar's non-interactive areas should get this — tabs are draggable
/// (to reorder panels) and must not move the window.
pub fn title_bar_drag_handlers(
this: Stateful<Div>,
window: &mut Window,
cx: &mut App,
) -> Stateful<Div> {
let state = window.use_state(cx, |_, _| WindowDragState { should_move: false });
this.window_control_area(WindowControlArea::Drag)
.on_mouse_down_out(window.listener_for(&state, |state, _, _, _| {
state.should_move = false;
}))
.on_mouse_down(
MouseButton::Left,
window.listener_for(&state, |state, _, _, _| {
state.should_move = true;
}),
)
.on_mouse_up(
MouseButton::Left,
window.listener_for(&state, |state, _, _, _| {
state.should_move = false;
}),
)
.on_mouse_move(window.listener_for(&state, |state, _, window, _| {
if state.should_move {
state.should_move = false;
window.start_window_move();
}
}))
.on_click(|event, window, _| {
if event.click_count() == 2 {
if cfg!(target_os = "macos") {
window.titlebar_double_click();
} else {
window.zoom_window();
}
}
})
}
+43
View File
@@ -0,0 +1,43 @@
use gpui::prelude::*;
use gpui::{App, Window, div, px};
use gpui_component::list::ListItem;
use gpui_component::tree::TreeEntry;
use gpui_component::{Icon, IconName, Sizable, h_flex};
/// One row of a file tree: icon + name, indented by depth.
/// Clicking a file runs `on_click`; folders expand/collapse via the tree itself.
pub fn tree_row<F>(ix: usize, entry: &TreeEntry, selected: bool, on_click: F) -> ListItem
where
F: Fn(&mut Window, &mut App) + 'static,
{
let item = entry.item();
let is_folder = entry.is_folder();
let icon = if is_folder {
if entry.is_expanded() {
IconName::FolderOpen
} else {
IconName::FolderClosed
}
} else {
IconName::File
};
ListItem::new(ix)
.pl(px(8.) + px(14.) * entry.depth() as f32)
.selected(selected)
.child(
h_flex()
.gap_2()
.overflow_hidden()
.child(Icon::new(icon).small())
.child(div().text_sm().text_ellipsis().child(item.label.clone())),
)
.on_click(move |_event, window, cx| {
// Folders expand/collapse via the tree itself.
if is_folder {
return;
}
on_click(window, cx);
})
}
+38
View File
@@ -0,0 +1,38 @@
/// `[head chars]...[tail chars]` middle truncation; the value is left alone
/// when it is too short for the ellipsis to save space.
pub fn middle_truncate(value: &str, head: usize, tail: usize) -> String {
let len = value.chars().count();
if len <= head + tail + 3 {
return value.to_string();
}
let head: String = value.chars().take(head).collect();
let tail: String = value.chars().skip(len - tail).collect();
format!("{head}...{tail}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn middle_truncates_long_values_only() {
assert_eq!(
middle_truncate(
"a008def15796fba9a0d6fab04e8fd57089285d9fd505da5a83fe8aad57a3564d",
10,
10,
),
"a008def157...ad57a3564d"
);
assert_eq!(
middle_truncate(
"30617:a008def15796fba9a0d6fab04e8fd57089285d9fd505da5a83fe8aad57a3564d:ngit",
10,
10
),
"30617:a008...3564d:ngit"
);
// Too short to save space with the ellipsis: left alone.
assert_eq!(middle_truncate("short", 10, 10), "short");
}
}