A trail of links to the current page, with an optional ellipsis for collapsed levels.
use gpui::{div, prelude::*, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::breadcrumb::Breadcrumb;
const TRAIL: [&str; 4] = ["Home", "Docs", "Components", "Breadcrumb"];
#[derive(Default)]
pub struct DocsTrail {
visited: Option<usize>,
}
impl Render for DocsTrail {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let status = match self.visited.and_then(|ix| TRAIL.get(ix)) {
Some(page) => format!("Navigate to {page}"),
None => "Click a link".to_string(),
};
div()
.flex()
.flex_col()
.items_center()
.gap_4()
.child(
Breadcrumb::new("trail")
.item(TRAIL[0])
.ellipsis()
.item(TRAIL[2])
.item(TRAIL[3])
.on_select(cx.listener(|this, ix: &usize, _, cx| {
// The ellipsis at index 1 stands in for "Docs".
this.visited = Some(*ix);
cx.notify();
})),
)
.child(div().text_xs().text_color(cx.theme().muted_foreground).child(status))
}
}Installation
Copies src/ui/breadcrumb.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/breadcrumb.rs.src/ui/breadcrumb.rs use std::{cell::Cell, rc::Rc, sync::Arc}; use gpui::{ canvas, div, point, prelude::*, px, AnimationExt, AnyElement, App, ElementId, Entity, Hsla, Interpolate, PathBuilder, SharedString, SpringAnimation, SpringAnimationElement, SpringConfig, Window, }; use crate::theme::ActiveTheme; type SelectHandler = Rc<dyn Fn(&usize, &mut Window, &mut App) + 'static>; type SeparatorFactory = Box<dyn Fn() -> AnyElement + 'static>; enum Crumb { Link(SharedString), Ellipsis, Element(AnyElement), } /// A trail of links to the current page. The last item is the current page and is not /// clickable; clicking any other link calls `on_select` with its index. #[derive(IntoElement)] pub struct Breadcrumb { id: ElementId, crumbs: Vec<Crumb>, on_select: Option<SelectHandler>, separator: Option<SeparatorFactory>, } impl Breadcrumb { pub fn new(id: impl Into<ElementId>) -> Self { Self { id: id.into(), crumbs: Vec::new(), on_select: None, separator: None, } } pub fn item(mut self, label: impl Into<SharedString>) -> Self { self.crumbs.push(Crumb::Link(label.into())); self } /// Stands in for collapsed levels of a deep trail. It takes an index like a link does. pub fn ellipsis(mut self) -> Self { self.crumbs.push(Crumb::Ellipsis); self } /// Any element as a crumb, such as a dropdown menu trigger. It takes an index like a link /// does, but handles its own clicks: `on_select` is not called for it. pub fn element(mut self, element: impl IntoElement) -> Self { self.crumbs.push(Crumb::Element(element.into_any_element())); self } /// Replaces the chevron between crumbs. The closure is called once per separator. pub fn separator<E: IntoElement>(mut self, separator: impl Fn() -> E + 'static) -> Self { self.separator = Some(Box::new(move || separator().into_any_element())); self } pub fn on_select(mut self, handler: impl Fn(&usize, &mut Window, &mut App) + 'static) -> Self { self.on_select = Some(Rc::new(handler)); self } } impl RenderOnce for Breadcrumb { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let (fg, muted) = (theme.foreground, theme.muted_foreground); let clear = gpui::transparent_black(); let last = self.crumbs.len().saturating_sub(1); let trail_id = Arc::new(self.id.clone()); let mut row = div() .id(self.id) .flex() .flex_wrap() .items_center() .gap(px(10.0)) .text_sm() .text_color(muted); for (ix, crumb) in self.crumbs.into_iter().enumerate() { if ix > 0 { row = match &self.separator { Some(separator) => row.child(separator()), None => row.child(chevron_right(muted)), }; } let current = ix == last; let handler = self.on_select.clone().filter(|_| !current); let item = || { div() .id(ix) .flex() .items_center() .when(!current, |this| this.cursor_pointer()) .when_some(handler, |this, handler| { this.on_click(move |_, window, cx| handler(&ix, window, cx)) }) }; // Links brighten on hover with shadcn's `transition-colors`. let eased = |element: gpui::Stateful<gpui::Div>, dots: bool, window: &mut Window, cx: &mut App| { let key = ElementId::NamedChild(trail_id.clone(), format!("crumb-{ix}").into()); let ease = ease_state(key.clone(), window, cx); let lit = current || ease.read(cx).hovered; let paint = Paint { bg: clear, fg: if lit { fg } else { muted }, border: clear }; let element = element.on_hover(track_hover(&ease)); ease_to(element, key, &ease, paint, cx, move |this, paint| { if dots { this.child(self::dots(paint.fg)) } else { this.text_color(paint.fg) } }) .into_any_element() }; row = row.child(match crumb { Crumb::Link(label) => eased(item().child(label), false, window, cx), Crumb::Ellipsis => { eased(item().size(px(20.0)).justify_center(), true, window, cx) } Crumb::Element(element) => element, }); } row } } /// Three dots built from divs, so it renders the same in any font. Text color does not reach /// fills, so the dots take their color directly. fn dots(color: Hsla) -> impl IntoElement { div() .flex() .gap(px(3.0)) .children((0..3).map(move |_| div().size(px(3.0)).rounded_full().bg(color))) } /// Lucide's chevron-right, drawn as a path because the preview fonts carry no icon glyphs. fn chevron_right(color: Hsla) -> impl IntoElement { canvas( |_, _, _| {}, move |bounds, _, window, _| { let origin = bounds.origin; let unit = bounds.size.width / 24.0; let at = |x: f32, y: f32| point(origin.x + unit * x, origin.y + unit * y); let mut path = PathBuilder::stroke(unit * 2.0); path.move_to(at(9.0, 6.0)); path.line_to(at(15.0, 12.0)); path.line_to(at(9.0, 18.0)); if let Ok(path) = path.build() { window.paint_path(path, color); } }, ) .flex_none() .size(px(14.0)) } /// shadcn's `transition-colors` (150ms) as a critically damped spring: quick, no overshoot. const EASE: SpringConfig = SpringConfig::new(900.0, 60.0, 1.0); /// The colors a control eases between as it is hovered or changes state. #[derive(Clone, Copy, PartialEq)] struct Paint { bg: Hsla, fg: Hsla, border: Hsla, } impl Paint { fn mix(self, to: Self, t: f32) -> Self { Self { bg: mix(self.bg, to.bg, t), fg: mix(self.fg, to.fg, t), border: mix(self.border, to.border, t), } } } /// Blends like CSS: a transparent end only fades the other color in or out, rather than /// passing through a dark gray. fn mix(from: Hsla, to: Hsla, t: f32) -> Hsla { let from = if from.a == 0.0 { to.opacity(0.0) } else { from }; let to = if to.a == 0.0 { from.opacity(0.0) } else { to }; Hsla::interpolate(from, to, t) } /// One control's hover flag and color transition, kept across frames. #[derive(Default)] struct Ease { hovered: bool, /// The colors eased from and to; `None` before the first render. from_to: Option<(Paint, Paint)>, /// Every new target moves the spring on by one, so an interrupted transition keeps its /// velocity; `start` is where the current one began. start: f32, run: f32, /// What the spring painted last and at which position, where the next transition starts. shown: Rc<Cell<Option<(Paint, f32)>>>, } fn ease_state(key: ElementId, window: &mut Window, cx: &mut App) -> Entity<Ease> { window.use_keyed_state(key, cx, |_, _| Ease::default()) } /// An `on_hover` listener that records hover in `ease`, re-rendering only on a change. fn track_hover(ease: &Entity<Ease>) -> impl Fn(&bool, &mut Window, &mut App) + 'static { let ease = ease.clone(); move |hovered, _, cx| { ease.update(cx, |ease, cx| { if ease.hovered != *hovered { ease.hovered = *hovered; cx.notify(); } }) } } /// Paints `element` with colors easing toward `target` from whatever was showing, like a CSS /// color transition. A newly mounted element starts at `target`, so nothing fades in on load. fn ease_to<E: IntoElement + 'static>( element: E, id: ElementId, ease: &Entity<Ease>, target: Paint, cx: &mut App, paint: impl FnOnce(E, Paint) -> E + 'static, ) -> SpringAnimationElement<E> { let (from, start, run, shown) = ease.update(cx, |ease, _| { match ease.from_to { Some((_, to)) if to == target => {} Some((_, to)) => { let (shown, position) = ease.shown.get().unwrap_or((to, ease.run)); ease.from_to = Some((shown, target)); ease.start = position; ease.run += 1.0; } None => ease.from_to = Some((target, target)), } let from = ease.from_to.map_or(target, |(from, _)| from); (from, ease.start, ease.run, ease.shown.clone()) }); element.with_spring(id, SpringAnimation::new(EASE).to(run), move |element, position| { let span = run - start; let t = if span > 0.0 { ((position - start) / span).clamp(0.0, 1.0) } else { 1.0 }; let now = from.mix(target, t); shown.set(Some((now, position))); paint(element, now) }) }Register the module
// src/ui/mod.rs pub mod breadcrumb;
Usage
use crate::ui::breadcrumb::*;Examples
Basic
A plain trail of links. The last item is the current page.
use gpui::prelude::*;
use crate::ui::breadcrumb::Breadcrumb;
pub fn breadcrumb_basic() -> impl IntoElement {
Breadcrumb::new("breadcrumb-basic")
.item("Home")
.item("Components")
.item("Breadcrumb")
}Custom separator
separator takes a closure that builds the element drawn between crumbs, here a dot in place of the chevron.
use gpui::{div, prelude::*, px, App, Window};
use crate::theme::ActiveTheme;
use crate::ui::breadcrumb::Breadcrumb;
pub fn breadcrumb_custom_separator(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let color = cx.theme().muted_foreground;
Breadcrumb::new("breadcrumb-custom-separator")
.item("Home")
.item("Components")
.item("Breadcrumb")
.separator(move || div().flex_none().size(px(4.0)).rounded_full().bg(color))
}Dropdown
element takes any element as a crumb. Here a DropdownMenu lets people jump to a sibling of the current section.
use gpui::{div, prelude::*, px, svg, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::breadcrumb::Breadcrumb;
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
use crate::icons::CHEVRON_DOWN;
#[derive(Default)]
pub struct BreadcrumbDropdown {
open: bool,
}
impl Render for BreadcrumbDropdown {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let (fg, muted) = (theme.foreground, theme.muted_foreground);
let trigger = div()
.id("breadcrumb-dropdown-trigger")
.flex()
.items_center()
.gap_1()
.cursor_pointer()
.hover(move |style| style.text_color(fg))
.child("Components")
.child(svg().data(CHEVRON_DOWN).size(px(14.0)).text_color(muted));
let menu = DropdownMenu::new("breadcrumb-dropdown-menu", self.open)
.trigger(trigger)
.width(px(160.0))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.item(MenuItem::new("Documentation"))
.item(MenuItem::new("Themes"))
.item(MenuItem::new("GitHub"));
// Top-aligned so the menu has room to open downward in the preview.
div().h(px(200.0)).child(
Breadcrumb::new("breadcrumb-dropdown")
.item("Home")
.element(menu)
.item("Breadcrumb"),
)
}
}Collapsed
ellipsis stands in for the middle levels of a deep trail to save space.
use gpui::prelude::*;
use crate::ui::breadcrumb::Breadcrumb;
pub fn breadcrumb_collapsed() -> impl IntoElement {
Breadcrumb::new("breadcrumb-collapsed")
.item("Home")
.ellipsis()
.item("Components")
.item("Breadcrumb")
}API Reference
Breadcrumb
A trail of links to the current page. The last item is the current page and is not clickable; clicking any other link calls on_select with its index.
Breadcrumb::new(id: impl Into<ElementId>) -> Self.item(label: impl Into<SharedString>).ellipsis()Stands in for collapsed levels of a deep trail. It takes an index like a link does.
.element(element: impl IntoElement)Any element as a crumb, such as a dropdown menu trigger. It takes an index like a link does, but handles its own clicks: on_select is not called for it.
Breadcrumb::separator<E: IntoElement>(mut self, separator: impl Fn() -> E + 'static) -> SelfReplaces the chevron between crumbs. The closure is called once per separator.
.on_select(handler: impl Fn(&usize, &mut Window, &mut App) + 'static)