Skip to main content

egui_pop_core/kit/
mod.rs

1//! Visual kits (`docs/kit.md`): what a component looks like, as data from
2//! the theme and drawing handlers, compiled once when the theme is
3//! installed.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! egui-pop's widgets keep the behaviour (clicks, drags, focus, the
9//! keyboard, accessibility) and compute a [`State`]; the kit measures and
10//! paints. Every component is described with the same words: per state
11//! (`rest`, `hover`, `active`, `focus`, `selected`, `disabled`) a box
12//! ([`BoxStyle`]: fill, border, radius, text colour, indicator), plus a
13//! `shape`, the name of the handler that draws it ([`Primitive`]). A
14//! token is always `component.state.term` (`tab.hover.fill`), or
15//! `component.term` for what does not change with the state
16//! (`tab.shape`, `tab.padding-x`).
17//!
18//! Nothing is resolved while drawing: [`install`] compiles the theme into
19//! a [`Kit`] of plain values, with every combination of states merged
20//! ahead (32 boxes per component), and the handlers picked by name.
21//! Drawing reads fields and makes one call per part.
22//!
23//! The default look is a kit like any other: the `tab.*` tokens of the
24//! built-in `pop-dark` theme, which every theme extends, drawn by the
25//! handlers shipped here (`box`, `underline`). An application adds its
26//! own handlers with [`register_tab_shape`] before installing a theme
27//! that names them.
28
29use 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/// The states a part can be in, combined (a selected tab under the
68/// pointer is `SELECTED | HOVER`). No flag is the resting state.
69#[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    /// The flags, in the order their boxes apply (a later one wins):
81    /// selected, hover, focus, active, disabled. The names are the
82    /// tokens' state names.
83    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    /// The state egui sees on a response: `HOVER` under the pointer,
96    /// `ACTIVE` while pressed, `FOCUS` with the keyboard focus, `DISABLED`
97    /// when not enabled. What only the widget knows (`SELECTED`) it adds
98    /// with [`State::with`].
99    ///
100    /// A focused widget whose state comes from here shows its focus by the
101    /// kit, so the focus plugin paints no ring of its own around it
102    /// ([`focus::own_ring`](crate::focus::own_ring)). `FOCUS` is set only
103    /// while the focus is visible ([`focus::ring_shown`](crate::focus::ring_shown),
104    /// the web's `:focus-visible`): a click focuses without the focus look,
105    /// except in a text field, which shows its focus however it came.
106    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    /// `self` with `other` set when `on`, cleared when not: the flag says
121    /// `on`, whatever `self` had. To add a flag only, pass what `self`
122    /// has too (`s.with(F, s.contains(F) || on)`).
123    #[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    /// `self` with `other` cleared.
133    #[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/// A side of a box.
147#[derive(Clone, Copy, Debug, PartialEq, Eq)]
148pub enum Side {
149    Top,
150    Bottom,
151    Left,
152    Right,
153}
154
155/// Where a label goes along its part.
156#[derive(Clone, Copy, Debug, PartialEq, Eq)]
157pub enum Align {
158    /// After the start padding.
159    Start,
160    /// On the part's centre, moved into its room when it does not fit
161    /// there.
162    Centre,
163    /// Before the end padding.
164    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/// What a part looks like in one state.
191#[derive(Clone, Copy, Debug, Default, PartialEq)]
192pub struct BoxStyle {
193    pub fill: Color32,
194    pub border_color: Color32,
195    /// Points; snapped to whole physical pixels when painted.
196    pub border_width: f32,
197    pub radius: f32,
198    pub text: Color32,
199    /// The bar on one side of the box ([`ComponentKit::indicator_side`]);
200    /// none when its size is zero or its colour transparent.
201    pub indicator_color: Color32,
202    pub indicator_size: f32,
203    /// The focus ring (usually given by the `focus` state only): an
204    /// outline `ring_offset` points outside the box (inside when
205    /// negative), none when its width is zero.
206    pub ring_color: Color32,
207    pub ring_width: f32,
208    pub ring_offset: f32,
209}
210
211/// The terms of a box, as a state gives them: only what differs.
212#[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/// A component's boxes for every combination of states, merged when the
272/// kit is compiled, and per tone when its tokens give tones
273/// ([`Tone`], `kit/tone.rs`).
274#[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    /// The box of a state, in the tone it carries ([`State::toned`]).
300    pub fn get(&self, state: State) -> &BoxStyle {
301        tone::get(&self.0, self.1.as_deref(), state)
302    }
303
304    /// Whether the component's tokens give tones.
305    pub fn toned(&self) -> bool {
306        self.1.is_some()
307    }
308
309    /// The widest border among every state and tone, in points: the room
310    /// a part keeps for its border whatever its state, so that a state
311    /// restyles the border (its colour, its width up to this one) without
312    /// moving the content. A part with no border at rest still keeps it,
313    /// the border then present but invisible.
314    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/// What a part is asked to paint.
325#[derive(Debug)]
326pub struct Part<'a> {
327    pub rect: Rect,
328    /// Where its label may go: the part's rectangle, or less when the
329    /// widget puts other things on it (a title bar's items).
330    pub room: Rect,
331    pub state: State,
332    /// Its label, laid out without a colour (the box's `text` is given at
333    /// paint).
334    pub label: Option<&'a Arc<Galley>>,
335}
336
337/// What a handler paints with.
338#[allow(missing_debug_implementations, reason = "egui's Painter has no Debug")]
339pub struct KitCx<'a> {
340    pub painter: &'a Painter,
341    /// Physical pixels per point: strokes snap to whole pixels.
342    pub ppp: f32,
343}
344
345/// A component's drawing handler. Every component's handlers have this
346/// shape; `D` is the component's data.
347pub trait Primitive<D>: Send + Sync {
348    /// The size of a part around a label of size `label`.
349    fn measure(&self, data: &D, label: Vec2) -> Vec2;
350    /// Paints a part's box (everything but its label).
351    fn paint(&self, cx: &KitCx<'_>, data: &D, part: &Part<'_>);
352    /// Paints a part's label, after the widget's own content.
353    fn paint_label(&self, cx: &KitCx<'_>, data: &D, part: &Part<'_>);
354    /// Whether `pos` hits the part (a part that is not a rectangle).
355    fn hit(&self, _data: &D, rect: Rect, pos: Pos2) -> bool {
356        rect.contains(pos)
357    }
358}
359
360/// The data of a component: its boxes per state, and what does not
361/// change with the state.
362#[derive(Clone, Debug, PartialEq)]
363pub struct ComponentKit {
364    pub states: States,
365    /// Points between the label and the part's side edges.
366    pub padding_x: f32,
367    /// Points between the content and the part's top and bottom edges
368    /// (a frame around content, [`Component::show`]).
369    pub padding_y: f32,
370    /// Points; zero when the component has no fixed height.
371    pub height: f32,
372    /// Points; zero when the component has no fixed width.
373    pub width: f32,
374    /// Points: the size of its text (`font-size`); zero when not given,
375    /// the widget's own size then.
376    pub font_size: f32,
377    /// Points: how far the part sits from the edge it is drawn on,
378    /// towards the outside (a side area's grip, off its area's edge).
379    pub offset: f32,
380    pub indicator_side: Side,
381    pub align: Align,
382    /// How opaque the whole part is, 0 to 1 (1 when not given): a
383    /// backdrop's strength.
384    pub opacity: f32,
385    /// The shadow it casts (`shadow-offset-x`, `shadow-offset-y`,
386    /// `shadow-blur`, `shadow-spread`, `shadow-color`); none when not
387    /// given.
388    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/// A component's data and the handler that draws it.
445#[derive(Clone)]
446pub struct Component {
447    /// The component's token name (`tab`, `list-row`).
448    pub name: String,
449    pub data: ComponentKit,
450    /// The handler's name (`tab.shape`).
451    pub shape: String,
452    handler: Arc<dyn Primitive<ComponentKit>>,
453    /// Whether the handler is the built-in `card`, which egui's own
454    /// [`Frame`] draws exactly ([`Component::show`]).
455    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    /// Paints a part's box.
464    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    /// Paints a part's label.
477    pub fn paint_label(&self, cx: &KitCx<'_>, part: &Part<'_>) {
478        self.handler.paint_label(cx, &self.data, part);
479    }
480
481    /// Paints a part, box then label (a widget with nothing of its own
482    /// between them).
483    pub fn paint_part(&self, cx: &KitCx<'_>, part: &Part<'_>) {
484        self.paint(cx, part);
485        self.paint_label(cx, part);
486    }
487
488    /// Where the default label painting puts a label of `size`
489    /// ([`label_rect`]): a widget gives it to assistive technology.
490    pub fn label_rect(&self, part: &Part<'_>, size: Vec2) -> Rect {
491        label_rect(&self.data, part, size)
492    }
493
494    /// The room a part keeps for its border at `ppp` physical pixels per
495    /// point, whatever its state: its widest border
496    /// ([`States::widest_border`]) on whole physical pixels, zero when
497    /// no state gives one. A widget laying out content in the part
498    /// insets it by this, never by the current state's border.
499    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    /// The box of a state (in the tone it carries).
509    pub fn style(&self, state: State) -> &BoxStyle {
510        self.data.states.get(state)
511    }
512
513    /// The box of a state in a tone.
514    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    /// The box of a state as an egui [`Frame`] at `ppp` physical pixels
523    /// per point: its fill, its border (its width snapped to whole
524    /// physical pixels, as the kit's own painting does) and corner
525    /// radius, the padding (`padding-x`, `padding-y`) as its inner
526    /// margin. No shadow: egui's own, from `Visuals`, is the caller's to
527    /// add. For a container that takes a frame in one state; a part egui
528    /// lays out around its content is better shown with
529    /// [`Component::show`], which also paints the focus ring, honours a
530    /// handler of the theme's and keeps the content in place across
531    /// states (this frame's border is its state's own, so its size
532    /// follows the state's border width).
533    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    /// Shows `add` inside the component's box in `state`, laid out by egui
552    /// (the part is as large as its content, its padding and its
553    /// border), with egui's `shadow` under it ([`Shadow::NONE`] for none).
554    ///
555    /// The layout keeps room for the widest border of any state
556    /// ([`Component::border_room`]): the state restyles the box by paint
557    /// alone, and the content never moves when the state changes.
558    ///
559    /// The built-in `card` handler is egui's [`Frame`] of the box, then
560    /// the state's focus ring, when the state's border is the widest.
561    /// Otherwise the handler paints once the content is laid out, its
562    /// shapes moved under the content: what it draws needs one
563    /// allocation per part and frame, which egui's frame does not.
564    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        // The box's room kept (padding and the widest border), nothing
598        // painted.
599        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    /// Paints a part's box into `slot`, a shape reserved (`Shape::Noop`)
621    /// before the widget drew its content: the box ends up under the
622    /// content although it is painted after it, once the part's
623    /// rectangle and state are known. `first` goes under the box (a
624    /// shadow). One allocation per part and frame. The `ui`'s opacity (a
625    /// disabled or fading `ui`) applies once, when the box is set into
626    /// its slot.
627    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
663/// Declares the kit's components: the `Kit` struct's fields, the
664/// [`COMPONENTS`] list (token name and default handler) and their
665/// compilation. One line per component, in alphabetical order, so that
666/// changes adding different components do not touch the same lines.
667macro_rules! components {
668    ($($(#[$doc:meta])* $field:ident: $name:literal => $default:literal,)*) => {
669        /// A compiled kit: every component egui-pop draws through one.
670        #[derive(Clone, Debug)]
671        #[non_exhaustive]
672        pub struct Kit {
673            $($(#[$doc])* pub $field: Component,)*
674            /// The icon of each glyph role (`glyph.*`).
675            pub glyphs: Glyphs,
676            /// The window's own terms (`title-bar.buttons-side`,
677            /// `title-bar.buttons-hover`, `window.corners`).
678            pub window: WindowKit,
679            /// The window's edge beside its line (`window.inactive`,
680            /// `window.radius`).
681            pub window_edge: WindowEdgeKit,
682            /// The sections' terms (`section-count.placement`).
683            pub sections: SectionsKit,
684            /// The drag cursors by kind (`drag-cursor.<kind>.hover`,
685            /// `.drag`, `.policy`), under the pointer profile's.
686            pub drag_cursors: DragCursorKit,
687            /// The line between two areas while hovered and dragged
688            /// (`side-area.hover.border-*`, `side-area.active.border-*`).
689            pub area_line: AreaLineKit,
690            /// The scroll bars' terms (`scroll-bar.width`, `width-rest`,
691            /// `opacity-rest`, `room`, `min-length`, `margin`, `placement`,
692            /// `visibility`, `track-fill`): egui's
693            /// `ScrollStyle` ([`ScrollBarKit::style`]).
694            pub scroll: ScrollBarKit,
695            /// egui's own widgets' visuals in a scope, per [`Stock`] kind
696            /// and tone ([`Kit::scope`]).
697            pub scoped: ScopedKit,
698            /// What could not be compiled as written (an unknown shape, a
699            /// bad side): fallbacks were used.
700            pub problems: Vec<String>,
701        }
702
703        /// The components a kit has (their token name), with the handler
704        /// drawn when a theme names none it knows.
705        pub const COMPONENTS: &[(&str, &str)] = &[$(($name, $default),)*];
706
707        impl Kit {
708            /// Every component of the kit, in [`COMPONENTS`]' order: what
709            /// a check walks.
710            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    /// A row of a tree, a list or a table: `selected`, `hover`, and
738    /// `focus` for the cursor of a focused view.
739    list_row: "list-row" => "box",
740    /// A dense row, based on `list-row`: a list item or a property row,
741    /// and the tree's and the list's rows; `active` while pressed,
742    /// `disabled`, its trailing text and a property's name in the
743    /// `muted` tone.
744    list_item: "list-item" => "box",
745    /// An indent guide down a nested row, a part with no width.
746    list_guide: "list-guide" => "outline",
747    /// A data view as a whole (tree, list, table, library grid): its
748    /// outline while it has the keyboard focus, painted over its rows.
749    list_view: "list-view" => "plain",
750    /// An item of a menu (command, check item, submenu): egui lays it out
751    /// and takes its clicks, the kit paints its box under it; `selected`
752    /// while its submenu is open, its shortcut in the `muted` tone.
753    menu_item: "menu-item" => "box",
754    /// The column on a menu item's left holding its icon, tick, radio dot
755    /// or spinner: its `width` (else the inline icon size plus `space.s`
756    /// on each side, [`Kit::menu_gutter`]); `selected` frames the icon of
757    /// a checked command.
758    menu_item_gutter: "menu-item-gutter" => "box",
759    /// A meter's track (its fill is a `progress-fill`).
760    meter: "meter" => "track",
761    /// A meter's threshold, a line across its track.
762    meter_tick: "meter-tick" => "tick",
763    /// A progress bar's track (its fill and sections are `progress-fill`).
764    progress_bar: "progress-bar" => "track",
765    /// A bar's caption: its name, and its value text in the `muted` tone.
766    progress_caption: "progress-caption" => "plain",
767    /// A stretch of a track, by tone: a bar's fill and sections, a
768    /// meter's fill, an indeterminate bar's segment.
769    progress_fill: "progress-fill" => "span",
770    /// A thin progress line's track (under a title, along a viewport).
771    progress_line: "progress-line" => "track",
772    /// A progress ring, colours only (its arc is drawn by egui-pop): the
773    /// track in `fill`, the arc in `indicator-color`, by tone.
774    progress_ring: "progress-ring" => "plain",
775    /// A side area of the workbench: egui draws it and its separator line
776    /// (none when `border-width` is 0).
777    side_area: "side-area" => "plain",
778    /// Every dock area of a window, side, bottom and centre alike, in the
779    /// main window and the others: `padding-x` and `padding-y` between
780    /// its edges and its panels, the one set of margins that keeps
781    /// neighbouring areas' tab strips level ([`Kit::dock_area_margin`]).
782    dock_area: "dock-area" => "plain",
783    /// A shape of a skeleton standing in for loading content.
784    skeleton: "skeleton" => "box",
785    /// The band crossing a skeleton's shapes, painted where they meet.
786    skeleton_shimmer: "skeleton-shimmer" => "box",
787    /// A slider's bar: its track and its label; `hover`, `active` while
788    /// dragged, `focus`. A range slider's bar is in the states of both
789    /// its thumbs.
790    slider: "slider" => "box",
791    /// A slider's fill, a strip along the bar's bottom (`height`, else
792    /// 15 % of the bar); not drawn on a gradient track.
793    slider_fill: "slider-fill" => "track",
794    /// A slider's thumb, a line across the bar, in its own thumb's state.
795    slider_thumb: "slider-thumb" => "tick",
796    /// The square button at a slider's end, its icon in `text`;
797    /// `selected` while its toggle is on.
798    slider_toggle: "slider-toggle" => "box",
799    /// A slider's value text, in the `warning` tone past the soft range.
800    slider_value: "slider-value" => "plain",
801    /// A spinner, colours only like `progress-ring`; its label in `text`.
802    spinner: "spinner" => "plain",
803    /// The line between two panes side by side (`width` thick): hover,
804    /// active while dragged, `focus` with the keyboard
805    /// (`widgets::Splitter`).
806    splitter: "splitter" => "plain",
807    /// A status bar indicator, colours only: its text by tone, its
808    /// progress line (`border-color` the track, `indicator-*` the fill).
809    status_indicator: "status-indicator" => "plain",
810    /// An icon of the activity bar, its icon in `text`: `selected` while
811    /// its panel is shown (never `hover` then).
812    activity_bar_item: "activity-bar-item" => "box",
813    /// A side area's resize grip at the middle of its edge (`width` its
814    /// thickness, `height` its length); egui takes the drag.
815    area_grip: "area-grip" => "box",
816    /// A folded side area's strip (`width`); a click unfolds the area.
817    area_strip: "area-strip" => "plain",
818    /// The frame of an editor's code assist popups (completions,
819    /// actions, hover cards).
820    assist_card: "assist-card" => "card",
821    /// A push button. egui's own widgets take their states from it:
822    /// rest, hover, active, and selected for an open menu or combo box;
823    /// by tone, `UiPop::button_tone` (`accent` a primary action, the
824    /// status tones a solid fill, `muted` no box at rest).
825    button: "button" => "box",
826    /// A card grouping content in a panel or a page (`UiPop::card`); by
827    /// tone, an edge in the status colour, `muted` a sunken well.
828    card: "card" => "card",
829    /// A checkbox's box, its mark the `check` or `indeterminate` glyph:
830    /// `selected` while checked (`widgets::Checkbox`).
831    checkbox: "checkbox" => "box",
832    /// A combo box's arrow, the `dropdown` glyph: `selected` while its
833    /// list is open (`widgets::combo_box`).
834    combo_arrow: "combo-arrow" => "plain",
835    /// The box of egui's combo box, which egui draws (handler `scoped`):
836    /// its states become egui's in a scope (`UiPop::combo_box`),
837    /// `selected` while its list is open.
838    combo_box: "combo-box" => "scoped",
839    /// A button running a command: egui lays it out and takes its clicks,
840    /// the kit paints its box; egui greys it when disabled.
841    command_button: "command-button" => "box",
842    /// A command in the command palette: egui lays it out, the kit paints
843    /// its box under it; `selected` for the one Enter runs, its matches in
844    /// the `accent` tone, its keys in the `muted` tone.
845    command_palette_row: "command-palette-row" => "box",
846    /// What dims the interface behind a modal dialog: its `fill` at
847    /// `opacity` (egui paints it).
848    backdrop: "backdrop" => "plain",
849    /// An icon button on a header band (a palette's close, roll and pin, a
850    /// dialog's close), its icon in `text`; `selected` for a pinned
851    /// palette.
852    band_icon_button: "band-icon-button" => "box",
853    /// A pane of the library's comparison: `selected` for the best
854    /// image, its ring painted again over the image.
855    compare_pane: "compare-pane" => "box",
856    /// A dialog's frame.
857    dialog: "dialog" => "card",
858    /// A resizable dialog's corner handle (lines in `text`, in a square
859    /// `height` across, `border-width` wide); `width` is how far the
860    /// dialog's edges take the pointer on either side of them.
861    dialog_grip: "dialog-grip" => "plain",
862    /// A dialog's title row, colours only: its title in `text`, on the
863    /// header band of a movable dialog (`padding-y` below it).
864    dialog_header: "dialog-header" => "plain",
865    /// Where a dragged tab or palette would dock (its fill at `opacity`);
866    /// `disabled` when refused, its label saying why.
867    dock_preview: "dock-preview" => "box",
868    /// The border of a panel's body in a dock (`kit::dock`): `rest`,
869    /// `hover` under the pointer, `focus` for the dock's focused panel;
870    /// its width, colour, corners and glow (the ring) per state. None in
871    /// a frameless area.
872    dock_body: "dock-body" => "plain",
873    /// The line between two panels of a dock (`width` thick): `hover`,
874    /// `active` while dragged, `focus` with the keyboard.
875    dock_separator: "dock-separator" => "plain",
876    /// What a drag carries under the pointer (`bus::drag::Ghost` in the
877    /// application API): the frame of the first item's thumbnail, with
878    /// `offset` edges behind it when more go, or an object's chip (its
879    /// icon and name in `text`); `width` the thumbnail's longest side,
880    /// `height` a chip's, painted at `opacity`.
881    drag_ghost: "drag-ghost" => "box",
882    /// How many items a drag carries, a badge on its ghost's corner.
883    drag_ghost_count: "drag-ghost-count" => "pill",
884    /// What a drop would do, a symbol on the ghost's other corner (in
885    /// `text`) while it hovers a target; `disabled` when refused.
886    drag_verdict: "drag-verdict" => "pill",
887    /// The outline of the drop target a drag hovers; `disabled` when it
888    /// refuses the drag.
889    drop_target: "drop-target" => "outline",
890    /// The frame around a text or code editor; `focus` while it has the
891    /// keyboard.
892    editor_frame: "editor-frame" => "card",
893    /// An empty place: its box (none in the default kit) around the
894    /// icon, title, sentence and action; the icon and the sentence in
895    /// `text`, the icon in the `danger` tone when something went wrong.
896    empty_state: "empty-state" => "card",
897    /// A text field. egui's text fields take their background from it.
898    field: "field" => "box",
899    /// The card standing in for a part that panicked.
900    fault_card: "fault-card" => "card",
901    /// An editor's find and replace bar.
902    find_bar: "find-bar" => "card",
903    /// An icon button of the find bar (previous, next, close).
904    find_bar_button: "find-bar-button" => "box",
905    /// The strip at the top of a full screen window, its way out.
906    fullscreen_exit: "fullscreen-exit" => "card",
907    /// The band at the top of a movable dialog and of a palette, dragged to
908    /// move it: `hover` under the pointer, `active` while dragged.
909    header_band: "header-band" => "band",
910    /// A button made of an icon alone (`IconWidget::sense_click`), its
911    /// icon in `text`, by tone; `selected` while it is on.
912    icon_button: "icon-button" => "box",
913    /// A count or short text badge (a micro-indicator): a pill by tone.
914    indicator_badge: "indicator-badge" => "pill",
915    /// The target of an interactive micro-indicator: `hover`, `active`,
916    /// `focus`, `disabled`, `selected` for a toggle that is on; its
917    /// `text` is an icon mark's colour.
918    indicator_button: "indicator-button" => "box",
919    /// A dot or an LED, colours only: its colour in `fill` by tone, an
920    /// LED that is off a ring in `border-color`.
921    indicator_dot: "indicator-dot" => "plain",
922    /// A flag, colours only: its colour in `fill` by tone.
923    indicator_flag: "indicator-flag" => "plain",
924    /// The ring separating an overhanging mark from its host, colours
925    /// only (`ring-color`, `ring-width`).
926    indicator_outline: "indicator-outline" => "plain",
927    /// A colour swatch's box: its outline and corners over the colour;
928    /// `text` the slash of no colour and the dash of mixed ones.
929    indicator_swatch: "indicator-swatch" => "box",
930    /// A job's log console, as plain lines.
931    job_log: "job-log" => "card",
932    /// A pick, reject or colour label toggle: `selected` while on.
933    mark_toggle: "mark-toggle" => "box",
934    /// A floating palette's window.
935    palette_window: "palette-window" => "card",
936    /// A pill over a thumbnail: a badge (by tone) or a stack's count.
937    pill: "pill" => "pill",
938    /// A chart's plot area (`egui_pop_views::plot`): its background and
939    /// frame, its axis text and grid in `text` (`hover` while the
940    /// pointer is over it).
941    plot: "plot" => "box",
942    /// A plot's time cursor, a line across its area (`width` thick).
943    plot_cursor: "plot-cursor" => "tick",
944    /// A popover's or a menu's surface.
945    popover: "popover" => "card",
946    /// A radio button's circle, its mark the `radio` glyph: `selected`
947    /// while chosen (`widgets::RadioButton`).
948    radio: "radio" => "pill",
949    /// A star of a rating (`rating::RatingStars`), drawn by the `star`
950    /// handler: `rest` an empty star's outline, `selected` a star of the
951    /// value, `hover` a star of the value the pointer previews, and
952    /// `selected` in the `muted` tone a star of the current value past
953    /// the preview (its ghost); `disabled` in a disabled `Ui`.
954    rating_star: "rating-star" => "star",
955    /// A star of a rating shown, not edited (a table's column, a file's
956    /// facts): based on `rating-star`, at rest or `selected`.
957    rating_star_display: "rating-star-display" => "star",
958    /// A viewport's pixel readout; its label is the readout's text.
959    readout: "readout" => "card",
960    /// The scroll bars of every scroll area, which egui draws (handler
961    /// `scoped`): `rest`, `hover` and `active` the thumb (its `fill` and
962    /// `radius`); the terms that do not change with the state are
963    /// [`Kit::scroll`].
964    scroll_bar: "scroll-bar" => "scoped",
965    /// The library's search field: `focus` while its text has the
966    /// keyboard.
967    search_field: "search-field" => "card",
968    /// The title band of a collapsible section (`sections::Sections`):
969    /// a line above and under it, `hover`, `active` while pressed,
970    /// `focus` with the keyboard; its title in `text`.
971    section_band: "section-band" => "section",
972    /// The count on a section's band, based on `indicator-badge`.
973    section_count: "section-count" => "pill",
974    /// A section band's disclosure mark, colours only: the
975    /// `disclosure-open` or `disclosure-closed` glyph in `text`,
976    /// `width` across, in the band's state.
977    section_disclosure: "section-disclosure" => "plain",
978    /// A row picked from a short list (`widgets::SelectableRow`): a
979    /// combo box's choices, the assist card's rows; `selected` for the
980    /// chosen one, never `hover` then.
981    selectable_row: "selectable-row" => "box",
982    /// An on/off switch's track (`widgets::Switch`), its thumb in `text`:
983    /// `selected` while on.
984    switch: "switch" => "pill",
985    /// A tab of the workbench's tab bars.
986    tab: "tab" => "box",
987    /// The bar behind a row of tabs.
988    tab_bar: "tab-bar" => "plain",
989    /// The ghost of a dragged tab where it would land in another area's
990    /// tab bar, drawn at rest; based on `tab` (its handler and sizes).
991    tab_preview: "tab-preview" => "box",
992    /// A column's header in a data table: `hover` when the column sorts,
993    /// `selected` when the table is sorted by it.
994    table_header_cell: "table-header-cell" => "box",
995    /// A row of a data table: `selected`, `hover` (never while
996    /// selected), `focus` for the cursor of a focused table. Based on
997    /// `list-row`, so a table's rows look like a list's unless a kit
998    /// gives them their own look (a quiet selection, a side marker).
999    table_row: "table-row" => "box",
1000    /// Behind every other row of a data table.
1001    table_stripe: "table-stripe" => "plain",
1002    /// A tag or filter chip: selected, hover, focus.
1003    tag_chip: "tag-chip" => "pill",
1004    /// A cell of the library's grid: `selected`, `hover` (never while
1005    /// selected), `focus` for the cursor of a focused grid.
1006    thumb_cell: "thumb-cell" => "box",
1007    /// What a library cell lays over its image, by tone: `muted` a
1008    /// rejected image's veil, `accent` a stack member's bar.
1009    thumb_layer: "thumb-layer" => "box",
1010    /// The box behind a cell's flag, labels and stars.
1011    thumb_overlay_badge: "thumb-overlay-badge" => "box",
1012    /// A thumbnail ([`crate::thumbnail`]): selected, hover, focus.
1013    thumbnail: "thumbnail" => "box",
1014    /// A window's own title bar; its label is the window's title.
1015    title_bar: "title-bar" => "plain",
1016    /// Where a drag over a tree drops: around the target row, or a line
1017    /// between rows (a part with no height); `disabled` when refused.
1018    tree_drop_marker: "tree-drop-marker" => "outline",
1019    /// The frame around a terminal's grid; `focus` while it has the
1020    /// keyboard. Its fill is the grid's default background.
1021    terminal_frame: "terminal-frame" => "card",
1022    /// A tip's card.
1023    tip_card: "tip-card" => "card",
1024    /// A toast's frame (its level's tone is its icon's); its `text` is
1025    /// the message's.
1026    toast: "toast" => "card",
1027    /// A tooltip's frame (`tooltip::TooltipExt`): its `text`, its
1028    /// `font-size` (else the `Body` style's), its `placement` (`widget`
1029    /// or `pointer`), its `offset` and, at the pointer, its `offset-x`.
1030    tooltip: "tooltip" => "card",
1031    /// egui's button shown on or off (`Button::selected`), which egui
1032    /// draws (handler `scoped`): its states become egui's in a scope,
1033    /// `selected` its fill and text while on.
1034    toggle_button: "toggle-button" => "scoped",
1035    /// A small toggle showing a text or a glyph (`widgets::ToggleChip`):
1036    /// the find bar's options; `selected` while on.
1037    toggle_chip: "toggle-chip" => "box",
1038    /// A toolbar's button (`toolbars`): its icon and label in `text`, a
1039    /// fill under the pointer; `selected`, framed, while its command is
1040    /// on.
1041    toolbar_button: "toolbar-button" => "box",
1042    /// An image viewport's outline while it has the keyboard focus.
1043    viewport_focus: "viewport-focus" => "plain",
1044    /// A label over an image (an overlay's name, a HUD's readout), its
1045    /// fill translucent so the image shows through; its label is the
1046    /// text, drawn at rest.
1047    viewport_label: "viewport-label" => "pill",
1048    /// Minimize and maximize (the glyph is drawn in the box's `text`),
1049    /// in the tones `warning` and `success`; `traffic-light` draws
1050    /// circles.
1051    window_button: "window-button" => "plain",
1052    /// The close button, in the tone `danger`.
1053    window_close: "window-close" => "plain",
1054}
1055
1056type Handlers = BTreeMap<String, Arc<dyn Primitive<ComponentKit>>>;
1057
1058/// The handlers a kit's `shape` tokens can name, per component.
1059#[derive(Clone)]
1060pub struct Shapes(BTreeMap<String, Handlers>);
1061
1062impl Default for Shapes {
1063    /// The handlers egui-pop ships: `plain` for every component, and each
1064    /// handler module's own (`shapes::built_in`).
1065    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    /// The handler a component's `shape` names: its own, else one its
1077    /// base has (`<component>.based-on`, followed along a chain), so that
1078    /// a component based on another is drawn as it is.
1079    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    /// Adds a handler for a component under a name.
1100    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
1123/// The shapes registered by components, compiled into the next kit.
1124const SHAPES: Slot<Shapes> = Slot::opaque("core.kit.shapes");
1125/// The compiled kits, per egui theme.
1126const KIT: Slot<Kits> = Slot::opaque("core.kit");
1127
1128/// The kits installed, one per egui theme (the same one twice for a
1129/// theme alone).
1130#[derive(Clone, Debug)]
1131pub struct Kits {
1132    pub dark: Arc<Kit>,
1133    pub light: Arc<Kit>,
1134}
1135
1136impl Kits {
1137    /// The kit of one of egui's themes.
1138    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
1146/// Registers a handler for a component (one of [`COMPONENTS`]) under a
1147/// name its `shape` token can give. In use from the next theme install.
1148pub 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
1157/// Registers a tab handler ([`register_shape`] for `tab`).
1158pub 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    /// Compiles the kit a theme describes, with the handlers given.
1171    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    /// `add` in a scope where egui's own widgets of a [`Stock`] kind are
1213    /// drawn from the kit's component, in a tone ([`Tone::Neutral`] for
1214    /// its own box): its states become egui's widget visuals
1215    /// ([`ScopedVisuals`], compiled with the kit), so egui keeps drawing
1216    /// the widget, with its layout, icons and shortcut text. Outside the
1217    /// scope, egui's visuals are unchanged.
1218    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    /// The icon a kit draws for a glyph role.
1235    pub fn glyph(&self, glyph: Glyph) -> crate::icon::Icon {
1236        self.glyphs.get(glyph)
1237    }
1238
1239    /// The width of a menu's gutter (`menu-item-gutter.width`), else the
1240    /// inline icon size plus `space.s` on each side: 24 points in the
1241    /// comfortable density, 16 in the compact one.
1242    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    /// The kit of the theme drawn now (of egui's theme of the moment,
1252    /// as `Tokens::of`), or the ones of the installed tokens, compiled on
1253    /// first use. Read it while drawing; a cache keeping what it drew
1254    /// from it across frames keeps the `Arc` and compares it
1255    /// (`Arc::ptr_eq`): a new kit comes with a theme install and with
1256    /// egui's light or dark mode. Keep it, not only its address, which a
1257    /// dropped kit can lend to the next one.
1258    ///
1259    /// Inside a `ScopedTheme`'s `show`, it is the scoped theme's kit.
1260    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
1273/// What egui's own widgets, drawn from `button` and `field`
1274/// (`theme::visuals_with`), and egui's separator of a side area cannot
1275/// show of them: a kit giving it is told, rather than seeing it dropped
1276/// in silence.
1277fn 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    // egui draws a side area's separator with its non-interactive
1308    // widgets' stroke: the button's width at rest, `border.default`.
1309    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
1325/// Compiles the kit of `tokens` with the registered handlers and
1326/// installs it for both of egui's themes.
1327pub 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
1339/// Compiles the kits of a dark and a light theme (one kit when they are
1340/// the same set) and installs them. Called by `theme::install_variants`,
1341/// between frames.
1342pub 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
1357/// A kit compiled for tokens with the shapes registered in `ctx`, not
1358/// installed (a scoped theme's).
1359pub(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            // A component without shadow terms casts none.
1421            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        // A theme saying nothing keeps egui's strokes.
1447        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        // Width 0: no line on hover nor drag.
1455        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        // A colour alone keeps the width at rest; a width alone egui's colour.
1474        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        // What `selected` does not give stays the rest's.
1558        assert_eq!(s.get(State::SELECTED).radius, s.get(State::REST).radius);
1559        // Hover applies after selected: its fill (this theme's) and its
1560        // text (pop-dark's) win; selected's text shows when not hovered.
1561        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        // Start: right after the leading items and the padding.
1588        assert_eq!(kit.title_bar.label_rect(&part, size).left(), 100.0 + pad);
1589        // Centre (the default kit): on the bar's centre, which fits here...
1590        let centred = Kit::compile(&Tokens::default(), &Shapes::default());
1591        assert_eq!(centred.title_bar.label_rect(&part, size).center().x, 400.0);
1592        // ...and moved into the room when it does not.
1593        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        // The default shapes differ where they must.
1653        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        // A kit gives the LEDs other shapes.
1659        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        // Two states that would differ by colour alone go back to
1672        // egui-pop's shapes, and the kit is told.
1673        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        // A busy LED may share the on LED's shape: it pulses.
1690        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        // The cursor: a ring one pixel inside the row's edge.
1705        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        // Rest, hovered, selected, the cursor (focus), the selected cursor.
1729        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        // Focused: the ring inside the bar, no hover border under it.
1765        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        // The tone's own hover wins over the component's hover.
1862        assert_eq!(hex(danger(State::HOVER).fill), "#ff4040");
1863        // A state the tone does not give still applies over it.
1864        assert_eq!(hex(danger(State::DISABLED).text), "#303030");
1865        assert_eq!(hex(danger(State::DISABLED).fill), "#ff0000");
1866        // A tone the component does not give is its own box.
1867        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        // The tone travels in the state: handlers honour it unchanged.
1876        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        // The default kit's toned components alias the status tokens.
1892        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        // A command button looks like egui's buttons, which `button` draws.
1919        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        // A dragged tab's ghost: the tab's handler and size, the selected
1937        // fill faded, an accent border.
1938        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        // The same colour, give or take the premultiplied rounding.
1949        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        // What egui cannot draw: the field's radius differs from the button's.
1984        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        // Hiding the line is what egui honours: nothing to report.
2026        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        // Its border is whole physical pixels: one at 1.25, not 1.25.
2082        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        // Registered for `button` only: `command-button` is based on it.
2221        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        // The base's restyle reaches it; its own focus box stays.
2239        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        // A shape of its own wins over the base's.
2248        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}