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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
//! Disclosure & DisclosureGroup — HeroUI v3 `Disclosure`.
//!
//! A single collapsible section: a trigger and a `p-2` body, which is all v3's
//! `disclosure.css` gives it -- not an `Accordion` with one item, which is what
//! this used to render. `DisclosureGroup` keeps the accordion, whose group
//! behaviour (single or multiple expansion) it needs.
use std::collections::HashSet;
use gpui::{
px, AnyElement, App, ElementId, InteractiveElement, IntoElement, ParentElement, RenderOnce,
SharedString, Styled, Window,
};
use herogpui_core::element_id;
use herogpui_theme::ActiveTheme;
use crate::a11y::{self, A11y as _};
/// The values HeroUI passes to a Disclosure children render function.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DisclosureRenderState {
/// Whether the disclosure is expanded.
pub is_expanded: bool,
/// Whether the disclosure is disabled.
pub is_disabled: bool,
}
type DisclosureContent = std::sync::Arc<dyn Fn(DisclosureRenderState) -> AnyElement + 'static>;
/// Single Disclosure — like an accordion with one item.
#[must_use = "a component does nothing until it is rendered: add it as a child or return it from `render`"]
#[derive(IntoElement)]
pub struct Disclosure {
id: ElementId,
title: SharedString,
is_expanded: Option<bool>,
default_expanded: bool,
is_disabled: bool,
children: Vec<AnyElement>,
content: Option<DisclosureContent>,
on_toggle: Option<std::sync::Arc<dyn Fn(&bool, &mut Window, &mut App) + 'static>>,
/// The `sx` slot, refined over the root style at the end of render.
sx: Option<Box<gpui::StyleRefinement>>,
}
impl Disclosure {
/// `onExpandedChange` — reports the expansion the press moves to.
pub fn on_expanded_change(
mut self,
handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
) -> Self {
self.on_toggle = Some(std::sync::Arc::new(handler));
self
}
/// Creates a disclosure with the given id and title.
pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
title: title.into(),
is_expanded: None,
default_expanded: false,
is_disabled: false,
children: Vec::new(),
content: None,
on_toggle: None,
sx: None,
}
}
/// Sets whether the disclosure is expanded.
pub fn is_expanded(mut self, v: bool) -> Self {
self.is_expanded = Some(v);
self
}
/// `defaultExpanded` — seeds the disclosure's own expansion state.
pub fn default_expanded(mut self, v: bool) -> Self {
self.default_expanded = v;
self
}
/// Sets whether the disclosure is disabled.
pub fn is_disabled(mut self, v: bool) -> Self {
self.is_disabled = v;
self
}
/// `children` as a render function — replaces static body children and is
/// handed the current expanded and disabled state on every render.
pub fn content(
mut self,
render: impl Fn(DisclosureRenderState) -> AnyElement + 'static,
) -> Self {
self.content = Some(std::sync::Arc::new(render));
self
}
/// The one slot for caller-owned low-level styling: GPUI's styling methods
/// (`bg`, `text_color`, `w`, `h`, `p`, `rounded`, `border_color`, …)
/// applied to the disclosure's root element after every value the trigger
/// variant and the active theme chose, so they win.
pub fn sx(mut self, style: impl FnOnce(gpui::Div) -> gpui::Div) -> Self {
crate::util::refine_sx(&mut self.sx, style);
self
}
}
impl ParentElement for Disclosure {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl RenderOnce for Disclosure {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
// A v3 Disclosure is not a small Accordion: `.disclosure` is `relative`,
// its trigger is whatever the caller passes (`<Button slot="trigger">`
// in v3's own examples) with a `.disclosure__indicator` chevron, and
// `.disclosure__body` is `p-2`. Rendering it as a one-item accordion
// gave it a card, a 16px trigger row and a separator that v3's sheet
// has no rule for.
let (expanded, expanded_own) = crate::util::controlled(
window,
cx,
element_id::scoped(&self.id, "expanded"),
self.is_expanded,
self.default_expanded,
);
let cb = self.on_toggle.clone();
let indicator_id = element_id::scoped(&self.id, "indicator");
let children = match self.content {
Some(render) => vec![render(DisclosureRenderState {
is_expanded: expanded,
is_disabled: self.is_disabled,
})],
None => self.children,
};
// `.disclosure__trigger` is `inline-block` with the focus ring on it;
// v3 passes a Button, which is what this builds.
let trigger = crate::button::Button::new(element_id::scoped(&self.id, "trigger"))
.variant(if expanded {
herogpui_core::Variant::Secondary
} else {
herogpui_core::Variant::Tertiary
})
.label(self.title.clone())
.is_disabled(self.is_disabled)
// `.disclosure__indicator` is `ms-auto size-4` and rotates one
// down-chevron through 180 degrees over 250ms when the panel opens.
.child(crate::anim::rotating_indicator(
&indicator_id,
expanded,
gpui::svg()
.size(px(16.))
.path(crate::icons::CHEVRON_DOWN)
.flex_shrink_0()
.text_color(cx.colors().muted),
window,
cx,
))
.on_press(move |_, w, cx| {
if let Some(held) = &expanded_own {
held.update(cx, |expanded, cx| {
*expanded = !*expanded;
cx.notify();
});
}
if let Some(f) = &cb {
f(&!expanded, w, cx);
}
});
let mut el = gpui::div()
.id(self.id.clone())
.relative()
.flex()
.flex_col()
.child(trigger);
// v3 transitions measured height and opacity. The shared collapsible
// helper retains the body for the 200ms closing phase and measures its
// natural height before driving the clipped outer panel.
let panel_id = element_id::scoped(&self.id, "panel");
let panel = gpui::div()
// `DisclosureBody` is an RAC `DisclosurePanel`
// (`disclosure/disclosure.js`), whose role is `group` and whose
// accessible name is the trigger (`Disclosure.mjs`:
// `role: role = 'group'`; `useDisclosure.js`:
// `'aria-labelledby': triggerId`). The trigger's own
// `aria-expanded` is carried by the caller-visible Button.
.id(panel_id.clone())
.a11y_named(a11y::Role::Group, &a11y::Name::labelled(self.title.clone()));
let body = gpui::div()
// `.disclosure__body` is `p-2`.
.p(px(8.))
.flex()
.flex_col()
.gap(px(6.))
.children(children)
.into_any_element();
if let Some(panel) =
crate::anim::collapsible_panel(&panel_id, expanded, panel, body, window, cx)
{
el = el.child(panel);
}
crate::util::apply_sx(el, &self.sx).into_any_element()
}
}
/// Group of Disclosures — mirrors Accordion but with `Disclosure` naming.
#[must_use = "a component does nothing until it is rendered: add it as a child or return it from `render`"]
#[derive(IntoElement)]
pub struct DisclosureGroup {
id: ElementId,
items: Vec<(SharedString, SharedString, Vec<AnyElement>)>,
expanded: Option<HashSet<SharedString>>,
default_expanded: HashSet<SharedString>,
allows_multiple_expanded: bool,
is_disabled: bool,
on_expanded_change:
Option<std::sync::Arc<dyn Fn(&HashSet<SharedString>, &mut Window, &mut App) + 'static>>,
/// The `sx` slot, refined over the root style at the end of render.
sx: Option<Box<gpui::StyleRefinement>>,
}
impl DisclosureGroup {
/// Creates an empty group with the given id.
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
items: Vec::new(),
expanded: None,
default_expanded: HashSet::new(),
allows_multiple_expanded: false,
is_disabled: false,
on_expanded_change: None,
sx: None,
}
}
/// Adds an item with the given key, title and content.
pub fn item(
mut self,
key: impl Into<SharedString>,
title: impl Into<SharedString>,
content: impl IntoElement,
) -> Self {
self.items
.push((key.into(), title.into(), vec![content.into_any_element()]));
self
}
/// `expandedKeys` — the caller-owned expanded set.
pub fn expanded_keys(
mut self,
keys: impl IntoIterator<Item = impl Into<SharedString>>,
) -> Self {
self.expanded = Some(keys.into_iter().map(Into::into).collect());
self
}
/// `defaultExpandedKeys` — seeds the group's own expanded set.
pub fn default_expanded_keys(
mut self,
keys: impl IntoIterator<Item = impl Into<SharedString>>,
) -> Self {
self.default_expanded = keys.into_iter().map(Into::into).collect();
self
}
/// `allowsMultipleExpanded` — otherwise opening one item closes the rest.
pub fn allows_multiple_expanded(mut self, v: bool) -> Self {
self.allows_multiple_expanded = v;
self
}
/// `isDisabled` — disables every disclosure in the group.
pub fn is_disabled(mut self, v: bool) -> Self {
self.is_disabled = v;
self
}
/// `onExpandedChange` — reports the complete next expanded set.
pub fn on_expanded_change(
mut self,
f: impl Fn(&HashSet<SharedString>, &mut Window, &mut App) + 'static,
) -> Self {
self.on_expanded_change = Some(std::sync::Arc::new(f));
self
}
/// The one slot for caller-owned low-level styling: GPUI's styling methods
/// (`bg`, `text_color`, `w`, `h`, `p`, `rounded`, `border_color`, …)
/// applied to the group's root element after every value the expansion
/// state and the active theme chose, so they win.
pub fn sx(mut self, style: impl FnOnce(gpui::Div) -> gpui::Div) -> Self {
crate::util::refine_sx(&mut self.sx, style);
self
}
}
impl RenderOnce for DisclosureGroup {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let (mut expanded, expanded_own) = crate::util::controlled(
window,
cx,
element_id::scoped(&self.id, "expanded"),
self.expanded,
self.default_expanded,
);
if !self.allows_multiple_expanded && expanded_own.is_some() && expanded.len() > 1 {
let retained = self
.items
.iter()
.find_map(|(key, _, _)| expanded.contains(key).then(|| key.clone()));
let next = retained.into_iter().collect::<HashSet<_>>();
if let Some(held) = &expanded_own {
let held_next = next.clone();
held.update(cx, |expanded, cx| {
*expanded = held_next;
cx.notify();
});
}
if let Some(callback) = self.on_expanded_change.clone() {
let reported = next.clone();
window.defer(cx, move |window, cx| callback(&reported, window, cx));
}
expanded = next;
}
// `.disclosure-group` is `w-full` and nothing else: v3's group *is* a
// column of `Disclosure`s, one of which may be open, so this renders
// them rather than an `Accordion` -- which would give every row the
// card, the padded trigger and the separator the sheet has no rule for.
let mut el = gpui::div().id(self.id.clone()).w_full().flex().flex_col();
for (key, title, children) in self.items {
let is_expanded = expanded.contains(&key);
let mut disclosure = Disclosure::new(key.clone(), title)
.is_expanded(is_expanded)
.is_disabled(self.is_disabled)
.children(children);
if expanded_own.is_some() || self.on_expanded_change.is_some() {
let current = expanded.clone();
let own = expanded_own.clone();
let cb = self.on_expanded_change.clone();
let allows_multiple = self.allows_multiple_expanded;
disclosure = disclosure.on_expanded_change(move |_next, window, cx| {
let next = crate::accordion::next_expanded(¤t, &key, allows_multiple);
if let Some(held) = &own {
let held_next = next.clone();
held.update(cx, |expanded, cx| {
*expanded = held_next;
cx.notify();
});
}
if let Some(f) = &cb {
f(&next, window, cx);
}
});
}
el = el.child(disclosure);
}
crate::util::apply_sx(el, &self.sx).into_any_element()
}
}
crate::util::impl_component_styled!(Disclosure, DisclosureGroup);