1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4 AccessibleAction, AnyElement, App, Bounds, ElementId, Entity, FocusHandle, Hsla, IntoElement,
5 ParentElement, Pixels, RenderOnce, Rgba, Role, SharedString, StatefulInteractiveElement,
6 StyleRefinement, Styled, Toggled, Window, canvas, div, prelude::FluentBuilder, px,
7};
8use gpui_base::{Button, StyledExt};
9use gpui_material_theme::{Argb, ColorRole, CornerShape, Direction, Elevation, MaterialTheme};
10
11use crate::{
12 InteractionFeedback, InteractionSource, Shape, ShapeFit, ShapePolygon,
13 control_feedback::{activate_feedback, feedback_target, ripple_state},
14 current_material_theme,
15};
16
17pub fn color(argb: Argb) -> Hsla {
19 let [a, r, g, b] = argb.channels().map(|channel| f32::from(channel) / 255.);
20 Rgba { r, g, b, a }.into()
21}
22
23pub fn scrim_color(theme: &MaterialTheme, opacity: f32) -> Hsla {
25 color(theme.colors.color(ColorRole::Scrim)).opacity(opacity.clamp(0., 1.))
26}
27
28pub fn elevation_shadow_pair(
30 elevation: f32,
31 scale: f32,
32 shadow: Hsla,
33) -> Option<[gpui::BoxShadow; 2]> {
34 let dp = elevation * scale;
35 if !dp.is_finite() || dp <= 0. || !scale.is_finite() || scale <= 0. {
36 return None;
37 }
38 Some([
39 gpui_base::box_shadow(0., dp * 0.4, dp, 0., shadow.opacity(0.18)),
40 gpui_base::box_shadow(0., scale, dp * 0.5, 0., shadow.opacity(0.13)),
41 ])
42}
43
44pub fn elevation_shadows(elevation: f32, scale: f32, shadow: Hsla) -> Vec<gpui::BoxShadow> {
48 elevation_shadow_pair(elevation, scale, shadow).map_or_else(Vec::new, Vec::from)
49}
50
51#[derive(Clone, Copy, Debug, PartialEq)]
53pub struct SurfaceBorder {
54 pub width: Pixels,
56 pub color: Hsla,
58}
59
60#[derive(Clone, Copy, Debug, PartialEq)]
62pub struct SurfaceFeedback {
63 pub state_layer: bool,
65 pub ripple: bool,
67 pub focus_ring: bool,
69 pub ink: Option<Hsla>,
71 pub focus_color: Option<Hsla>,
73}
74
75impl Default for SurfaceFeedback {
76 fn default() -> Self {
77 Self {
78 state_layer: true,
79 ripple: true,
80 focus_ring: true,
81 ink: None,
82 focus_color: None,
83 }
84 }
85}
86
87#[derive(Clone, Copy)]
88enum SurfaceAction {
89 Activate,
90 Select(bool),
91 Check(bool),
92}
93
94type Activate = Rc<dyn Fn(&mut Window, &mut App)>;
95
96struct Control {
97 id: ElementId,
98 label: SharedString,
99 action: SurfaceAction,
100 activate: Option<Activate>,
101}
102
103#[derive(IntoElement)]
105pub struct Surface {
106 style: StyleRefinement,
107 children: Vec<AnyElement>,
108 role: ColorRole,
109 container_color: Option<Hsla>,
110 content_color: Option<Hsla>,
111 inherit_content_color: bool,
112 shape: Option<CornerShape>,
113 polygon: Option<ShapePolygon>,
114 shape_fit: ShapeFit,
115 clip_backdrop: Option<Hsla>,
116 shape_hit_test: Option<bool>,
117 border: Option<SurfaceBorder>,
118 tonal_elevation: Elevation,
119 shadow_elevation: Elevation,
120 shadow_scale: f32,
121 theme: Option<MaterialTheme>,
122 control: Option<Control>,
123 disabled: bool,
124 focus: Option<FocusHandle>,
125 feedback: SurfaceFeedback,
126 interaction_source: Option<Entity<InteractionSource>>,
127}
128
129impl Surface {
130 pub fn new(role: ColorRole) -> Self {
132 Self {
133 style: StyleRefinement::default(),
134 children: Vec::new(),
135 role,
136 container_color: None,
137 content_color: None,
138 inherit_content_color: false,
139 shape: None,
140 polygon: None,
141 shape_fit: ShapeFit::Contain,
142 clip_backdrop: None,
143 shape_hit_test: None,
144 border: None,
145 tonal_elevation: Elevation::Level0,
146 shadow_elevation: Elevation::Level0,
147 shadow_scale: 1.,
148 theme: None,
149 control: None,
150 disabled: false,
151 focus: None,
152 feedback: SurfaceFeedback::default(),
153 interaction_source: None,
154 }
155 }
156
157 pub fn clickable(
159 id: impl Into<ElementId>,
160 label: impl Into<SharedString>,
161 role: ColorRole,
162 ) -> Self {
163 Self::interactive(id, label, role, SurfaceAction::Activate)
164 }
165
166 pub fn selectable(
168 id: impl Into<ElementId>,
169 label: impl Into<SharedString>,
170 role: ColorRole,
171 selected: bool,
172 ) -> Self {
173 Self::interactive(id, label, role, SurfaceAction::Select(selected))
174 }
175
176 pub fn toggleable(
178 id: impl Into<ElementId>,
179 label: impl Into<SharedString>,
180 role: ColorRole,
181 checked: bool,
182 ) -> Self {
183 Self::interactive(id, label, role, SurfaceAction::Check(checked))
184 }
185
186 fn interactive(
187 id: impl Into<ElementId>,
188 label: impl Into<SharedString>,
189 role: ColorRole,
190 action: SurfaceAction,
191 ) -> Self {
192 Self {
193 control: Some(Control {
194 id: id.into(),
195 label: label.into(),
196 action,
197 activate: None,
198 }),
199 ..Self::new(role)
200 }
201 }
202
203 pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
205 if let Some(control) = &mut self.control {
206 control.activate = Some(Rc::new(handler));
207 }
208 self
209 }
210
211 pub fn on_checked_change(
214 mut self,
215 handler: impl Fn(bool, &mut Window, &mut App) + 'static,
216 ) -> Self {
217 if let Some(control) = &mut self.control
218 && let SurfaceAction::Check(checked) = control.action
219 {
220 control.activate = Some(Rc::new(move |window, cx| handler(!checked, window, cx)));
221 }
222 self
223 }
224
225 pub fn disabled(mut self, disabled: bool) -> Self {
227 self.disabled = disabled;
228 self
229 }
230
231 pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
233 self.focus = Some(focus.clone());
234 self
235 }
236
237 pub fn feedback(mut self, feedback: SurfaceFeedback) -> Self {
239 self.feedback = feedback;
240 self
241 }
242
243 pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
246 self.interaction_source = Some(source.clone());
247 self
248 }
249
250 pub fn container_color(mut self, color: Hsla) -> Self {
252 self.container_color = Some(color);
253 self
254 }
255
256 pub fn content_color(mut self, color: Hsla) -> Self {
258 self.content_color = Some(color);
259 self
260 }
261
262 pub fn inherit_content_color(mut self, inherit: bool) -> Self {
264 self.inherit_content_color = inherit;
265 self
266 }
267
268 pub fn shape(mut self, shape: CornerShape) -> Self {
270 self.shape = Some(shape);
271 self.polygon = None;
272 self
273 }
274
275 pub fn polygon_shape(mut self, polygon: impl Into<ShapePolygon>) -> Self {
282 self.polygon = Some(polygon.into());
283 self.shape = None;
284 self
285 }
286
287 pub fn shape_fit(mut self, fit: ShapeFit) -> Self {
289 self.shape_fit = fit;
290 self
291 }
292
293 pub fn shape_clip_backdrop(mut self, backdrop: Hsla) -> Self {
297 self.clip_backdrop = Some(backdrop);
298 self
299 }
300
301 pub fn shape_hit_test(mut self, enabled: bool) -> Self {
306 self.shape_hit_test = Some(enabled);
307 self
308 }
309
310 pub fn border(mut self, border: SurfaceBorder) -> Self {
312 self.border = Some(border);
313 self
314 }
315
316 pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
318 self.tonal_elevation = elevation;
319 self
320 }
321
322 pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
324 self.shadow_elevation = elevation;
325 self
326 }
327
328 pub fn shadow_scale(mut self, scale: f32) -> Self {
330 self.shadow_scale = scale;
331 self
332 }
333
334 pub fn with_theme(mut self, theme: MaterialTheme) -> Self {
336 self.theme = Some(theme);
337 self
338 }
339}
340
341impl ParentElement for Surface {
342 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
343 self.children.extend(elements);
344 }
345}
346
347impl Styled for Surface {
348 fn style(&mut self) -> &mut StyleRefinement {
349 &mut self.style
350 }
351}
352
353#[derive(Clone)]
354enum ResolvedShape {
355 Corners(CornerShape, Direction),
356 Polygon(ShapePolygon, ShapeFit),
357}
358
359impl ResolvedShape {
360 fn build(&self, bounds: Bounds<Pixels>) -> Option<Shape> {
361 match self {
362 Self::Corners(shape, direction) => Shape::rounded(bounds, *shape, *direction),
363 Self::Polygon(polygon, fit) => Shape::polygon(bounds, polygon, *fit),
364 }
365 }
366}
367
368struct PolygonPaint {
369 background: Hsla,
370 shadow_elevation: f32,
371 shadow_scale: f32,
372 shadow_color: Hsla,
373 border: Option<(Pixels, Hsla)>,
374}
375
376impl RenderOnce for Surface {
377 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
378 let current;
379 let theme = match &self.theme {
380 Some(theme) => theme,
381 None => {
382 current = current_material_theme(window, cx);
383 &*current
384 }
385 };
386 let scheme = &theme.colors;
387 let default_focus = color(scheme.color(ColorRole::Secondary));
388 let shadow_color = color(scheme.color(ColorRole::Shadow));
389 let background = if self.role == ColorRole::Surface {
390 scheme.surface_at_elevation(self.tonal_elevation)
391 } else {
392 scheme.color(self.role)
393 };
394 let direction = theme.layout.direction;
395 let background = self.container_color.unwrap_or_else(|| color(background));
396 let foreground = self.content_color.or_else(|| {
397 if self.inherit_content_color || self.container_color.is_some() {
398 return None;
399 }
400 scheme.pair(self.role).map(|pair| color(pair.foreground))
401 });
402 if let Some(foreground) = foreground {
403 self.style.text.color = Some(foreground);
404 }
405 let border = self.border.map(|border| {
406 let border_width = if f32::from(border.width).is_finite() {
407 border.width.max(px(0.))
408 } else {
409 px(0.)
410 };
411 (border_width, border.color)
412 });
413 let polygon_paint = if self.polygon.is_some() {
414 Some(PolygonPaint {
415 background,
416 shadow_elevation: self.shadow_elevation.dp(),
417 shadow_scale: self.shadow_scale,
418 shadow_color,
419 border: border.filter(|(width, _)| *width > px(0.)),
420 })
421 } else {
422 self.style.background = Some(background.into());
423 let shadows =
424 elevation_shadows(self.shadow_elevation.dp(), self.shadow_scale, shadow_color);
425 if !shadows.is_empty() {
426 self.style.box_shadow = Some(shadows);
427 }
428 if let Some(shape) = self.shape {
429 if shape == CornerShape::Full {
430 self = self.rounded_full();
431 } else {
432 let [tl, tr, br, bl] = shape.radii(f32::MAX, f32::MAX, direction);
433 self = self
434 .rounded_tl(px(tl))
435 .rounded_tr(px(tr))
436 .rounded_br(px(br))
437 .rounded_bl(px(bl));
438 }
439 }
440 if let Some((border_width, border_color)) = border {
441 let width = Some(border_width.into());
442 self.style.border_widths.top = width;
443 self.style.border_widths.right = width;
444 self.style.border_widths.bottom = width;
445 self.style.border_widths.left = width;
446 self.style.border_color = Some(if border_width > px(0.) {
447 border_color
448 } else {
449 gpui::transparent_black()
450 });
451 }
452 None
453 };
454 let resolved_shape = self.resolve_shape(direction, window);
455 let Some(control) = self.control.take() else {
456 return self.render_passive(resolved_shape, polygon_paint);
457 };
458 self.render_control(
459 control,
460 resolved_shape,
461 polygon_paint,
462 default_focus,
463 window,
464 cx,
465 )
466 }
467}
468
469impl Surface {
470 fn resolve_shape(&self, direction: Direction, window: &Window) -> ResolvedShape {
471 if let Some(polygon) = &self.polygon {
472 ResolvedShape::Polygon(polygon.clone(), self.shape_fit)
473 } else if let Some(shape) = self.shape {
474 ResolvedShape::Corners(shape, direction)
475 } else {
476 let radii = &self.style.corner_radii;
477 let radius = |value: Option<gpui::AbsoluteLength>| {
478 value.map_or(0., |value| value.to_pixels(window.rem_size()).into())
479 };
480 ResolvedShape::Corners(
481 CornerShape::Radii([
482 radius(radii.top_left),
483 radius(radii.top_right),
484 radius(radii.bottom_right),
485 radius(radii.bottom_left),
486 ]),
487 Direction::Ltr,
488 )
489 }
490 }
491
492 fn render_passive(
493 self,
494 resolved_shape: ResolvedShape,
495 polygon_paint: Option<PolygonPaint>,
496 ) -> AnyElement {
497 let clip_backdrop = self.clip_backdrop;
498 if polygon_paint.is_none() && clip_backdrop.is_none() {
499 return div()
500 .refine_style(&self.style)
501 .children(self.children)
502 .into_any_element();
503 }
504 let prepared: Rc<RefCell<Option<Shape>>> = Rc::new(RefCell::new(None));
505 let border = polygon_paint.as_ref().and_then(|paint| paint.border);
506 let prepaint_shape = prepared.clone();
507 let bg_shape = prepared.clone();
508 let background_layer = polygon_paint.map(|paint| {
509 let spec = resolved_shape.clone();
510 canvas(
511 move |bounds, _, _| {
512 *prepaint_shape.borrow_mut() = spec.build(bounds);
513 },
514 move |_, _, window, _| {
515 if let Some(shape) = bg_shape.borrow().as_ref() {
516 shape.paint_shadow(
517 paint.shadow_elevation,
518 paint.shadow_scale,
519 paint.shadow_color,
520 window,
521 );
522 shape.paint(paint.background, window);
523 }
524 },
525 )
526 .absolute()
527 .inset_0()
528 });
529 let needs_fg = clip_backdrop.is_some() || border.is_some();
530 let fg_prepaint = prepared.clone();
531 let fg_paint = prepared;
532 let has_bg = background_layer.is_some();
533 let foreground_layer = needs_fg.then(|| {
534 canvas(
535 move |bounds, _, _| {
536 if !has_bg {
537 *fg_prepaint.borrow_mut() = resolved_shape.build(bounds);
538 }
539 },
540 move |bounds, _, window, _| {
541 if let Some(shape) = fg_paint.borrow().as_ref() {
542 if let Some(backdrop) = clip_backdrop {
543 shape.paint_backdrop_mask(bounds, backdrop, window);
544 }
545 if let Some((width, color)) = border {
546 shape.paint_stroke(width, color, window);
547 }
548 }
549 },
550 )
551 .absolute()
552 .inset_0()
553 });
554 div()
555 .relative()
556 .when(clip_backdrop.is_some(), Styled::overflow_hidden)
557 .refine_style(&self.style)
558 .children(background_layer)
559 .children(self.children)
560 .children(foreground_layer)
561 .into_any_element()
562 }
563
564 fn render_control(
565 self,
566 control: Control,
567 resolved_shape: ResolvedShape,
568 polygon_paint: Option<PolygonPaint>,
569 default_focus: Hsla,
570 window: &mut Window,
571 cx: &mut App,
572 ) -> AnyElement {
573 let focus = self.focus.unwrap_or_else(|| {
574 window
575 .use_keyed_state((control.id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
576 .read(cx)
577 .clone()
578 });
579 let state = ripple_state(&control.id, !self.disabled, window, cx);
580 let shape_hit_test = self.shape_hit_test.unwrap_or(polygon_paint.is_some());
581 state.borrow_mut().set_shape_hit_test(shape_hit_test);
582 let tracker = self
583 .interaction_source
584 .as_ref()
585 .map(|source| InteractionSource::track(source, &control.id, window, cx));
586 let interaction = state
587 .borrow_mut()
588 .track(!self.disabled, &focus, tracker, window, cx);
589 let appearance = self.feedback;
590 let ink = appearance
591 .ink
592 .or(self.style.text.color)
593 .unwrap_or_else(|| window.text_style().color);
594 let ring = if appearance.focus_ring {
595 appearance.focus_color.unwrap_or(default_focus)
596 } else {
597 gpui::transparent_black()
598 };
599 let clip_backdrop = self.clip_backdrop;
600 let border = polygon_paint.as_ref().and_then(|paint| paint.border);
601 let bg_geometry = state.clone();
602 let bg_paint = state.clone();
603 let background_layer = polygon_paint.map(|paint| {
604 let spec = resolved_shape.clone();
605 canvas(
606 move |bounds, window, _| {
607 bg_geometry
608 .borrow_mut()
609 .set_shape(spec.build(bounds), window);
610 },
611 move |_, _, window, _| {
612 if let Some(shape) = &bg_paint.borrow().shape {
613 shape.paint_shadow(
614 paint.shadow_elevation,
615 paint.shadow_scale,
616 paint.shadow_color,
617 window,
618 );
619 shape.paint(paint.background, window);
620 }
621 },
622 )
623 .absolute()
624 .inset_0()
625 });
626 let has_bg = background_layer.is_some();
627 let geometry = state.clone();
628 let paint = state.clone();
629 let visual = canvas(
630 move |bounds, window, _| {
631 if !has_bg {
632 match &resolved_shape {
633 ResolvedShape::Corners(corners, direction) => {
634 geometry
635 .borrow_mut()
636 .set_rounded_shape(bounds, *corners, *direction, window);
637 }
638 ResolvedShape::Polygon(polygon, fit) => {
639 geometry
640 .borrow_mut()
641 .set_shape(Shape::polygon(bounds, polygon, *fit), window);
642 }
643 }
644 }
645 },
646 move |bounds, _, window, cx| {
647 let state = paint.borrow();
648 if let Some(shape) = &state.shape {
649 if let Some(backdrop) = clip_backdrop {
650 shape.paint_backdrop_mask(bounds, backdrop, window);
651 }
652 if let Some((width, color)) = border {
653 shape.paint_stroke(width, color, window);
654 }
655 let reduced = cx.reduce_motion();
656 let ripple = state.ripple.as_ref().filter(|_| appearance.ripple);
657 let layer = interaction
658 .layer_with_ripple(reduced || ripple.is_none())
659 .filter(|_| appearance.state_layer)
660 .map_or(0., |layer| layer.opacity());
661 InteractionFeedback::new(interaction, ink, ring).paint_with_opacity(
662 shape,
663 ripple,
664 layer,
665 cx.background_executor().now(),
666 reduced,
667 window,
668 );
669 }
670 },
671 )
672 .absolute()
673 .inset_0();
674 let button = Button::new(control.id)
675 .block()
676 .items_stretch()
677 .justify_start()
678 .when(clip_backdrop.is_some(), Styled::overflow_hidden)
679 .line_height(window.text_style().line_height)
680 .refine_style(&self.style)
681 .accessibility_label(control.label)
682 .track_focus(&focus)
683 .disabled(self.disabled);
684 let button = match control.action {
685 SurfaceAction::Activate => button,
686 SurfaceAction::Select(value) => button.role(Role::ListBoxOption).aria_selected(value),
687 SurfaceAction::Check(value) => button.role(Role::CheckBox).aria_toggled(if value {
688 Toggled::True
689 } else {
690 Toggled::False
691 }),
692 };
693 let button = if let Some(activate) = control.activate.filter(|_| !self.disabled) {
694 let accessible = activate.clone();
695 let feedback = state.clone();
696 button
697 .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
698 accessible(window, cx);
699 })
700 .on_click(move |event, window, cx| {
701 cx.stop_propagation();
702 if !feedback.borrow().blocks_activation(event) {
703 activate_feedback(event, &feedback, window, cx);
704 activate(window, cx);
705 }
706 })
707 } else {
708 button
709 };
710 button
711 .when(!self.disabled, |button| {
712 feedback_target(button, state, true, Some(focus))
713 })
714 .children(background_layer)
715 .children(self.children)
716 .child(visual)
717 .into_any_element()
718 }
719}