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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! ScrollShadow — port of `@heroui/scroll-shadow` (v3).
//!
//! A scrollable container with soft fading edges. Mirrors the React API:
//! `orientation`, `variant`, `size`, `offset`, `hideScrollBar`, `isEnabled`
//! and `visibility`.
use gpui::{
canvas, div, prelude::*, px, AnyElement, App, ElementId, IntoElement, ParentElement, Pixels,
RenderOnce, ScrollHandle, Styled, Window,
};
use herogpui_core::{element_id, Orientation};
use herogpui_theme::ActiveTheme;
/// The shadow effect style. v3 ships one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ScrollShadowVariant {
/// A fading shadow.
#[default]
Fade,
}
/// Which edges show a shadow (`visibility`).
///
/// `Auto` is derived from the live scroll offset: a tracked `ScrollHandle`
/// reports where the content sits, so the leading fade appears once it has been
/// scrolled away from the start and the trailing one goes when the end is
/// reached. The offset is a frame behind -- gpui fills the handle during
/// prepaint -- which `onVisibilityChange` reports from a canvas in the same
/// frame.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ScrollShadowVisibility {
/// Derived from the scroll position.
#[default]
Auto,
/// Both edges of the scroll axis.
Both,
/// Shadow at the top edge only.
Top,
/// Shadow at the bottom edge only.
Bottom,
/// Shadow at the left edge only.
Left,
/// Shadow at the right edge only.
Right,
/// No shadow.
None,
}
impl ScrollShadowVisibility {
/// Whether the leading edge (top / left) should be shaded.
fn shows_start(self, orientation: Orientation) -> bool {
match self {
// `Auto` is resolved before this is asked; `Both` is unconditional.
Self::Auto | Self::Both => true,
Self::Top => !orientation.is_horizontal(),
Self::Left => orientation.is_horizontal(),
_ => false,
}
}
/// Whether the trailing edge (bottom / right) should be shaded.
fn shows_end(self, orientation: Orientation) -> bool {
match self {
Self::Auto | Self::Both => true,
Self::Bottom => !orientation.is_horizontal(),
Self::Right => orientation.is_horizontal(),
_ => false,
}
}
}
/// HeroUI ScrollShadow.
#[must_use = "a component does nothing until it is rendered: add it as a child or return it from `render`"]
#[derive(IntoElement)]
pub struct ScrollShadow {
id: ElementId,
orientation: Orientation,
/// Gradient depth in pixels (`size`, default 40).
size: Pixels,
/// Scroll distance before the shadow appears (`offset`).
offset: Pixels,
is_enabled: bool,
visibility: ScrollShadowVisibility,
/// `onVisibilityChange` — reports the edges that are shaded, whenever that
/// changes.
on_visibility_change:
Option<std::sync::Arc<dyn Fn(&ScrollShadowVisibility, &mut Window, &mut App) + 'static>>,
max_h: Option<Pixels>,
max_w: Option<Pixels>,
gap: Pixels,
children: Vec<AnyElement>,
hide_scroll_bar: bool,
/// Makes the scroll axis fill its parent. Standalone shadows keep their
/// intrinsic/max-constrained sizing; composed controls opt into a bounded
/// viewport when they own an adjacent panel.
fill_axis: bool,
/// An owner can provide its existing scroll handle so edge shadows and
/// external controls observe the same offset and max range.
external_scroll: Option<ScrollHandle>,
/// The `sx` slot, refined over the root style at the end of render.
sx: Option<Box<gpui::StyleRefinement>>,
}
impl ScrollShadow {
/// Creates a scroll shadow with the given element id.
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
orientation: Orientation::Vertical,
size: px(40.),
offset: px(0.),
is_enabled: true,
visibility: ScrollShadowVisibility::Auto,
on_visibility_change: None,
max_h: Some(px(240.)),
max_w: None,
gap: px(8.),
children: Vec::new(),
hide_scroll_bar: false,
fill_axis: false,
external_scroll: None,
sx: None,
}
}
/// `hideScrollBar` — omit the painted overlay thumb. GPUI has no native
/// scrollbar on a overflow div; this is the port of v3's CSS hide.
pub fn hide_scroll_bar(mut self, v: bool) -> Self {
self.hide_scroll_bar = v;
self
}
/// Reuses a caller-owned scroll handle for composed controls.
pub(crate) fn scroll_handle(mut self, handle: ScrollHandle) -> Self {
self.external_scroll = Some(handle);
self
}
/// Sets the scroll direction (v3 `orientation`).
pub fn orientation(mut self, orientation: Orientation) -> Self {
self.orientation = orientation;
self
}
/// Gradient depth in pixels.
pub fn size(mut self, size: impl Into<Pixels>) -> Self {
self.size = size.into();
self
}
/// Sets the scroll distance before the shadow appears (v3 `offset`).
pub fn offset(mut self, offset: impl Into<Pixels>) -> Self {
self.offset = offset.into();
self
}
/// Turns shadow rendering off while keeping the scroll behaviour.
pub fn is_enabled(mut self, v: bool) -> Self {
self.is_enabled = v;
self
}
/// `onVisibilityChange` — fires when the shaded edges change, with the
/// resolved visibility (never `Auto`: the resolved value is what changed).
pub fn on_visibility_change(
mut self,
handler: impl Fn(&ScrollShadowVisibility, &mut Window, &mut App) + 'static,
) -> Self {
self.on_visibility_change = Some(std::sync::Arc::new(handler));
self
}
/// Sets which edges show a shadow (v3 `visibility`).
pub fn visibility(mut self, visibility: ScrollShadowVisibility) -> Self {
self.visibility = visibility;
self
}
/// Removes the standalone 240px height cap when the caller supplies a
/// full-height viewport.
pub(crate) fn unbounded_h(mut self) -> Self {
self.max_h = None;
self
}
pub(crate) fn fill_axis(mut self, value: bool) -> Self {
self.fill_axis = value;
self
}
/// Sets the maximum height.
pub fn max_h(mut self, v: impl Into<Pixels>) -> Self {
self.max_h = Some(v.into());
self
}
/// Sets the maximum width.
pub fn max_w(mut self, v: impl Into<Pixels>) -> Self {
self.max_w = Some(v.into());
self
}
/// Gap between children inside the scroll area.
pub fn gap(mut self, gap: impl Into<Pixels>) -> Self {
self.gap = gap.into();
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 scroll shadow's root element after every value the
/// orientation, the size 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 ScrollShadow {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl RenderOnce for ScrollShadow {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
// Where the content sits, as of the last frame: `use_keyed_state` takes
// `cx` mutably, so both slots precede the theme borrow.
let scroll = self.external_scroll.clone().unwrap_or_else(|| {
window
.use_keyed_state(element_id::scoped(&self.id, "scroll"), cx, |_, _| {
ScrollHandle::new()
})
.read(cx)
.clone()
});
let reported = window.use_keyed_state(
element_id::scoped(&self.id, "shadow-visibility"),
cx,
|_, _| ScrollShadowVisibility::None,
);
let bg = cx.colors().background;
let horizontal = self.orientation.is_horizontal();
let mut scroller = div()
.id(self.id.clone())
.track_scroll(&scroll)
.restrict_scroll_to_axis()
.overflow_hidden()
.flex()
.gap(self.gap);
scroller = if horizontal {
scroller.flex_row().overflow_x_scroll()
} else {
scroller.flex_col().overflow_y_scroll()
};
// A mouse wheel reports only `deltaY`, and the web platform forwards
// the raw axes, so shift+wheel never reaches a horizontal scroller
// there (native platforms translate it themselves). Until that lands
// upstream, drive the handle's x offset from the vertical delta here;
// see `util::shift_wheel_scroll_x`. `restrict_scroll_to_axis` already
// drops the vertical component from `track_scroll`, so the two do not
// double-scroll. Native builds keep flowing through `track_scroll`
// untouched: the helper is a web-only no-op elsewhere.
if horizontal {
let wheel_scroll = scroll.clone();
scroller = scroller.on_scroll_wheel(move |event, _window, _cx| {
crate::util::shift_wheel_scroll_x(&wheel_scroll, event);
});
}
if self.fill_axis {
scroller = if horizontal {
scroller.w_full().min_w(px(0.))
} else {
scroller.h_full().min_h(px(0.))
};
}
if let Some(h) = self.max_h {
scroller = scroller.max_h(h);
}
if let Some(w) = self.max_w {
scroller = scroller.max_w(w);
}
scroller = scroller.children(self.children);
let bar = (!self.hide_scroll_bar).then(|| {
crate::scrollbar::Scrollbar::new(
element_id::scoped(&self.id, "scrollbar"),
scroll.clone(),
)
.orientation(self.orientation)
});
if !self.is_enabled || self.visibility == ScrollShadowVisibility::None {
let mut root = div().relative().child(scroller);
if let Some(bar) = bar {
root = root.child(bar);
}
return crate::util::apply_sx(root, &self.sx).into_any_element();
}
// `Auto`: the leading fade once the content has been scrolled away from
// the start, the trailing one until the end is reached. `offset` counts
// *backwards* from zero, and `max_offset` is how far it can go.
//
// The scroller's wheel listener adds the delta straight into the
// tracked handle's offset cell during event dispatch; layout clamps it
// into `[-max, 0]` only on the next pass. A wheel over a box whose
// content fits (`max` = 0) would therefore read as a one-frame -40px
// offset here and resolve `Auto` to a spurious one-frame edge shadow.
// Clamp what this render reads to the same range layout clamps to:
// `Auto` must never report an edge while the offset sits outside the
// scrollable range, which is exactly the "nothing to scroll" case —
// v3's contract is that content which fits shows no shadow, ever.
let offset = scroll.offset();
let max = scroll.max_offset();
let (scrolled, scroll_max) = if horizontal {
(
f32::from(offset.x).clamp(-f32::from(max.x), 0.0),
f32::from(max.x),
)
} else {
(
f32::from(offset.y).clamp(-f32::from(max.y), 0.0),
f32::from(max.y),
)
};
let (past_start, before_end) = (
scrolled < -f32::from(self.offset),
scrolled - f32::from(self.offset) > -scroll_max,
);
let resolved = if self.visibility == ScrollShadowVisibility::Auto {
match (past_start, before_end) {
(true, true) => ScrollShadowVisibility::Both,
(true, false) if horizontal => ScrollShadowVisibility::Left,
(true, false) => ScrollShadowVisibility::Top,
(false, true) if horizontal => ScrollShadowVisibility::Right,
(false, true) => ScrollShadowVisibility::Bottom,
(false, false) => ScrollShadowVisibility::None,
}
} else {
self.visibility
};
let reports_visibility = self.visibility == ScrollShadowVisibility::Auto;
// The fades are absolutely positioned siblings so they do not scroll
// with the content.
// Fade to the *same* colour at zero alpha. Interpolating toward
// `transparent_black` would drag the midpoint through grey.
let clear = bg.alpha(0.0);
let fade = |from_start: bool| {
let stops = if from_start { (bg, clear) } else { (clear, bg) };
let angle = if horizontal { 90.0 } else { 180.0 };
let mut el = div().absolute().bg(gpui::linear_gradient(
angle,
gpui::linear_color_stop(stops.0, 0.0),
gpui::linear_color_stop(stops.1, 1.0),
));
el = if horizontal {
el.top_0().bottom_0().w(self.size)
} else {
el.left_0().right_0().h(self.size)
};
match (horizontal, from_start) {
(true, true) => el.left(self.offset),
(true, false) => el.right(self.offset),
(false, true) => el.top(self.offset),
(false, false) => el.bottom(self.offset),
}
};
let root = div()
.relative()
.child(scroller)
.when(resolved.shows_start(self.orientation), |el| {
el.child(fade(true))
})
.when(resolved.shows_end(self.orientation), |el| {
el.child(fade(false))
})
.when_some(bar, |el, bar| el.child(bar))
.when(reports_visibility, |el| {
// The offset is written during prepaint, so what changed is
// known here and reported from here.
let handler = self.on_visibility_change.clone();
el.child(
canvas(
move |_, window, cx| {
if *reported.read(cx) != resolved {
reported.update(cx, |value, cx| {
*value = resolved;
cx.notify();
});
if let Some(f) = &handler {
f(&resolved, window, cx);
}
}
},
|_, _, _, _| {},
)
.absolute()
.size(px(0.)),
)
});
crate::util::apply_sx(root, &self.sx).into_any_element()
}
}
crate::util::impl_component_styled!(ScrollShadow);