1use std::collections::BTreeMap;
30use std::sync::Arc;
31
32use egui::epaint::{Shadow, Shape};
33use egui::layers::ShapeIdx;
34use egui::{
35 Color32, Context, Frame, Galley, InnerResponse, Margin, Painter, Pos2, Rect, Response, Stroke,
36 Ui, Vec2,
37};
38use egui_pop_tokens::Value;
39
40use crate::state::Slot;
41use crate::theme::Tokens;
42
43pub(crate) mod dock;
44mod drag;
45mod glyph;
46mod paint;
47mod scoped;
48mod scroll;
49mod shapes;
50mod source;
51mod tone;
52mod window;
53
54pub use dock::{AreaLineKit, AreaLineState, FoldGuide};
55pub use drag::DragCursorKit;
56pub use glyph::{Glyph, Glyphs};
57
58pub use paint::{Corners, label_rect, paint_box, paint_indicator, paint_label, paint_ring};
59pub use scoped::{ScopedKit, ScopedVisuals, Stock};
60pub use scroll::{Placement, ScrollBarKit, Visibility};
61pub use source::KitSource;
62pub use tone::Tone;
63pub use window::{
64 ButtonsHover, ButtonsSide, CountPlacement, SectionsKit, WindowCorners, WindowEdgeKit, WindowKit,
65};
66
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
70pub struct State(u8);
71
72impl State {
73 pub const REST: State = State(0);
74 pub const HOVER: State = State(1);
75 pub const ACTIVE: State = State(1 << 1);
76 pub const FOCUS: State = State(1 << 2);
77 pub const SELECTED: State = State(1 << 3);
78 pub const DISABLED: State = State(1 << 4);
79
80 pub const ORDER: [(State, &'static str); 5] = [
84 (State::SELECTED, "selected"),
85 (State::HOVER, "hover"),
86 (State::FOCUS, "focus"),
87 (State::ACTIVE, "active"),
88 (State::DISABLED, "disabled"),
89 ];
90
91 pub fn contains(self, other: State) -> bool {
92 self.0 & other.0 == other.0
93 }
94
95 pub fn from_response(r: &Response) -> State {
107 if r.has_focus() {
108 crate::ring::own(&r.ctx, r.id);
109 }
110 let focus = r.has_focus()
111 && (crate::focus::ring_shown(&r.ctx)
112 || egui::TextEdit::load_state(&r.ctx, r.id).is_some());
113 State::REST
114 .with(State::HOVER, r.hovered())
115 .with(State::ACTIVE, r.is_pointer_button_down_on())
116 .with(State::FOCUS, focus)
117 .with(State::DISABLED, !r.enabled())
118 }
119
120 #[must_use]
124 pub fn with(self, other: State, on: bool) -> State {
125 if on {
126 State(self.0 | other.0)
127 } else {
128 self.without(other)
129 }
130 }
131
132 #[must_use]
134 pub fn without(self, other: State) -> State {
135 State(self.0 & !other.0)
136 }
137}
138
139impl std::ops::BitOr for State {
140 type Output = State;
141 fn bitor(self, rhs: State) -> State {
142 State(self.0 | rhs.0)
143 }
144}
145
146#[derive(Clone, Copy, Debug, PartialEq, Eq)]
148pub enum Side {
149 Top,
150 Bottom,
151 Left,
152 Right,
153}
154
155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
157pub enum Align {
158 Start,
160 Centre,
163 End,
165}
166
167impl Align {
168 fn parse(s: &str) -> Option<Align> {
169 Some(match s {
170 "start" => Align::Start,
171 "centre" | "center" => Align::Centre,
172 "end" => Align::End,
173 _ => return None,
174 })
175 }
176}
177
178impl Side {
179 fn parse(s: &str) -> Option<Side> {
180 Some(match s {
181 "top" => Side::Top,
182 "bottom" => Side::Bottom,
183 "left" => Side::Left,
184 "right" => Side::Right,
185 _ => return None,
186 })
187 }
188}
189
190#[derive(Clone, Copy, Debug, Default, PartialEq)]
192pub struct BoxStyle {
193 pub fill: Color32,
194 pub border_color: Color32,
195 pub border_width: f32,
197 pub radius: f32,
198 pub text: Color32,
199 pub indicator_color: Color32,
202 pub indicator_size: f32,
203 pub ring_color: Color32,
207 pub ring_width: f32,
208 pub ring_offset: f32,
209}
210
211#[derive(Clone, Copy, Debug, Default, PartialEq)]
213struct BoxPatch {
214 fill: Option<Color32>,
215 border_color: Option<Color32>,
216 border_width: Option<f32>,
217 radius: Option<f32>,
218 text: Option<Color32>,
219 indicator_color: Option<Color32>,
220 indicator_size: Option<f32>,
221 ring_color: Option<Color32>,
222 ring_width: Option<f32>,
223 ring_offset: Option<f32>,
224}
225
226impl BoxPatch {
227 fn read(t: &Tokens, prefix: &str) -> BoxPatch {
228 let r = t.resolved();
229 let c = |term: &str| t.color(&format!("{prefix}.{term}"));
230 let d = |term: &str| r.dimension(&format!("{prefix}.{term}"));
231 BoxPatch {
232 fill: c("fill"),
233 border_color: c("border-color"),
234 border_width: d("border-width"),
235 radius: d("radius"),
236 text: c("text"),
237 indicator_color: c("indicator-color"),
238 indicator_size: d("indicator-size"),
239 ring_color: c("ring-color"),
240 ring_width: d("ring-width"),
241 ring_offset: d("ring-offset"),
242 }
243 }
244
245 fn apply(&self, b: &mut BoxStyle) {
246 let BoxPatch {
247 fill,
248 border_color,
249 border_width,
250 radius,
251 text,
252 indicator_color,
253 indicator_size,
254 ring_color,
255 ring_width,
256 ring_offset,
257 } = *self;
258 b.fill = fill.unwrap_or(b.fill);
259 b.border_color = border_color.unwrap_or(b.border_color);
260 b.border_width = border_width.unwrap_or(b.border_width);
261 b.radius = radius.unwrap_or(b.radius);
262 b.text = text.unwrap_or(b.text);
263 b.indicator_color = indicator_color.unwrap_or(b.indicator_color);
264 b.indicator_size = indicator_size.unwrap_or(b.indicator_size);
265 b.ring_color = ring_color.unwrap_or(b.ring_color);
266 b.ring_width = ring_width.unwrap_or(b.ring_width);
267 b.ring_offset = ring_offset.unwrap_or(b.ring_offset);
268 }
269}
270
271#[derive(Clone, Debug, PartialEq)]
275pub struct States([BoxStyle; 32], Option<Box<tone::Tones>>);
276
277impl States {
278 fn compile(t: &Tokens, component: &str) -> States {
279 let mut rest = BoxStyle::default();
280 BoxPatch::read(t, &format!("{component}.rest")).apply(&mut rest);
281 let patches: Vec<(State, BoxPatch)> = State::ORDER
282 .iter()
283 .map(|(s, name)| (*s, BoxPatch::read(t, &format!("{component}.{name}"))))
284 .collect();
285 let boxes = std::array::from_fn(|bits| {
286 let state = State(bits as u8);
287 let mut b = rest;
288 for (s, patch) in &patches {
289 if state.contains(*s) {
290 patch.apply(&mut b);
291 }
292 }
293 b
294 });
295 let tones = tone::compile(t, component, &rest, &patches);
296 States(boxes, tones)
297 }
298
299 pub fn get(&self, state: State) -> &BoxStyle {
301 tone::get(&self.0, self.1.as_deref(), state)
302 }
303
304 pub fn toned(&self) -> bool {
306 self.1.is_some()
307 }
308
309 pub fn widest_border(&self) -> f32 {
315 let tones = self.1.iter().flat_map(|t| t.iter().flatten());
316 self.0
317 .iter()
318 .chain(tones)
319 .map(|b| b.border_width)
320 .fold(0.0, f32::max)
321 }
322}
323
324#[derive(Debug)]
326pub struct Part<'a> {
327 pub rect: Rect,
328 pub room: Rect,
331 pub state: State,
332 pub label: Option<&'a Arc<Galley>>,
335}
336
337#[allow(missing_debug_implementations, reason = "egui's Painter has no Debug")]
339pub struct KitCx<'a> {
340 pub painter: &'a Painter,
341 pub ppp: f32,
343}
344
345pub trait Primitive<D>: Send + Sync {
348 fn measure(&self, data: &D, label: Vec2) -> Vec2;
350 fn paint(&self, cx: &KitCx<'_>, data: &D, part: &Part<'_>);
352 fn paint_label(&self, cx: &KitCx<'_>, data: &D, part: &Part<'_>);
354 fn hit(&self, _data: &D, rect: Rect, pos: Pos2) -> bool {
356 rect.contains(pos)
357 }
358}
359
360#[derive(Clone, Debug, PartialEq)]
363pub struct ComponentKit {
364 pub states: States,
365 pub padding_x: f32,
367 pub padding_y: f32,
370 pub height: f32,
372 pub width: f32,
374 pub font_size: f32,
377 pub offset: f32,
380 pub indicator_side: Side,
381 pub align: Align,
382 pub opacity: f32,
385 pub shadow: Shadow,
389}
390
391impl ComponentKit {
392 fn compile(t: &Tokens, component: &str, problems: &mut Vec<String>) -> ComponentKit {
393 let r = t.resolved();
394 let side = string(t, &format!("{component}.indicator-side"));
395 let indicator_side = match side.as_deref().map(Side::parse) {
396 None => Side::Bottom,
397 Some(Some(s)) => s,
398 Some(None) => {
399 problems.push(format!(
400 "{component}.indicator-side: `{}` is not top, bottom, left or right",
401 side.unwrap_or_default()
402 ));
403 Side::Bottom
404 }
405 };
406 let align_asked = string(t, &format!("{component}.align"));
407 let align = match align_asked.as_deref().map(Align::parse) {
408 None => Align::Centre,
409 Some(Some(a)) => a,
410 Some(None) => {
411 problems.push(format!(
412 "{component}.align: `{}` is not start, centre or end",
413 align_asked.unwrap_or_default()
414 ));
415 Align::Centre
416 }
417 };
418 ComponentKit {
419 states: States::compile(t, component),
420 width: r.dimension(&format!("{component}.width")).unwrap_or(0.0),
421 font_size: r
422 .dimension(&format!("{component}.font-size"))
423 .unwrap_or(0.0)
424 .max(0.0),
425 offset: r.dimension(&format!("{component}.offset")).unwrap_or(0.0),
426 align,
427 padding_x: r
428 .dimension(&format!("{component}.padding-x"))
429 .unwrap_or(0.0),
430 padding_y: r
431 .dimension(&format!("{component}.padding-y"))
432 .unwrap_or(0.0),
433 height: r.dimension(&format!("{component}.height")).unwrap_or(0.0),
434 indicator_side,
435 opacity: r
436 .dimension(&format!("{component}.opacity"))
437 .map_or(1.0, |o| o.clamp(0.0, 1.0)),
438 shadow: crate::theme::shadow(r, &format!("{component}.shadow-"))
439 .unwrap_or(Shadow::NONE),
440 }
441 }
442}
443
444#[derive(Clone)]
446pub struct Component {
447 pub name: String,
449 pub data: ComponentKit,
450 pub shape: String,
452 handler: Arc<dyn Primitive<ComponentKit>>,
453 egui_frame: bool,
456}
457
458impl Component {
459 pub fn measure(&self, label: Vec2) -> Vec2 {
460 self.handler.measure(&self.data, label)
461 }
462
463 pub fn paint(&self, cx: &KitCx<'_>, part: &Part<'_>) {
465 crate::inspect::painted(
466 cx.painter,
467 &self.name,
468 &self.shape,
469 part.state,
470 part.rect,
471 self.style(part.state),
472 );
473 self.handler.paint(cx, &self.data, part);
474 }
475
476 pub fn paint_label(&self, cx: &KitCx<'_>, part: &Part<'_>) {
478 self.handler.paint_label(cx, &self.data, part);
479 }
480
481 pub fn paint_part(&self, cx: &KitCx<'_>, part: &Part<'_>) {
484 self.paint(cx, part);
485 self.paint_label(cx, part);
486 }
487
488 pub fn label_rect(&self, part: &Part<'_>, size: Vec2) -> Rect {
491 label_rect(&self.data, part, size)
492 }
493
494 pub fn border_room(&self, ppp: f32) -> f32 {
500 let w = self.data.states.widest_border();
501 if w > 0.0 {
502 crate::scale::snap(w, ppp)
503 } else {
504 0.0
505 }
506 }
507
508 pub fn style(&self, state: State) -> &BoxStyle {
510 self.data.states.get(state)
511 }
512
513 pub fn style_toned(&self, tone: Tone, state: State) -> &BoxStyle {
515 self.data.states.get(state.toned(tone))
516 }
517
518 pub fn hit(&self, rect: Rect, pos: Pos2) -> bool {
519 self.handler.hit(&self.data, rect, pos)
520 }
521
522 pub fn frame(&self, state: State, ppp: f32) -> Frame {
534 let b = self.style(state);
535 let m = |p: f32| p.round().clamp(-128.0, 127.0) as i8;
536 let stroke = if b.border_width > 0.0 {
537 Stroke::new(crate::scale::snap(b.border_width, ppp), b.border_color)
538 } else {
539 Stroke::NONE
540 };
541 Frame::new()
542 .fill(b.fill)
543 .stroke(stroke)
544 .corner_radius(b.radius)
545 .inner_margin(Margin::symmetric(
546 m(self.data.padding_x),
547 m(self.data.padding_y),
548 ))
549 }
550
551 pub fn show<R>(
565 &self,
566 ui: &mut Ui,
567 state: State,
568 shadow: Shadow,
569 add: impl FnOnce(&mut Ui) -> R,
570 ) -> InnerResponse<R> {
571 let ppp = ui.ctx().pixels_per_point();
572 let b = *self.style(state);
573 let room = self.border_room(ppp);
574 let own = if b.border_width > 0.0 {
575 crate::scale::snap(b.border_width, ppp)
576 } else {
577 0.0
578 };
579 if self.egui_frame && own == room {
580 let r = self.frame(state, ppp).shadow(shadow).show(ui, add);
581 let cx = KitCx {
582 painter: ui.painter(),
583 ppp,
584 };
585 paint_ring(&cx, r.response.rect, &b, Corners::All);
586 crate::inspect::painted(
587 cx.painter,
588 &self.name,
589 &self.shape,
590 state,
591 r.response.rect,
592 &b,
593 );
594 return r;
595 }
596 let slot = ui.painter().add(Shape::Noop);
597 let r = self
600 .frame(state, ppp)
601 .fill(Color32::TRANSPARENT)
602 .stroke(Stroke::new(room, Color32::TRANSPARENT))
603 .show(ui, add);
604 let rect = r.response.rect;
605 let shadow = (shadow != Shadow::NONE).then(|| Shape::from(shadow.as_shape(rect, b.radius)));
606 self.paint_under(
607 ui,
608 slot,
609 &Part {
610 rect,
611 room: rect,
612 state,
613 label: None,
614 },
615 shadow,
616 );
617 r
618 }
619
620 pub fn paint_under(&self, ui: &Ui, slot: ShapeIdx, part: &Part<'_>, first: Option<Shape>) {
628 let layer = ui.layer_id();
629 let start = ui.ctx().graphics_mut(|g| g.entry(layer).next_idx());
630 let mut painter = ui.painter().clone();
631 painter.set_opacity(1.0);
632 self.paint(
633 &KitCx {
634 painter: &painter,
635 ppp: ui.ctx().pixels_per_point(),
636 },
637 part,
638 );
639 let mut shapes: Vec<Shape> = first.into_iter().collect();
640 ui.ctx().graphics_mut(|g| {
641 let list = g.entry(layer);
642 let end = list.next_idx().0;
643 for i in start.0..end {
644 list.mutate_shape(ShapeIdx(i), |c| {
645 shapes.push(std::mem::replace(&mut c.shape, Shape::Noop));
646 });
647 }
648 });
649 ui.painter().set(slot, Shape::Vec(shapes));
650 }
651}
652
653impl std::fmt::Debug for Component {
654 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
655 f.debug_struct("Component")
656 .field("name", &self.name)
657 .field("shape", &self.shape)
658 .field("data", &self.data)
659 .finish_non_exhaustive()
660 }
661}
662
663macro_rules! components {
668 ($($(#[$doc:meta])* $field:ident: $name:literal => $default:literal,)*) => {
669 #[derive(Clone, Debug)]
671 #[non_exhaustive]
672 pub struct Kit {
673 $($(#[$doc])* pub $field: Component,)*
674 pub glyphs: Glyphs,
676 pub window: WindowKit,
679 pub window_edge: WindowEdgeKit,
682 pub sections: SectionsKit,
684 pub drag_cursors: DragCursorKit,
687 pub area_line: AreaLineKit,
690 pub scroll: ScrollBarKit,
695 pub scoped: ScopedKit,
698 pub problems: Vec<String>,
701 }
702
703 pub const COMPONENTS: &[(&str, &str)] = &[$(($name, $default),)*];
706
707 impl Kit {
708 pub fn components(&self) -> impl Iterator<Item = &Component> {
711 [$(&self.$field,)*].into_iter()
712 }
713
714 fn compile_components(
715 mut component: impl FnMut(&str, &str) -> Component,
716 glyphs: Glyphs,
717 problems: Vec<String>,
718 ) -> Kit {
719 Kit {
720 $($field: component($name, $default),)*
721 glyphs,
722 window: WindowKit::default(),
723 window_edge: WindowEdgeKit::default(),
724 sections: SectionsKit::default(),
725 drag_cursors: DragCursorKit::default(),
726 scroll: ScrollBarKit::default(),
727 area_line: AreaLineKit::default(),
728 scoped: ScopedKit::default(),
729 problems,
730 }
731 }
732 }
733 };
734}
735
736components! {
737 list_row: "list-row" => "box",
740 list_item: "list-item" => "box",
745 list_guide: "list-guide" => "outline",
747 list_view: "list-view" => "plain",
750 menu_item: "menu-item" => "box",
754 menu_item_gutter: "menu-item-gutter" => "box",
759 meter: "meter" => "track",
761 meter_tick: "meter-tick" => "tick",
763 progress_bar: "progress-bar" => "track",
765 progress_caption: "progress-caption" => "plain",
767 progress_fill: "progress-fill" => "span",
770 progress_line: "progress-line" => "track",
772 progress_ring: "progress-ring" => "plain",
775 side_area: "side-area" => "plain",
778 dock_area: "dock-area" => "plain",
783 skeleton: "skeleton" => "box",
785 skeleton_shimmer: "skeleton-shimmer" => "box",
787 slider: "slider" => "box",
791 slider_fill: "slider-fill" => "track",
794 slider_thumb: "slider-thumb" => "tick",
796 slider_toggle: "slider-toggle" => "box",
799 slider_value: "slider-value" => "plain",
801 spinner: "spinner" => "plain",
803 splitter: "splitter" => "plain",
807 status_indicator: "status-indicator" => "plain",
810 activity_bar_item: "activity-bar-item" => "box",
813 area_grip: "area-grip" => "box",
816 area_strip: "area-strip" => "plain",
818 assist_card: "assist-card" => "card",
821 button: "button" => "box",
826 card: "card" => "card",
829 checkbox: "checkbox" => "box",
832 combo_arrow: "combo-arrow" => "plain",
835 combo_box: "combo-box" => "scoped",
839 command_button: "command-button" => "box",
842 command_palette_row: "command-palette-row" => "box",
846 backdrop: "backdrop" => "plain",
849 band_icon_button: "band-icon-button" => "box",
853 compare_pane: "compare-pane" => "box",
856 dialog: "dialog" => "card",
858 dialog_grip: "dialog-grip" => "plain",
862 dialog_header: "dialog-header" => "plain",
865 dock_preview: "dock-preview" => "box",
868 dock_body: "dock-body" => "plain",
873 dock_separator: "dock-separator" => "plain",
876 drag_ghost: "drag-ghost" => "box",
882 drag_ghost_count: "drag-ghost-count" => "pill",
884 drag_verdict: "drag-verdict" => "pill",
887 drop_target: "drop-target" => "outline",
890 editor_frame: "editor-frame" => "card",
893 empty_state: "empty-state" => "card",
897 field: "field" => "box",
899 fault_card: "fault-card" => "card",
901 find_bar: "find-bar" => "card",
903 find_bar_button: "find-bar-button" => "box",
905 fullscreen_exit: "fullscreen-exit" => "card",
907 header_band: "header-band" => "band",
910 icon_button: "icon-button" => "box",
913 indicator_badge: "indicator-badge" => "pill",
915 indicator_button: "indicator-button" => "box",
919 indicator_dot: "indicator-dot" => "plain",
922 indicator_flag: "indicator-flag" => "plain",
924 indicator_outline: "indicator-outline" => "plain",
927 indicator_swatch: "indicator-swatch" => "box",
930 job_log: "job-log" => "card",
932 mark_toggle: "mark-toggle" => "box",
934 palette_window: "palette-window" => "card",
936 pill: "pill" => "pill",
938 plot: "plot" => "box",
942 plot_cursor: "plot-cursor" => "tick",
944 popover: "popover" => "card",
946 radio: "radio" => "pill",
949 rating_star: "rating-star" => "star",
955 rating_star_display: "rating-star-display" => "star",
958 readout: "readout" => "card",
960 scroll_bar: "scroll-bar" => "scoped",
965 search_field: "search-field" => "card",
968 section_band: "section-band" => "section",
972 section_count: "section-count" => "pill",
974 section_disclosure: "section-disclosure" => "plain",
978 selectable_row: "selectable-row" => "box",
982 switch: "switch" => "pill",
985 tab: "tab" => "box",
987 tab_bar: "tab-bar" => "plain",
989 tab_preview: "tab-preview" => "box",
992 table_header_cell: "table-header-cell" => "box",
995 table_row: "table-row" => "box",
1000 table_stripe: "table-stripe" => "plain",
1002 tag_chip: "tag-chip" => "pill",
1004 thumb_cell: "thumb-cell" => "box",
1007 thumb_layer: "thumb-layer" => "box",
1010 thumb_overlay_badge: "thumb-overlay-badge" => "box",
1012 thumbnail: "thumbnail" => "box",
1014 title_bar: "title-bar" => "plain",
1016 tree_drop_marker: "tree-drop-marker" => "outline",
1019 terminal_frame: "terminal-frame" => "card",
1022 tip_card: "tip-card" => "card",
1024 toast: "toast" => "card",
1027 tooltip: "tooltip" => "card",
1031 toggle_button: "toggle-button" => "scoped",
1035 toggle_chip: "toggle-chip" => "box",
1038 toolbar_button: "toolbar-button" => "box",
1042 viewport_focus: "viewport-focus" => "plain",
1044 viewport_label: "viewport-label" => "pill",
1048 window_button: "window-button" => "plain",
1052 window_close: "window-close" => "plain",
1054}
1055
1056type Handlers = BTreeMap<String, Arc<dyn Primitive<ComponentKit>>>;
1057
1058#[derive(Clone)]
1060pub struct Shapes(BTreeMap<String, Handlers>);
1061
1062impl Default for Shapes {
1063 fn default() -> Self {
1066 let mut shapes = Shapes(BTreeMap::new());
1067 for (component, _) in COMPONENTS {
1068 shapes.insert(component, "plain", Arc::new(shapes::Plain));
1069 }
1070 shapes::built_in(&mut shapes);
1071 shapes
1072 }
1073}
1074
1075impl Shapes {
1076 fn find(
1080 &self,
1081 t: &Tokens,
1082 component: &str,
1083 name: &str,
1084 ) -> Option<Arc<dyn Primitive<ComponentKit>>> {
1085 let mut at = component.to_string();
1086 let mut seen = Vec::new();
1087 loop {
1088 if let Some(h) = self.0.get(&at).and_then(|h| h.get(name)) {
1089 return Some(h.clone());
1090 }
1091 seen.push(at.clone());
1092 match string(t, &format!("{at}.{}", egui_pop_tokens::BASED_ON)) {
1093 Some(base) if !seen.contains(&base) => at = base,
1094 _ => return None,
1095 }
1096 }
1097 }
1098
1099 pub fn insert(
1101 &mut self,
1102 component: &str,
1103 name: &str,
1104 handler: Arc<dyn Primitive<ComponentKit>>,
1105 ) {
1106 self.0
1107 .entry(component.into())
1108 .or_default()
1109 .insert(name.into(), handler);
1110 }
1111}
1112
1113impl std::fmt::Debug for Shapes {
1114 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1115 let mut m = f.debug_map();
1116 for (c, h) in &self.0 {
1117 m.entry(c, &h.keys().collect::<Vec<_>>());
1118 }
1119 m.finish()
1120 }
1121}
1122
1123const SHAPES: Slot<Shapes> = Slot::opaque("core.kit.shapes");
1125const KIT: Slot<Kits> = Slot::opaque("core.kit");
1127
1128#[derive(Clone, Debug)]
1131pub struct Kits {
1132 pub dark: Arc<Kit>,
1133 pub light: Arc<Kit>,
1134}
1135
1136impl Kits {
1137 pub fn get(&self, theme: egui::Theme) -> &Arc<Kit> {
1139 match theme {
1140 egui::Theme::Dark => &self.dark,
1141 egui::Theme::Light => &self.light,
1142 }
1143 }
1144}
1145
1146pub fn register_shape(
1149 ctx: &Context,
1150 component: &str,
1151 name: &str,
1152 handler: Arc<dyn Primitive<ComponentKit>>,
1153) {
1154 SHAPES.update(ctx, |s| s.insert(component, name, handler));
1155}
1156
1157pub fn register_tab_shape(ctx: &Context, name: &str, handler: Arc<dyn Primitive<ComponentKit>>) {
1159 register_shape(ctx, "tab", name, handler);
1160}
1161
1162fn string(t: &Tokens, path: &str) -> Option<String> {
1163 match t.resolved().value(path) {
1164 Some(Value::Other(serde_json::Value::String(s))) => Some(s.clone()),
1165 _ => None,
1166 }
1167}
1168
1169impl Kit {
1170 pub fn compile(t: &Tokens, shapes: &Shapes) -> Kit {
1172 let mut problems = Vec::new();
1173 let component = |name: &str, default: &str| {
1174 let handlers = &shapes.0[name];
1175 let data = ComponentKit::compile(t, name, &mut problems);
1176 let asked = string(t, &format!("{name}.shape")).unwrap_or_else(|| default.into());
1177 let (shape, handler) = match shapes.find(t, name, &asked) {
1178 Some(h) => (asked, h),
1179 None => {
1180 problems.push(format!(
1181 "{name}.shape: no handler named `{asked}` (known: {}), `{default}` is drawn",
1182 handlers.keys().cloned().collect::<Vec<_>>().join(", ")
1183 ));
1184 (default.to_string(), handlers[default].clone())
1185 }
1186 };
1187 let egui_frame = Arc::ptr_eq(&handler, &shapes::CARD);
1188 Component {
1189 name: name.to_string(),
1190 data,
1191 shape,
1192 handler,
1193 egui_frame,
1194 }
1195 };
1196 let mut kit = Kit::compile_components(component, Glyphs::default(), Vec::new());
1197 kit.glyphs = Glyphs::compile(t, &mut problems);
1198 kit.window = WindowKit::compile(t, &mut problems);
1199 kit.window_edge = WindowEdgeKit::compile(t);
1200 kit.sections = SectionsKit::compile(t, &mut problems);
1201 kit.drag_cursors = DragCursorKit::compile(t, &mut problems);
1202 kit.area_line = dock::AreaLineKit::compile(t, &kit.side_area);
1203 kit.scroll = ScrollBarKit::compile(t, &kit.scroll_bar.data, &mut problems);
1204 kit.scoped = ScopedKit::compile(&kit);
1205 problems.extend(egui_losses(t, &kit));
1206 problems.extend(scoped::losses(&kit));
1207 problems.extend(scroll::losses(t, &kit));
1208 kit.problems = problems;
1209 kit
1210 }
1211
1212 pub fn scope<R>(
1219 &self,
1220 ui: &mut Ui,
1221 stock: Stock,
1222 tone: Tone,
1223 add: impl FnOnce(&mut Ui) -> R,
1224 ) -> InnerResponse<R> {
1225 let visuals = self.scoped.get(stock, tone);
1226 let ppp = ui.ctx().pixels_per_point();
1227 ui.scope(|ui| {
1228 let enabled = ui.is_enabled();
1229 visuals.apply(ui.visuals_mut(), enabled, ppp);
1230 add(ui)
1231 })
1232 }
1233
1234 pub fn glyph(&self, glyph: Glyph) -> crate::icon::Icon {
1236 self.glyphs.get(glyph)
1237 }
1238
1239 pub fn menu_gutter(&self, t: &Tokens) -> f32 {
1243 let width = self.menu_item_gutter.data.width;
1244 if width > 0.0 {
1245 width
1246 } else {
1247 t.size.icon_inline + 2.0 * t.space.s
1248 }
1249 }
1250
1251 pub fn of(ctx: &Context) -> Arc<Kit> {
1261 if let Some(scoped) = crate::theme::ScopedTheme::current(ctx) {
1262 return scoped.kit().clone();
1263 }
1264 let theme = ctx.theme();
1265 if let Some(k) = KIT.get(ctx) {
1266 return k.get(theme).clone();
1267 }
1268 let v = crate::theme::variants(ctx);
1269 install_variants(ctx, &v.dark, &v.light).get(theme).clone()
1270 }
1271}
1272
1273fn egui_losses(t: &Tokens, kit: &Kit) -> Vec<String> {
1278 let mut lost = Vec::new();
1279 for (state, name) in [
1280 (State::REST, "rest"),
1281 (State::HOVER, "hover"),
1282 (State::ACTIVE, "active"),
1283 (State::SELECTED, "selected"),
1284 ] {
1285 let b = kit.button.style(state);
1286 if b.indicator_size > 0.0 && b.indicator_color.a() > 0 {
1287 lost.push(format!(
1288 "button.{name}: egui's widgets draw no indicator (kept for egui-pop's own buttons)"
1289 ));
1290 }
1291 if b.ring_width > 0.0 && b.ring_color.a() > 0 {
1292 lost.push(format!(
1293 "button.{name}: egui's widgets draw no focus ring (kept for egui-pop's own buttons)"
1294 ));
1295 }
1296 }
1297 let (f, b) = (kit.field.style(State::REST), kit.button.style(State::REST));
1298 if (f.border_color, f.border_width, f.radius) != (b.border_color, b.border_width, b.radius) {
1299 lost.push(
1300 "field.rest: egui's text fields outside a `Field` scope take their outline from `button` (egui shares widget states)"
1301 .into(),
1302 );
1303 }
1304 if f.text != b.text {
1305 lost.push("field.rest.text: egui's text fields outside a `Field` scope take the button's text colour".into());
1306 }
1307 let side = kit.side_area.style(State::REST);
1310 if side.border_width > 0.0 && side.border_width != b.border_width {
1311 lost.push(format!(
1312 "side-area.rest.border-width: egui draws the separator line {} wide (the button's at rest); only 0 hides it",
1313 b.border_width
1314 ));
1315 }
1316 if side.border_width > 0.0 && side.border_color.a() > 0 && side.border_color != t.border.default
1317 {
1318 lost.push(
1319 "side-area.rest.border-color: egui draws the separator line in `border.default`".into(),
1320 );
1321 }
1322 lost
1323}
1324
1325pub fn install(ctx: &Context, tokens: &Tokens) -> Arc<Kit> {
1328 let kit = compile_logged(ctx, tokens);
1329 KIT.set(
1330 ctx,
1331 Kits {
1332 dark: kit.clone(),
1333 light: kit.clone(),
1334 },
1335 );
1336 kit
1337}
1338
1339pub fn install_variants(ctx: &Context, dark: &Arc<Tokens>, light: &Arc<Tokens>) -> Kits {
1343 let dark_kit = compile_logged(ctx, dark);
1344 let light_kit = if Arc::ptr_eq(dark, light) {
1345 dark_kit.clone()
1346 } else {
1347 compile_logged(ctx, light)
1348 };
1349 let kits = Kits {
1350 dark: dark_kit,
1351 light: light_kit,
1352 };
1353 KIT.set(ctx, kits.clone());
1354 kits
1355}
1356
1357pub(crate) fn compile_in(ctx: &Context, tokens: &Tokens) -> Arc<Kit> {
1360 compile_logged(ctx, tokens)
1361}
1362
1363fn compile_logged(ctx: &Context, tokens: &Tokens) -> Arc<Kit> {
1364 let shapes = SHAPES.get_or_default(ctx);
1365 let kit = Arc::new(Kit::compile(tokens, &shapes));
1366 for p in &kit.problems {
1367 log::warn!(target: "egui_pop", "kit: {p}");
1368 }
1369 kit
1370}
1371
1372#[cfg(test)]
1373mod tests {
1374 use super::*;
1375 use crate::icon::Icon;
1376 use egui::pos2;
1377 use egui_pop_tokens::{ThemeSpec, Themes};
1378
1379 fn tokens_with(json: &str) -> Tokens {
1380 let mut themes = Themes::default();
1381 themes.add_text("kit-test", json).expect("test theme reads");
1382 Tokens::new(themes.resolve(&ThemeSpec::new("kit-test")))
1383 }
1384
1385 #[test]
1386 fn with_sets_a_flag_when_on_and_clears_it_when_not() {
1387 let s = State::SELECTED | State::HOVER | State::FOCUS;
1388 let off = s.with(State::HOVER, false);
1389 assert!(!off.contains(State::HOVER), "cleared");
1390 assert!(off.contains(State::SELECTED) && off.contains(State::FOCUS));
1391 assert_eq!(off, s.without(State::HOVER));
1392 assert_eq!(off.with(State::HOVER, true), s, "set again");
1393 assert_eq!(State::REST.with(State::DISABLED, false), State::REST);
1394 }
1395
1396 #[test]
1397 fn the_default_kit_compiles_without_problems() {
1398 let kit = Kit::compile(&Tokens::default(), &Shapes::default());
1399 assert!(kit.problems.is_empty(), "{:?}", kit.problems);
1400 assert_eq!(kit.tab.shape, "box");
1401 assert!(kit.tab_bar.data.height > 0.0);
1402 }
1403
1404 #[test]
1405 fn shadows_come_from_tokens_with_egui_s_own_look_by_default() {
1406 let themes = Themes::default();
1407 for (name, dark) in [("pop-dark", true), ("pop-light", false)] {
1408 let t = Tokens::new(themes.resolve(&ThemeSpec::new(name)));
1409 let egui = if dark {
1410 egui::Visuals::dark()
1411 } else {
1412 egui::Visuals::light()
1413 };
1414 let v = crate::theme::visuals(&t);
1415 assert_eq!(v.window_shadow, egui.window_shadow, "{name}");
1416 assert_eq!(v.popup_shadow, egui.popup_shadow, "{name}");
1417 let kit = Kit::compile(&t, &Shapes::default());
1418 assert_eq!(kit.side_area.data.shadow, t.shadow.side, "{name}");
1419 assert_ne!(kit.side_area.data.shadow, Shadow::NONE, "{name}");
1420 assert_eq!(kit.tab.data.shadow, Shadow::NONE);
1422 }
1423 let t = tokens_with(
1424 r##"{
1425 "$extends": "pop-dark",
1426 "side-area": {
1427 "shadow-offset-x": {"$type": "dimension", "$value": {"value": 3, "unit": "px"}},
1428 "shadow-spread": {"$type": "dimension", "$value": {"value": -2, "unit": "px"}},
1429 "shadow-color": {"$type": "color", "$value": "#ff000080"}
1430 }
1431 }"##,
1432 );
1433 let s = Kit::compile(&t, &Shapes::default()).side_area.data.shadow;
1434 assert_eq!(s.offset, [3, 0]);
1435 assert_eq!(s.spread, 0, "egui's spread is never negative");
1436 assert_eq!(s.blur, 32);
1437 assert_eq!(s.color, Color32::from_rgba_unmultiplied(255, 0, 0, 128));
1438 }
1439
1440 #[test]
1441 fn the_area_line_s_states_come_from_tokens_else_from_egui() {
1442 use egui_stack::PartState;
1443 let style = egui::Style::default();
1444 let w = &style.visuals.widgets;
1445 let (hover, drag) = (PartState::HOVERED, PartState::DRAGGED);
1446 let kit = Kit::compile(&Tokens::default(), &Shapes::default());
1448 assert_eq!(kit.area_line, AreaLineKit::default());
1449 let s = |kit: &Kit, f| kit.area_line_stroke(&style, f, 1.0);
1450 assert_eq!(s(&kit, hover), Some(w.hovered.fg_stroke));
1451 assert_eq!(s(&kit, PartState::FOCUSED), Some(w.hovered.fg_stroke));
1452 assert_eq!(s(&kit, drag), Some(w.active.fg_stroke));
1453 assert_eq!(s(&kit, PartState::NONE), Some(w.noninteractive.bg_stroke));
1454 let t = tokens_with(
1456 r##"{
1457 "$extends": "pop-dark",
1458 "side-area": {
1459 "hover": {"border-width": {"$type": "dimension", "$value": {"value": 0, "unit": "px"}}},
1460 "active": {"border-width": {"$type": "dimension", "$value": {"value": 0, "unit": "px"}}}
1461 }
1462 }"##,
1463 );
1464 let kit = Kit::compile(&t, &Shapes::default());
1465 assert!(kit.problems.is_empty(), "{:?}", kit.problems);
1466 assert_eq!(s(&kit, hover), None);
1467 assert_eq!(s(&kit, drag), None);
1468 assert_eq!(
1469 s(&kit, PartState::NONE),
1470 Some(w.noninteractive.bg_stroke),
1471 "the line at rest is unchanged"
1472 );
1473 let t = tokens_with(
1475 r##"{
1476 "$extends": "pop-dark",
1477 "side-area": {
1478 "hover": {"border-color": {"$type": "color", "$value": "#ff0000"}},
1479 "active": {"border-width": {"$type": "dimension", "$value": {"value": 3, "unit": "px"}}}
1480 }
1481 }"##,
1482 );
1483 let kit = Kit::compile(&t, &Shapes::default());
1484 assert_eq!(s(&kit, hover), Some(Stroke::new(1.0, Color32::RED)));
1485 assert_eq!(
1486 s(&kit, drag),
1487 Some(Stroke::new(3.0, w.active.fg_stroke.color))
1488 );
1489 }
1490
1491 #[test]
1492 fn the_fold_guide_comes_from_tokens_else_from_egui_stack() {
1493 let default = Stroke::new(1.0, Color32::BLUE);
1494 let kit = Kit::compile(&Tokens::default(), &Shapes::default());
1495 assert_eq!(kit.fold_guide_stroke(default, 1.0), Some(default));
1496 let fold = |body: &str| {
1497 let t = tokens_with(&format!(
1498 r##"{{"$extends": "pop-dark", "side-area": {{"fold": {{{body}}}}}}}"##
1499 ));
1500 let kit = Kit::compile(&t, &Shapes::default());
1501 assert!(kit.problems.is_empty(), "{:?}", kit.problems);
1502 kit.fold_guide_stroke(default, 1.0)
1503 };
1504 let width = |w: u32| {
1505 format!(
1506 r#""border-width": {{"$type": "dimension", "$value": {{"value": {w}, "unit": "px"}}}}"#
1507 )
1508 };
1509 let red = r##""border-color": {"$type": "color", "$value": "#ff0000"}"##;
1510 assert_eq!(fold(&width(0)), None, "width 0: no guide");
1511 assert_eq!(
1512 fold(red),
1513 Some(Stroke::new(1.0, Color32::RED)),
1514 "a colour alone keeps the width"
1515 );
1516 assert_eq!(
1517 fold(&width(3)),
1518 Some(Stroke::new(3.0, Color32::BLUE)),
1519 "a width alone keeps the colour"
1520 );
1521 assert_eq!(
1522 fold(&format!("{}, {red}", width(2))),
1523 Some(Stroke::new(2.0, Color32::RED))
1524 );
1525 }
1526
1527 #[test]
1528 fn every_built_in_theme_compiles_its_kit() {
1529 let themes = Themes::default();
1530 for name in themes.names() {
1531 let t = Tokens::new(themes.resolve(&ThemeSpec::new(name)));
1532 let kit = Kit::compile(&t, &Shapes::default());
1533 assert!(kit.problems.is_empty(), "{name}: {:?}", kit.problems);
1534 }
1535 }
1536
1537 #[test]
1538 fn states_merge_in_order_and_only_what_they_give() {
1539 let t = tokens_with(
1540 r##"
1541 $extends: "pop-dark"
1542 tab:
1543 rest:
1544 fill: {$type: "color", $value: "#101010"}
1545 text: {$type: "color", $value: "#808080"}
1546 selected:
1547 text: {$type: "color", $value: "#ffffff"}
1548 hover:
1549 fill: {$type: "color", $value: "#202020"}
1550 "##,
1551 );
1552 let kit = Kit::compile(&t, &Shapes::default());
1553 let s = &kit.tab.data.states;
1554 let hex = |c: Color32| format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b());
1555 assert_eq!(hex(s.get(State::REST).fill), "#101010");
1556 assert_eq!(hex(s.get(State::SELECTED).text), "#ffffff");
1557 assert_eq!(s.get(State::SELECTED).radius, s.get(State::REST).radius);
1559 let both = s.get(State::SELECTED | State::HOVER);
1562 assert_eq!(hex(both.fill), "#202020");
1563 assert_eq!(both.text, s.get(State::HOVER).text);
1564 }
1565
1566 #[test]
1567 fn a_label_goes_where_align_says_inside_the_room() {
1568 let t = tokens_with(
1569 r#"
1570 $extends: "pop-dark"
1571 title-bar:
1572 align: {$type: "string", $value: "start"}
1573 "#,
1574 );
1575 let kit = Kit::compile(&t, &Shapes::default());
1576 assert_eq!(kit.title_bar.data.align, Align::Start);
1577 let bar = Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 32.0));
1578 let room = Rect::from_min_max(pos2(100.0, 0.0), pos2(600.0, 32.0));
1579 let part = Part {
1580 rect: bar,
1581 room,
1582 state: State::REST,
1583 label: None,
1584 };
1585 let pad = kit.title_bar.data.padding_x;
1586 let size = Vec2::new(120.0, 16.0);
1587 assert_eq!(kit.title_bar.label_rect(&part, size).left(), 100.0 + pad);
1589 let centred = Kit::compile(&Tokens::default(), &Shapes::default());
1591 assert_eq!(centred.title_bar.label_rect(&part, size).center().x, 400.0);
1592 let narrow = Part {
1594 room: Rect::from_min_max(pos2(500.0, 0.0), pos2(780.0, 32.0)),
1595 ..part
1596 };
1597 assert_eq!(
1598 centred.title_bar.label_rect(&narrow, size).left(),
1599 500.0 + pad
1600 );
1601 }
1602
1603 #[test]
1604 fn a_focus_ring_is_data_of_the_focus_state() {
1605 let t = tokens_with(
1606 r#"
1607 $extends: "pop-dark"
1608 tab:
1609 focus:
1610 ring-color: {$type: "color", $value: "{focus.ring}"}
1611 ring-width: {$type: "dimension", $value: {value: 2, unit: "px"}}
1612 ring-offset: {$type: "dimension", $value: {value: 1, unit: "px"}}
1613 "#,
1614 );
1615 let kit = Kit::compile(&t, &Shapes::default());
1616 assert!(kit.problems.is_empty(), "{:?}", kit.problems);
1617 let s = &kit.tab.data.states;
1618 assert_eq!(s.get(State::REST).ring_width, 0.0);
1619 let focus = s.get(State::FOCUS | State::HOVER);
1620 assert_eq!((focus.ring_width, focus.ring_offset), (2.0, 1.0));
1621 assert_eq!(focus.ring_color, t.focus_ring);
1622 }
1623
1624 #[test]
1625 fn every_glyph_role_has_its_default_icon_in_the_default_kit() {
1626 let kit = Kit::compile(&Tokens::default(), &Shapes::default());
1627 for g in Glyph::ALL {
1628 assert_eq!(kit.glyph(*g), g.default_icon(), "{}", g.name());
1629 }
1630 assert_eq!(kit.glyph(Glyph::DisclosureClosed), Icon::TriangleRight);
1631 }
1632
1633 #[test]
1634 fn a_kit_remaps_a_glyph_and_an_unknown_icon_is_reported() {
1635 let t = tokens_with(
1636 r#"
1637 $extends: "pop-dark"
1638 glyph:
1639 disclosure-closed: {$type: "string", $value: "chevron-right"}
1640 check: {$type: "string", $value: "tick-mark"}
1641 "#,
1642 );
1643 let kit = Kit::compile(&t, &Shapes::default());
1644 assert_eq!(kit.glyph(Glyph::DisclosureClosed), Icon::ChevronRight);
1645 assert_eq!(kit.glyph(Glyph::Check), Icon::Check);
1646 assert_eq!(kit.problems.len(), 1, "{:?}", kit.problems);
1647 assert!(kit.problems[0].starts_with("glyph.check: no icon named `tick-mark`"));
1648 }
1649
1650 #[test]
1651 fn the_led_and_flag_shapes_are_glyphs_a_kit_remaps_but_never_merges() {
1652 let kit = Kit::compile(&Tokens::default(), &Shapes::default());
1654 for (a, b) in egui_pop_tokens::kit::DISTINCT_GLYPHS {
1655 let role = |n: &str| *Glyph::ALL.iter().find(|g| g.name() == n).unwrap();
1656 assert_ne!(kit.glyph(role(a)), kit.glyph(role(b)), "{a} and {b}");
1657 }
1658 let t = tokens_with(
1660 r#"
1661 $extends: "pop-dark"
1662 glyph:
1663 led-error: {$type: "string", $value: "close"}
1664 flag-pinned: {$type: "string", $value: "lock"}
1665 "#,
1666 );
1667 let kit = Kit::compile(&t, &Shapes::default());
1668 assert_eq!(kit.glyph(Glyph::LedError), Icon::Close);
1669 assert_eq!(kit.glyph(Glyph::FlagPinned), Icon::Lock);
1670 assert!(kit.problems.is_empty(), "{:?}", kit.problems);
1671 let t = tokens_with(
1674 r#"
1675 $extends: "pop-dark"
1676 glyph:
1677 led-warning: {$type: "string", $value: "square"}
1678 "#,
1679 );
1680 let kit = Kit::compile(&t, &Shapes::default());
1681 assert_eq!(kit.glyph(Glyph::LedWarning), Icon::Triangle);
1682 assert_eq!(kit.glyph(Glyph::LedError), Icon::Square);
1683 assert_eq!(kit.problems.len(), 1, "{:?}", kit.problems);
1684 assert!(
1685 kit.problems[0].starts_with("glyph.led-warning and glyph.led-error both draw"),
1686 "{:?}",
1687 kit.problems
1688 );
1689 assert_eq!(kit.glyph(Glyph::LedBusy), kit.glyph(Glyph::LedOn));
1691 }
1692
1693 #[test]
1694 fn the_default_rows_alias_the_system_tokens() {
1695 let t = Tokens::default();
1696 let kit = Kit::compile(&t, &Shapes::default());
1697 let row = &kit.list_row;
1698 assert_eq!(row.shape, "box");
1699 assert_eq!(row.style(State::REST).fill, Color32::TRANSPARENT);
1700 assert_eq!(row.style(State::REST).text, t.text.default);
1701 let selected = row.style(State::SELECTED);
1702 assert_eq!((selected.fill, selected.text), (t.selection, t.text.strong));
1703 assert_eq!(row.style(State::HOVER).fill, t.surface.hover);
1704 let cursor = row.style(State::SELECTED | State::FOCUS);
1706 assert_eq!(cursor.fill, t.selection);
1707 assert_eq!(
1708 (cursor.ring_color, cursor.ring_width, cursor.ring_offset),
1709 (t.focus_ring, 1.0, -2.0)
1710 );
1711 let view = kit.list_view.style(State::FOCUS);
1712 assert_eq!((view.ring_width, view.ring_offset), (1.0, -1.0));
1713 assert_eq!(kit.list_view.style(State::REST).ring_width, 0.0);
1714 assert_eq!(kit.tree_drop_marker.shape, "outline");
1715 assert_eq!(
1716 kit.tree_drop_marker.style(State::DISABLED).border_color,
1717 t.status.danger
1718 );
1719 assert_eq!(kit.table_stripe.style(State::REST).fill, t.surface.raised);
1720 assert_eq!(kit.table_header_cell.data.align, Align::Start);
1721 }
1722
1723 #[test]
1724 fn a_table_row_looks_like_a_list_row_unless_a_kit_says_otherwise() {
1725 let t = Tokens::default();
1726 let kit = Kit::compile(&t, &Shapes::default());
1727 assert_eq!(kit.table_row.shape, "box");
1728 for state in [
1730 State::REST,
1731 State::HOVER,
1732 State::SELECTED,
1733 State::FOCUS,
1734 State::SELECTED | State::FOCUS,
1735 State::SELECTED | State::HOVER,
1736 ] {
1737 assert_eq!(
1738 kit.table_row.style(state),
1739 kit.list_row.style(state),
1740 "{state:?}"
1741 );
1742 }
1743 assert_eq!(
1744 kit.table_row.border_room(1.0),
1745 kit.list_row.border_room(1.0)
1746 );
1747 }
1748
1749 #[test]
1750 fn the_default_sliders_alias_the_system_tokens() {
1751 let t = Tokens::default();
1752 let kit = Kit::compile(&t, &Shapes::default());
1753 let bar = &kit.slider;
1754 assert_eq!(bar.shape, "box");
1755 assert_eq!(bar.style(State::REST).fill, t.border.default);
1756 assert_eq!(bar.style(State::REST).border_width, 0.0);
1757 assert_eq!(bar.data.align, Align::Start);
1758 assert_eq!(bar.data.padding_x, t.space.s);
1759 let hover = bar.style(State::HOVER);
1760 assert_eq!(
1761 (hover.border_color, hover.border_width),
1762 (t.border.strong, 1.0)
1763 );
1764 let focus = bar.style(State::FOCUS | State::HOVER);
1766 assert_eq!(
1767 (focus.ring_color, focus.ring_width, focus.ring_offset),
1768 (t.focus_ring, 2.0, -2.0)
1769 );
1770 assert_eq!(focus.border_width, 0.0);
1771 assert_eq!(kit.slider_fill.style(State::REST).fill, t.accent.default);
1772 assert_eq!(kit.slider_thumb.style(State::REST).fill, t.text.strong);
1773 assert_eq!(kit.slider_thumb.data.width, 2.0);
1774 let value = &kit.slider_value;
1775 assert_eq!(value.data.align, Align::End);
1776 assert_eq!(value.style(State::REST).text, t.text.default);
1777 assert_eq!(
1778 value.style_toned(Tone::Warning, State::FOCUS).text,
1779 t.status.warning
1780 );
1781 let toggle = &kit.slider_toggle;
1782 assert_eq!(toggle.style(State::REST).text, t.text.default);
1783 assert_eq!(toggle.style(State::SELECTED).text, t.accent.default);
1784 assert_eq!(kit.slider.style(State::REST).fill, t.border.default);
1785 }
1786
1787 #[test]
1788 fn an_icon_button_s_states_win_over_its_tone() {
1789 let t = Tokens::default();
1790 let kit = Kit::compile(&t, &Shapes::default());
1791 let b = &kit.icon_button;
1792 assert_eq!(b.style(State::REST).fill, Color32::TRANSPARENT);
1793 assert_eq!(b.style(State::REST).text, t.text.default);
1794 assert_eq!(
1795 b.style_toned(Tone::Danger, State::REST).text,
1796 t.status.danger
1797 );
1798 assert_eq!(
1799 b.style_toned(Tone::Danger, State::HOVER).text,
1800 t.text.strong
1801 );
1802 assert_eq!(
1803 b.style_toned(Tone::Accent, State::DISABLED).text,
1804 t.text.muted
1805 );
1806 assert_eq!(b.style(State::SELECTED).text, t.accent.default);
1807 let focus = b.style(State::FOCUS);
1808 assert_eq!(
1809 (focus.ring_color, focus.ring_width, focus.ring_offset),
1810 (t.focus_ring, 1.5, 1.0)
1811 );
1812 }
1813
1814 #[test]
1815 fn the_default_placeholders_alias_the_system_tokens() {
1816 let t = Tokens::default();
1817 let kit = Kit::compile(&t, &Shapes::default());
1818 assert_eq!(kit.skeleton.style(State::REST).fill, t.surface.active);
1819 assert_eq!(kit.skeleton.style(State::REST).radius, t.radius.widget);
1820 assert_eq!(
1821 kit.skeleton_shimmer.style(State::REST).fill,
1822 t.surface.hover
1823 );
1824 let empty = &kit.empty_state;
1825 assert_eq!(empty.shape, "card");
1826 assert_eq!(empty.data.padding_y, t.space.l);
1827 assert_eq!(empty.style(State::REST).fill, Color32::TRANSPARENT);
1828 assert_eq!(empty.style(State::REST).text, t.text.muted);
1829 assert_eq!(
1830 empty.style_toned(Tone::Danger, State::REST).text,
1831 t.status.danger
1832 );
1833 }
1834
1835 #[test]
1836 fn tones_merge_after_rest_and_states_keep_what_they_give() {
1837 let t = tokens_with(
1838 r##"
1839 $extends: "pop-dark"
1840 tab:
1841 rest:
1842 fill: {$type: "color", $value: "#101010"}
1843 hover:
1844 fill: {$type: "color", $value: "#202020"}
1845 disabled:
1846 text: {$type: "color", $value: "#303030"}
1847 tone:
1848 danger:
1849 fill: {$type: "color", $value: "#ff0000"}
1850 text: {$type: "color", $value: "#ffffff"}
1851 hover:
1852 fill: {$type: "color", $value: "#ff4040"}
1853 "##,
1854 );
1855 let kit = Kit::compile(&t, &Shapes::default());
1856 let hex = |c: Color32| format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b());
1857 let tab = &kit.tab;
1858 assert!(tab.data.states.toned());
1859 let danger = |s: State| tab.style_toned(Tone::Danger, s);
1860 assert_eq!(hex(danger(State::REST).fill), "#ff0000");
1861 assert_eq!(hex(danger(State::HOVER).fill), "#ff4040");
1863 assert_eq!(hex(danger(State::DISABLED).text), "#303030");
1865 assert_eq!(hex(danger(State::DISABLED).fill), "#ff0000");
1866 assert_eq!(
1868 tab.style_toned(Tone::Info, State::HOVER),
1869 tab.style(State::HOVER)
1870 );
1871 assert_eq!(
1872 tab.style_toned(Tone::Neutral, State::REST),
1873 tab.style(State::REST)
1874 );
1875 let s = State::HOVER.toned(Tone::Danger);
1877 assert_eq!(s.tone(), Tone::Danger);
1878 assert!(s.contains(State::HOVER));
1879 assert_eq!(tab.style(s), danger(State::HOVER));
1880 assert_eq!(s.toned(Tone::Neutral), State::HOVER);
1881 }
1882
1883 #[test]
1884 fn a_component_without_tones_has_no_table() {
1885 let kit = Kit::compile(&Tokens::default(), &Shapes::default());
1886 assert!(!kit.tab.data.states.toned());
1887 assert_eq!(
1888 kit.tab.style_toned(Tone::Danger, State::HOVER),
1889 kit.tab.style(State::HOVER)
1890 );
1891 let t = Tokens::default();
1893 let fill = |tone| kit.progress_fill.style_toned(tone, State::REST).fill;
1894 assert_eq!(fill(Tone::Neutral), t.accent.default);
1895 assert_eq!(fill(Tone::Accent), t.accent.default);
1896 assert_eq!(fill(Tone::Info), t.status.info);
1897 assert_eq!(fill(Tone::Success), t.status.success);
1898 assert_eq!(fill(Tone::Warning), t.status.warning);
1899 assert_eq!(fill(Tone::Danger), t.status.danger);
1900 assert_eq!(fill(Tone::Muted), t.text.muted);
1901 }
1902
1903 #[test]
1904 fn the_default_chrome_aliases_the_system_tokens() {
1905 let t = Tokens::default();
1906 let kit = Kit::compile(&t, &Shapes::default());
1907 assert_eq!(kit.header_band.shape, "band");
1908 assert_eq!(kit.header_band.style(State::REST).fill, t.surface.raised);
1909 assert_eq!(kit.header_band.data.padding_y, t.space.xs);
1910 assert_eq!(kit.dialog_header.data.padding_y, t.space.m);
1911 let pinned = kit.band_icon_button.style(State::SELECTED);
1912 assert_eq!(
1913 (pinned.fill, pinned.text),
1914 (t.surface.raised, t.text.strong)
1915 );
1916 let focus = kit.band_icon_button.style(State::FOCUS);
1917 assert_eq!((focus.ring_color, focus.ring_width), (t.focus_ring, 2.0));
1918 for s in [State::REST, State::HOVER, State::ACTIVE] {
1920 let (c, b) = (kit.command_button.style(s), kit.button.style(s));
1921 assert_eq!(
1922 (c.fill, c.border_color, c.text),
1923 (b.fill, b.border_color, b.text)
1924 );
1925 }
1926 let row = &kit.command_palette_row;
1927 assert_eq!(row.style(State::SELECTED).fill, t.selection);
1928 assert_eq!(row.style_toned(Tone::Muted, State::REST).text, t.text.muted);
1929 assert_eq!(
1930 kit.activity_bar_item.style(State::SELECTED).fill,
1931 t.accent.subtle
1932 );
1933 let refused = kit.dock_preview.style(State::DISABLED);
1934 assert_eq!(refused.border_color, t.status.danger);
1935 assert_eq!(kit.dock_preview.data.opacity, 0.5);
1936 let ghost = kit.tab_preview.style(State::REST);
1939 assert_eq!(kit.tab_preview.shape, kit.tab.shape);
1940 assert_eq!(kit.tab_preview.data.height, kit.tab.data.height);
1941 assert_eq!(kit.tab_preview.data.padding_x, kit.tab.data.padding_x);
1942 assert_eq!(ghost.border_color, t.accent.default);
1943 let selected = kit.tab.style(State::SELECTED).fill;
1944 let (g, s) = (
1945 ghost.fill.to_srgba_unmultiplied(),
1946 selected.to_srgba_unmultiplied(),
1947 );
1948 assert!((0..3).all(|i| g[i].abs_diff(s[i]) <= 1), "{g:?} {s:?}");
1950 assert!(ghost.fill.a() < selected.a());
1951 }
1952
1953 #[test]
1954 fn egui_s_widgets_take_their_states_from_the_kit_s_button() {
1955 let t = tokens_with(
1956 r##"
1957 $extends: "pop-dark"
1958 button:
1959 hover:
1960 fill: {$type: "color", $value: "#123456"}
1961 rest:
1962 radius: {$type: "dimension", $value: {value: 9, unit: "px"}}
1963 field:
1964 rest:
1965 fill: {$type: "color", $value: "#0a0b0c"}
1966 "##,
1967 );
1968 let ctx = Context::default();
1969 crate::theme::install_tokens(&ctx, t);
1970 let v = ctx.global_style().visuals.clone();
1971 assert_eq!(
1972 v.widgets.hovered.bg_fill,
1973 Color32::from_rgb(0x12, 0x34, 0x56)
1974 );
1975 assert_eq!(
1976 v.widgets.inactive.corner_radius,
1977 egui::CornerRadius::same(9)
1978 );
1979 assert_eq!(
1980 v.text_edit_bg_color,
1981 Some(Color32::from_rgb(0x0a, 0x0b, 0x0c))
1982 );
1983 let kit = Kit::of(&ctx);
1985 assert!(
1986 kit.problems
1987 .iter()
1988 .any(|p| p.starts_with("field.rest: egui's text fields")),
1989 "{:?}",
1990 kit.problems
1991 );
1992 }
1993
1994 #[test]
1995 fn a_button_indicator_is_reported_as_beyond_egui_s_widgets() {
1996 let t = tokens_with(
1997 r#"
1998 $extends: "pop-dark"
1999 button:
2000 selected:
2001 indicator-color: {$type: "color", $value: "{accent.default}"}
2002 indicator-size: {$type: "dimension", $value: {value: 2, unit: "px"}}
2003 "#,
2004 );
2005 let kit = Kit::compile(&t, &Shapes::default());
2006 assert_eq!(kit.problems.len(), 1, "{:?}", kit.problems);
2007 assert!(kit.problems[0].starts_with("button.selected: egui's widgets draw no indicator"));
2008 }
2009
2010 #[test]
2011 fn a_side_area_separator_egui_cannot_draw_is_reported() {
2012 let t = tokens_with(
2013 r##"
2014 $extends: "pop-dark"
2015 side-area:
2016 rest:
2017 border-width: {$type: "dimension", $value: {value: 3, unit: "px"}}
2018 border-color: {$type: "color", $value: "#ff0000"}
2019 "##,
2020 );
2021 let kit = Kit::compile(&t, &Shapes::default());
2022 assert_eq!(kit.problems.len(), 2, "{:?}", kit.problems);
2023 assert!(kit.problems[0].starts_with("side-area.rest.border-width"));
2024 assert!(kit.problems[1].starts_with("side-area.rest.border-color"));
2025 let t = tokens_with(
2027 r##"
2028 $extends: "pop-dark"
2029 side-area:
2030 rest:
2031 border-width: {$type: "dimension", $value: {value: 0, unit: "px"}}
2032 "##,
2033 );
2034 assert!(Kit::compile(&t, &Shapes::default()).problems.is_empty());
2035 }
2036
2037 #[test]
2038 fn a_bad_align_is_reported() {
2039 let t = tokens_with(
2040 r#"
2041 $extends: "pop-dark"
2042 title-bar:
2043 align: {$type: "string", $value: "middle"}
2044 "#,
2045 );
2046 let kit = Kit::compile(&t, &Shapes::default());
2047 assert_eq!(kit.title_bar.data.align, Align::Centre);
2048 assert!(
2049 kit.problems[0].starts_with("title-bar.align: `middle`"),
2050 "{:?}",
2051 kit.problems
2052 );
2053 }
2054
2055 #[test]
2056 fn an_unknown_shape_is_reported_and_the_default_drawn() {
2057 let t = tokens_with(
2058 r#"
2059 $extends: "pop-dark"
2060 tab:
2061 shape: {$type: "string", $value: "zigzag"}
2062 "#,
2063 );
2064 let kit = Kit::compile(&t, &Shapes::default());
2065 assert_eq!(kit.tab.shape, "box");
2066 assert!(
2067 kit.problems[0].starts_with("tab.shape: no handler named `zigzag`"),
2068 "{:?}",
2069 kit.problems
2070 );
2071 }
2072
2073 #[test]
2074 fn a_frame_is_the_box_as_egui_draws_it() {
2075 let t = Tokens::default();
2076 let kit = Kit::compile(&t, &Shapes::default());
2077 assert_eq!(kit.dialog.shape, "card");
2078 let f = kit.dialog.frame(State::REST, 1.0);
2079 assert_eq!(f.fill, t.surface.overlay);
2080 assert_eq!(f.stroke, Stroke::new(1.0, t.border.default));
2081 assert_eq!(kit.dialog.frame(State::REST, 1.25).stroke.width, 0.8);
2083 assert_eq!(f.corner_radius, egui::CornerRadius::from(t.radius.window));
2084 assert_eq!(f.inner_margin, Margin::from(t.space.l));
2085 assert_eq!(kit.dialog.data.width, t.size.dialog_width);
2086 assert!((kit.backdrop.data.opacity - 0.392).abs() < 1e-6);
2087 }
2088
2089 #[test]
2090 fn the_editor_and_terminal_frames_show_the_focus() {
2091 let t = Tokens::default();
2092 let kit = Kit::compile(&t, &Shapes::default());
2093 let editor = &kit.editor_frame.data.states;
2094 assert_eq!(editor.get(State::REST).ring_width, 0.0);
2095 let focus = editor.get(State::FOCUS);
2096 assert_eq!(
2097 (focus.ring_color, focus.ring_width, focus.ring_offset),
2098 (t.focus_ring, 1.0, -1.0)
2099 );
2100 let terminal = &kit.terminal_frame.data.states;
2101 assert_eq!(terminal.get(State::REST).border_color, t.border.default);
2102 assert_eq!(terminal.get(State::FOCUS).border_color, t.focus_ring);
2103 assert_eq!(terminal.get(State::REST).fill, t.surface.sunken);
2104 }
2105
2106 #[test]
2107 fn a_frame_handler_of_its_own_paints_under_the_content() {
2108 struct Blot;
2109 impl Primitive<ComponentKit> for Blot {
2110 fn measure(&self, _: &ComponentKit, label: Vec2) -> Vec2 {
2111 label
2112 }
2113 fn paint(&self, cx: &KitCx<'_>, _: &ComponentKit, part: &Part<'_>) {
2114 cx.painter.rect_filled(part.rect, 0.0, Color32::RED);
2115 }
2116 fn paint_label(&self, _: &KitCx<'_>, _: &ComponentKit, _: &Part<'_>) {}
2117 }
2118 let ctx = Context::default();
2119 register_shape(&ctx, "dialog", "blot", Arc::new(Blot));
2120 let t = tokens_with(
2121 r#"
2122 $extends: "pop-dark"
2123 dialog:
2124 shape: {$type: "string", $value: "blot"}
2125 "#,
2126 );
2127 let kit = install(&ctx, &t);
2128 assert!(kit.problems.is_empty(), "{:?}", kit.problems);
2129 let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
2130 kit.dialog.show(ui, State::REST, egui::Shadow::NONE, |ui| {
2131 ui.label("content")
2132 });
2133 });
2134 let kinds: Vec<&str> = out
2135 .shapes
2136 .iter()
2137 .filter_map(|c| match &c.shape {
2138 Shape::Vec(v) if !v.is_empty() => Some("box"),
2139 Shape::Text(_) => Some("text"),
2140 Shape::Rect(r) if r.fill == Color32::RED => Some("box drawn over"),
2141 _ => None,
2142 })
2143 .collect();
2144 assert_eq!(kinds, ["box", "text"]);
2145 out.textures_delta.clear();
2146 }
2147
2148 #[test]
2149 fn a_box_painted_under_fades_once_with_its_ui() {
2150 let ctx = Context::default();
2151 let kit = install(&ctx, &Tokens::default());
2152 let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
2153 ui.multiply_opacity(0.5);
2154 let slot = ui.painter().add(Shape::Noop);
2155 let rect = Rect::from_min_size(Pos2::ZERO, Vec2::splat(20.0));
2156 let part = Part {
2157 rect,
2158 room: rect,
2159 state: State::REST,
2160 label: None,
2161 };
2162 kit.button.paint_under(ui, slot, &part, None);
2163 });
2164 let fill = out
2165 .shapes
2166 .iter()
2167 .find_map(|c| match &c.shape {
2168 Shape::Vec(v) => v.iter().find_map(|s| match s {
2169 Shape::Rect(r) if r.fill.a() > 0 => Some(r.fill),
2170 _ => None,
2171 }),
2172 _ => None,
2173 })
2174 .expect("the box is painted");
2175 let rest = kit.button.style(State::REST).fill;
2176 assert_eq!(fill, rest.gamma_multiply(0.5));
2177 out.textures_delta.clear();
2178 }
2179
2180 #[test]
2181 fn a_registered_handler_can_be_named_by_a_theme() {
2182 struct Dot;
2183 impl Primitive<ComponentKit> for Dot {
2184 fn measure(&self, _: &ComponentKit, label: Vec2) -> Vec2 {
2185 label
2186 }
2187 fn paint(&self, _: &KitCx<'_>, _: &ComponentKit, _: &Part<'_>) {}
2188 fn paint_label(&self, _: &KitCx<'_>, _: &ComponentKit, _: &Part<'_>) {}
2189 }
2190 let ctx = Context::default();
2191 register_tab_shape(&ctx, "dot", Arc::new(Dot));
2192 let t = tokens_with(
2193 r#"
2194 $extends: "pop-dark"
2195 tab:
2196 shape: {$type: "string", $value: "dot"}
2197 "#,
2198 );
2199 let kit = install(&ctx, &t);
2200 assert_eq!(kit.tab.shape, "dot");
2201 assert_eq!(kit.tab_preview.shape, "dot", "the ghost follows the tab");
2202 assert!(kit.problems.is_empty());
2203 assert_eq!(
2204 kit.tab.measure(Vec2::new(30.0, 10.0)),
2205 Vec2::new(30.0, 10.0)
2206 );
2207 }
2208
2209 #[test]
2210 fn a_component_based_on_another_is_drawn_by_its_base_s_handler() {
2211 struct Wide;
2212 impl Primitive<ComponentKit> for Wide {
2213 fn measure(&self, _: &ComponentKit, label: Vec2) -> Vec2 {
2214 label * 2.0
2215 }
2216 fn paint(&self, _: &KitCx<'_>, _: &ComponentKit, _: &Part<'_>) {}
2217 fn paint_label(&self, _: &KitCx<'_>, _: &ComponentKit, _: &Part<'_>) {}
2218 }
2219 let ctx = Context::default();
2220 register_shape(&ctx, "button", "wide", Arc::new(Wide));
2222 let t = tokens_with(
2223 r##"
2224 $extends: "pop-dark"
2225 button:
2226 shape: {$type: "string", $value: "wide"}
2227 hover:
2228 fill: {$type: "color", $value: "#102030"}
2229 "##,
2230 );
2231 let kit = install(&ctx, &t);
2232 assert!(kit.problems.is_empty(), "{:?}", kit.problems);
2233 assert_eq!(kit.command_button.shape, "wide");
2234 assert_eq!(
2235 kit.command_button.measure(Vec2::new(10.0, 5.0)),
2236 Vec2::new(20.0, 10.0)
2237 );
2238 assert_eq!(
2240 kit.command_button.style(State::HOVER).fill,
2241 Color32::from_rgb(0x10, 0x20, 0x30)
2242 );
2243 assert_eq!(
2244 kit.command_button.style(State::FOCUS).border_color,
2245 Tokens::default().focus_ring
2246 );
2247 let t = tokens_with(
2249 r##"
2250 $extends: "pop-dark"
2251 button:
2252 shape: {$type: "string", $value: "wide"}
2253 command-button:
2254 shape: {$type: "string", $value: "box"}
2255 "##,
2256 );
2257 assert_eq!(install(&ctx, &t).command_button.shape, "box");
2258 }
2259
2260 #[test]
2261 fn the_default_kit_s_copies_are_based_on_their_component() {
2262 let t = Tokens::default();
2263 let r = t.resolved();
2264 for (component, base) in [
2265 ("command-button", "button"),
2266 ("command-palette-row", "menu-item"),
2267 ("dialog-header", "header-band"),
2268 ("band-icon-button", "icon-button"),
2269 ("find-bar-button", "icon-button"),
2270 ("toolbar-button", "icon-button"),
2271 ("thumb-overlay-badge", "pill"),
2272 ("thumbnail", "thumb-cell"),
2273 ] {
2274 assert_eq!(
2275 string(&t, &format!("{component}.based-on")).as_deref(),
2276 Some(base),
2277 "{component}"
2278 );
2279 let alias = r
2280 .get(&format!("{component}.rest.fill"))
2281 .and_then(|t| t.alias.clone());
2282 assert_eq!(alias, Some(format!("{base}.rest.fill")), "{component}");
2283 }
2284 }
2285}