1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
//! Breadcrumb: the path to the current page → Carbon `Breadcrumb` /
//! `BreadcrumbItem` (`.cds--breadcrumb`). Place it above the page title.
//!
//! - **Behavior**: each ancestor is a Base `Button` (focus, Enter/Space,
//! pointer) that runs the caller's navigation; the current page is plain
//! text.
//! - **Appearance**: body-compact-01 (label-01 when `sm`) `.cds--link` items in
//! `link-primary`, `link-primary-hover` + underline on hover, a 1px `focus`
//! outline when focused; the current item in `text-primary` without hover;
//! `/` separators in `text-primary` 0.5rem (sm 0.25rem) on each side; no
//! trailing slash by default; the row wraps.
//! - **Custom items**: [`BreadcrumbItem::custom`] holds the caller's element
//! (an overflow menu of folded levels) in place of a link.
//! - **Motion**: `.cds--link { transition: color 70ms cubic-bezier(0.2, 0, 0.38, 0.9) }`.
use super::overlay::{Callback, rem};
use crate::{
motion::{self, Curve, Motion, Speed},
theme::color,
tokens::{ColorRole, TypeStyle},
typography::TypeStyled as _,
};
use gpui_kit::{
AnyElement, App, CursorStyle, ElementId, Hsla, IntoElement, ParentElement, RenderOnce,
SharedString, StatefulInteractiveElement as _, Styled, Window, div,
prelude::FluentBuilder as _,
};
use std::rc::Rc;
/// `.cds--link { transition: color 70ms cubic-bezier(0.2, 0, 0.38, 0.9) }`.
pub const LINK_MOTION: Motion = Motion::new(Curve::ProductiveStandard, Speed::Fast01);
/// Breadcrumb size (`.cds--breadcrumb--sm`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum BreadcrumbSize {
/// `sm`: label-01, 0.25rem gaps.
Sm,
/// `md` (default): body-compact-01, 0.5rem gaps.
#[default]
Md,
}
impl BreadcrumbSize {
/// Both sizes.
pub const ALL: [BreadcrumbSize; 2] = [Self::Sm, Self::Md];
/// The Carbon name.
pub const fn name(self) -> &'static str {
match self {
Self::Sm => "sm",
Self::Md => "md",
}
}
/// The gap on each side of a separator (`margin-inline-end` /
/// `::after { margin-inline-start }`).
pub const fn gap(self) -> f32 {
match self {
Self::Sm => 4.,
Self::Md => 8.,
}
}
}
/// The color of a breadcrumb item.
pub fn item_color(current: bool, hovered: bool) -> Hsla {
if current {
// `.cds--breadcrumb-item [aria-current=page] { color: var(--text-primary) }`.
color(ColorRole::TextPrimary)
} else if hovered {
color(ColorRole::LinkPrimaryHover)
} else {
color(ColorRole::LinkPrimary)
}
}
/// One step of the path.
pub struct BreadcrumbItem {
label: SharedString,
current: bool,
on_click: Option<Callback>,
content: Option<AnyElement>,
}
impl BreadcrumbItem {
/// An item showing `label`.
pub fn new(label: impl Into<SharedString>) -> Self {
Self {
label: label.into(),
current: false,
on_click: None,
content: None,
}
}
/// An item holding the caller's element instead of a link (a
/// `BreadcrumbItem` whose child is an `OverflowMenu`, the folded middle
/// levels of the overflow-content pattern). The caller's element brings
/// its own behavior and focus; the separator follows it as usual.
pub fn custom(content: impl IntoElement) -> Self {
Self {
content: Some(content.into_any_element()),
..Self::new(SharedString::default())
}
}
/// The current page (`isCurrentPage`): text, not a link.
pub fn current(mut self, current: bool) -> Self {
self.current = current;
self
}
/// Navigate when activated (the reference's `href`).
pub fn on_click(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_click = Some(Rc::new(f));
self
}
}
/// A Carbon breadcrumb. See the module docs.
#[derive(IntoElement)]
pub struct Breadcrumb {
id: ElementId,
items: Vec<BreadcrumbItem>,
no_trailing_slash: bool,
size: BreadcrumbSize,
}
impl Breadcrumb {
/// A breadcrumb with a stable `id`.
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
items: Vec::new(),
no_trailing_slash: true,
size: BreadcrumbSize::Md,
}
}
/// Append an item.
pub fn item(mut self, item: BreadcrumbItem) -> Self {
self.items.push(item);
self
}
/// Hide the slash after the last item (default true).
pub fn no_trailing_slash(mut self, hide: bool) -> Self {
self.no_trailing_slash = hide;
self
}
/// Size (default md).
pub fn size(mut self, size: BreadcrumbSize) -> Self {
self.size = size;
self
}
}
impl RenderOnce for Breadcrumb {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let gap = self.size.gap();
let style = match self.size {
BreadcrumbSize::Sm => TypeStyle::Label01,
BreadcrumbSize::Md => TypeStyle::BodyCompact01,
};
let count = self.items.len();
// Under `dir="rtl"` items run right to left and each separator follows
// its item on the left (Carbon's logical margins mirror).
let rtl = super::direction::is_rtl();
let mut row = div()
.flex()
.map(|d| {
if rtl {
d.flex_row_reverse()
} else {
d.flex_row()
}
})
.flex_wrap()
.items_center()
.type_style(style);
for (index, item) in self.items.into_iter().enumerate() {
let item_id = ElementId::NamedChild(
std::sync::Arc::new(id.clone()),
SharedString::from(format!("item-{index}")),
);
let hover = window.use_keyed_state((item_id.clone(), "hover"), cx, |_, _| false);
let hovered = *hover.read(cx) && !item.current;
let text = motion::animate_color(
(item_id.clone(), "text"),
item_color(item.current, hovered),
LINK_MOTION,
window,
cx,
);
let focus = window
.use_keyed_state((item_id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
.read(cx)
.clone();
let focused = focus.is_focused(window);
let label = if let Some(content) = item.content {
content
} else if item.current {
div()
.whitespace_nowrap()
// Same 1px box as the links' focus outline, so text lines up.
.border_1()
.border_color(Hsla::transparent_black())
.text_color(text)
.child(item.label.clone())
.into_any_element()
} else {
let on_click = item.on_click.clone();
gpui_kit::base::Button::new((item_id.clone(), "link"))
.track_focus(&focus)
.accessibility_label(item.label.clone())
.whitespace_nowrap()
.text_color(text)
.when(hovered || focused, |this| this.underline())
// `.cds--link:focus { outline: 1px solid var(--focus) }`.
.border_1()
.border_color(if focused {
color(ColorRole::Focus)
} else {
Hsla::transparent_black()
})
.cursor(CursorStyle::PointingHand)
.on_hover(move |h, _, cx| {
hover.update(cx, |v, cx| {
*v = *h;
cx.notify();
})
})
.on_click(move |_, window, cx| {
if let Some(f) = &on_click {
f(window, cx)
}
})
.child(item.label.clone())
.into_any_element()
};
let last = index + 1 == count;
row = row.child(
div()
.flex()
.map(|d| {
if rtl {
d.flex_row_reverse()
} else {
d.flex_row()
}
})
.items_center()
.when(!last, |this| {
if rtl {
this.ml(rem(gap))
} else {
this.mr(rem(gap))
}
})
.child(label)
.when(!(last && self.no_trailing_slash), |this| {
let slash = div().text_color(color(ColorRole::TextPrimary)).child("/");
this.child(if rtl {
slash.mr(rem(gap))
} else {
slash.ml(rem(gap))
})
}),
);
}
row
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tokens::CarbonTheme;
fn hex(c: Hsla) -> String {
let c = c.to_rgb();
let b = |v: f32| (v * 255.).round() as u8;
format!("#{:02x}{:02x}{:02x}", b(c.r), b(c.g), b(c.b))
}
#[test]
fn colors_and_gaps_follow_breadcrumb_css() {
crate::theme::tests_set(CarbonTheme::White);
assert_eq!(hex(item_color(false, false)), "#0f62fe");
assert_eq!(hex(item_color(false, true)), "#0043ce");
assert_eq!(hex(item_color(true, true)), "#161616");
assert_eq!(
(BreadcrumbSize::Md.gap(), BreadcrumbSize::Sm.gap()),
(8., 4.)
);
assert!(Breadcrumb::new("b").no_trailing_slash);
}
#[test]
fn a_custom_item_holds_the_callers_element() {
let item = BreadcrumbItem::custom(div());
assert!(item.content.is_some() && !item.current && item.on_click.is_none());
assert!(BreadcrumbItem::new("Servers").content.is_none());
}
}