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