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            if masked {
493                coord.set_a11y_masked(&id);
494            }
495            coord.set_default_layer(None);
496            if let Some(t) = set {
497                let fields = coord.text_fields_mut();
498                fields.clear(&id);
499                if !t.is_empty() {
500                    fields.set_text(&id, t);
501                }
502            }
503            let focused = v.is_focused(&id);
504            let (text, caret, preedit, engaged, selection) = {
505                let fields = coord.text_fields();
506                match fields.field_state(&id) {
507                    Some(s) => {
508                        let (text, caret, preedit) = s.display();
509                        let selection = preedit.is_none().then(|| s.selection_range()).flatten();
510                        (text, caret, preedit, s.engaged, selection)
511                    }
512                    None => (String::new(), 0, None, false, None),
513                }
514            };
515            let shown = if masked { "\u{2022}".repeat(text.chars().count()) } else { text.clone() };
516            let blink = focused && engaged && coord.text_fields().cursor_visible(now_ms);
517            if clip {
518                render.save();
519                render.begin_path();
520                render.rect(fr.x, fr.y, fr.width, fr.height);
521                render.clip();
522            }
523            if let Some(range) = selection {
524                render.set_font(&format!("400 {px}px {family}"));
525                paint_field_selection(render, fr.x, fr.y, fr.height, &shown, range, &sel_color);
526            }
527            let pos = draw_field_text_ime(render, fr, &shown, placeholder, blink.then_some(caret), preedit, px, &color, &ph_color, family);
528            if clip {
529                render.restore();
530            }
531            let ime = (focused && caret < pos.len()).then(|| Rect::new(pos[caret], fr.y, 1.0, fr.height));
532            let fields = coord.text_fields_mut();
533            let pos = match fields.field_state(&id) {
534                Some(s) => s.buffer_positions(pos),
535                None => pos,
536            };
537            fields.update_field(&id, (fr.x, fr.y, fr.width, fr.height), pos);
538            (FieldResponse { text, focused }, ime)
539        });
540        if let Some(at) = ime {
541            cx.ime_area(at);
542        }
543        out
544    }
545}
546
547// -- tabs -------------------------------------------------------------------
548
549/// A row of equal-width tabs. Start with [`tabs`].
550pub struct TabsBuilder<'a> {
551    id: WidgetId,
552    rect: Rect,
553    labels: &'a [&'a str],
554    selected: usize,
555    bind: Option<&'a mut usize>,
556}
557
558/// Tabs labelled `labels`, laid out across `rect`. Parts are `"{id}:tab:{i}"`.
559pub fn tabs<'a>(id: impl Into<WidgetId>, rect: Rect, labels: &'a [&'a str]) -> TabsBuilder<'a> {
560    TabsBuilder { id: id.into(), rect, labels, selected: 0, bind: None }
561}
562
563impl<'a> TabsBuilder<'a> {
564    /// The active tab.
565    pub fn selected(mut self, i: usize) -> Self {
566        self.selected = i;
567        self
568    }
569    /// Read the active tab from `i` and write a click back to it.
570    pub fn bind(mut self, i: &'a mut usize) -> Self {
571        self.selected = *i;
572        self.bind = Some(i);
573        self
574    }
575
576    /// Register and draw.
577    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
578        let theme = theme_of(cx);
579        let n = self.labels.len().max(1) as f64;
580        let w = self.rect.width / n;
581        let mut r = cx.with_paint(|render, widgets, v, _| {
582            let mut r = Response::of(v, &self.id);
583            r.index = picked(v, &self.id, "tab");
584            let settings = TabSettings { theme: Box::new(theme), ..Default::default() };
585            let (coord, _, layer) = parts(widgets);
586            let active = r.index.unwrap_or(self.selected);
587            for (i, label) in self.labels.iter().enumerate() {
588                let tid = child(&self.id, "tab", i);
589                let tr = Rect::new(self.rect.x + w * i as f64, self.rect.y, w, self.rect.height);
590                register_tab_on_layer(coord, tid.clone(), tr, focusable(), None, layer);
591                coord.set_a11y(&tid, *label, Some(i == active));
592                r.hovered |= v.is_hovered(&tid);
593                r.focused |= v.is_focused(&tid);
594                let mut cfg = TabConfig::new(tid.as_str(), *label);
595                cfg.active = i == active;
596                let view = TabView { tab: &cfg, hovered: v.is_hovered(&tid), pressed: v.is_pressed(&tid), close_btn_hovered: false };
597                draw_tab(render, tr, &view, &settings);
598            }
599            r
600        });
601        if let Some(i) = r.index {
602            r.changed = i != self.selected;
603            if let Some(b) = self.bind {
604                *b = i;
605            }
606        }
607        r
608    }
609}
610
611// -- list -------------------------------------------------------------------
612
613/// A vertical list of selectable text rows. Start with [`list`].
614pub struct ListBuilder<'a> {
615    id: WidgetId,
616    rect: Rect,
617    rows: &'a [&'a str],
618    row_height: f64,
619    scroll: f64,
620    selected: Option<usize>,
621    bind: Option<&'a mut Option<usize>>,
622}
623
624/// Rows `rows` inside `rect`. Parts are `"{id}:row:{i}"`. Rows outside
625/// `rect` (after `.scroll`) are neither painted nor hit.
626pub fn list<'a>(id: impl Into<WidgetId>, rect: Rect, rows: &'a [&'a str]) -> ListBuilder<'a> {
627    ListBuilder { id: id.into(), rect, rows, row_height: 28.0, scroll: 0.0, selected: None, bind: None }
628}
629
630impl<'a> ListBuilder<'a> {
631    /// Row height in px (default 28).
632    pub fn row_height(mut self, h: f64) -> Self {
633        self.row_height = h;
634        self
635    }
636    /// Scroll offset in px from the top.
637    pub fn scroll(mut self, y: f64) -> Self {
638        self.scroll = y;
639        self
640    }
641    /// The highlighted row.
642    pub fn selected(mut self, i: Option<usize>) -> Self {
643        self.selected = i;
644        self
645    }
646    /// Read the selection from `i` and write a click back to it.
647    pub fn bind(mut self, i: &'a mut Option<usize>) -> Self {
648        self.selected = *i;
649        self.bind = Some(i);
650        self
651    }
652    /// Total content height, for a scrollbar.
653    pub fn content_height(&self) -> f64 {
654        self.rows.len() as f64 * self.row_height
655    }
656
657    /// Register and draw.
658    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
659        let theme = theme_of(cx);
660        let mut r = cx.with_paint(|render, widgets, v, _| {
661            let mut r = Response::of(v, &self.id);
662            r.index = picked(v, &self.id, "row");
663            let settings = ItemSettings::default().with_theme(Box::new(theme));
664            let (coord, _, layer) = parts(widgets);
665            let sel = r.index.or(self.selected);
666            let (top, bottom) = (self.rect.y, self.rect.y + self.rect.height);
667            for (i, row) in self.rows.iter().enumerate() {
668                let y = top + i as f64 * self.row_height - self.scroll;
669                if y < top || y + self.row_height > bottom {
670                    continue;
671                }
672                let rid = child(&self.id, "row", i);
673                let rr = Rect::new(self.rect.x, y, self.rect.width, self.row_height);
674                coord.register_atomic(rid.clone(), WidgetKind::Item, rr, focusable(), layer);
675                coord.set_a11y(&rid, *row, Some(sel == Some(i)));
676                r.hovered |= v.is_hovered(&rid);
677                r.focused |= v.is_focused(&rid);
678                let ws = if sel == Some(i) { WidgetState::Active } else { interaction_state(v, &rid, false) };
679                let view = ItemView { label: Some(row), icon: None, svg: None };
680                draw_item(render, rr, ws, &view, &settings, &ItemRenderKind::Label, |_, _, _, _| {}, |_, _, _, _| {});
681            }
682            r
683        });
684        if let Some(i) = r.index {
685            r.changed = Some(i) != self.selected;
686            if let Some(b) = self.bind {
687                *b = Some(i);
688            }
689        }
690        r
691    }
692}
693
694// -- table ------------------------------------------------------------------
695
696/// A table with a header row and selectable body rows. Start with [`table`].
697pub struct TableBuilder<'a> {
698    id: WidgetId,
699    rect: Rect,
700    columns: &'a [&'a str],
701    rows: &'a [Vec<String>],
702    tracks: Option<&'a str>,
703    row_height: f64,
704    scroll: f64,
705    selected: Option<usize>,
706    bind: Option<&'a mut Option<usize>>,
707    font: &'a str,
708}
709
710/// A table of `rows` under `columns` in `rect`. Parts are `"{id}:col:{j}"`
711/// (header cells, a click reports `column`) and `"{id}:row:{i}"` (rows, a
712/// click reports `index`). Rows outside `rect` after `.scroll` are skipped.
713pub fn table<'a>(id: impl Into<WidgetId>, rect: Rect, columns: &'a [&'a str], rows: &'a [Vec<String>]) -> TableBuilder<'a> {
714    TableBuilder {
715        id: id.into(),
716        rect,
717        columns,
718        rows,
719        tracks: None,
720        row_height: 28.0,
721        scroll: 0.0,
722        selected: None,
723        bind: None,
724        font: "13px sans-serif",
725    }
726}
727
728impl<'a> TableBuilder<'a> {
729    /// Column widths as CSS grid tracks (`"2fr 1fr 80px"`, `minmax()`); default equal `1fr`.
730    pub fn columns(mut self, tracks: &'a str) -> Self {
731        self.tracks = Some(tracks);
732        self
733    }
734    /// Header and row height in px (default 28).
735    pub fn row_height(mut self, h: f64) -> Self {
736        self.row_height = h;
737        self
738    }
739    /// Body scroll offset in px (the header stays put, like `position: sticky`).
740    pub fn scroll(mut self, y: f64) -> Self {
741        self.scroll = y;
742        self
743    }
744    /// The highlighted row.
745    pub fn selected(mut self, i: Option<usize>) -> Self {
746        self.selected = i;
747        self
748    }
749    /// Read the selection from `i` and write a row click back to it.
750    pub fn bind(mut self, i: &'a mut Option<usize>) -> Self {
751        self.selected = *i;
752        self.bind = Some(i);
753        self
754    }
755    /// Cell font shorthand.
756    pub fn font(mut self, f: &'a str) -> Self {
757        self.font = f;
758        self
759    }
760    /// Body content height, for a scrollbar.
761    pub fn content_height(&self) -> f64 {
762        self.rows.len() as f64 * self.row_height
763    }
764
765    /// Register and draw.
766    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
767        use uzor::ui::widgets::atomic::text::theme::TextTheme;
768        use uzor::ui::widgets::composite::panel::theme::PanelTheme;
769        let theme = theme_of(cx);
770        let Self { id, rect, columns, rows, tracks, row_height, scroll, selected, bind, font } = self;
771        let mut r = cx.with_paint(|render, widgets, v, _| {
772            let mut r = Response::of(v, &id);
773            r.index = picked(v, &id, "row");
774            r.column = picked(v, &id, "col");
775            let (coord, _, layer) = parts(widgets);
776            let even = vec!["1fr"; columns.len().max(1)].join(" ");
777            let spec = tracks.unwrap_or(&even);
778            let cols = uzor::ui::flow::grid_tracks(rect.width, &uzor::ui::flow::parse_tracks(spec, rect.width, 0.0), 0.0);
779            let sel = r.index.or(selected);
780            render.set_font(font);
781            render.set_text_align(uzor::render::TextAlign::Left);
782            render.set_text_baseline(uzor::render::TextBaseline::Middle);
783            let cells = |render: &mut dyn RenderContext, y: f64, texts: &mut dyn Iterator<Item = &str>, color: &str| {
784                render.set_fill_color(color);
785                for ((x, w), t) in cols.iter().zip(texts) {
786                    render.save();
787                    render.clip_rect(rect.x + x, y, *w, row_height);
788                    render.fill_text(t, rect.x + x + 8.0, y + row_height / 2.0);
789                    render.restore();
790                }
791            };
792            // Header.
793            render.set_fill_color(theme.column_header_bg());
794            render.fill_rect(rect.x, rect.y, rect.width, row_height);
795            for (j, (x, w)) in cols.iter().enumerate().take(columns.len()) {
796                let cid = child(&id, "col", j);
797                coord.register_atomic(cid.clone(), WidgetKind::Item, Rect::new(rect.x + x, rect.y, *w, row_height), focusable(), layer);
798                coord.set_a11y(&cid, columns[j], None);
799                r.hovered |= v.is_hovered(&cid);
800                r.focused |= v.is_focused(&cid);
801            }
802            cells(render, rect.y, &mut columns.iter().copied(), theme.column_header_text());
803            // Body.
804            let (top, bottom) = (rect.y + row_height, rect.y + rect.height);
805            for (i, row) in rows.iter().enumerate() {
806                let y = top + i as f64 * row_height - scroll;
807                if y < top || y + row_height > bottom {
808                    continue;
809                }
810                let rid = child(&id, "row", i);
811                let rr = Rect::new(rect.x, y, rect.width, row_height);
812                coord.register_atomic(rid.clone(), WidgetKind::Item, rr, focusable(), layer);
813                coord.set_a11y(&rid, &row.join(", "), Some(sel == Some(i)));
814                let hov = v.is_hovered(&rid);
815                r.hovered |= hov;
816                r.focused |= v.is_focused(&rid);
817                let bg = if sel == Some(i) { theme.row_bg_selected() } else if hov { theme.row_bg_hover() } else { theme.row_bg_normal() };
818                render.set_fill_color(bg);
819                render.fill_rect(rr.x, rr.y, rr.width, rr.height);
820                render.set_fill_color(theme.divider());
821                render.fill_rect(rr.x, rr.y + rr.height - 1.0, rr.width, 1.0);
822                cells(render, y, &mut row.iter().map(String::as_str), theme.text_color());
823            }
824            r
825        });
826        if let Some(i) = r.index {
827            r.changed = Some(i) != selected;
828            if let Some(b) = bind {
829                *b = Some(i);
830            }
831        }
832        r
833    }
834}
835
836// -- drawer -----------------------------------------------------------------
837
838/// The edge a drawer slides from.
839#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
840pub enum Side {
841    /// From the left edge.
842    Left,
843    /// From the right edge (default).
844    #[default]
845    Right,
846}
847
848/// A side panel over the content with a scrim. Start with [`drawer`].
849pub struct DrawerBuilder<'a> {
850    id: WidgetId,
851    area: Rect,
852    open: &'a mut bool,
853    side: Side,
854    width: f64,
855    title: Option<&'a str>,
856    progress: f64,
857    dim: bool,
858}
859
860/// A drawer over `area`, shown while `*open`. A click on the scrim
861/// (`"{id}:scrim"`) clears `open` and reports `changed`. Paint the body in
862/// [`DrawerBuilder::body_rect`] after `build`.
863pub fn drawer<'a>(id: impl Into<WidgetId>, area: Rect, open: &'a mut bool) -> DrawerBuilder<'a> {
864    DrawerBuilder { id: id.into(), area, open, side: Side::Right, width: 320.0, title: None, progress: 1.0, dim: true }
865}
866
867impl<'a> DrawerBuilder<'a> {
868    /// Edge it slides from.
869    pub fn side(mut self, s: Side) -> Self {
870        self.side = s;
871        self
872    }
873    /// Panel width in px (default 320, capped to the area).
874    pub fn width(mut self, w: f64) -> Self {
875        self.width = w;
876        self
877    }
878    /// Accessible name.
879    pub fn title(mut self, t: &'a str) -> Self {
880        self.title = Some(t);
881        self
882    }
883    /// Slide position, 0 (hidden) to 1 (shown): drive it from a
884    /// [`Motion`](uzor::ui::motion::Motion) value or a timer for an animated open.
885    pub fn progress(mut self, t: f64) -> Self {
886        self.progress = t.clamp(0.0, 1.0);
887        self
888    }
889    /// Dim the content behind (default on).
890    pub fn dim(mut self, on: bool) -> Self {
891        self.dim = on;
892        self
893    }
894    /// The panel's rect at the current progress.
895    pub fn body_rect(&self) -> Rect {
896        let w = self.width.min(self.area.width);
897        let shown = w * self.progress;
898        let x = match self.side {
899            Side::Left => self.area.x - w + shown,
900            Side::Right => self.area.x + self.area.width - shown,
901        };
902        Rect::new(x, self.area.y, w, self.area.height)
903    }
904
905    /// Register and draw the scrim and the panel frame.
906    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
907        use uzor::ui::widgets::composite::modal::theme::ModalTheme;
908        use uzor::ui::widgets::composite::panel::theme::PanelTheme;
909        if !*self.open {
910            return Response::default();
911        }
912        let theme = theme_of(cx);
913        let body = self.body_rect();
914        let scrim = WidgetId::from(format!("{}:scrim", self.id.as_str()));
915        let r = cx.with_paint(|render, widgets, v, _| {
916            let (coord, _, layer) = parts(widgets);
917            coord.register_atomic(scrim.clone(), WidgetKind::Custom, self.area, Sense::CLICK, layer);
918            coord.register_atomic(self.id.clone(), WidgetKind::Custom, body, Sense::CLICK | Sense::HOVER, layer);
919            coord.set_a11y(&self.id, self.title.unwrap_or(""), None);
920            if self.dim {
921                render.set_global_alpha(self.progress);
922                render.set_fill_color(ModalTheme::backdrop_dim(&theme));
923                render.fill_rect(self.area.x, self.area.y, self.area.width, self.area.height);
924                render.set_global_alpha(1.0);
925            }
926            render.set_fill_color(PanelTheme::bg(&theme));
927            render.fill_rect(body.x, body.y, body.width, body.height);
928            let edge = if self.side == Side::Right { body.x } else { body.x + body.width - 1.0 };
929            render.set_fill_color(PanelTheme::border(&theme));
930            render.fill_rect(edge, body.y, 1.0, body.height);
931            let mut r = Response::of(v, &self.id);
932            r.clicked = v.clicked(&scrim);
933            r
934        });
935        if r.clicked {
936            *self.open = false;
937            return Response { changed: true, ..r };
938        }
939        r
940    }
941}
942
943// -- select -----------------------------------------------------------------
944
945#[derive(Default)]
946struct SelectOpen {
947    open: bool,
948    list: SelectState,
949}
950
951/// A button that opens a list of options. Start with [`select`].
952pub struct SelectBuilder<'a> {
953    id: WidgetId,
954    rect: Rect,
955    options: &'a [&'a str],
956    selected: usize,
957    bind: Option<&'a mut usize>,
958    disabled: bool,
959    searchable: Option<bool>,
960    within: Option<Rect>,
961    style: Option<SelectStyle>,
962    key: Option<&'a KeyInput>,
963}
964
965/// A select showing `options[selected]`. The trigger is `id`; options are
966/// `"{id}:list:item:{i}"` (`i` = index into `options`). The open state (flag,
967/// highlighted row, search text, scroll) lives in the widget state store.
968///
969/// The open list behaves like a native one ([`SelectState`]): forward this
970/// frame's key with [`.key`](SelectBuilder::key) and arrows / Page / Home /
971/// End move, Enter picks, Escape closes, typing filters a searchable list;
972/// Enter, Space or ArrowDown on the focused trigger opens it. The list opens
973/// under the trigger and stays inside [`.within`](SelectBuilder::within)
974/// (the dialog that hosts it), flipping above or shifting as needed.
975pub fn select<'a>(id: impl Into<WidgetId>, rect: Rect, options: &'a [&'a str]) -> SelectBuilder<'a> {
976    SelectBuilder { id: id.into(), rect, options, selected: 0, bind: None, disabled: false, searchable: None, within: None, style: None, key: None }
977}
978
979/// Whether the select `id` is open (its list shows). An app that closes its
980/// dialog on Escape asks this first: Escape belongs to the open list.
981pub fn select_is_open<'c, C: ContentCx<'c>>(cx: &mut C, id: &str) -> bool {
982    cx.with_paint(|_, widgets, _, _| widgets.states.get_or_insert_with(WidgetId::from(format!("{id}:open")), SelectOpen::default).open)
983}
984
985impl<'a> SelectBuilder<'a> {
986    /// The chosen option.
987    pub fn selected(mut self, i: usize) -> Self {
988        self.selected = i;
989        self
990    }
991    /// Read the choice from `i` and write a pick back to it.
992    pub fn bind(mut self, i: &'a mut usize) -> Self {
993        self.selected = *i;
994        self.bind = Some(i);
995        self
996    }
997    /// Disabled colours; does not open.
998    pub fn disabled(mut self, on: bool) -> Self {
999        self.disabled = on;
1000        self
1001    }
1002    /// A search line on top of the list (default: more options than the list shows).
1003    pub fn searchable(mut self, on: bool) -> Self {
1004        self.searchable = Some(on);
1005        self
1006    }
1007    /// Keep the open list inside `container` (a modal card, a panel).
1008    pub fn within(mut self, container: Rect) -> Self {
1009        self.within = Some(container);
1010        self
1011    }
1012    /// The list's look (e.g. `SelectStyle::from_sheet(&sheet, "div.select-list")`).
1013    pub fn style(mut self, s: SelectStyle) -> Self {
1014        self.style = Some(s);
1015        self
1016    }
1017    /// This frame's key press, if any (the app forwards unhandled keys).
1018    pub fn key(mut self, k: Option<&'a KeyInput>) -> Self {
1019        self.key = k.filter(|k| k.state != crate::KeyState::Up);
1020        self
1021    }
1022
1023    /// Register and draw (the open list paints after the trigger). `Response::checked`
1024    /// tells whether the list is open after this frame; `Response::pressed` that the key
1025    /// given to [`.key`](Self::key) was used.
1026    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1027        let theme = theme_of(cx);
1028        let ls = self.style.unwrap_or_default();
1029        let searchable = self.searchable.unwrap_or(self.options.len() > ls.window());
1030        let ls = match self.within {
1031            Some(w) => ls.fit(room(self.rect, w, ls.gap), searchable),
1032            None => ls,
1033        };
1034        let win = ls.window();
1035        let labels: Vec<(&str, &str)> = self.options.iter().map(|o| (*o, *o)).collect();
1036        let mut r = cx.with_paint(|render, widgets, v, tokens| {
1037            let mut r = Response::of(v, &self.id);
1038            let sid = WidgetId::from(format!("{}:open", self.id.as_str()));
1039            let mut key_used = false;
1040            let mut close = false;
1041            let (open, list) = {
1042                let st = widgets.states.get_or_insert_with(sid, SelectOpen::default);
1043                r.index = picked(v, &self.id, "list:item");
1044                let was = st.open;
1045                if self.disabled || r.index.is_some() || (st.open && clicked_outside(v, &self.id)) {
1046                    st.open = false;
1047                } else if r.clicked {
1048                    st.open = !st.open;
1049                } else if let Some(k) = self.key {
1050                    use uzor::input::keyboard::KeyCode as K;
1051                    if st.open {
1052                        let rows = filter(&labels, &st.list.query);
1053                        match st.list.key(k.code, k.text.as_deref(), k.mods.ctrl || k.mods.meta, rows.len(), searchable, win) {
1054                            SelectKey::Changed => key_used = true,
1055                            SelectKey::Pick(i) => {
1056                                r.index = rows.get(i).copied();
1057                                st.open = false;
1058                                key_used = true;
1059                            }
1060                            SelectKey::Close => {
1061                                close = true;
1062                                key_used = true;
1063                            }
1064                            SelectKey::Ignored => {}
1065                        }
1066                    } else if r.focused && matches!(k.code, K::Enter | K::Space | K::ArrowDown) {
1067                        st.open = true;
1068                        key_used = true;
1069                    }
1070                }
1071                if close {
1072                    st.open = false;
1073                }
1074                if st.open && !was {
1075                    st.list = SelectState::open_at(Some(self.selected), win);
1076                }
1077                (st.open, st.list.clone())
1078            };
1079            r.pressed = key_used;
1080            let label = self.options.get(r.index.unwrap_or(self.selected)).copied().unwrap_or("");
1081            let view = ButtonView {
1082                icon: None,
1083                text: Some(label),
1084                active: open,
1085                disabled: self.disabled,
1086                active_border: None,
1087                hover_chevron: None,
1088            };
1089            let mut bs = button_settings(tokens);
1090            bs.theme = Box::new(theme.clone());
1091            paint_button(render, widgets, v, self.id.clone(), self.rect, &view, &bs);
1092            widgets.coord.set_a11y(&self.id, label, None);
1093            if open {
1094                let rows = filter(&labels, &list.query);
1095                let (w, h) = ls.list_size(rows.len(), searchable, self.rect.width);
1096                let within = self.within.unwrap_or(Rect::new(-1.0e6, -1.0e6, 2.0e6, 2.0e6));
1097                let b = place(self.rect, w, h, within, ls.gap);
1098                let shown: Vec<(&str, bool)> = rows.iter().map(|&i| (self.options[i], i == self.selected)).collect();
1099                let pre = format!("{}:list:item:", self.id.as_str());
1100                let hovered: Option<usize> = v.hovered().and_then(|w| w.as_str().strip_prefix(pre.as_str())?.parse().ok());
1101                let hover = |k: usize| hovered.is_some() && rows.get(k).copied() == hovered;
1102                let painted = draw_list(render, b, &shown, &list, searchable.then_some(list.query.as_str()), &hover, &ls);
1103                let (coord, _, layer) = parts(widgets);
1104                coord.register_atomic(WidgetId::from(format!("{}:list", self.id.as_str())), WidgetKind::Custom, b, Sense::CLICK | Sense::HOVER, layer);
1105                for (k, rr) in painted {
1106                    let oi = rows[k];
1107                    let rid = child(&self.id, "list:item", oi);
1108                    coord.register_atomic(rid.clone(), WidgetKind::Item, rr, Sense::CLICK | Sense::HOVER, layer);
1109                    coord.set_a11y(&rid, self.options[oi], Some(oi == self.selected));
1110                }
1111            }
1112            r.checked = open;
1113            r
1114        });
1115        if let Some(i) = r.index {
1116            r.changed = i != self.selected;
1117            if let Some(b) = self.bind {
1118                *b = i;
1119            }
1120        }
1121        r
1122    }
1123}
1124
1125// -- menu -------------------------------------------------------------------
1126
1127/// A context menu. Start with [`menu`].
1128pub struct MenuBuilder<'a> {
1129    id: WidgetId,
1130    at: (f64, f64),
1131    items: &'a [&'a str],
1132    open: &'a mut bool,
1133    title: Option<&'a str>,
1134    danger: Option<usize>,
1135}
1136
1137/// A menu of `items` at `at` while `*open`. Items are `"{id}:item:{i}"`.
1138/// A pick or a click elsewhere clears `*open`.
1139pub fn menu<'a>(id: impl Into<WidgetId>, at: (f64, f64), items: &'a [&'a str], open: &'a mut bool) -> MenuBuilder<'a> {
1140    MenuBuilder { id: id.into(), at, items, open, title: None, danger: None }
1141}
1142
1143impl<'a> MenuBuilder<'a> {
1144    /// Header line.
1145    pub fn title(mut self, t: &'a str) -> Self {
1146        self.title = Some(t);
1147        self
1148    }
1149    /// Draw item `i` in the danger colour (delete, sign out).
1150    pub fn danger(mut self, i: usize) -> Self {
1151        self.danger = Some(i);
1152        self
1153    }
1154
1155    /// Register and draw when open.
1156    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1157        if !*self.open {
1158            return Response::default();
1159        }
1160        let theme = theme_of(cx);
1161        let r = cx.with_paint(|render, widgets, v, _| {
1162            let mut r = Response::of(v, &self.id);
1163            r.index = picked(v, &self.id, "item");
1164            if r.index.is_some() || clicked_outside(v, &self.id) {
1165                return (r, false);
1166            }
1167            let items: Vec<ContextMenuItem<'_>> = self
1168                .items
1169                .iter()
1170                .enumerate()
1171                .map(|(i, l)| ContextMenuItem { action: l, label: l, icon: None, danger: self.danger == Some(i), separator_after: false, enabled: true })
1172                .collect();
1173            let state = ContextMenuState { is_open: true, x: self.at.0, y: self.at.1, ..Default::default() };
1174            let view = ContextMenuView { items: &items, target_id: None, title: self.title };
1175            let settings = ContextMenuSettings { theme: Box::new(theme), ..Default::default() };
1176            let (coord, _, layer) = parts(widgets);
1177            register_input_coordinator_context_menu(coord, self.id.clone(), &state, &view, &settings, &ContextMenuRenderKind::Default, layer);
1178            for (i, l) in self.items.iter().enumerate() {
1179                coord.set_a11y(&child(&self.id, "item", i), *l, None);
1180            }
1181            draw_context_menu(render, &state, &view, &settings, &ContextMenuRenderKind::Default);
1182            (r, true)
1183        });
1184        *self.open = r.1;
1185        let mut r = r.0;
1186        r.changed = r.index.is_some();
1187        r
1188    }
1189}
1190
1191// -- dialog -----------------------------------------------------------------
1192
1193/// A modal frame with a title, close button and footer. Start with [`dialog`].
1194pub struct DialogBuilder<'a> {
1195    id: WidgetId,
1196    rect: Rect,
1197    title: Option<&'a str>,
1198    footer: &'a [&'a str],
1199    dim: bool,
1200}
1201
1202/// A dialog in `rect`. Close is `"{id}:close"` (reported as `clicked`),
1203/// footer buttons `"{id}:footer:{i}"` (reported as `index`; the first is
1204/// primary). The app decides whether either closes it.
1205pub fn dialog<'a>(id: impl Into<WidgetId>, rect: Rect) -> DialogBuilder<'a> {
1206    DialogBuilder { id: id.into(), rect, title: None, footer: &[], dim: true }
1207}
1208
1209impl<'a> DialogBuilder<'a> {
1210    /// Header title, also the accessible name.
1211    pub fn title(mut self, t: &'a str) -> Self {
1212        self.title = Some(t);
1213        self
1214    }
1215    /// Footer button labels, primary first.
1216    pub fn footer(mut self, labels: &'a [&'a str]) -> Self {
1217        self.footer = labels;
1218        self
1219    }
1220    /// Dim what is behind (default on).
1221    pub fn dim(mut self, on: bool) -> Self {
1222        self.dim = on;
1223        self
1224    }
1225
1226    /// Register and draw the frame. Paint the body after this, inside the
1227    /// returned content area of `rect`.
1228    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1229        let theme = theme_of(cx);
1230        cx.with_paint(|render, widgets, v, _| {
1231            let mut r = Response::of(v, &self.id);
1232            r.clicked = v.clicked(&WidgetId::from(format!("{}:close", self.id.as_str())));
1233            r.index = picked(v, &self.id, "footer");
1234            r.changed = r.clicked || r.index.is_some();
1235            let buttons: Vec<FooterBtn<'_>> = self
1236                .footer
1237                .iter()
1238                .enumerate()
1239                .map(|(i, l)| FooterBtn { label: l, style: if i == 0 { FooterBtnStyle::Primary } else { FooterBtnStyle::Ghost } })
1240                .collect();
1241            let mut view = ModalView {
1242                title: self.title,
1243                tabs: &[],
1244                footer_buttons: &buttons,
1245                wizard_pages: &[],
1246                backdrop: if self.dim { BackdropKind::Dim } else { BackdropKind::None },
1247                overflow: Default::default(),
1248                resizable: false,
1249            };
1250            let kind = if buttons.is_empty() { ModalRenderKind::WithHeader } else { ModalRenderKind::WithHeaderFooter };
1251            let settings = ModalSettings { theme: Box::new(theme), ..Default::default() };
1252            let (coord, states, layer) = parts(widgets);
1253            let state = states.get_or_insert_with(self.id.clone(), ModalState::default);
1254            register_input_coordinator_modal(coord, self.id.clone(), self.rect, state, &mut view, &settings, &kind, layer);
1255            if let Some(t) = self.title {
1256                coord.set_a11y(&self.id, t, None);
1257            }
1258            for (i, l) in self.footer.iter().enumerate() {
1259                coord.set_a11y(&child(&self.id, "footer", i), *l, None);
1260            }
1261            coord.set_a11y(&WidgetId::from(format!("{}:close", self.id.as_str())), "Close", None);
1262            draw_modal(render, self.rect, state, &mut view, &settings, &kind);
1263            r
1264        })
1265    }
1266}
1267
1268// -- splitter ---------------------------------------------------------------
1269
1270/// A draggable pane edge. Start with [`splitter`].
1271pub struct SplitterBuilder<'a> {
1272    id: WidgetId,
1273    axis: Axis,
1274    span: Rect,
1275    pos: &'a mut f64,
1276    min: f64,
1277    max: f64,
1278    grab: f64,
1279}
1280
1281/// An edge at `*pos` along `axis` across `span`. Dragging writes `*pos`.
1282pub fn splitter<'a>(id: impl Into<WidgetId>, axis: Axis, span: Rect, pos: &'a mut f64) -> SplitterBuilder<'a> {
1283    SplitterBuilder { id: id.into(), axis, span, pos, min: f64::MIN, max: f64::MAX, grab: 9.0 }
1284}
1285
1286impl<'a> SplitterBuilder<'a> {
1287    /// Clamp the edge to `min..=max`.
1288    pub fn range(mut self, min: f64, max: f64) -> Self {
1289        self.min = min;
1290        self.max = max;
1291        self
1292    }
1293    /// Width of the grab strip in px (default 9).
1294    pub fn grab(mut self, px: f64) -> Self {
1295        self.grab = px;
1296        self
1297    }
1298
1299    /// Register and draw. `changed` is set on every drag step; `pressed`
1300    /// while dragging. Persist the size when the drag ends (`pressed` falls).
1301    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1302        let theme = theme_of(cx);
1303        cx.with_paint(|render, widgets, v, _| {
1304            let mut r = Response::of(v, &self.id);
1305            let (coord, states, layer) = parts(widgets);
1306            let s = states.get_or_insert_with(self.id.clone(), Splitter::default);
1307            if let SplitterEvent::Drag(p) = s.update(v, &self.id, self.axis) {
1308                let p = p.clamp(self.min, self.max);
1309                r.changed = (p - *self.pos).abs() > f64::EPSILON;
1310                *self.pos = p;
1311            }
1312            r.pressed = s.dragging();
1313            let hot = s.hot(v, &self.id);
1314            register_splitter(coord, self.id.clone(), grab_rect(self.axis, *self.pos, self.span, self.grab), layer);
1315            let (line, orientation) = match self.axis {
1316                Axis::X => (Rect::new(*self.pos, self.span.y, 1.0, self.span.height), SeparatorOrientation::Vertical),
1317                Axis::Y => (Rect::new(self.span.x, *self.pos, self.span.width, 1.0), SeparatorOrientation::Horizontal),
1318            };
1319            let view = SeparatorView { kind: SeparatorType::Divider { orientation }, hovered: hot, dragging: r.pressed };
1320            let settings = SeparatorSettings { theme: Box::new(theme), style: Box::new(DefaultSeparatorStyle) };
1321            draw_separator(render, line, &view, &settings);
1322            r
1323        })
1324    }
1325}
1326
1327// -- toast ------------------------------------------------------------------
1328
1329/// The toast stack. Start with [`toasts`].
1330pub struct ToastsBuilder<'a> {
1331    id: WidgetId,
1332    area: Rect,
1333    stack: &'a mut ToastStackState,
1334    now_ms: u64,
1335}
1336
1337/// Paint the live toasts of `stack` in the bottom-right of `area`, dropping
1338/// expired ones. Push new ones with [`ToastStackState::push`].
1339pub fn toasts<'a>(id: impl Into<WidgetId>, area: Rect, stack: &'a mut ToastStackState, now_ms: u64) -> ToastsBuilder<'a> {
1340    ToastsBuilder { id: id.into(), area, stack, now_ms }
1341}
1342
1343impl<'a> ToastsBuilder<'a> {
1344    /// Draw. `changed` is true while any toast is shown, so the app keeps
1345    /// asking for frames until the last one fades.
1346    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1347        let theme = theme_of(cx);
1348        let live = self.stack.tick(self.now_ms);
1349        cx.with_paint(|render, _widgets, v, _| {
1350            let mut r = Response::of(v, &self.id);
1351            r.changed = !live.is_empty();
1352            if r.changed {
1353                render.save();
1354                render.translate(self.area.x, self.area.y);
1355                draw_toast_stack(render, live, &theme, self.area.width, self.area.height, self.now_ms);
1356                render.restore();
1357            }
1358            r
1359        })
1360    }
1361}
1362
1363#[cfg(test)]
1364#[path = "kit_tests.rs"]
1365mod tests;
1366
1367// -- DOM trees ----------------------------------------------------------------
1368
1369/// A DOM tree ([`uzor::ui::dom`]) inside a kit panel. Start with [`dom`].
1370pub struct DomBuilder<'a> {
1371    rect: Rect,
1372    sheet: &'a uzor::ui::style::Sheet,
1373    root: uzor::ui::dom::El,
1374    scroll: f64,
1375    viewport: Option<Rect>,
1376}
1377
1378/// What a [`dom`] tree did this frame.
1379#[derive(Clone, Debug, Default)]
1380pub struct DomResponse {
1381    /// The laid-out tree (rects by id, embed slots, a11y nodes).
1382    pub dom: uzor::ui::dom::Dom,
1383    /// The element id clicked this frame (topmost first).
1384    pub clicked: Option<String>,
1385    /// The element id under the pointer.
1386    pub hovered: Option<String>,
1387    /// The focused element id.
1388    pub focused: Option<String>,
1389    /// Text inputs whose value the user changed this frame: `(id, new value)`.
1390    pub edited: Vec<(String, String)>,
1391}
1392
1393/// Lay out `root` with `sheet` in `rect` (scrolled up by [`DomBuilder::scroll`]),
1394/// paint it, and register every element with an id: buttons, switches, checkboxes and
1395/// rows become focusable click targets named by their accessible name ([`El::name`]
1396/// first, then text) with their checked state; DOM text inputs
1397/// ([`uzor::ui::dom::Control::Input`]) become text-store fields, so caret, selection,
1398/// drag, clipboard and IME work as in [`field`]. `position: fixed` elements (a select
1399/// popover, a side panel) are placed against the panel and stay put while it scrolls.
1400///
1401/// Kit widgets go *inside* the tree through embed slots: call them at
1402/// `resp.dom.slots()` after `build`.
1403///
1404/// [`El::name`]: uzor::ui::dom::El::name
1405pub fn dom<'a>(rect: Rect, sheet: &'a uzor::ui::style::Sheet, root: uzor::ui::dom::El) -> DomBuilder<'a> {
1406    DomBuilder { rect, sheet, root, scroll: 0.0, viewport: None }
1407}
1408
1409impl<'a> DomBuilder<'a> {
1410    /// Scroll the tree up by `y` (fixed elements do not move).
1411    pub fn scroll(mut self, y: f64) -> Self {
1412        self.scroll = y;
1413        self
1414    }
1415    /// The viewport fixed elements are placed against (the panel rect by default).
1416    pub fn viewport(mut self, r: Rect) -> Self {
1417        self.viewport = Some(r);
1418        self
1419    }
1420
1421    /// Paint the tree and register its hit targets and fields.
1422    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> DomResponse {
1423        use uzor::ui::dom::{Control, El};
1424        use uzor::ui::style::State;
1425        let now_ms = cx.time_ms();
1426        let DomBuilder { rect, sheet, mut root, scroll, viewport } = self;
1427        let (resp, ime) = cx.with_paint(|render, widgets, v, _| {
1428            let (coord, _, layer) = parts(widgets);
1429            let mut edited = Vec::new();
1430            let mut seed: Vec<(WidgetId, String)> = Vec::new();
1431            // Feed the text store's state into the tree's inputs (seeding new fields).
1432            fn walk(e: &mut El, f: &mut dyn FnMut(&str, &mut uzor::ui::dom::Edit)) {
1433                if let (Some(id), Some(Control::Input(ed))) = (e.id.as_deref(), e.control.as_mut()) {
1434                    f(id, ed);
1435                }
1436                for c in &mut e.children {
1437                    walk(c, f);
1438                }
1439            }
1440            walk(&mut root, &mut |id, ed| {
1441                let wid = WidgetId::from(id);
1442                if coord.text_fields().field_state(&wid).is_none() {
1443                    seed.push((wid.clone(), ed.value.clone()));
1444                }
1445                let focused = v.is_focused(&wid);
1446                if let Some(s) = coord.text_fields().field_state(&wid) {
1447                    let text = s.text.clone();
1448                    if text != ed.value {
1449                        edited.push((id.to_string(), text.clone()));
1450                        ed.value = text;
1451                    }
1452                    let caret = s.cursor.min(ed.value.chars().count());
1453                    let composing = !s.preedit.is_empty();
1454                    let sel = (!composing).then(|| s.selection_range()).flatten();
1455                    ed.caret = focused.then_some(caret);
1456                    ed.anchor = sel.filter(|_| focused).map(|(a, b)| if b == caret { a } else { b });
1457                    ed.preedit = (focused && composing).then(|| s.preedit.clone());
1458                    ed.caret_on = focused && s.engaged && coord.text_fields().cursor_visible(now_ms);
1459                } else {
1460                    ed.caret = None;
1461                }
1462            });
1463            let state = |id: &str| {
1464                let w = WidgetId::from(id);
1465                let mut s = State::NONE;
1466                if v.is_hovered(&w) {
1467                    s = s | State::HOVER;
1468                }
1469                if v.is_pressed(&w) {
1470                    s = s | State::ACTIVE;
1471                }
1472                if v.is_focused(&w) {
1473                    // `:focus-visible` like the browser: keyboard focus only, not a click.
1474                    s = s | State::FOCUS;
1475                    if v.focus_visible() {
1476                        s = s | State::FOCUS_VISIBLE;
1477                    }
1478                }
1479                s
1480            };
1481            let vp = viewport.unwrap_or(rect);
1482            let d = uzor::ui::dom::lay_out_in(render, sheet, &root, rect.x, rect.y, rect.width, Some(vp), &state);
1483            let d = if scroll != 0.0 { d.moved(0.0, -scroll) } else { d };
1484            render.save();
1485            render.begin_path();
1486            render.rect(rect.x, rect.y, rect.width, rect.height);
1487            render.clip();
1488            uzor::ui::dom::paint(render, &d);
1489            render.restore();
1490            coord.set_default_layer(Some(layer.clone()));
1491            let mut ime = None;
1492            for b in &d.boxes {
1493                let Some(id) = b.id.as_deref() else { continue };
1494                // What is visible of it: inside the panel (unless fixed) and its clips.
1495                let mut vis = b.clip.map_or(b.rect, |c| c.intersect(b.rect));
1496                if !b.fixed {
1497                    vis = vis.intersect(rect);
1498                }
1499                if vis.width <= 0.0 || vis.height <= 0.0 {
1500                    continue;
1501                }
1502                let wid = WidgetId::from(id);
1503                let name = b.accessible_name().unwrap_or_default().to_string();
1504                if let Some(Control::Input(e)) = &b.control {
1505                    let cfg = if e.masked { uzor::TextFieldConfig::password() } else { uzor::TextFieldConfig::text() };
1506                    coord.register_text_field(wid.clone(), vis, cfg);
1507                    if let Some((_, v)) = seed.iter().find(|(s, _)| *s == wid) {
1508                        coord.text_fields_mut().set_text(&wid, v);
1509                    }
1510                    coord.set_a11y(&wid, &name, None);
1511                    let c = uzor::ui::dom::content_box(b);
1512                    let sx = c.x - b.input_scroll();
1513                    // Boundaries of the shown text (value + composition), mapped back to the buffer.
1514                    let pos: Vec<f64> = b.bounds.iter().map(|x| sx + x).collect();
1515                    let _ = e;
1516                    let fields = coord.text_fields_mut();
1517                    let pos = match fields.field_state(&wid) {
1518                        Some(s) => s.buffer_positions(pos),
1519                        None => pos,
1520                    };
1521                    fields.update_field(&wid, (c.x, c.y, c.width, c.height), pos);
1522                    if e.caret.is_some() {
1523                        ime = b.caret_rect();
1524                    }
1525                } else if b.tab || b.id.is_some() {
1526                    let sense = if b.tab { focusable() } else { Sense::CLICK | Sense::HOVER };
1527                    coord.register_atomic(wid.clone(), WidgetKind::Button, vis, sense, layer);
1528                    coord.set_a11y(&wid, &name, b.control.as_ref().and_then(Control::checked));
1529                }
1530            }
1531            coord.set_default_layer(None);
1532            let ids: Vec<&str> = d.boxes.iter().rev().filter_map(|b| b.id.as_deref()).collect();
1533            let clicked = ids.iter().find(|i| v.clicked(&WidgetId::from(**i))).map(|s| s.to_string());
1534            let hovered = ids.iter().find(|i| v.is_hovered(&WidgetId::from(**i))).map(|s| s.to_string());
1535            let focused = ids.iter().find(|i| v.is_focused(&WidgetId::from(**i))).map(|s| s.to_string());
1536            (DomResponse { dom: d, clicked, hovered, focused, edited }, ime)
1537        });
1538        if let Some(at) = ime {
1539            cx.ime_area(at);
1540        }
1541        resp
1542    }
1543}