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