Skip to main content

uzor_framework/widgets/
kit.rs

1//! The component kit: one builder shape for the reusable pieces of a
2//! DOM-like app (roadmap item 10).
3//!
4//! Every piece follows the same three steps:
5//!
6//! 1. `kit::thing(id, rect, data)` starts a builder. The id is a stable
7//!    [`WidgetId`]; child parts get `"{id}:…"` ids (`"{id}:tab:2"`,
8//!    `"{id}:row:5"`, `"{id}:footer:0"`).
9//! 2. Chain options (`.selected(i)`, `.bind(&mut v)`, `.disabled(true)`, …).
10//! 3. `.build(cx)` registers hits, names the parts for assistive tech,
11//!    paints with the token theme of `cx`, and returns a [`Response`].
12//!
13//! The app keeps its own values (text, selection, sizes): a piece reads them
14//! from the builder and reports changes through `Response` or `.bind`. State
15//! that only exists to drive a widget (a select's open flag, a dialog's
16//! drag position, a splitter's drag) lives in the frame's widget state store
17//! under the piece's id, as a DOM element keeps its own `:open`.
18//!
19//! | Piece    | Start                          | Reports                         |
20//! |----------|--------------------------------|---------------------------------|
21//! | button   | [`button`]`(id, rect)`         | `.on_click`, `.bind_count`      |
22//! | input    | [`input`]`(id, rect, &mut text)` | `changed`, focused; edits itself |
23//! | select   | [`select`]`(id, rect, options)`| `index` picked, `changed`       |
24//! | menu     | [`menu`]`(id, at, items, open)`| `index` picked                  |
25//! | dialog   | [`dialog`]`(id, rect)`         | `index` footer button, `clicked` close |
26//! | tabs     | [`tabs`]`(id, rect, labels)`   | `index` clicked, `changed`      |
27//! | list     | [`list`]`(id, rect, rows)`     | `index` clicked, `changed`      |
28//! | splitter | [`splitter`]`(id, axis, span, &mut pos)` | `changed`, `pressed` while dragging |
29//! | tooltip  | [`tooltip`]`(id, rect)`        | —                               |
30//! | toast    | [`toasts`]`(id, area, &mut stack, now_ms)` | `changed` while any is shown |
31//! | checkbox | [`checkbox`]`(id, rect)` + `.bind(&mut b)` | `.build_response`: `checked`, `changed` |
32//! | switch   | [`switch`]`(id, rect)` + `.bind(&mut b)`   | `.build_response`: `checked`, `changed` |
33//! | table    | [`table`]`(id, rect, columns, rows)`       | `index` row, `column` header, `changed` |
34//! | drawer   | [`drawer`]`(id, area, &mut open)`          | `changed` when the scrim closes it |
35//! | field    | [`field`]`(id, rect)` in the app's own chrome | `text` shown, `focused`; edits itself |
36//!
37//! An app that paints its own chrome (its CSS, not the token theme) and
38//! registers hits itself uses the paint half from
39//! `uzor::ui::widgets::composite::dialog`: `text_button_at` (sized text
40//! button), `draw_close_button` (`✕` on a circle, a rounded rect or bare),
41//! `fill_circle`, `draw_switch`, `draw_card`.
42//!
43//! Overlay-like pieces (select's list, menu, dialog) paint where they are
44//! built: build them last in a panel, or inside an overlay hook, so they sit
45//! on top.
46//!
47//! ```ignore
48//! use uzor_framework::widgets::kit;
49//! let r = kit::tabs("settings-tabs", tabs_rect, &["General", "Usage"]).bind(&mut self.tab).build(cx);
50//! kit::input("name", name_rect, &mut self.name).placeholder("Name").build(cx);
51//! if kit::button("save", save_rect).text("Save").build_response(cx).clicked { self.save(); }
52//! ```
53
54use uzor::input::{Sense, WidgetKind};
55use uzor::ui::widgets::atomic::item::{draw_item, ItemRenderKind, ItemSettings, ItemView};
56use uzor::ui::widgets::atomic::separator::{
57    draw_separator, DefaultSeparatorStyle, SeparatorOrientation, SeparatorSettings, SeparatorType,
58    SeparatorView,
59};
60use uzor::ui::widgets::atomic::tab::{draw_tab, register_tab_on_layer, TabConfig, TabSettings, TabView};
61use uzor::ui::widgets::atomic::text_input::{
62    draw_input, draw_input_cursor, InputType, InputView, TextFieldConfig as InputConfig, TextInputSettings,
63};
64use uzor::ui::widgets::atomic::toast::{draw_toast_stack, ToastStackState};
65use uzor::ui::widgets::composite::context_menu::{
66    draw_context_menu, register_input_coordinator_context_menu, ContextMenuItem,
67    ContextMenuRenderKind, ContextMenuSettings, ContextMenuState, ContextMenuView,
68};
69use uzor::ui::widgets::composite::dropdown::{
70    draw_dropdown, register_input_coordinator_dropdown, DropdownItem, DropdownItemRight,
71    DropdownRenderKind, DropdownSettings, DropdownState, DropdownView, DropdownViewKind,
72};
73use uzor::ui::widgets::composite::modal::render::draw_modal;
74use uzor::ui::widgets::composite::modal::{
75    register_input_coordinator_modal, BackdropKind, FooterBtn, FooterBtnStyle, ModalRenderKind,
76    ModalSettings, ModalState, ModalView,
77};
78use uzor::ui::widgets::atomic::button::ButtonView;
79use uzor::render::RenderContext;
80use uzor::{Rect, WidgetId, WidgetState};
81
82use crate::handle::VisualView;
83use crate::types::spec::Spec;
84
85use super::button::{button_settings, paint_button};
86use super::host::ContentCx;
87use super::paint::{interaction_state, parts, theme_of};
88use super::splitter::{grab_rect, register as register_splitter, Splitter, SplitterEvent};
89
90pub use super::lm::{
91    button, checkbox, toggle as switch, tooltip, ButtonBuilder, CheckboxBuilder, ToggleBuilder as SwitchBuilder,
92    TooltipBuilder,
93};
94pub use super::splitter::Axis;
95pub use uzor::ui::widgets::atomic::toast::{ToastSeverity, ToastType};
96
97/// What a piece reports after `.build(cx)`.
98#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
99pub struct Response {
100    /// The pointer is over the piece (any part of it).
101    pub hovered: bool,
102    /// The piece is held (a press, or a splitter drag).
103    pub pressed: bool,
104    /// Keyboard focus is on the piece or one of its parts.
105    pub focused: bool,
106    /// The piece itself was clicked (a dialog: its close button).
107    pub clicked: bool,
108    /// The value changed this frame (`.bind` targets are already updated).
109    pub changed: bool,
110    /// The part picked this frame: tab, row, option, menu item or footer button.
111    pub index: Option<usize>,
112    /// A table's header column clicked this frame (for sorting).
113    pub column: Option<usize>,
114    /// The state a checkbox or switch shows after this frame.
115    pub checked: bool,
116}
117
118impl Response {
119    fn of<S: Spec>(v: &VisualView<S>, id: &WidgetId) -> Self {
120        Response {
121            hovered: v.is_hover_within(id) || v.is_hovered(id),
122            pressed: v.is_pressed(id),
123            focused: v.is_focus_within(id) || v.is_focused(id),
124            clicked: v.clicked(id),
125            ..Default::default()
126        }
127    }
128}
129
130fn child(id: &WidgetId, part: &str, i: usize) -> WidgetId {
131    WidgetId::from(format!("{}:{}:{}", id.as_str(), part, i))
132}
133
134/// The index of the clicked `"{id}:{part}:{i}"` child, if any.
135fn picked<S: Spec>(v: &VisualView<S>, id: &WidgetId, part: &str) -> Option<usize> {
136    let pre = format!("{}:{}:", id.as_str(), part);
137    v.clicks().iter().find_map(|(w, _)| w.as_str().strip_prefix(pre.as_str())?.parse().ok())
138}
139
140/// A click this frame that landed outside every `"{id}…"` part.
141fn clicked_outside<S: Spec>(v: &VisualView<S>, id: &WidgetId) -> bool {
142    !v.clicks().is_empty() && !v.clicks().iter().any(|(w, _)| w.as_str().starts_with(id.as_str()))
143}
144
145fn focusable() -> Sense {
146    (Sense::CLICK | Sense::HOVER).with_focus()
147}
148
149// -- button response --------------------------------------------------------
150
151impl<'a> ButtonBuilder<'a> {
152    /// [`build`](Self::build), then report like the other kit pieces.
153    pub fn build_response<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
154        let id = self.id_ref().clone();
155        self.build(cx);
156        cx.with_paint(|_, _, v, _| Response::of(v, &id))
157    }
158}
159
160// -- checkbox / switch ------------------------------------------------------
161
162impl<'a> CheckboxBuilder<'a> {
163    /// [`build`](Self::build), name it for assistive tech, and report:
164    /// `checked` is the new state, `changed` a user flip.
165    pub fn build_response<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
166        let (id, label) = self.id_label();
167        let (id, label) = (id.clone(), label.unwrap_or("").to_owned());
168        let on = self.build(cx);
169        cx.with_paint(|_, w, v, _| {
170            w.coord.set_a11y(&id, &label, Some(on));
171            let r = Response::of(v, &id);
172            Response { changed: r.clicked, checked: on, ..r }
173        })
174    }
175}
176
177impl<'a> SwitchBuilder<'a> {
178    /// [`build`](Self::build), name it for assistive tech, and report:
179    /// `checked` is the new state, `changed` a user flip.
180    pub fn build_response<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
181        let (id, label, disabled) = self.id_label();
182        let (id, label) = (id.clone(), label.unwrap_or("").to_owned());
183        let on = self.build(cx);
184        cx.with_paint(|_, w, v, _| {
185            w.coord.set_a11y(&id, &label, Some(on));
186            let r = Response::of(v, &id);
187            Response { changed: r.clicked && !disabled, checked: on, ..r }
188        })
189    }
190}
191
192// -- input ------------------------------------------------------------------
193
194/// Single-line editable text field. Start with [`input`].
195///
196/// The framework's text store edits it: caret, selection (drag, double and
197/// triple click, Shift+arrows, select all), clipboard, IME composition with
198/// the candidate window at the caret, and undo / redo (Ctrl+Z, Ctrl+Shift+Z
199/// or Ctrl+Y; typing undoes a word at a time). The bound `String` is
200/// two-way: a user edit is written back to it (`changed`), and a value the
201/// app sets is pushed into the field, which drops its undo history the way
202/// `input.value = ..` does. Enter reports `TextIntent::Submitted`.
203pub struct InputBuilder<'a> {
204    id: WidgetId,
205    rect: Rect,
206    value: &'a mut String,
207    placeholder: &'a str,
208    label: Option<&'a str>,
209    kind: InputType,
210    disabled: bool,
211    max_len: Option<usize>,
212}
213
214/// An editable text field bound to `value`.
215pub fn input<'a>(id: impl Into<WidgetId>, rect: Rect, value: &'a mut String) -> InputBuilder<'a> {
216    InputBuilder {
217        id: id.into(),
218        rect,
219        value,
220        placeholder: "",
221        label: None,
222        kind: InputType::Text,
223        disabled: false,
224        max_len: None,
225    }
226}
227
228impl<'a> InputBuilder<'a> {
229    /// Grey hint shown while empty. Also the accessible name without `.label`.
230    pub fn placeholder(mut self, p: &'a str) -> Self {
231        self.placeholder = p;
232        self
233    }
234    /// Accessible name.
235    pub fn label(mut self, l: &'a str) -> Self {
236        self.label = Some(l);
237        self
238    }
239    /// Field kind (text, number, search, password).
240    pub fn kind(mut self, k: InputType) -> Self {
241        self.kind = k;
242        self
243    }
244    /// Masked password field (copy and cut are refused).
245    pub fn password(self) -> Self {
246        self.kind(InputType::Password)
247    }
248    /// Most chars the field takes, like `maxlength`.
249    pub fn max_len(mut self, n: usize) -> Self {
250        self.max_len = Some(n);
251        self
252    }
253    /// Disabled colours; not focusable or editable.
254    pub fn disabled(mut self, on: bool) -> Self {
255        self.disabled = on;
256        self
257    }
258
259    /// Register, sync the value, and draw.
260    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
261        let theme = theme_of(cx);
262        let InputBuilder { id, rect, value, placeholder, label, kind, disabled, max_len } = self;
263        let (r, ime) = cx.with_paint(|render, widgets, v, _| {
264            let mut r = Response::of(v, &id);
265            let settings = TextInputSettings::with_config(InputConfig::text()).with_theme(Box::new(theme));
266            let (coord, states, layer) = parts(widgets);
267            if disabled {
268                coord.register_atomic(id.clone(), WidgetKind::Custom, rect, Sense::HOVER, layer);
269            } else {
270                let mut config = if kind == InputType::Password { uzor::TextFieldConfig::password() } else { uzor::TextFieldConfig::text() };
271                if let Some(n) = max_len {
272                    config = config.with_max_len(n);
273                }
274                coord.set_default_layer(Some(layer.clone()));
275                coord.register_text_field(id.clone(), rect, config);
276                coord.set_default_layer(None);
277            }
278            coord.set_a11y(&id, label.unwrap_or(placeholder), None);
279            // Two-way sync against the value both sides saw last frame.
280            let synced = states.get_or_insert_with(WidgetId::from(format!("{}:value", id.as_str())), String::new);
281            let fields = coord.text_fields_mut();
282            if fields.has_field(&id) {
283                let now = fields.text(&id).to_owned();
284                if now != *synced {
285                    *value = now.clone();
286                    *synced = now;
287                    r.changed = true;
288                } else if *value != *synced {
289                    fields.set_text(&id, value);
290                    *synced = value.clone();
291                }
292            }
293            let st = fields.field_state(&id);
294            let (shown, caret, preedit) = st.map(|s| s.display()).unwrap_or_else(|| (value.clone(), value.chars().count(), None));
295            let selection = st.filter(|_| preedit.is_none()).and_then(|s| s.selection_range());
296            let shown = if kind == InputType::Password { "\u{2022}".repeat(shown.chars().count()) } else { shown };
297            let focused = !disabled && (r.focused || fields.is_focused(&id));
298            r.focused = focused;
299            let view = InputView {
300                text: &shown,
301                placeholder,
302                cursor: caret,
303                selection,
304                focused,
305                disabled,
306                input_type: kind,
307            };
308            let ws = interaction_state(v, &id, disabled);
309            let res = draw_input(render, rect, ws, &view, &settings);
310            let tint = settings.theme.cursor();
311            let mut ime = None;
312            if focused {
313                draw_input_cursor(render, res.cursor_x, res.cursor_y, res.cursor_height, 1.0, tint);
314                ime = Some(Rect::new(res.cursor_x, res.cursor_y, 1.0, res.cursor_height));
315            }
316            if let Some((a, b)) = preedit {
317                // Composition text is underlined, as the DOM draws it.
318                let x = |i: usize| res.char_x_positions.get(i).copied().unwrap_or(res.cursor_x);
319                draw_input_cursor(render, x(a), res.cursor_y + res.cursor_height, (x(b) - x(a)).max(0.0), 1.0, tint);
320            }
321            let fields = coord.text_fields_mut();
322            if let Some(s) = fields.field_state(&id) {
323                let pos = s.buffer_positions(res.char_x_positions);
324                fields.update_field(&id, (rect.x, rect.y, rect.width, rect.height), pos);
325            }
326            (r, ime)
327        });
328        if let Some(at) = ime {
329            cx.ime_area(at);
330        }
331        r
332    }
333}
334
335// -- field ------------------------------------------------------------------
336
337/// A borderless text field inside the app's own chrome. Start with [`field`].
338pub struct FieldBuilder<'a> {
339    id: WidgetId,
340    rect: Rect,
341    text_rect: Option<Rect>,
342    config: uzor::TextFieldConfig,
343    name: &'a str,
344    placeholder: &'a str,
345    masked: bool,
346    clip: bool,
347    px: f64,
348    family: &'a str,
349    color: Option<&'a str>,
350    placeholder_color: Option<&'a str>,
351    set: Option<&'a str>,
352    parent: Option<WidgetId>,
353}
354
355/// What a [`field`] shows this frame.
356#[derive(Clone, Debug, Default, PartialEq)]
357pub struct FieldResponse {
358    /// The shown text, composition included (unmasked).
359    pub text: String,
360    /// Keyboard focus is in the field.
361    pub focused: bool,
362}
363
364/// A text field whose box the app paints itself (a search pill, a dialog row, a sign-in
365/// input): the kit registers it at `rect`, names it, draws text, placeholder, caret and
366/// composition, and feeds caret geometry and the IME area back to the text store. The
367/// edit state lives in the store; seed or clear it there before `build`.
368pub fn field<'a>(id: impl Into<WidgetId>, rect: Rect) -> FieldBuilder<'a> {
369    FieldBuilder {
370        id: id.into(),
371        rect,
372        text_rect: None,
373        config: uzor::TextFieldConfig::text(),
374        name: "",
375        placeholder: "",
376        masked: false,
377        clip: false,
378        px: 13.0,
379        family: "sans-serif",
380        color: None,
381        placeholder_color: None,
382        set: None,
383        parent: None,
384    }
385}
386
387fn css_hex(c: [u8; 4]) -> String {
388    format!("#{:02x}{:02x}{:02x}{:02x}", c[0], c[1], c[2], c[3])
389}
390
391impl<'a> FieldBuilder<'a> {
392    /// Editing behaviour (text, search, password, multiline, max length).
393    pub fn config(mut self, c: uzor::TextFieldConfig) -> Self {
394        self.config = c;
395        self
396    }
397    /// Accessible name (defaults to the placeholder).
398    pub fn name(mut self, n: &'a str) -> Self {
399        self.name = n;
400        self
401    }
402    /// Grey hint while empty.
403    pub fn placeholder(mut self, p: &'a str) -> Self {
404        self.placeholder = p;
405        self
406    }
407    /// Draw bullets instead of the text.
408    pub fn masked(mut self, on: bool) -> Self {
409        self.masked = on;
410        self
411    }
412    /// Where the text runs, when it is inset inside the hit rect.
413    pub fn text_rect(mut self, r: Rect) -> Self {
414        self.text_rect = Some(r);
415        self
416    }
417    /// Clip the text to its rect.
418    pub fn clip(mut self, on: bool) -> Self {
419        self.clip = on;
420        self
421    }
422    /// Font size and CSS family.
423    pub fn font(mut self, px: f64, family: &'a str) -> Self {
424        self.px = px;
425        self.family = family;
426        self
427    }
428    /// Text and placeholder colours (CSS); the theme's when unset.
429    pub fn colors(mut self, text: &'a str, placeholder: &'a str) -> Self {
430        self.color = Some(text);
431        self.placeholder_color = Some(placeholder);
432        self
433    }
434
435    /// Replace the text this frame (`Some("")` clears it, undo included); the
436    /// caret goes to the end.
437    pub fn set(mut self, text: Option<&'a str>) -> Self {
438        self.set = text;
439        self
440    }
441    /// Nest the field under a container (a dialog scrim) for focus scoping.
442    pub fn parent(mut self, p: impl Into<WidgetId>) -> Self {
443        self.parent = Some(p.into());
444        self
445    }
446
447    /// Register, draw, and feed the store.
448    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> FieldResponse {
449        use uzor::ui::widgets::atomic::text_input::TextInputTheme;
450        use uzor::ui::widgets::composite::dialog::draw_field_text_ime;
451        let theme = theme_of(cx);
452        let color = self.color.map_or_else(|| css_hex(theme.text_normal()), str::to_owned);
453        let ph_color = self.placeholder_color.map_or_else(|| css_hex(theme.placeholder()), str::to_owned);
454        let FieldBuilder { id, rect, text_rect, config, name, placeholder, masked, clip, px, family, set, parent, .. } = self;
455        let fr = text_rect.unwrap_or(rect);
456        let (out, ime) = cx.with_paint(|render, widgets, v, _| {
457            let (coord, _, layer) = parts(widgets);
458            coord.set_default_layer(Some(layer.clone()));
459            coord.register_text_field(id.clone(), rect, config);
460            if let Some(p) = &parent {
461                coord.set_widget_parent(&id, p);
462            }
463            coord.set_a11y(&id, if name.is_empty() { placeholder } else { name }, None);
464            coord.set_default_layer(None);
465            if let Some(t) = set {
466                let fields = coord.text_fields_mut();
467                fields.clear(&id);
468                if !t.is_empty() {
469                    fields.set_text(&id, t);
470                }
471            }
472            let focused = v.is_focused(&id);
473            let (text, caret, preedit) = coord.text_fields().field_state(&id).map(|s| s.display()).unwrap_or_default();
474            let shown = if masked { "\u{2022}".repeat(text.chars().count()) } else { text.clone() };
475            if clip {
476                render.save();
477                render.begin_path();
478                render.rect(fr.x, fr.y, fr.width, fr.height);
479                render.clip();
480            }
481            let pos = draw_field_text_ime(render, fr, &shown, placeholder, focused.then_some(caret), preedit, px, &color, &ph_color, family);
482            if clip {
483                render.restore();
484            }
485            let ime = (focused && caret < pos.len()).then(|| Rect::new(pos[caret], fr.y, 1.0, fr.height));
486            let fields = coord.text_fields_mut();
487            let pos = match fields.field_state(&id) {
488                Some(s) => s.buffer_positions(pos),
489                None => pos,
490            };
491            fields.update_field(&id, (fr.x, fr.y, fr.width, fr.height), pos);
492            (FieldResponse { text, focused }, ime)
493        });
494        if let Some(at) = ime {
495            cx.ime_area(at);
496        }
497        out
498    }
499}
500
501// -- tabs -------------------------------------------------------------------
502
503/// A row of equal-width tabs. Start with [`tabs`].
504pub struct TabsBuilder<'a> {
505    id: WidgetId,
506    rect: Rect,
507    labels: &'a [&'a str],
508    selected: usize,
509    bind: Option<&'a mut usize>,
510}
511
512/// Tabs labelled `labels`, laid out across `rect`. Parts are `"{id}:tab:{i}"`.
513pub fn tabs<'a>(id: impl Into<WidgetId>, rect: Rect, labels: &'a [&'a str]) -> TabsBuilder<'a> {
514    TabsBuilder { id: id.into(), rect, labels, selected: 0, bind: None }
515}
516
517impl<'a> TabsBuilder<'a> {
518    /// The active tab.
519    pub fn selected(mut self, i: usize) -> Self {
520        self.selected = i;
521        self
522    }
523    /// Read the active tab from `i` and write a click back to it.
524    pub fn bind(mut self, i: &'a mut usize) -> Self {
525        self.selected = *i;
526        self.bind = Some(i);
527        self
528    }
529
530    /// Register and draw.
531    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
532        let theme = theme_of(cx);
533        let n = self.labels.len().max(1) as f64;
534        let w = self.rect.width / n;
535        let mut r = cx.with_paint(|render, widgets, v, _| {
536            let mut r = Response::of(v, &self.id);
537            r.index = picked(v, &self.id, "tab");
538            let settings = TabSettings { theme: Box::new(theme), ..Default::default() };
539            let (coord, _, layer) = parts(widgets);
540            let active = r.index.unwrap_or(self.selected);
541            for (i, label) in self.labels.iter().enumerate() {
542                let tid = child(&self.id, "tab", i);
543                let tr = Rect::new(self.rect.x + w * i as f64, self.rect.y, w, self.rect.height);
544                register_tab_on_layer(coord, tid.clone(), tr, focusable(), None, layer);
545                coord.set_a11y(&tid, *label, Some(i == active));
546                r.hovered |= v.is_hovered(&tid);
547                r.focused |= v.is_focused(&tid);
548                let mut cfg = TabConfig::new(tid.as_str(), *label);
549                cfg.active = i == active;
550                let view = TabView { tab: &cfg, hovered: v.is_hovered(&tid), pressed: v.is_pressed(&tid), close_btn_hovered: false };
551                draw_tab(render, tr, &view, &settings);
552            }
553            r
554        });
555        if let Some(i) = r.index {
556            r.changed = i != self.selected;
557            if let Some(b) = self.bind {
558                *b = i;
559            }
560        }
561        r
562    }
563}
564
565// -- list -------------------------------------------------------------------
566
567/// A vertical list of selectable text rows. Start with [`list`].
568pub struct ListBuilder<'a> {
569    id: WidgetId,
570    rect: Rect,
571    rows: &'a [&'a str],
572    row_height: f64,
573    scroll: f64,
574    selected: Option<usize>,
575    bind: Option<&'a mut Option<usize>>,
576}
577
578/// Rows `rows` inside `rect`. Parts are `"{id}:row:{i}"`. Rows outside
579/// `rect` (after `.scroll`) are neither painted nor hit.
580pub fn list<'a>(id: impl Into<WidgetId>, rect: Rect, rows: &'a [&'a str]) -> ListBuilder<'a> {
581    ListBuilder { id: id.into(), rect, rows, row_height: 28.0, scroll: 0.0, selected: None, bind: None }
582}
583
584impl<'a> ListBuilder<'a> {
585    /// Row height in px (default 28).
586    pub fn row_height(mut self, h: f64) -> Self {
587        self.row_height = h;
588        self
589    }
590    /// Scroll offset in px from the top.
591    pub fn scroll(mut self, y: f64) -> Self {
592        self.scroll = y;
593        self
594    }
595    /// The highlighted row.
596    pub fn selected(mut self, i: Option<usize>) -> Self {
597        self.selected = i;
598        self
599    }
600    /// Read the selection from `i` and write a click back to it.
601    pub fn bind(mut self, i: &'a mut Option<usize>) -> Self {
602        self.selected = *i;
603        self.bind = Some(i);
604        self
605    }
606    /// Total content height, for a scrollbar.
607    pub fn content_height(&self) -> f64 {
608        self.rows.len() as f64 * self.row_height
609    }
610
611    /// Register and draw.
612    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
613        let theme = theme_of(cx);
614        let mut r = cx.with_paint(|render, widgets, v, _| {
615            let mut r = Response::of(v, &self.id);
616            r.index = picked(v, &self.id, "row");
617            let settings = ItemSettings::default().with_theme(Box::new(theme));
618            let (coord, _, layer) = parts(widgets);
619            let sel = r.index.or(self.selected);
620            let (top, bottom) = (self.rect.y, self.rect.y + self.rect.height);
621            for (i, row) in self.rows.iter().enumerate() {
622                let y = top + i as f64 * self.row_height - self.scroll;
623                if y < top || y + self.row_height > bottom {
624                    continue;
625                }
626                let rid = child(&self.id, "row", i);
627                let rr = Rect::new(self.rect.x, y, self.rect.width, self.row_height);
628                coord.register_atomic(rid.clone(), WidgetKind::Item, rr, focusable(), layer);
629                coord.set_a11y(&rid, *row, Some(sel == Some(i)));
630                r.hovered |= v.is_hovered(&rid);
631                r.focused |= v.is_focused(&rid);
632                let ws = if sel == Some(i) { WidgetState::Active } else { interaction_state(v, &rid, false) };
633                let view = ItemView { label: Some(row), icon: None, svg: None };
634                draw_item(render, rr, ws, &view, &settings, &ItemRenderKind::Label, |_, _, _, _| {}, |_, _, _, _| {});
635            }
636            r
637        });
638        if let Some(i) = r.index {
639            r.changed = Some(i) != self.selected;
640            if let Some(b) = self.bind {
641                *b = Some(i);
642            }
643        }
644        r
645    }
646}
647
648// -- table ------------------------------------------------------------------
649
650/// A table with a header row and selectable body rows. Start with [`table`].
651pub struct TableBuilder<'a> {
652    id: WidgetId,
653    rect: Rect,
654    columns: &'a [&'a str],
655    rows: &'a [Vec<String>],
656    tracks: Option<&'a str>,
657    row_height: f64,
658    scroll: f64,
659    selected: Option<usize>,
660    bind: Option<&'a mut Option<usize>>,
661    font: &'a str,
662}
663
664/// A table of `rows` under `columns` in `rect`. Parts are `"{id}:col:{j}"`
665/// (header cells, a click reports `column`) and `"{id}:row:{i}"` (rows, a
666/// click reports `index`). Rows outside `rect` after `.scroll` are skipped.
667pub fn table<'a>(id: impl Into<WidgetId>, rect: Rect, columns: &'a [&'a str], rows: &'a [Vec<String>]) -> TableBuilder<'a> {
668    TableBuilder {
669        id: id.into(),
670        rect,
671        columns,
672        rows,
673        tracks: None,
674        row_height: 28.0,
675        scroll: 0.0,
676        selected: None,
677        bind: None,
678        font: "13px sans-serif",
679    }
680}
681
682impl<'a> TableBuilder<'a> {
683    /// Column widths as CSS grid tracks (`"2fr 1fr 80px"`, `minmax()`); default equal `1fr`.
684    pub fn columns(mut self, tracks: &'a str) -> Self {
685        self.tracks = Some(tracks);
686        self
687    }
688    /// Header and row height in px (default 28).
689    pub fn row_height(mut self, h: f64) -> Self {
690        self.row_height = h;
691        self
692    }
693    /// Body scroll offset in px (the header stays put, like `position: sticky`).
694    pub fn scroll(mut self, y: f64) -> Self {
695        self.scroll = y;
696        self
697    }
698    /// The highlighted row.
699    pub fn selected(mut self, i: Option<usize>) -> Self {
700        self.selected = i;
701        self
702    }
703    /// Read the selection from `i` and write a row click back to it.
704    pub fn bind(mut self, i: &'a mut Option<usize>) -> Self {
705        self.selected = *i;
706        self.bind = Some(i);
707        self
708    }
709    /// Cell font shorthand.
710    pub fn font(mut self, f: &'a str) -> Self {
711        self.font = f;
712        self
713    }
714    /// Body content height, for a scrollbar.
715    pub fn content_height(&self) -> f64 {
716        self.rows.len() as f64 * self.row_height
717    }
718
719    /// Register and draw.
720    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
721        use uzor::ui::widgets::atomic::text::theme::TextTheme;
722        use uzor::ui::widgets::composite::panel::theme::PanelTheme;
723        let theme = theme_of(cx);
724        let Self { id, rect, columns, rows, tracks, row_height, scroll, selected, bind, font } = self;
725        let mut r = cx.with_paint(|render, widgets, v, _| {
726            let mut r = Response::of(v, &id);
727            r.index = picked(v, &id, "row");
728            r.column = picked(v, &id, "col");
729            let (coord, _, layer) = parts(widgets);
730            let even = vec!["1fr"; columns.len().max(1)].join(" ");
731            let spec = tracks.unwrap_or(&even);
732            let cols = uzor::ui::flow::grid_tracks(rect.width, &uzor::ui::flow::parse_tracks(spec, rect.width, 0.0), 0.0);
733            let sel = r.index.or(selected);
734            render.set_font(font);
735            render.set_text_align(uzor::render::TextAlign::Left);
736            render.set_text_baseline(uzor::render::TextBaseline::Middle);
737            let cells = |render: &mut dyn RenderContext, y: f64, texts: &mut dyn Iterator<Item = &str>, color: &str| {
738                render.set_fill_color(color);
739                for ((x, w), t) in cols.iter().zip(texts) {
740                    render.save();
741                    render.clip_rect(rect.x + x, y, *w, row_height);
742                    render.fill_text(t, rect.x + x + 8.0, y + row_height / 2.0);
743                    render.restore();
744                }
745            };
746            // Header.
747            render.set_fill_color(theme.column_header_bg());
748            render.fill_rect(rect.x, rect.y, rect.width, row_height);
749            for (j, (x, w)) in cols.iter().enumerate().take(columns.len()) {
750                let cid = child(&id, "col", j);
751                coord.register_atomic(cid.clone(), WidgetKind::Item, Rect::new(rect.x + x, rect.y, *w, row_height), focusable(), layer);
752                coord.set_a11y(&cid, columns[j], None);
753                r.hovered |= v.is_hovered(&cid);
754                r.focused |= v.is_focused(&cid);
755            }
756            cells(render, rect.y, &mut columns.iter().copied(), theme.column_header_text());
757            // Body.
758            let (top, bottom) = (rect.y + row_height, rect.y + rect.height);
759            for (i, row) in rows.iter().enumerate() {
760                let y = top + i as f64 * row_height - scroll;
761                if y < top || y + row_height > bottom {
762                    continue;
763                }
764                let rid = child(&id, "row", i);
765                let rr = Rect::new(rect.x, y, rect.width, row_height);
766                coord.register_atomic(rid.clone(), WidgetKind::Item, rr, focusable(), layer);
767                coord.set_a11y(&rid, &row.join(", "), Some(sel == Some(i)));
768                let hov = v.is_hovered(&rid);
769                r.hovered |= hov;
770                r.focused |= v.is_focused(&rid);
771                let bg = if sel == Some(i) { theme.row_bg_selected() } else if hov { theme.row_bg_hover() } else { theme.row_bg_normal() };
772                render.set_fill_color(bg);
773                render.fill_rect(rr.x, rr.y, rr.width, rr.height);
774                render.set_fill_color(theme.divider());
775                render.fill_rect(rr.x, rr.y + rr.height - 1.0, rr.width, 1.0);
776                cells(render, y, &mut row.iter().map(String::as_str), theme.text_color());
777            }
778            r
779        });
780        if let Some(i) = r.index {
781            r.changed = Some(i) != selected;
782            if let Some(b) = bind {
783                *b = Some(i);
784            }
785        }
786        r
787    }
788}
789
790// -- drawer -----------------------------------------------------------------
791
792/// The edge a drawer slides from.
793#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
794pub enum Side {
795    /// From the left edge.
796    Left,
797    /// From the right edge (default).
798    #[default]
799    Right,
800}
801
802/// A side panel over the content with a scrim. Start with [`drawer`].
803pub struct DrawerBuilder<'a> {
804    id: WidgetId,
805    area: Rect,
806    open: &'a mut bool,
807    side: Side,
808    width: f64,
809    title: Option<&'a str>,
810    progress: f64,
811    dim: bool,
812}
813
814/// A drawer over `area`, shown while `*open`. A click on the scrim
815/// (`"{id}:scrim"`) clears `open` and reports `changed`. Paint the body in
816/// [`DrawerBuilder::body_rect`] after `build`.
817pub fn drawer<'a>(id: impl Into<WidgetId>, area: Rect, open: &'a mut bool) -> DrawerBuilder<'a> {
818    DrawerBuilder { id: id.into(), area, open, side: Side::Right, width: 320.0, title: None, progress: 1.0, dim: true }
819}
820
821impl<'a> DrawerBuilder<'a> {
822    /// Edge it slides from.
823    pub fn side(mut self, s: Side) -> Self {
824        self.side = s;
825        self
826    }
827    /// Panel width in px (default 320, capped to the area).
828    pub fn width(mut self, w: f64) -> Self {
829        self.width = w;
830        self
831    }
832    /// Accessible name.
833    pub fn title(mut self, t: &'a str) -> Self {
834        self.title = Some(t);
835        self
836    }
837    /// Slide position, 0 (hidden) to 1 (shown): drive it from a
838    /// [`Motion`](uzor::ui::motion::Motion) value or a timer for an animated open.
839    pub fn progress(mut self, t: f64) -> Self {
840        self.progress = t.clamp(0.0, 1.0);
841        self
842    }
843    /// Dim the content behind (default on).
844    pub fn dim(mut self, on: bool) -> Self {
845        self.dim = on;
846        self
847    }
848    /// The panel's rect at the current progress.
849    pub fn body_rect(&self) -> Rect {
850        let w = self.width.min(self.area.width);
851        let shown = w * self.progress;
852        let x = match self.side {
853            Side::Left => self.area.x - w + shown,
854            Side::Right => self.area.x + self.area.width - shown,
855        };
856        Rect::new(x, self.area.y, w, self.area.height)
857    }
858
859    /// Register and draw the scrim and the panel frame.
860    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
861        use uzor::ui::widgets::composite::modal::theme::ModalTheme;
862        use uzor::ui::widgets::composite::panel::theme::PanelTheme;
863        if !*self.open {
864            return Response::default();
865        }
866        let theme = theme_of(cx);
867        let body = self.body_rect();
868        let scrim = WidgetId::from(format!("{}:scrim", self.id.as_str()));
869        let r = cx.with_paint(|render, widgets, v, _| {
870            let (coord, _, layer) = parts(widgets);
871            coord.register_atomic(scrim.clone(), WidgetKind::Custom, self.area, Sense::CLICK, layer);
872            coord.register_atomic(self.id.clone(), WidgetKind::Custom, body, Sense::CLICK | Sense::HOVER, layer);
873            coord.set_a11y(&self.id, self.title.unwrap_or(""), None);
874            if self.dim {
875                render.set_global_alpha(self.progress);
876                render.set_fill_color(ModalTheme::backdrop_dim(&theme));
877                render.fill_rect(self.area.x, self.area.y, self.area.width, self.area.height);
878                render.set_global_alpha(1.0);
879            }
880            render.set_fill_color(PanelTheme::bg(&theme));
881            render.fill_rect(body.x, body.y, body.width, body.height);
882            let edge = if self.side == Side::Right { body.x } else { body.x + body.width - 1.0 };
883            render.set_fill_color(PanelTheme::border(&theme));
884            render.fill_rect(edge, body.y, 1.0, body.height);
885            let mut r = Response::of(v, &self.id);
886            r.clicked = v.clicked(&scrim);
887            r
888        });
889        if r.clicked {
890            *self.open = false;
891            return Response { changed: true, ..r };
892        }
893        r
894    }
895}
896
897// -- select -----------------------------------------------------------------
898
899#[derive(Default)]
900struct SelectOpen(bool);
901
902/// A button that opens a list of options. Start with [`select`].
903pub struct SelectBuilder<'a> {
904    id: WidgetId,
905    rect: Rect,
906    options: &'a [&'a str],
907    selected: usize,
908    bind: Option<&'a mut usize>,
909    disabled: bool,
910}
911
912/// A select showing `options[selected]`. The trigger is `id`; options are
913/// `"{id}:list:item:{i}"`. The open flag lives in the widget state store.
914pub fn select<'a>(id: impl Into<WidgetId>, rect: Rect, options: &'a [&'a str]) -> SelectBuilder<'a> {
915    SelectBuilder { id: id.into(), rect, options, selected: 0, bind: None, disabled: false }
916}
917
918impl<'a> SelectBuilder<'a> {
919    /// The chosen option.
920    pub fn selected(mut self, i: usize) -> Self {
921        self.selected = i;
922        self
923    }
924    /// Read the choice from `i` and write a pick back to it.
925    pub fn bind(mut self, i: &'a mut usize) -> Self {
926        self.selected = *i;
927        self.bind = Some(i);
928        self
929    }
930    /// Disabled colours; does not open.
931    pub fn disabled(mut self, on: bool) -> Self {
932        self.disabled = on;
933        self
934    }
935
936    /// Register and draw (the open list paints after the trigger).
937    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
938        let theme = theme_of(cx);
939        let ids: Vec<String> = (0..self.options.len()).map(|i| i.to_string()).collect();
940        let mut r = cx.with_paint(|render, widgets, v, tokens| {
941            let mut r = Response::of(v, &self.id);
942            r.index = picked(v, &self.id, "list:item");
943            let open = {
944                let st = widgets.states.get_or_insert_with(WidgetId::from(format!("{}:open", self.id.as_str())), SelectOpen::default);
945                if self.disabled || r.index.is_some() || (st.0 && clicked_outside(v, &self.id)) {
946                    st.0 = false;
947                } else if r.clicked {
948                    st.0 = !st.0;
949                }
950                st.0
951            };
952            let label = self.options.get(r.index.unwrap_or(self.selected)).copied().unwrap_or("");
953            let view = ButtonView {
954                icon: None,
955                text: Some(label),
956                active: open,
957                disabled: self.disabled,
958                active_border: None,
959                hover_chevron: None,
960            };
961            let mut bs = button_settings(tokens);
962            bs.theme = Box::new(theme.clone());
963            paint_button(render, widgets, v, self.id.clone(), self.rect, &view, &bs);
964            widgets.coord.set_a11y(&self.id, label, None);
965            if open {
966                let items: Vec<DropdownItem<'_>> = self
967                    .options
968                    .iter()
969                    .zip(&ids)
970                    .map(|(l, id)| DropdownItem::Item {
971                        id: id.as_str(),
972                        label: l,
973                        icon: None,
974                        right: DropdownItemRight::None,
975                        disabled: false,
976                        danger: false,
977                        accent_color: None,
978                    })
979                    .collect();
980                let hovered = v.hovered().and_then(|w| w.as_str().strip_prefix(&format!("{}:list:item:", self.id.as_str())).map(str::to_owned));
981                let mut state = DropdownState::default();
982                state.open_below(self.rect, 4.0);
983                let dv = DropdownView {
984                    anchor: Some(self.rect),
985                    position_override: None,
986                    open: true,
987                    kind: DropdownViewKind::Flat { items: &items, hovered_id: hovered.as_deref(), submenu_items: None, submenu_hovered_id: None },
988                    size_mode: Default::default(),
989                    overflow: Default::default(),
990                    submenu_width: Default::default(),
991                };
992                let ds = DropdownSettings { theme: Box::new(theme), ..Default::default() };
993                let (coord, _, layer) = parts(widgets);
994                register_input_coordinator_dropdown(coord, WidgetId::from(format!("{}:list", self.id.as_str())), self.rect, &state, &dv, &ds, DropdownRenderKind::Flat, layer);
995                draw_dropdown(render, self.rect, &state, &dv, &ds, DropdownRenderKind::Flat);
996            }
997            r
998        });
999        if let Some(i) = r.index {
1000            r.changed = i != self.selected;
1001            if let Some(b) = self.bind {
1002                *b = i;
1003            }
1004        }
1005        r
1006    }
1007}
1008
1009// -- menu -------------------------------------------------------------------
1010
1011/// A context menu. Start with [`menu`].
1012pub struct MenuBuilder<'a> {
1013    id: WidgetId,
1014    at: (f64, f64),
1015    items: &'a [&'a str],
1016    open: &'a mut bool,
1017    title: Option<&'a str>,
1018    danger: Option<usize>,
1019}
1020
1021/// A menu of `items` at `at` while `*open`. Items are `"{id}:item:{i}"`.
1022/// A pick or a click elsewhere clears `*open`.
1023pub fn menu<'a>(id: impl Into<WidgetId>, at: (f64, f64), items: &'a [&'a str], open: &'a mut bool) -> MenuBuilder<'a> {
1024    MenuBuilder { id: id.into(), at, items, open, title: None, danger: None }
1025}
1026
1027impl<'a> MenuBuilder<'a> {
1028    /// Header line.
1029    pub fn title(mut self, t: &'a str) -> Self {
1030        self.title = Some(t);
1031        self
1032    }
1033    /// Draw item `i` in the danger colour (delete, sign out).
1034    pub fn danger(mut self, i: usize) -> Self {
1035        self.danger = Some(i);
1036        self
1037    }
1038
1039    /// Register and draw when open.
1040    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1041        if !*self.open {
1042            return Response::default();
1043        }
1044        let theme = theme_of(cx);
1045        let r = cx.with_paint(|render, widgets, v, _| {
1046            let mut r = Response::of(v, &self.id);
1047            r.index = picked(v, &self.id, "item");
1048            if r.index.is_some() || clicked_outside(v, &self.id) {
1049                return (r, false);
1050            }
1051            let items: Vec<ContextMenuItem<'_>> = self
1052                .items
1053                .iter()
1054                .enumerate()
1055                .map(|(i, l)| ContextMenuItem { action: l, label: l, icon: None, danger: self.danger == Some(i), separator_after: false, enabled: true })
1056                .collect();
1057            let state = ContextMenuState { is_open: true, x: self.at.0, y: self.at.1, ..Default::default() };
1058            let view = ContextMenuView { items: &items, target_id: None, title: self.title };
1059            let settings = ContextMenuSettings { theme: Box::new(theme), ..Default::default() };
1060            let (coord, _, layer) = parts(widgets);
1061            register_input_coordinator_context_menu(coord, self.id.clone(), &state, &view, &settings, &ContextMenuRenderKind::Default, layer);
1062            for (i, l) in self.items.iter().enumerate() {
1063                coord.set_a11y(&child(&self.id, "item", i), *l, None);
1064            }
1065            draw_context_menu(render, &state, &view, &settings, &ContextMenuRenderKind::Default);
1066            (r, true)
1067        });
1068        *self.open = r.1;
1069        let mut r = r.0;
1070        r.changed = r.index.is_some();
1071        r
1072    }
1073}
1074
1075// -- dialog -----------------------------------------------------------------
1076
1077/// A modal frame with a title, close button and footer. Start with [`dialog`].
1078pub struct DialogBuilder<'a> {
1079    id: WidgetId,
1080    rect: Rect,
1081    title: Option<&'a str>,
1082    footer: &'a [&'a str],
1083    dim: bool,
1084}
1085
1086/// A dialog in `rect`. Close is `"{id}:close"` (reported as `clicked`),
1087/// footer buttons `"{id}:footer:{i}"` (reported as `index`; the first is
1088/// primary). The app decides whether either closes it.
1089pub fn dialog<'a>(id: impl Into<WidgetId>, rect: Rect) -> DialogBuilder<'a> {
1090    DialogBuilder { id: id.into(), rect, title: None, footer: &[], dim: true }
1091}
1092
1093impl<'a> DialogBuilder<'a> {
1094    /// Header title, also the accessible name.
1095    pub fn title(mut self, t: &'a str) -> Self {
1096        self.title = Some(t);
1097        self
1098    }
1099    /// Footer button labels, primary first.
1100    pub fn footer(mut self, labels: &'a [&'a str]) -> Self {
1101        self.footer = labels;
1102        self
1103    }
1104    /// Dim what is behind (default on).
1105    pub fn dim(mut self, on: bool) -> Self {
1106        self.dim = on;
1107        self
1108    }
1109
1110    /// Register and draw the frame. Paint the body after this, inside the
1111    /// returned content area of `rect`.
1112    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1113        let theme = theme_of(cx);
1114        cx.with_paint(|render, widgets, v, _| {
1115            let mut r = Response::of(v, &self.id);
1116            r.clicked = v.clicked(&WidgetId::from(format!("{}:close", self.id.as_str())));
1117            r.index = picked(v, &self.id, "footer");
1118            r.changed = r.clicked || r.index.is_some();
1119            let buttons: Vec<FooterBtn<'_>> = self
1120                .footer
1121                .iter()
1122                .enumerate()
1123                .map(|(i, l)| FooterBtn { label: l, style: if i == 0 { FooterBtnStyle::Primary } else { FooterBtnStyle::Ghost } })
1124                .collect();
1125            let mut view = ModalView {
1126                title: self.title,
1127                tabs: &[],
1128                footer_buttons: &buttons,
1129                wizard_pages: &[],
1130                backdrop: if self.dim { BackdropKind::Dim } else { BackdropKind::None },
1131                overflow: Default::default(),
1132                resizable: false,
1133            };
1134            let kind = if buttons.is_empty() { ModalRenderKind::WithHeader } else { ModalRenderKind::WithHeaderFooter };
1135            let settings = ModalSettings { theme: Box::new(theme), ..Default::default() };
1136            let (coord, states, layer) = parts(widgets);
1137            let state = states.get_or_insert_with(self.id.clone(), ModalState::default);
1138            register_input_coordinator_modal(coord, self.id.clone(), self.rect, state, &mut view, &settings, &kind, layer);
1139            if let Some(t) = self.title {
1140                coord.set_a11y(&self.id, t, None);
1141            }
1142            for (i, l) in self.footer.iter().enumerate() {
1143                coord.set_a11y(&child(&self.id, "footer", i), *l, None);
1144            }
1145            coord.set_a11y(&WidgetId::from(format!("{}:close", self.id.as_str())), "Close", None);
1146            draw_modal(render, self.rect, state, &mut view, &settings, &kind);
1147            r
1148        })
1149    }
1150}
1151
1152// -- splitter ---------------------------------------------------------------
1153
1154/// A draggable pane edge. Start with [`splitter`].
1155pub struct SplitterBuilder<'a> {
1156    id: WidgetId,
1157    axis: Axis,
1158    span: Rect,
1159    pos: &'a mut f64,
1160    min: f64,
1161    max: f64,
1162    grab: f64,
1163}
1164
1165/// An edge at `*pos` along `axis` across `span`. Dragging writes `*pos`.
1166pub fn splitter<'a>(id: impl Into<WidgetId>, axis: Axis, span: Rect, pos: &'a mut f64) -> SplitterBuilder<'a> {
1167    SplitterBuilder { id: id.into(), axis, span, pos, min: f64::MIN, max: f64::MAX, grab: 9.0 }
1168}
1169
1170impl<'a> SplitterBuilder<'a> {
1171    /// Clamp the edge to `min..=max`.
1172    pub fn range(mut self, min: f64, max: f64) -> Self {
1173        self.min = min;
1174        self.max = max;
1175        self
1176    }
1177    /// Width of the grab strip in px (default 9).
1178    pub fn grab(mut self, px: f64) -> Self {
1179        self.grab = px;
1180        self
1181    }
1182
1183    /// Register and draw. `changed` is set on every drag step; `pressed`
1184    /// while dragging. Persist the size when the drag ends (`pressed` falls).
1185    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1186        let theme = theme_of(cx);
1187        cx.with_paint(|render, widgets, v, _| {
1188            let mut r = Response::of(v, &self.id);
1189            let (coord, states, layer) = parts(widgets);
1190            let s = states.get_or_insert_with(self.id.clone(), Splitter::default);
1191            if let SplitterEvent::Drag(p) = s.update(v, &self.id, self.axis) {
1192                let p = p.clamp(self.min, self.max);
1193                r.changed = (p - *self.pos).abs() > f64::EPSILON;
1194                *self.pos = p;
1195            }
1196            r.pressed = s.dragging();
1197            let hot = s.hot(v, &self.id);
1198            register_splitter(coord, self.id.clone(), grab_rect(self.axis, *self.pos, self.span, self.grab), layer);
1199            let (line, orientation) = match self.axis {
1200                Axis::X => (Rect::new(*self.pos, self.span.y, 1.0, self.span.height), SeparatorOrientation::Vertical),
1201                Axis::Y => (Rect::new(self.span.x, *self.pos, self.span.width, 1.0), SeparatorOrientation::Horizontal),
1202            };
1203            let view = SeparatorView { kind: SeparatorType::Divider { orientation }, hovered: hot, dragging: r.pressed };
1204            let settings = SeparatorSettings { theme: Box::new(theme), style: Box::new(DefaultSeparatorStyle) };
1205            draw_separator(render, line, &view, &settings);
1206            r
1207        })
1208    }
1209}
1210
1211// -- toast ------------------------------------------------------------------
1212
1213/// The toast stack. Start with [`toasts`].
1214pub struct ToastsBuilder<'a> {
1215    id: WidgetId,
1216    area: Rect,
1217    stack: &'a mut ToastStackState,
1218    now_ms: u64,
1219}
1220
1221/// Paint the live toasts of `stack` in the bottom-right of `area`, dropping
1222/// expired ones. Push new ones with [`ToastStackState::push`].
1223pub fn toasts<'a>(id: impl Into<WidgetId>, area: Rect, stack: &'a mut ToastStackState, now_ms: u64) -> ToastsBuilder<'a> {
1224    ToastsBuilder { id: id.into(), area, stack, now_ms }
1225}
1226
1227impl<'a> ToastsBuilder<'a> {
1228    /// Draw. `changed` is true while any toast is shown, so the app keeps
1229    /// asking for frames until the last one fades.
1230    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1231        let theme = theme_of(cx);
1232        let live = self.stack.tick(self.now_ms);
1233        cx.with_paint(|render, _widgets, v, _| {
1234            let mut r = Response::of(v, &self.id);
1235            r.changed = !live.is_empty();
1236            if r.changed {
1237                render.save();
1238                render.translate(self.area.x, self.area.y);
1239                draw_toast_stack(render, live, &theme, self.area.width, self.area.height, self.now_ms);
1240                render.restore();
1241            }
1242            r
1243        })
1244    }
1245}
1246
1247#[cfg(test)]
1248#[path = "kit_tests.rs"]
1249mod tests;