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