1use std::ops::Range;
30
31use egui::scroll_area::ScrollAreaOutput;
32use egui::{
33 ComboBox, InnerResponse, Layout, Rect, Response, RichText, ScrollArea, Sense, Shadow, Ui,
34 UiBuilder, Vec2, Widget, WidgetText,
35};
36
37use crate::fonts::{self, Role, Weight};
38use crate::kit::{Kit, State};
39pub use crate::kit::{Stock, Tone};
40pub use crate::theme::TextRole;
41use crate::theme::Tokens;
42
43pub mod layout;
44pub use layout::{Align, Cells, Flow, FlowCells, Grid, Length, Row, Track};
45
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
50pub enum Space {
51 Inline,
53 Group,
55 Section,
57 Page,
59}
60
61impl Space {
62 pub const ALL: [Space; 4] = [Space::Inline, Space::Group, Space::Section, Space::Page];
63
64 pub fn token(self) -> &'static str {
66 match self {
67 Space::Inline => "space.inline",
68 Space::Group => "space.group",
69 Space::Section => "space.section",
70 Space::Page => "space.page",
71 }
72 }
73
74 pub fn points(self, tokens: &Tokens) -> f32 {
76 let s = &tokens.space;
77 match self {
78 Space::Inline => s.inline,
79 Space::Group => s.group,
80 Space::Section => s.section,
81 Space::Page => s.page,
82 }
83 }
84}
85
86pub fn role_text(ui: &Ui, role: TextRole, text: impl Into<String>) -> RichText {
91 let t = Tokens::of(ui.ctx());
92 styled_text(ui, t.text_role.get(role), text)
93}
94
95pub fn strong_text(ui: &Ui, text: impl Into<String>) -> RichText {
103 let t = Tokens::of(ui.ctx());
104 styled_text(ui, &t.text_role.strong, text)
105}
106
107fn styled_text(ui: &Ui, style: &crate::theme::TextRoleStyle, text: impl Into<String>) -> RichText {
108 let rich = RichText::new(text)
109 .size(style.size.max(4.0))
110 .color(style.color);
111 match role_family(ui.ctx(), style.weight) {
112 Some(family) => rich.family(family),
113 None => rich,
114 }
115}
116
117pub fn tone_color(tokens: &Tokens, tone: Tone) -> egui::Color32 {
125 match tone {
126 Tone::Neutral => tokens.text_role.body.color,
127 Tone::Accent => tokens.accent.default,
128 Tone::Info => tokens.status.info,
129 Tone::Success => tokens.status.success,
130 Tone::Warning => tokens.status.warning,
131 Tone::Danger | Tone::Record => tokens.status.danger,
132 Tone::Muted => tokens.text_role.muted.color,
133 }
134}
135
136pub(crate) fn role_family(ctx: &egui::Context, weight: Weight) -> Option<egui::FontFamily> {
141 if weight.nearest_installed() == Weight::REGULAR {
142 return None;
143 }
144 if fonts::previewing(ctx) {
145 return fonts::preview_family(ctx, Role::Ui, weight);
146 }
147 let family = fonts::family(Role::Ui, weight);
148 ctx.fonts(|f| f.definitions().families.contains_key(&family))
151 .then_some(family)
152}
153
154pub fn contain_wheel<R>(ui: &Ui, out: &ScrollAreaOutput<R>) {
167 let ways = crate::scroll_keys::axes(ui.ctx(), out);
168 let over = ui.ctx().viewport(|v| {
171 [0_usize, 1_usize]
172 .iter()
173 .filter(|d| ways[**d])
174 .filter_map(|d| v.this_pass.widgets.get(out.id.with(*d)))
175 .fold(out.inner_rect, |rect, bar| rect.union(bar.rect))
176 });
177 contain_wheel_in(ui, over, ways);
178}
179
180pub fn contain_wheel_in(ui: &Ui, rect: Rect, ways: [bool; 2]) {
185 if !ways[0] && !ways[1] || !ui.is_enabled() || !ui.rect_contains_pointer(rect) {
186 return;
187 }
188 let either = ui.style().always_scroll_the_only_direction && ways[0] != ways[1];
189 ui.input_mut(|i| {
190 if ways[0] || either {
191 i.smooth_scroll_delta.x = 0.0;
192 }
193 if ways[1] || either {
194 i.smooth_scroll_delta.y = 0.0;
195 }
196 });
197}
198
199pub fn set_scroll_offset(ctx: &egui::Context, id: egui::Id, offset: egui::Vec2) -> bool {
207 use egui::scroll_area::State;
208 let Some(state) = State::load(ctx, id) else {
209 return false;
210 };
211 let Ok(mut value) = serde_json::to_value(state) else {
212 return false;
213 };
214 let (Some(fields), Ok(offset)) = (value.as_object_mut(), serde_json::to_value(offset)) else {
215 return false;
216 };
217 fields.insert("offset".to_owned(), offset);
218 let Ok(state) = serde_json::from_value::<State>(value) else {
219 return false;
220 };
221 state.store(ctx, id);
222 true
223}
224
225#[cfg(test)]
231const EGUI_UI_METHODS: &[&str] = &[
232 "add",
233 "add_enabled",
234 "add_enabled_ui",
235 "add_sized",
236 "add_space",
237 "add_visible",
238 "advance_cursor_after_rect",
239 "allocate_at_least",
240 "allocate_exact_size",
241 "allocate_painter",
242 "allocate_rect",
243 "allocate_response",
244 "allocate_space",
245 "allocate_ui",
246 "allocate_ui_with_layout",
247 "auto_id_with",
248 "available_height",
249 "available_rect_before_wrap",
250 "available_size",
251 "available_size_before_wrap",
252 "available_width",
253 "button",
254 "centered_and_justified",
255 "checkbox",
256 "clip_rect",
257 "close",
258 "close_kind",
259 "code",
260 "code_editor",
261 "collapsing",
262 "color_edit_button_hsva",
263 "color_edit_button_rgb",
264 "color_edit_button_rgba_premultiplied",
265 "color_edit_button_rgba_unmultiplied",
266 "color_edit_button_srgb",
267 "color_edit_button_srgba",
268 "color_edit_button_srgba_premultiplied",
269 "color_edit_button_srgba_unmultiplied",
270 "colored_label",
271 "columns",
272 "columns_const",
273 "ctx",
274 "cursor",
275 "debug_paint_cursor",
276 "disable",
277 "dnd_drag_source",
278 "dnd_drop_zone",
279 "drag_angle",
280 "drag_angle_tau",
281 "end_row",
282 "expand_to_include_rect",
283 "expand_to_include_x",
284 "expand_to_include_y",
285 "force_set_min_rect",
286 "group",
287 "heading",
288 "horizontal",
289 "horizontal_centered",
290 "horizontal_top",
291 "horizontal_wrapped",
292 "hyperlink",
293 "hyperlink_to",
294 "id",
295 "image",
296 "indent",
297 "interact",
298 "interact_opt",
299 "is_enabled",
300 "is_grid",
301 "is_rect_visible",
302 "is_sizing_pass",
303 "is_tooltip",
304 "is_visible",
305 "label",
306 "label_inputs_by",
307 "layer_id",
308 "layout",
309 "link",
310 "make_persistent_id",
311 "max_rect",
312 "menu_button",
313 "menu_image_button",
314 "menu_image_text_button",
315 "min_rect",
316 "min_size",
317 "monospace",
318 "multiply_opacity",
319 "name_inputs",
320 "new",
321 "new_child",
322 "next_auto_id",
323 "next_widget_position",
324 "opacity",
325 "painter",
326 "painter_at",
327 "pixels_per_point",
328 "place",
329 "placer",
330 "push_id",
331 "put",
332 "radio",
333 "radio_value",
334 "rect_contains_pointer",
335 "reset_style",
336 "response",
337 "save_grid",
338 "scope",
339 "scope_builder",
340 "scope_dyn",
341 "scope_id",
342 "scroll_to_cursor",
343 "scroll_to_cursor_animation",
344 "scroll_to_rect",
345 "scroll_to_rect_animation",
346 "scroll_with_delta",
347 "scroll_with_delta_animation",
348 "selectable_label",
349 "selectable_value",
350 "separator",
351 "set_clip_rect",
352 "set_cursor",
353 "set_grid",
354 "set_height",
355 "set_height_range",
356 "set_invisible",
357 "set_max_height",
358 "set_max_size",
359 "set_max_width",
360 "set_min_height",
361 "set_min_size",
362 "set_min_width",
363 "set_opacity",
364 "set_row_height",
365 "set_style",
366 "set_width",
367 "set_width_range",
368 "should_close",
369 "shrink_clip_rect",
370 "shrink_height_to_current",
371 "shrink_width_to_current",
372 "skip_ahead_auto_ids",
373 "small",
374 "small_button",
375 "spacing",
376 "spacing_mut",
377 "spinner",
378 "stack",
379 "strong",
380 "style",
381 "style_mut",
382 "take_available_height",
383 "take_available_space",
384 "take_available_width",
385 "text_edit_multiline",
386 "text_edit_singleline",
387 "text_style_height",
388 "text_valign",
389 "toggle_value",
390 "ui_contains_pointer",
391 "unique_id",
392 "vertical",
393 "vertical_centered",
394 "vertical_centered_justified",
395 "visuals",
396 "visuals_mut",
397 "weak",
398 "widget_style",
399 "will_parent_close",
400 "with_layout",
401 "with_visual_transform",
402 "wrap_mode",
403];
404
405#[cfg(test)]
407const SHADOWED_DEPRECATED: &[&str] = &["strong"];
408
409mod sealed {
410 pub trait Sealed {}
411 impl Sealed for egui::Ui {}
412}
413
414pub trait UiPop: sealed::Sealed {
417 fn text_role(&mut self, role: TextRole, text: impl Into<String>) -> Response;
421
422 fn section_title(&mut self, text: impl Into<String>) -> Response;
427
428 fn muted(&mut self, text: impl Into<String>) -> Response;
433
434 fn meta(&mut self, text: impl Into<String>) -> Response;
438
439 fn strong_text(&mut self, text: impl Into<String>) -> Response;
448
449 #[deprecated(note = "egui's inherent `Ui::strong` shadows it: use `UiPop::strong_text`")]
455 fn strong(&mut self, text: impl Into<String>) -> Response {
456 self.strong_text(text)
457 }
458
459 fn code_text(&mut self, text: impl Into<String>) -> Response;
470
471 fn text_tone(&mut self, tone: Tone, text: impl Into<String>) -> Response;
486
487 fn divider(&mut self) -> Response;
498
499 fn sized(&mut self, size: Vec2, widget: impl Widget) -> Response;
508
509 fn sized_ui<R>(
520 &mut self,
521 size: Vec2,
522 layout: Layout,
523 add: impl FnOnce(&mut Ui) -> R,
524 ) -> InnerResponse<R>;
525
526 fn rect_ui<R>(
536 &mut self,
537 rect: Rect,
538 layout: Layout,
539 add: impl FnOnce(&mut Ui) -> R,
540 ) -> InnerResponse<R>;
541
542 fn space_role(&mut self, space: Space);
547
548 fn card<R>(&mut self, tone: Tone, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R>;
553
554 fn popover<R>(&mut self, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R>;
565
566 fn button_tone(&mut self, tone: Tone, text: impl Into<WidgetText>) -> Response;
573
574 fn scoped<R>(
583 &mut self,
584 stock: Stock,
585 tone: Tone,
586 add: impl FnOnce(&mut Ui) -> R,
587 ) -> InnerResponse<R>;
588
589 fn combo_box<R>(
596 &mut self,
597 combo: ComboBox,
598 add: impl FnOnce(&mut Ui) -> R,
599 ) -> InnerResponse<Option<R>>;
600
601 fn scroll_area<R>(
616 &mut self,
617 area: ScrollArea,
618 add: impl FnOnce(&mut Ui) -> R,
619 ) -> ScrollAreaOutput<R>;
620
621 fn scroll_area_viewport<R>(
630 &mut self,
631 area: ScrollArea,
632 add: impl FnOnce(&mut Ui, Rect) -> R,
633 ) -> ScrollAreaOutput<R>;
634
635 fn scroll_area_rows<R>(
641 &mut self,
642 area: ScrollArea,
643 row_height: f32,
644 rows: usize,
645 add: impl FnOnce(&mut Ui, Range<usize>) -> R,
646 ) -> ScrollAreaOutput<R>;
647
648 fn scroll_area_contained<R>(
655 &mut self,
656 area: ScrollArea,
657 add: impl FnOnce(&mut Ui) -> R,
658 ) -> ScrollAreaOutput<R>;
659
660 fn drag_cursor<'a>(
670 &self,
671 response: &'a Response,
672 kind: crate::pointer::DragKind,
673 ) -> crate::pointer::DragCursorFor<'a>;
674
675 fn row<R>(&mut self, row: Row, add: impl FnOnce(&mut Cells<'_>) -> R) -> InnerResponse<R>;
680
681 fn grid<R>(&mut self, grid: Grid, add: impl FnOnce(&mut Cells<'_>) -> R) -> InnerResponse<R>;
685
686 fn flow<R>(
692 &mut self,
693 flow: Flow,
694 add: impl FnOnce(&mut FlowCells<'_>) -> R,
695 ) -> InnerResponse<R>;
696}
697
698impl UiPop for Ui {
699 fn text_role(&mut self, role: TextRole, text: impl Into<String>) -> Response {
700 let rich = role_text(self, role, text);
701 self.label(rich)
702 }
703
704 fn section_title(&mut self, text: impl Into<String>) -> Response {
705 self.text_role(TextRole::Section, text)
706 }
707
708 fn muted(&mut self, text: impl Into<String>) -> Response {
709 self.text_role(TextRole::Muted, text)
710 }
711
712 fn meta(&mut self, text: impl Into<String>) -> Response {
713 self.text_role(TextRole::Meta, text)
714 }
715
716 fn strong_text(&mut self, text: impl Into<String>) -> Response {
717 let rich = strong_text(self, text);
718 self.label(rich)
719 }
720
721 fn code_text(&mut self, text: impl Into<String>) -> Response {
722 let color = Tokens::of(self.ctx()).text_role.body.color;
723 self.label(RichText::new(text).monospace().color(color))
724 }
725
726 fn text_tone(&mut self, tone: Tone, text: impl Into<String>) -> Response {
727 let color = tone_color(&Tokens::of(self.ctx()), tone);
728 let rich = role_text(self, TextRole::Body, text).color(color);
729 self.label(rich)
730 }
731
732 fn divider(&mut self) -> Response {
733 let t = Tokens::of(self.ctx());
734 let across = self.layout().main_dir().is_horizontal();
735 let room = if self.is_sizing_pass() {
736 egui::Vec2::ZERO
737 } else {
738 self.available_size_before_wrap()
739 };
740 let size = if across {
741 egui::vec2(t.space.group, room.y)
742 } else {
743 egui::vec2(room.x, t.space.group)
744 };
745 let (rect, response) = self.allocate_exact_size(size, egui::Sense::hover());
746 if self.is_rect_visible(rect) {
747 let painter = self.painter();
748 let width = crate::scale::snap(1.0, self.ctx().pixels_per_point());
749 let stroke = egui::Stroke::new(width, t.border.default);
750 if across {
751 let x = painter.round_to_pixel_center(rect.center().x);
752 painter.vline(x, rect.y_range(), stroke);
753 } else {
754 let y = painter.round_to_pixel_center(rect.center().y);
755 painter.hline(rect.x_range(), y, stroke);
756 }
757 }
758 response
759 }
760
761 fn sized(&mut self, size: Vec2, widget: impl Widget) -> Response {
762 let layout = if self.layout().main_dir().is_horizontal() {
763 Layout::centered_and_justified(egui::Direction::LeftToRight)
764 } else {
765 Layout::centered_and_justified(egui::Direction::TopDown)
766 };
767 self.sized_ui(size, layout, |ui| ui.add(widget)).inner
768 }
769
770 fn sized_ui<R>(
771 &mut self,
772 size: Vec2,
773 layout: Layout,
774 add: impl FnOnce(&mut Ui) -> R,
775 ) -> InnerResponse<R> {
776 let (rect, response) = self.allocate_exact_size(size, Sense::hover());
777 let mut child = self.new_child(UiBuilder::new().max_rect(rect).layout(layout));
778 let inner = add(&mut child);
779 InnerResponse::new(inner, response)
780 }
781
782 fn rect_ui<R>(
783 &mut self,
784 rect: Rect,
785 layout: Layout,
786 add: impl FnOnce(&mut Ui) -> R,
787 ) -> InnerResponse<R> {
788 let clip = rect.intersect(self.clip_rect());
789 self.scope_builder(UiBuilder::new().max_rect(rect).layout(layout), |ui| {
790 ui.set_clip_rect(clip);
791 add(ui)
792 })
793 }
794
795 fn space_role(&mut self, space: Space) {
796 let points = space.points(&Tokens::of(self.ctx()));
797 self.add_space(points);
798 }
799
800 fn card<R>(&mut self, tone: Tone, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> {
801 let kit = Kit::of(self.ctx());
802 kit.card
803 .show(self, State::REST.toned(tone), Shadow::NONE, add)
804 }
805
806 fn popover<R>(&mut self, add: impl FnOnce(&mut Ui) -> R) -> InnerResponse<R> {
807 let kit = Kit::of(self.ctx());
808 let shadow = self.visuals().popup_shadow;
809 kit.popover.show(self, State::REST, shadow, add)
810 }
811
812 fn button_tone(&mut self, tone: Tone, text: impl Into<WidgetText>) -> Response {
813 if tone == Tone::Neutral {
814 return self.button(text);
815 }
816 self.scoped(Stock::Button, tone, |ui| ui.button(text)).inner
817 }
818
819 fn scoped<R>(
820 &mut self,
821 stock: Stock,
822 tone: Tone,
823 add: impl FnOnce(&mut Ui) -> R,
824 ) -> InnerResponse<R> {
825 Kit::of(self.ctx()).scope(self, stock, tone, add)
826 }
827
828 fn combo_box<R>(
829 &mut self,
830 combo: ComboBox,
831 add: impl FnOnce(&mut Ui) -> R,
832 ) -> InnerResponse<Option<R>> {
833 self.scoped(Stock::ComboBox, Tone::Neutral, |ui| combo.show_ui(ui, add))
834 .inner
835 }
836
837 fn scroll_area<R>(
838 &mut self,
839 area: ScrollArea,
840 add: impl FnOnce(&mut Ui) -> R,
841 ) -> ScrollAreaOutput<R> {
842 self.scroll_area_viewport(area, |ui, _| add(ui))
843 }
844
845 fn scroll_area_viewport<R>(
846 &mut self,
847 area: ScrollArea,
848 add: impl FnOnce(&mut Ui, Rect) -> R,
849 ) -> ScrollAreaOutput<R> {
850 let style = self.style().clone();
856 let kit = crate::kit::Kit::of(self.ctx());
857 self.scoped(Stock::ScrollBar, Tone::Neutral, |ui| {
858 let start = crate::scroll_keys::start(ui);
859 let track = ui.next_auto_id().with("egui_pop.scroll_track");
863 let mut area = area;
864 if kit.scroll.margin_track > 0.0
865 && let Some(inner) = ui.data(|d| d.get_temp::<Rect>(track))
866 && let Some(rect) = kit.scroll.track_rect(inner)
867 {
868 area = area.scroll_bar_rect(rect);
869 }
870 let out = area.show_viewport(ui, |ui, viewport| {
871 ui.set_style(style);
872 add(ui, viewport)
873 });
874 if kit.scroll.margin_track > 0.0 {
875 let before = ui.data_mut(|d| d.get_temp::<Rect>(track));
876 if before != Some(out.inner_rect) {
877 ui.data_mut(|d| d.insert_temp(track, out.inner_rect));
878 ui.ctx().request_repaint();
879 }
880 }
881 crate::scroll_keys::answer(ui, &out, start);
882 out
883 })
884 .inner
885 }
886
887 fn scroll_area_rows<R>(
888 &mut self,
889 area: ScrollArea,
890 row_height: f32,
891 rows: usize,
892 add: impl FnOnce(&mut Ui, Range<usize>) -> R,
893 ) -> ScrollAreaOutput<R> {
894 let spacing = self.spacing().item_spacing.y;
896 let pitch = row_height + spacing;
897 self.scroll_area_viewport(area, |ui, viewport| {
898 ui.set_height((pitch * rows as f32 - spacing).max(0.0));
899 let mut first = (viewport.min.y / pitch).floor() as usize;
900 let mut last = (viewport.max.y / pitch).ceil() as usize + 1;
901 if last > rows {
902 let span = last.saturating_sub(first);
903 last = rows;
904 first = rows.saturating_sub(span);
905 }
906 let top = ui.max_rect().top();
907 let rect = Rect::from_x_y_ranges(
908 ui.max_rect().x_range(),
909 top + first as f32 * pitch..=top + last as f32 * pitch,
910 );
911 ui.scope_builder(UiBuilder::new().max_rect(rect), |ui| {
912 ui.skip_ahead_auto_ids(first);
914 add(ui, first..last)
915 })
916 .inner
917 })
918 }
919
920 fn scroll_area_contained<R>(
921 &mut self,
922 area: ScrollArea,
923 add: impl FnOnce(&mut Ui) -> R,
924 ) -> ScrollAreaOutput<R> {
925 let out = self.scroll_area(area, add);
926 contain_wheel(self, &out);
927 out
928 }
929
930 fn drag_cursor<'a>(
931 &self,
932 response: &'a Response,
933 kind: crate::pointer::DragKind,
934 ) -> crate::pointer::DragCursorFor<'a> {
935 crate::pointer::drag_cursor(response, kind)
936 }
937
938 fn row<R>(&mut self, row: Row, add: impl FnOnce(&mut Cells<'_>) -> R) -> InnerResponse<R> {
939 layout::show(self, row.0, add)
940 }
941
942 fn grid<R>(&mut self, grid: Grid, add: impl FnOnce(&mut Cells<'_>) -> R) -> InnerResponse<R> {
943 layout::show(self, grid.0, add)
944 }
945
946 fn flow<R>(
947 &mut self,
948 flow: Flow,
949 add: impl FnOnce(&mut FlowCells<'_>) -> R,
950 ) -> InnerResponse<R> {
951 layout::show_flow(self, flow, add)
952 }
953}
954
955#[cfg(test)]
956mod tests {
957 use super::*;
958 use crate::theme::{self, ThemeSpec};
959
960 fn ui_pop_methods() -> Vec<&'static str> {
962 let source = include_str!("ui.rs");
963 let start = source.find("pub trait UiPop").expect("the trait");
964 let end = start + source[start..].find("\n}\n").expect("its end");
965 source[start..end]
966 .lines()
967 .filter_map(|line| line.trim_start().strip_prefix("fn "))
968 .map(|rest| {
969 let len = rest
970 .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
971 .unwrap_or(rest.len());
972 &rest[..len]
973 })
974 .collect()
975 }
976
977 #[test]
978 fn no_ui_pop_method_is_shadowed_by_an_inherent_ui_method() {
979 let names = ui_pop_methods();
980 assert!(names.contains(&"strong_text") && names.contains(&"grid"));
981 let shadowed: Vec<_> = names
982 .iter()
983 .filter(|n| EGUI_UI_METHODS.contains(n) && !SHADOWED_DEPRECATED.contains(n))
984 .collect();
985 assert!(
986 shadowed.is_empty(),
987 "egui's `Ui` has inherent methods of these names, which `ui.name(..)` \
988 calls instead of `UiPop`'s: {shadowed:?}"
989 );
990 for name in SHADOWED_DEPRECATED {
991 assert!(names.contains(name), "`{name}` is no longer in the trait");
992 }
993 }
994
995 fn pass(ctx: &egui::Context, add: impl FnMut(&mut Ui)) {
996 let mut out = ctx.run_ui(egui::RawInput::default(), add);
997 out.textures_delta.clear();
998 }
999
1000 #[test]
1001 fn a_popover_surface_in_an_app_placed_area_is_the_kits_popover() {
1002 let ctx = egui::Context::default();
1003 theme::install(&ctx, &ThemeSpec::new("pop-dark"));
1004 let kit = Kit::of(&ctx);
1005 let fill = kit.popover.style(State::REST).fill;
1006 assert_ne!(fill, egui::Color32::TRANSPARENT);
1007 let area = egui::Id::unique("test.notice");
1008 let mut shown = None;
1009 let mut frame = |ctx: &egui::Context, time: f64| {
1010 let input = egui::RawInput {
1011 time: Some(time),
1012 ..Default::default()
1013 };
1014 let mut out = ctx.run_ui(input, |ui| {
1015 egui::Area::new(area)
1016 .order(egui::Order::Foreground)
1017 .fixed_pos(egui::pos2(40.0, 40.0))
1018 .show(ui.ctx(), |ui| {
1019 shown = Some(ui.popover(|ui| ui.label("A notice")).response.rect);
1020 });
1021 });
1022 out.textures_delta.clear();
1023 out
1024 };
1025 frame(&ctx, 0.0);
1027 frame(&ctx, 1.0);
1028 let out = frame(&ctx, 2.0);
1029 let rect = shown.expect("drawn");
1030 assert_eq!(rect.min, egui::pos2(40.0, 40.0));
1032 fn rects(shape: &egui::Shape, into: &mut Vec<(Rect, egui::Color32)>) {
1034 match shape {
1035 egui::Shape::Rect(r) => into.push((r.rect, r.fill)),
1036 egui::Shape::Vec(v) => v.iter().for_each(|s| rects(s, into)),
1037 _ => {}
1038 }
1039 }
1040 let mut all = Vec::new();
1041 out.shapes.iter().for_each(|c| rects(&c.shape, &mut all));
1042 let boxed = all.iter().any(|(r, f)| {
1043 *f == fill && rect.expand(1.0).contains_rect(*r) && r.contains_rect(rect.shrink(2.0))
1044 });
1045 assert!(
1046 boxed,
1047 "the popover's box ({fill:?}) under the notice at {rect:?}: {all:?}"
1048 );
1049 }
1050
1051 #[test]
1052 fn spacing_by_intent_reads_the_density() {
1053 let ctx = egui::Context::default();
1054 let t = theme::install(&ctx, &ThemeSpec::new("pop-dark"));
1055 assert_eq!(Space::Group.points(&t), t.space.m);
1056 assert_eq!(Space::Page.points(&t), t.space.xl);
1057 let compact = theme::install(
1058 &ctx,
1059 &ThemeSpec::new("pop-dark").density(theme::Density::Compact),
1060 );
1061 assert!(Space::Group.points(&compact) < Space::Group.points(&t));
1062 let mut moved = 0.0;
1063 pass(&ctx, |ui| {
1064 let before = ui.cursor().top();
1065 ui.space_role(Space::Section);
1066 moved = ui.cursor().top() - before;
1067 });
1068 assert_eq!(moved, compact.space.section);
1069 }
1070
1071 #[test]
1072 fn a_role_s_weight_waits_for_the_theme_fonts() {
1073 let ctx = egui::Context::default();
1074 pass(&ctx, |ui| {
1076 assert_eq!(role_family(ui.ctx(), Weight::SEMIBOLD), None);
1077 ui.text_role(TextRole::Title, "Title");
1078 });
1079 let t = theme::install(&ctx, &ThemeSpec::new("pop-dark"));
1080 for _ in 0..2 {
1081 pass(&ctx, |ui| {
1082 ui.section_title("Section");
1083 ui.muted("Muted");
1084 ui.meta("Meta");
1085 ui.text_role(TextRole::Title, "Title");
1086 });
1087 }
1088 assert_eq!(
1089 role_family(&ctx, t.text_role.section.weight),
1090 Some(fonts::family(Role::Ui, t.text_role.section.weight))
1091 );
1092 assert_eq!(role_family(&ctx, t.text_role.muted.weight), None);
1094 }
1095
1096 #[test]
1097 fn a_toned_button_and_card_show_their_content() {
1098 let ctx = egui::Context::default();
1099 theme::install(&ctx, &ThemeSpec::new("pop-light"));
1100 pass(&ctx, |ui| {
1101 let fill = ui.visuals().widgets.inactive.weak_bg_fill;
1102 for tone in [Tone::Neutral, Tone::Accent, Tone::Danger, Tone::Muted] {
1103 let r = ui.button_tone(tone, "Go");
1104 assert!(r.rect.width() > 0.0);
1105 }
1106 assert_eq!(ui.visuals().widgets.inactive.weak_bg_fill, fill);
1108 let inner = ui.card(Tone::Warning, |ui| ui.label("Inside").rect);
1109 assert!(inner.response.rect.contains_rect(inner.inner));
1110 });
1111 }
1112}