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// -- area (multiline text) ---------------------------------------------------
612
613/// One laid line of a [`area`]: chars `start..end` of the shown text (a hard line
614/// break's `\n` is not in any line), and whether a `\n` ends it.
615#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
616pub struct AreaLine {
617    /// First char of the line.
618    pub start: usize,
619    /// One past its last char.
620    pub end: usize,
621    /// A `\n` ends it (else a soft wrap or the text's end).
622    pub hard: bool,
623}
624
625/// Lay `text` out the way [`area`] paints it in a box `width` wide with the font
626/// already set on `render`: hard lines at `\n`, soft wrap after spaces (a word longer
627/// than the box breaks between chars). For sizing before layout (an auto-growing
628/// composer counts `lines.len()`). Never empty: an empty text is one empty line.
629pub fn area_lines(render: &mut dyn RenderContext, text: &str, width: f64) -> Vec<AreaLine> {
630    let chars: Vec<char> = text.chars().collect();
631    let mut out = Vec::new();
632    let mut start = 0;
633    while start <= chars.len() {
634        let hard_end = chars[start..].iter().position(|c| *c == '\n').map_or(chars.len(), |i| start + i);
635        // Soft wrap inside the hard line by summed char advances (fast; the caret
636        // positions of a laid line are measured on its prefixes when painted).
637        let mut ls = start;
638        let mut w = 0.0;
639        let mut brk: Option<usize> = None;
640        let mut i = start;
641        let mut buf = [0u8; 4];
642        while i < hard_end {
643            let c = chars[i];
644            let cw = render.measure_text(c.encode_utf8(&mut buf));
645            if w + cw > width && i > ls && !c.is_whitespace() {
646                let at = brk.filter(|b| *b > ls).unwrap_or(i);
647                out.push(AreaLine { start: ls, end: at, hard: false });
648                ls = at;
649                brk = None;
650                w = chars[ls..i].iter().map(|c| render.measure_text(c.encode_utf8(&mut buf))).sum();
651                continue;
652            }
653            w += cw;
654            if c.is_whitespace() {
655                brk = Some(i + 1);
656            }
657            i += 1;
658        }
659        let hard = hard_end < chars.len();
660        out.push(AreaLine { start: ls, end: hard_end, hard });
661        if !hard {
662            break;
663        }
664        start = hard_end + 1;
665    }
666    out
667}
668
669/// A multiline text area (a `<textarea>`) whose box the app paints itself: the kit
670/// registers it at `rect`, wraps the text to its width, paints text, placeholder,
671/// selection, IME composition and a blinking caret line by line, and feeds per-line
672/// caret geometry to the text store, so clicks, drags, double / triple clicks,
673/// ArrowUp / ArrowDown and Home / End work by laid lines. Start with [`area`].
674pub struct AreaBuilder<'a> {
675    id: WidgetId,
676    rect: Rect,
677    text_rect: Option<Rect>,
678    config: uzor::TextFieldConfig,
679    name: &'a str,
680    placeholder: &'a str,
681    within: Option<Rect>,
682    px: f64,
683    line_h: Option<f64>,
684    family: &'a str,
685    weight: u16,
686    color: Option<&'a str>,
687    placeholder_color: Option<&'a str>,
688    caret_color: Option<&'a str>,
689    set: Option<&'a str>,
690    parent: Option<WidgetId>,
691    scroll: f64,
692}
693
694/// What an [`area`] shows this frame.
695#[derive(Clone, Debug, Default, PartialEq)]
696pub struct AreaResponse {
697    /// The shown text, composition included.
698    pub text: String,
699    /// Keyboard focus is in the area.
700    pub focused: bool,
701    /// Laid lines (at least one).
702    pub lines: usize,
703    /// Height of all the lines (`lines × line height`).
704    pub content_h: f64,
705    /// The caret line's top, from the first line's top (scroll it into view).
706    pub caret_top: f64,
707    /// The line height used.
708    pub line_h: f64,
709}
710
711/// A multiline text area at `rect` (see [`AreaBuilder`]). The text box is `rect`
712/// unless [`AreaBuilder::text_rect`]; it scrolls up by [`AreaBuilder::scroll`].
713pub fn area<'a>(id: impl Into<WidgetId>, rect: Rect) -> AreaBuilder<'a> {
714    AreaBuilder {
715        id: id.into(),
716        rect,
717        text_rect: None,
718        config: uzor::TextFieldConfig::text().multiline(),
719        name: "",
720        placeholder: "",
721        within: None,
722        px: 13.0,
723        line_h: None,
724        family: "sans-serif",
725        weight: 400,
726        color: None,
727        placeholder_color: None,
728        caret_color: None,
729        set: None,
730        parent: None,
731        scroll: 0.0,
732    }
733}
734
735impl<'a> AreaBuilder<'a> {
736    /// Editing behaviour (max length, filter, read-only); multiline is kept on.
737    pub fn config(mut self, c: uzor::TextFieldConfig) -> Self {
738        self.config = c.multiline();
739        self
740    }
741    /// Accessible name (defaults to the placeholder).
742    pub fn name(mut self, n: &'a str) -> Self {
743        self.name = n;
744        self
745    }
746    /// Grey hint while empty.
747    pub fn placeholder(mut self, p: &'a str) -> Self {
748        self.placeholder = p;
749        self
750    }
751    /// Where the lines run, when inset inside the hit rect.
752    pub fn text_rect(mut self, r: Rect) -> Self {
753        self.text_rect = Some(r);
754        self
755    }
756    /// Clip paint and hits to `r` too (the scroll viewport the area sits in).
757    pub fn clip_to(mut self, r: Rect) -> Self {
758        self.within = Some(r);
759        self
760    }
761    /// Font size, CSS family and weight.
762    pub fn font(mut self, px: f64, family: &'a str) -> Self {
763        self.px = px;
764        self.family = family;
765        self
766    }
767    /// Font weight (400 by default).
768    pub fn weight(mut self, w: u16) -> Self {
769        self.weight = w;
770        self
771    }
772    /// Line height (default `1.45 × px`).
773    pub fn line_height(mut self, h: f64) -> Self {
774        self.line_h = Some(h);
775        self
776    }
777    /// Text and placeholder colours (CSS); the theme's when unset.
778    pub fn colors(mut self, text: &'a str, placeholder: &'a str) -> Self {
779        self.color = Some(text);
780        self.placeholder_color = Some(placeholder);
781        self
782    }
783    /// Caret colour (the text colour when unset).
784    pub fn caret_color(mut self, c: &'a str) -> Self {
785        self.caret_color = Some(c);
786        self
787    }
788    /// Replace the text this frame (`Some("")` clears it); the caret goes to the end.
789    pub fn set(mut self, text: Option<&'a str>) -> Self {
790        self.set = text;
791        self
792    }
793    /// Nest the area under a container (a dialog scrim) for focus scoping.
794    pub fn parent(mut self, p: impl Into<WidgetId>) -> Self {
795        self.parent = Some(p.into());
796        self
797    }
798    /// Scroll the lines up by `y` (the host's scroll view offset).
799    pub fn scroll(mut self, y: f64) -> Self {
800        self.scroll = y;
801        self
802    }
803
804    /// Register, draw, and feed the store.
805    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> AreaResponse {
806        use uzor::ui::css_text::{fill_text_css, INTER};
807        use uzor::ui::widgets::atomic::text_input::TextInputTheme;
808        let now_ms = cx.time_ms();
809        let theme = theme_of(cx);
810        let color = self.color.map_or_else(|| css_hex(theme.text_normal()), str::to_owned);
811        let ph_color = self.placeholder_color.map_or_else(|| css_hex(theme.placeholder()), str::to_owned);
812        let sel_color = css_hex(theme.selection());
813        let AreaBuilder { id, rect, text_rect, config, name, placeholder, within, px, line_h, family, weight, set, parent, scroll, caret_color, .. } = self;
814        let lh = line_h.unwrap_or((px * 1.45).round());
815        let fr = text_rect.unwrap_or(rect);
816        let hit = within.map_or(rect, |w| w.intersect(rect));
817        let (out, ime) = cx.with_paint(|render, widgets, v, _| {
818            let (coord, _, layer) = parts(widgets);
819            coord.set_default_layer(Some(layer.clone()));
820            coord.register_text_field(id.clone(), hit, config);
821            if let Some(p) = &parent {
822                coord.set_widget_parent(&id, p);
823            }
824            coord.set_a11y(&id, if name.is_empty() { placeholder } else { name }, None);
825            coord.set_default_layer(None);
826            if let Some(t) = set {
827                let fields = coord.text_fields_mut();
828                fields.clear(&id);
829                if !t.is_empty() {
830                    fields.set_text(&id, t);
831                }
832            }
833            let focused = v.is_focused(&id);
834            let (text, caret, preedit, engaged, selection) = match coord.text_fields().field_state(&id) {
835                Some(s) => {
836                    let (text, caret, preedit) = s.display();
837                    let selection = preedit.is_none().then(|| s.selection_range()).flatten();
838                    (text, caret, preedit, s.engaged, selection)
839                }
840                None => (String::new(), 0, None, false, None),
841            };
842            let blink = focused && engaged && coord.text_fields().cursor_visible(now_ms);
843            render.set_font(&format!("{weight} {px}px {family}"));
844            let lines = area_lines(render, &text, fr.width);
845            let chars: Vec<char> = text.chars().collect();
846            // Per boundary: x and line top (buffer of the shown text).
847            let n = chars.len();
848            let mut xs = vec![fr.x; n + 1];
849            let mut tops = vec![fr.y - scroll; n + 1];
850            let mut widths = Vec::with_capacity(lines.len());
851            for (li, l) in lines.iter().enumerate() {
852                let top = fr.y - scroll + li as f64 * lh;
853                let mut acc = String::new();
854                xs[l.start] = fr.x;
855                tops[l.start] = top;
856                for i in l.start..l.end {
857                    acc.push(chars[i]);
858                    xs[i + 1] = fr.x + render.measure_text(&acc);
859                    tops[i + 1] = top;
860                }
861                widths.push(xs[l.end] - fr.x);
862            }
863            let cut = within.map_or(fr, |w| w.intersect(fr));
864            let caret_line = lines.iter().rposition(|l| l.start <= caret).unwrap_or(0);
865            if cut.width > 0.0 && cut.height > 0.0 {
866                render.save();
867                render.begin_path();
868                // A little room for the caret at the right edge and descenders.
869                render.rect(cut.x - 2.0, cut.y, cut.width + 4.0, cut.height);
870                render.clip();
871                let visible = |top: f64| top + lh >= cut.y && top <= cut.y + cut.height;
872                if text.is_empty() {
873                    if !placeholder.is_empty() {
874                        render.set_fill_color(&ph_color);
875                        fill_text_css(render, placeholder, fr.x, fr.y - scroll, px, lh, INTER, uzor::render::TextAlign::Left);
876                    }
877                } else {
878                    if let Some((lo, hi)) = selection {
879                        render.set_fill_color(&sel_color);
880                        for l in &lines {
881                            let (a, b) = (lo.max(l.start), hi.min(l.end));
882                            let top = tops[l.start];
883                            if a > b || !visible(top) || (a == b && !(l.hard && hi > l.end)) {
884                                continue;
885                            }
886                            // A selected line break shows as a narrow slot past the line.
887                            let tail = if l.hard && hi > l.end && lo <= l.end { px * 0.33 } else { 0.0 };
888                            render.fill_rect(xs[a], top, xs[b] - xs[a] + tail, lh);
889                        }
890                    }
891                    render.set_fill_color(&color);
892                    for l in &lines {
893                        let top = tops[l.start];
894                        if l.end > l.start && visible(top) {
895                            let s: String = chars[l.start..l.end].iter().collect();
896                            fill_text_css(render, &s, fr.x, top, px, lh, INTER, uzor::render::TextAlign::Left);
897                        }
898                    }
899                    if let Some((a, b)) = preedit {
900                        for i in a..b.min(n) {
901                            if tops[i] == tops[i + 1] && visible(tops[i]) {
902                                render.fill_rect(xs[i].round(), (tops[i] + lh - 2.0).round(), (xs[i + 1] - xs[i]).max(1.0), 1.0);
903                            }
904                        }
905                    }
906                }
907                if blink && visible(tops[caret.min(n)]) {
908                    let c = caret.min(n);
909                    render.set_fill_color(caret_color.unwrap_or(&color));
910                    let ch = (px * 1.25).min(lh).round();
911                    render.fill_rect(xs[c].round(), (tops[c] + (lh - ch) / 2.0).round(), 1.0, ch);
912                }
913                render.restore();
914            }
915            let c = caret.min(n);
916            let ime = focused.then(|| Rect::new(xs[c], tops[c], 1.0, lh));
917            let fields = coord.text_fields_mut();
918            let (xs, tops) = match fields.field_state(&id) {
919                Some(s) => (s.buffer_positions(xs), s.buffer_positions(tops)),
920                None => (xs, tops),
921            };
922            fields.update_field_lines(&id, (fr.x, fr.y, fr.width, fr.height), xs, tops, lh);
923            let _ = widths;
924            let resp = AreaResponse { text, focused, lines: lines.len(), content_h: lines.len() as f64 * lh, caret_top: caret_line as f64 * lh, line_h: lh };
925            (resp, ime)
926        });
927        if let Some(at) = ime {
928            cx.ime_area(at);
929        }
930        out
931    }
932}
933
934// -- tabs -------------------------------------------------------------------
935
936/// A row of equal-width tabs. Start with [`tabs`].
937pub struct TabsBuilder<'a> {
938    id: WidgetId,
939    rect: Rect,
940    labels: &'a [&'a str],
941    selected: usize,
942    bind: Option<&'a mut usize>,
943}
944
945/// Tabs labelled `labels`, laid out across `rect`. Parts are `"{id}:tab:{i}"`.
946pub fn tabs<'a>(id: impl Into<WidgetId>, rect: Rect, labels: &'a [&'a str]) -> TabsBuilder<'a> {
947    TabsBuilder { id: id.into(), rect, labels, selected: 0, bind: None }
948}
949
950impl<'a> TabsBuilder<'a> {
951    /// The active tab.
952    pub fn selected(mut self, i: usize) -> Self {
953        self.selected = i;
954        self
955    }
956    /// Read the active tab from `i` and write a click back to it.
957    pub fn bind(mut self, i: &'a mut usize) -> Self {
958        self.selected = *i;
959        self.bind = Some(i);
960        self
961    }
962
963    /// Register and draw.
964    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
965        let theme = theme_of(cx);
966        let n = self.labels.len().max(1) as f64;
967        let w = self.rect.width / n;
968        let mut r = cx.with_paint(|render, widgets, v, _| {
969            let mut r = Response::of(v, &self.id);
970            r.index = picked(v, &self.id, "tab");
971            let settings = TabSettings { theme: Box::new(theme), ..Default::default() };
972            let (coord, _, layer) = parts(widgets);
973            let active = r.index.unwrap_or(self.selected);
974            for (i, label) in self.labels.iter().enumerate() {
975                let tid = child(&self.id, "tab", i);
976                let tr = Rect::new(self.rect.x + w * i as f64, self.rect.y, w, self.rect.height);
977                register_tab_on_layer(coord, tid.clone(), tr, focusable(), None, layer);
978                coord.set_a11y(&tid, *label, Some(i == active));
979                r.hovered |= v.is_hovered(&tid);
980                r.focused |= v.is_focused(&tid);
981                let mut cfg = TabConfig::new(tid.as_str(), *label);
982                cfg.active = i == active;
983                let view = TabView { tab: &cfg, hovered: v.is_hovered(&tid), pressed: v.is_pressed(&tid), close_btn_hovered: false };
984                draw_tab(render, tr, &view, &settings);
985            }
986            r
987        });
988        if let Some(i) = r.index {
989            r.changed = i != self.selected;
990            if let Some(b) = self.bind {
991                *b = i;
992            }
993        }
994        r
995    }
996}
997
998// -- list -------------------------------------------------------------------
999
1000/// A vertical list of selectable text rows. Start with [`list`].
1001pub struct ListBuilder<'a> {
1002    id: WidgetId,
1003    rect: Rect,
1004    rows: &'a [&'a str],
1005    row_height: f64,
1006    scroll: f64,
1007    selected: Option<usize>,
1008    bind: Option<&'a mut Option<usize>>,
1009}
1010
1011/// Rows `rows` inside `rect`. Parts are `"{id}:row:{i}"`. Rows outside
1012/// `rect` (after `.scroll`) are neither painted nor hit.
1013pub fn list<'a>(id: impl Into<WidgetId>, rect: Rect, rows: &'a [&'a str]) -> ListBuilder<'a> {
1014    ListBuilder { id: id.into(), rect, rows, row_height: 28.0, scroll: 0.0, selected: None, bind: None }
1015}
1016
1017impl<'a> ListBuilder<'a> {
1018    /// Row height in px (default 28).
1019    pub fn row_height(mut self, h: f64) -> Self {
1020        self.row_height = h;
1021        self
1022    }
1023    /// Scroll offset in px from the top.
1024    pub fn scroll(mut self, y: f64) -> Self {
1025        self.scroll = y;
1026        self
1027    }
1028    /// The highlighted row.
1029    pub fn selected(mut self, i: Option<usize>) -> Self {
1030        self.selected = i;
1031        self
1032    }
1033    /// Read the selection from `i` and write a click back to it.
1034    pub fn bind(mut self, i: &'a mut Option<usize>) -> Self {
1035        self.selected = *i;
1036        self.bind = Some(i);
1037        self
1038    }
1039    /// Total content height, for a scrollbar.
1040    pub fn content_height(&self) -> f64 {
1041        self.rows.len() as f64 * self.row_height
1042    }
1043
1044    /// Register and draw.
1045    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1046        let theme = theme_of(cx);
1047        let mut r = cx.with_paint(|render, widgets, v, _| {
1048            let mut r = Response::of(v, &self.id);
1049            r.index = picked(v, &self.id, "row");
1050            let settings = ItemSettings::default().with_theme(Box::new(theme));
1051            let (coord, _, layer) = parts(widgets);
1052            let sel = r.index.or(self.selected);
1053            let (top, bottom) = (self.rect.y, self.rect.y + self.rect.height);
1054            for (i, row) in self.rows.iter().enumerate() {
1055                let y = top + i as f64 * self.row_height - self.scroll;
1056                if y < top || y + self.row_height > bottom {
1057                    continue;
1058                }
1059                let rid = child(&self.id, "row", i);
1060                let rr = Rect::new(self.rect.x, y, self.rect.width, self.row_height);
1061                coord.register_atomic(rid.clone(), WidgetKind::Item, rr, focusable(), layer);
1062                coord.set_a11y(&rid, *row, Some(sel == Some(i)));
1063                r.hovered |= v.is_hovered(&rid);
1064                r.focused |= v.is_focused(&rid);
1065                let ws = if sel == Some(i) { WidgetState::Active } else { interaction_state(v, &rid, false) };
1066                let view = ItemView { label: Some(row), icon: None, svg: None };
1067                draw_item(render, rr, ws, &view, &settings, &ItemRenderKind::Label, |_, _, _, _| {}, |_, _, _, _| {});
1068            }
1069            r
1070        });
1071        if let Some(i) = r.index {
1072            r.changed = Some(i) != self.selected;
1073            if let Some(b) = self.bind {
1074                *b = Some(i);
1075            }
1076        }
1077        r
1078    }
1079}
1080
1081// -- table ------------------------------------------------------------------
1082
1083/// A table with a header row and selectable body rows. Start with [`table`].
1084pub struct TableBuilder<'a> {
1085    id: WidgetId,
1086    rect: Rect,
1087    columns: &'a [&'a str],
1088    rows: &'a [Vec<String>],
1089    tracks: Option<&'a str>,
1090    row_height: f64,
1091    scroll: f64,
1092    selected: Option<usize>,
1093    bind: Option<&'a mut Option<usize>>,
1094    font: &'a str,
1095}
1096
1097/// A table of `rows` under `columns` in `rect`. Parts are `"{id}:col:{j}"`
1098/// (header cells, a click reports `column`) and `"{id}:row:{i}"` (rows, a
1099/// click reports `index`). Rows outside `rect` after `.scroll` are skipped.
1100pub fn table<'a>(id: impl Into<WidgetId>, rect: Rect, columns: &'a [&'a str], rows: &'a [Vec<String>]) -> TableBuilder<'a> {
1101    TableBuilder {
1102        id: id.into(),
1103        rect,
1104        columns,
1105        rows,
1106        tracks: None,
1107        row_height: 28.0,
1108        scroll: 0.0,
1109        selected: None,
1110        bind: None,
1111        font: "13px sans-serif",
1112    }
1113}
1114
1115impl<'a> TableBuilder<'a> {
1116    /// Column widths as CSS grid tracks (`"2fr 1fr 80px"`, `minmax()`); default equal `1fr`.
1117    pub fn columns(mut self, tracks: &'a str) -> Self {
1118        self.tracks = Some(tracks);
1119        self
1120    }
1121    /// Header and row height in px (default 28).
1122    pub fn row_height(mut self, h: f64) -> Self {
1123        self.row_height = h;
1124        self
1125    }
1126    /// Body scroll offset in px (the header stays put, like `position: sticky`).
1127    pub fn scroll(mut self, y: f64) -> Self {
1128        self.scroll = y;
1129        self
1130    }
1131    /// The highlighted row.
1132    pub fn selected(mut self, i: Option<usize>) -> Self {
1133        self.selected = i;
1134        self
1135    }
1136    /// Read the selection from `i` and write a row click back to it.
1137    pub fn bind(mut self, i: &'a mut Option<usize>) -> Self {
1138        self.selected = *i;
1139        self.bind = Some(i);
1140        self
1141    }
1142    /// Cell font shorthand.
1143    pub fn font(mut self, f: &'a str) -> Self {
1144        self.font = f;
1145        self
1146    }
1147    /// Body content height, for a scrollbar.
1148    pub fn content_height(&self) -> f64 {
1149        self.rows.len() as f64 * self.row_height
1150    }
1151
1152    /// Register and draw.
1153    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1154        use uzor::ui::widgets::atomic::text::theme::TextTheme;
1155        use uzor::ui::widgets::composite::panel::theme::PanelTheme;
1156        let theme = theme_of(cx);
1157        let Self { id, rect, columns, rows, tracks, row_height, scroll, selected, bind, font } = self;
1158        let mut r = cx.with_paint(|render, widgets, v, _| {
1159            let mut r = Response::of(v, &id);
1160            r.index = picked(v, &id, "row");
1161            r.column = picked(v, &id, "col");
1162            let (coord, _, layer) = parts(widgets);
1163            let even = vec!["1fr"; columns.len().max(1)].join(" ");
1164            let spec = tracks.unwrap_or(&even);
1165            let cols = uzor::ui::flow::grid_tracks(rect.width, &uzor::ui::flow::parse_tracks(spec, rect.width, 0.0), 0.0);
1166            let sel = r.index.or(selected);
1167            render.set_font(font);
1168            render.set_text_align(uzor::render::TextAlign::Left);
1169            render.set_text_baseline(uzor::render::TextBaseline::Middle);
1170            let cells = |render: &mut dyn RenderContext, y: f64, texts: &mut dyn Iterator<Item = &str>, color: &str| {
1171                render.set_fill_color(color);
1172                for ((x, w), t) in cols.iter().zip(texts) {
1173                    render.save();
1174                    render.clip_rect(rect.x + x, y, *w, row_height);
1175                    render.fill_text(t, rect.x + x + 8.0, y + row_height / 2.0);
1176                    render.restore();
1177                }
1178            };
1179            // Header.
1180            render.set_fill_color(theme.column_header_bg());
1181            render.fill_rect(rect.x, rect.y, rect.width, row_height);
1182            for (j, (x, w)) in cols.iter().enumerate().take(columns.len()) {
1183                let cid = child(&id, "col", j);
1184                coord.register_atomic(cid.clone(), WidgetKind::Item, Rect::new(rect.x + x, rect.y, *w, row_height), focusable(), layer);
1185                coord.set_a11y(&cid, columns[j], None);
1186                r.hovered |= v.is_hovered(&cid);
1187                r.focused |= v.is_focused(&cid);
1188            }
1189            cells(render, rect.y, &mut columns.iter().copied(), theme.column_header_text());
1190            // Body.
1191            let (top, bottom) = (rect.y + row_height, rect.y + rect.height);
1192            for (i, row) in rows.iter().enumerate() {
1193                let y = top + i as f64 * row_height - scroll;
1194                if y < top || y + row_height > bottom {
1195                    continue;
1196                }
1197                let rid = child(&id, "row", i);
1198                let rr = Rect::new(rect.x, y, rect.width, row_height);
1199                coord.register_atomic(rid.clone(), WidgetKind::Item, rr, focusable(), layer);
1200                coord.set_a11y(&rid, &row.join(", "), Some(sel == Some(i)));
1201                let hov = v.is_hovered(&rid);
1202                r.hovered |= hov;
1203                r.focused |= v.is_focused(&rid);
1204                let bg = if sel == Some(i) { theme.row_bg_selected() } else if hov { theme.row_bg_hover() } else { theme.row_bg_normal() };
1205                render.set_fill_color(bg);
1206                render.fill_rect(rr.x, rr.y, rr.width, rr.height);
1207                render.set_fill_color(theme.divider());
1208                render.fill_rect(rr.x, rr.y + rr.height - 1.0, rr.width, 1.0);
1209                cells(render, y, &mut row.iter().map(String::as_str), theme.text_color());
1210            }
1211            r
1212        });
1213        if let Some(i) = r.index {
1214            r.changed = Some(i) != selected;
1215            if let Some(b) = bind {
1216                *b = Some(i);
1217            }
1218        }
1219        r
1220    }
1221}
1222
1223// -- drawer -----------------------------------------------------------------
1224
1225/// The edge a drawer slides from.
1226#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1227pub enum Side {
1228    /// From the left edge.
1229    Left,
1230    /// From the right edge (default).
1231    #[default]
1232    Right,
1233}
1234
1235/// A side panel over the content with a scrim. Start with [`drawer`].
1236pub struct DrawerBuilder<'a> {
1237    id: WidgetId,
1238    area: Rect,
1239    open: &'a mut bool,
1240    side: Side,
1241    width: f64,
1242    title: Option<&'a str>,
1243    progress: f64,
1244    dim: bool,
1245}
1246
1247/// A drawer over `area`, shown while `*open`. A click on the scrim
1248/// (`"{id}:scrim"`) clears `open` and reports `changed`. Paint the body in
1249/// [`DrawerBuilder::body_rect`] after `build`.
1250pub fn drawer<'a>(id: impl Into<WidgetId>, area: Rect, open: &'a mut bool) -> DrawerBuilder<'a> {
1251    DrawerBuilder { id: id.into(), area, open, side: Side::Right, width: 320.0, title: None, progress: 1.0, dim: true }
1252}
1253
1254impl<'a> DrawerBuilder<'a> {
1255    /// Edge it slides from.
1256    pub fn side(mut self, s: Side) -> Self {
1257        self.side = s;
1258        self
1259    }
1260    /// Panel width in px (default 320, capped to the area).
1261    pub fn width(mut self, w: f64) -> Self {
1262        self.width = w;
1263        self
1264    }
1265    /// Accessible name.
1266    pub fn title(mut self, t: &'a str) -> Self {
1267        self.title = Some(t);
1268        self
1269    }
1270    /// Slide position, 0 (hidden) to 1 (shown): drive it from a
1271    /// [`Motion`](uzor::ui::motion::Motion) value or a timer for an animated open.
1272    pub fn progress(mut self, t: f64) -> Self {
1273        self.progress = t.clamp(0.0, 1.0);
1274        self
1275    }
1276    /// Dim the content behind (default on).
1277    pub fn dim(mut self, on: bool) -> Self {
1278        self.dim = on;
1279        self
1280    }
1281    /// The panel's rect at the current progress.
1282    pub fn body_rect(&self) -> Rect {
1283        let w = self.width.min(self.area.width);
1284        let shown = w * self.progress;
1285        let x = match self.side {
1286            Side::Left => self.area.x - w + shown,
1287            Side::Right => self.area.x + self.area.width - shown,
1288        };
1289        Rect::new(x, self.area.y, w, self.area.height)
1290    }
1291
1292    /// Register and draw the scrim and the panel frame.
1293    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1294        use uzor::ui::widgets::composite::modal::theme::ModalTheme;
1295        use uzor::ui::widgets::composite::panel::theme::PanelTheme;
1296        if !*self.open {
1297            return Response::default();
1298        }
1299        let theme = theme_of(cx);
1300        let body = self.body_rect();
1301        let scrim = WidgetId::from(format!("{}:scrim", self.id.as_str()));
1302        let r = cx.with_paint(|render, widgets, v, _| {
1303            let (coord, _, layer) = parts(widgets);
1304            coord.register_atomic(scrim.clone(), WidgetKind::Custom, self.area, Sense::CLICK, layer);
1305            coord.register_atomic(self.id.clone(), WidgetKind::Custom, body, Sense::CLICK | Sense::HOVER, layer);
1306            coord.set_a11y(&self.id, self.title.unwrap_or(""), None);
1307            if self.dim {
1308                render.set_global_alpha(self.progress);
1309                render.set_fill_color(ModalTheme::backdrop_dim(&theme));
1310                render.fill_rect(self.area.x, self.area.y, self.area.width, self.area.height);
1311                render.set_global_alpha(1.0);
1312            }
1313            render.set_fill_color(PanelTheme::bg(&theme));
1314            render.fill_rect(body.x, body.y, body.width, body.height);
1315            let edge = if self.side == Side::Right { body.x } else { body.x + body.width - 1.0 };
1316            render.set_fill_color(PanelTheme::border(&theme));
1317            render.fill_rect(edge, body.y, 1.0, body.height);
1318            let mut r = Response::of(v, &self.id);
1319            r.clicked = v.clicked(&scrim);
1320            r
1321        });
1322        if r.clicked {
1323            *self.open = false;
1324            return Response { changed: true, ..r };
1325        }
1326        r
1327    }
1328}
1329
1330// -- select -----------------------------------------------------------------
1331
1332#[derive(Default)]
1333struct SelectOpen {
1334    open: bool,
1335    list: SelectState,
1336}
1337
1338/// A button that opens a list of options. Start with [`select`].
1339pub struct SelectBuilder<'a> {
1340    id: WidgetId,
1341    rect: Rect,
1342    options: &'a [&'a str],
1343    selected: usize,
1344    bind: Option<&'a mut usize>,
1345    disabled: bool,
1346    searchable: Option<bool>,
1347    within: Option<Rect>,
1348    style: Option<SelectStyle>,
1349    key: Option<&'a KeyInput>,
1350}
1351
1352/// A select showing `options[selected]`. The trigger is `id`; options are
1353/// `"{id}:list:item:{i}"` (`i` = index into `options`). The open state (flag,
1354/// highlighted row, search text, scroll) lives in the widget state store.
1355///
1356/// The open list behaves like a native one ([`SelectState`]): forward this
1357/// frame's key with [`.key`](SelectBuilder::key) and arrows / Page / Home /
1358/// End move, Enter picks, Escape closes, typing filters a searchable list;
1359/// Enter, Space or ArrowDown on the focused trigger opens it. The list opens
1360/// under the trigger and stays inside [`.within`](SelectBuilder::within)
1361/// (the dialog that hosts it), flipping above or shifting as needed.
1362pub fn select<'a>(id: impl Into<WidgetId>, rect: Rect, options: &'a [&'a str]) -> SelectBuilder<'a> {
1363    SelectBuilder { id: id.into(), rect, options, selected: 0, bind: None, disabled: false, searchable: None, within: None, style: None, key: None }
1364}
1365
1366/// Whether the select `id` is open (its list shows). An app that closes its
1367/// dialog on Escape asks this first: Escape belongs to the open list.
1368pub fn select_is_open<'c, C: ContentCx<'c>>(cx: &mut C, id: &str) -> bool {
1369    cx.with_paint(|_, widgets, _, _| widgets.states.get_or_insert_with(WidgetId::from(format!("{id}:open")), SelectOpen::default).open)
1370}
1371
1372impl<'a> SelectBuilder<'a> {
1373    /// The chosen option.
1374    pub fn selected(mut self, i: usize) -> Self {
1375        self.selected = i;
1376        self
1377    }
1378    /// Read the choice from `i` and write a pick back to it.
1379    pub fn bind(mut self, i: &'a mut usize) -> Self {
1380        self.selected = *i;
1381        self.bind = Some(i);
1382        self
1383    }
1384    /// Disabled colours; does not open.
1385    pub fn disabled(mut self, on: bool) -> Self {
1386        self.disabled = on;
1387        self
1388    }
1389    /// A search line on top of the list (default: more options than the list shows).
1390    pub fn searchable(mut self, on: bool) -> Self {
1391        self.searchable = Some(on);
1392        self
1393    }
1394    /// Keep the open list inside `container` (a modal card, a panel).
1395    pub fn within(mut self, container: Rect) -> Self {
1396        self.within = Some(container);
1397        self
1398    }
1399    /// The list's look (e.g. `SelectStyle::from_sheet(&sheet, "div.select-list")`).
1400    pub fn style(mut self, s: SelectStyle) -> Self {
1401        self.style = Some(s);
1402        self
1403    }
1404    /// This frame's key press, if any (the app forwards unhandled keys).
1405    pub fn key(mut self, k: Option<&'a KeyInput>) -> Self {
1406        self.key = k.filter(|k| k.state != crate::KeyState::Up);
1407        self
1408    }
1409
1410    /// Register and draw (the open list paints after the trigger). `Response::checked`
1411    /// tells whether the list is open after this frame; `Response::pressed` that the key
1412    /// given to [`.key`](Self::key) was used.
1413    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1414        let theme = theme_of(cx);
1415        let ls = self.style.unwrap_or_default();
1416        let searchable = self.searchable.unwrap_or(self.options.len() > ls.window());
1417        let ls = match self.within {
1418            Some(w) => ls.fit(room(self.rect, w, ls.gap), searchable),
1419            None => ls,
1420        };
1421        let win = ls.window();
1422        let labels: Vec<(&str, &str)> = self.options.iter().map(|o| (*o, *o)).collect();
1423        let mut r = cx.with_paint(|render, widgets, v, tokens| {
1424            let mut r = Response::of(v, &self.id);
1425            let sid = WidgetId::from(format!("{}:open", self.id.as_str()));
1426            let mut key_used = false;
1427            let mut close = false;
1428            let (open, list) = {
1429                let st = widgets.states.get_or_insert_with(sid, SelectOpen::default);
1430                r.index = picked(v, &self.id, "list:item");
1431                let was = st.open;
1432                if self.disabled || r.index.is_some() || (st.open && clicked_outside(v, &self.id)) {
1433                    st.open = false;
1434                } else if r.clicked {
1435                    st.open = !st.open;
1436                } else if let Some(k) = self.key {
1437                    use uzor::input::keyboard::KeyCode as K;
1438                    if st.open {
1439                        let rows = filter(&labels, &st.list.query);
1440                        match st.list.key(k.code, k.text.as_deref(), k.mods.ctrl || k.mods.meta, rows.len(), searchable, win) {
1441                            SelectKey::Changed => key_used = true,
1442                            SelectKey::Pick(i) => {
1443                                r.index = rows.get(i).copied();
1444                                st.open = false;
1445                                key_used = true;
1446                            }
1447                            SelectKey::Close => {
1448                                close = true;
1449                                key_used = true;
1450                            }
1451                            SelectKey::Ignored => {}
1452                        }
1453                    } else if r.focused && matches!(k.code, K::Enter | K::Space | K::ArrowDown) {
1454                        st.open = true;
1455                        key_used = true;
1456                    }
1457                }
1458                if close {
1459                    st.open = false;
1460                }
1461                if st.open && !was {
1462                    st.list = SelectState::open_at(Some(self.selected), win);
1463                }
1464                (st.open, st.list.clone())
1465            };
1466            r.pressed = key_used;
1467            let label = self.options.get(r.index.unwrap_or(self.selected)).copied().unwrap_or("");
1468            let view = ButtonView {
1469                icon: None,
1470                text: Some(label),
1471                active: open,
1472                disabled: self.disabled,
1473                active_border: None,
1474                hover_chevron: None,
1475            };
1476            let mut bs = button_settings(tokens);
1477            bs.theme = Box::new(theme.clone());
1478            paint_button(render, widgets, v, self.id.clone(), self.rect, &view, &bs);
1479            widgets.coord.set_a11y(&self.id, label, None);
1480            if open {
1481                let rows = filter(&labels, &list.query);
1482                let (w, h) = ls.list_size(rows.len(), searchable, self.rect.width);
1483                let within = self.within.unwrap_or(Rect::new(-1.0e6, -1.0e6, 2.0e6, 2.0e6));
1484                let b = place(self.rect, w, h, within, ls.gap);
1485                let shown: Vec<(&str, bool)> = rows.iter().map(|&i| (self.options[i], i == self.selected)).collect();
1486                let pre = format!("{}:list:item:", self.id.as_str());
1487                let hovered: Option<usize> = v.hovered().and_then(|w| w.as_str().strip_prefix(pre.as_str())?.parse().ok());
1488                let hover = |k: usize| hovered.is_some() && rows.get(k).copied() == hovered;
1489                let painted = draw_list(render, b, &shown, &list, searchable.then_some(list.query.as_str()), &hover, &ls);
1490                let (coord, _, layer) = parts(widgets);
1491                coord.register_atomic(WidgetId::from(format!("{}:list", self.id.as_str())), WidgetKind::Custom, b, Sense::CLICK | Sense::HOVER, layer);
1492                for (k, rr) in painted {
1493                    let oi = rows[k];
1494                    let rid = child(&self.id, "list:item", oi);
1495                    coord.register_atomic(rid.clone(), WidgetKind::Item, rr, Sense::CLICK | Sense::HOVER, layer);
1496                    coord.set_a11y(&rid, self.options[oi], Some(oi == self.selected));
1497                }
1498            }
1499            r.checked = open;
1500            r
1501        });
1502        if let Some(i) = r.index {
1503            r.changed = i != self.selected;
1504            if let Some(b) = self.bind {
1505                *b = i;
1506            }
1507        }
1508        r
1509    }
1510}
1511
1512// -- menu -------------------------------------------------------------------
1513
1514/// A context menu. Start with [`menu`].
1515pub struct MenuBuilder<'a> {
1516    id: WidgetId,
1517    at: (f64, f64),
1518    items: &'a [&'a str],
1519    open: &'a mut bool,
1520    title: Option<&'a str>,
1521    danger: Option<usize>,
1522}
1523
1524/// A menu of `items` at `at` while `*open`. Items are `"{id}:item:{i}"`.
1525/// A pick or a click elsewhere clears `*open`.
1526pub fn menu<'a>(id: impl Into<WidgetId>, at: (f64, f64), items: &'a [&'a str], open: &'a mut bool) -> MenuBuilder<'a> {
1527    MenuBuilder { id: id.into(), at, items, open, title: None, danger: None }
1528}
1529
1530impl<'a> MenuBuilder<'a> {
1531    /// Header line.
1532    pub fn title(mut self, t: &'a str) -> Self {
1533        self.title = Some(t);
1534        self
1535    }
1536    /// Draw item `i` in the danger colour (delete, sign out).
1537    pub fn danger(mut self, i: usize) -> Self {
1538        self.danger = Some(i);
1539        self
1540    }
1541
1542    /// Register and draw when open.
1543    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1544        if !*self.open {
1545            return Response::default();
1546        }
1547        let theme = theme_of(cx);
1548        let r = cx.with_paint(|render, widgets, v, _| {
1549            let mut r = Response::of(v, &self.id);
1550            r.index = picked(v, &self.id, "item");
1551            if r.index.is_some() || clicked_outside(v, &self.id) {
1552                return (r, false);
1553            }
1554            let items: Vec<ContextMenuItem<'_>> = self
1555                .items
1556                .iter()
1557                .enumerate()
1558                .map(|(i, l)| ContextMenuItem { action: l, label: l, icon: None, danger: self.danger == Some(i), separator_after: false, enabled: true })
1559                .collect();
1560            let state = ContextMenuState { is_open: true, x: self.at.0, y: self.at.1, ..Default::default() };
1561            let view = ContextMenuView { items: &items, target_id: None, title: self.title };
1562            let settings = ContextMenuSettings { theme: Box::new(theme), ..Default::default() };
1563            let (coord, _, layer) = parts(widgets);
1564            register_input_coordinator_context_menu(coord, self.id.clone(), &state, &view, &settings, &ContextMenuRenderKind::Default, layer);
1565            for (i, l) in self.items.iter().enumerate() {
1566                coord.set_a11y(&child(&self.id, "item", i), *l, None);
1567            }
1568            draw_context_menu(render, &state, &view, &settings, &ContextMenuRenderKind::Default);
1569            (r, true)
1570        });
1571        *self.open = r.1;
1572        let mut r = r.0;
1573        r.changed = r.index.is_some();
1574        r
1575    }
1576}
1577
1578// -- dialog -----------------------------------------------------------------
1579
1580/// A modal frame with a title, close button and footer. Start with [`dialog`].
1581pub struct DialogBuilder<'a> {
1582    id: WidgetId,
1583    rect: Rect,
1584    title: Option<&'a str>,
1585    footer: &'a [&'a str],
1586    dim: bool,
1587}
1588
1589/// A dialog in `rect`. Close is `"{id}:close"` (reported as `clicked`),
1590/// footer buttons `"{id}:footer:{i}"` (reported as `index`; the first is
1591/// primary). The app decides whether either closes it.
1592pub fn dialog<'a>(id: impl Into<WidgetId>, rect: Rect) -> DialogBuilder<'a> {
1593    DialogBuilder { id: id.into(), rect, title: None, footer: &[], dim: true }
1594}
1595
1596impl<'a> DialogBuilder<'a> {
1597    /// Header title, also the accessible name.
1598    pub fn title(mut self, t: &'a str) -> Self {
1599        self.title = Some(t);
1600        self
1601    }
1602    /// Footer button labels, primary first.
1603    pub fn footer(mut self, labels: &'a [&'a str]) -> Self {
1604        self.footer = labels;
1605        self
1606    }
1607    /// Dim what is behind (default on).
1608    pub fn dim(mut self, on: bool) -> Self {
1609        self.dim = on;
1610        self
1611    }
1612
1613    /// Register and draw the frame. Paint the body after this, inside the
1614    /// returned content area of `rect`.
1615    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1616        let theme = theme_of(cx);
1617        cx.with_paint(|render, widgets, v, _| {
1618            let mut r = Response::of(v, &self.id);
1619            r.clicked = v.clicked(&WidgetId::from(format!("{}:close", self.id.as_str())));
1620            r.index = picked(v, &self.id, "footer");
1621            r.changed = r.clicked || r.index.is_some();
1622            let buttons: Vec<FooterBtn<'_>> = self
1623                .footer
1624                .iter()
1625                .enumerate()
1626                .map(|(i, l)| FooterBtn { label: l, style: if i == 0 { FooterBtnStyle::Primary } else { FooterBtnStyle::Ghost } })
1627                .collect();
1628            let mut view = ModalView {
1629                title: self.title,
1630                tabs: &[],
1631                footer_buttons: &buttons,
1632                wizard_pages: &[],
1633                backdrop: if self.dim { BackdropKind::Dim } else { BackdropKind::None },
1634                overflow: Default::default(),
1635                resizable: false,
1636            };
1637            let kind = if buttons.is_empty() { ModalRenderKind::WithHeader } else { ModalRenderKind::WithHeaderFooter };
1638            let settings = ModalSettings { theme: Box::new(theme), ..Default::default() };
1639            let (coord, states, layer) = parts(widgets);
1640            let state = states.get_or_insert_with(self.id.clone(), ModalState::default);
1641            register_input_coordinator_modal(coord, self.id.clone(), self.rect, state, &mut view, &settings, &kind, layer);
1642            if let Some(t) = self.title {
1643                coord.set_a11y(&self.id, t, None);
1644            }
1645            for (i, l) in self.footer.iter().enumerate() {
1646                coord.set_a11y(&child(&self.id, "footer", i), *l, None);
1647            }
1648            coord.set_a11y(&WidgetId::from(format!("{}:close", self.id.as_str())), "Close", None);
1649            draw_modal(render, self.rect, state, &mut view, &settings, &kind);
1650            r
1651        })
1652    }
1653}
1654
1655// -- splitter ---------------------------------------------------------------
1656
1657/// A draggable pane edge. Start with [`splitter`].
1658pub struct SplitterBuilder<'a> {
1659    id: WidgetId,
1660    axis: Axis,
1661    span: Rect,
1662    pos: &'a mut f64,
1663    min: f64,
1664    max: f64,
1665    grab: f64,
1666}
1667
1668/// An edge at `*pos` along `axis` across `span`. Dragging writes `*pos`.
1669pub fn splitter<'a>(id: impl Into<WidgetId>, axis: Axis, span: Rect, pos: &'a mut f64) -> SplitterBuilder<'a> {
1670    SplitterBuilder { id: id.into(), axis, span, pos, min: f64::MIN, max: f64::MAX, grab: 9.0 }
1671}
1672
1673impl<'a> SplitterBuilder<'a> {
1674    /// Clamp the edge to `min..=max`.
1675    pub fn range(mut self, min: f64, max: f64) -> Self {
1676        self.min = min;
1677        self.max = max;
1678        self
1679    }
1680    /// Width of the grab strip in px (default 9).
1681    pub fn grab(mut self, px: f64) -> Self {
1682        self.grab = px;
1683        self
1684    }
1685
1686    /// Register and draw. `changed` is set on every drag step; `pressed`
1687    /// while dragging. Persist the size when the drag ends (`pressed` falls).
1688    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1689        let theme = theme_of(cx);
1690        cx.with_paint(|render, widgets, v, _| {
1691            let mut r = Response::of(v, &self.id);
1692            let (coord, states, layer) = parts(widgets);
1693            let s = states.get_or_insert_with(self.id.clone(), Splitter::default);
1694            if let SplitterEvent::Drag(p) = s.update(v, &self.id, self.axis) {
1695                let p = p.clamp(self.min, self.max);
1696                r.changed = (p - *self.pos).abs() > f64::EPSILON;
1697                *self.pos = p;
1698            }
1699            r.pressed = s.dragging();
1700            let hot = s.hot(v, &self.id);
1701            register_splitter(coord, self.id.clone(), grab_rect(self.axis, *self.pos, self.span, self.grab), layer);
1702            let (line, orientation) = match self.axis {
1703                Axis::X => (Rect::new(*self.pos, self.span.y, 1.0, self.span.height), SeparatorOrientation::Vertical),
1704                Axis::Y => (Rect::new(self.span.x, *self.pos, self.span.width, 1.0), SeparatorOrientation::Horizontal),
1705            };
1706            let view = SeparatorView { kind: SeparatorType::Divider { orientation }, hovered: hot, dragging: r.pressed };
1707            let settings = SeparatorSettings { theme: Box::new(theme), style: Box::new(DefaultSeparatorStyle) };
1708            draw_separator(render, line, &view, &settings);
1709            r
1710        })
1711    }
1712}
1713
1714// -- toast ------------------------------------------------------------------
1715
1716/// The toast stack. Start with [`toasts`].
1717pub struct ToastsBuilder<'a> {
1718    id: WidgetId,
1719    area: Rect,
1720    stack: &'a mut ToastStackState,
1721    now_ms: u64,
1722}
1723
1724/// Paint the live toasts of `stack` in the bottom-right of `area`, dropping
1725/// expired ones. Push new ones with [`ToastStackState::push`].
1726pub fn toasts<'a>(id: impl Into<WidgetId>, area: Rect, stack: &'a mut ToastStackState, now_ms: u64) -> ToastsBuilder<'a> {
1727    ToastsBuilder { id: id.into(), area, stack, now_ms }
1728}
1729
1730impl<'a> ToastsBuilder<'a> {
1731    /// Draw. `changed` is true while any toast is shown, so the app keeps
1732    /// asking for frames until the last one fades.
1733    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> Response {
1734        let theme = theme_of(cx);
1735        let live = self.stack.tick(self.now_ms);
1736        cx.with_paint(|render, _widgets, v, _| {
1737            let mut r = Response::of(v, &self.id);
1738            r.changed = !live.is_empty();
1739            if r.changed {
1740                render.save();
1741                render.translate(self.area.x, self.area.y);
1742                draw_toast_stack(render, live, &theme, self.area.width, self.area.height, self.now_ms);
1743                render.restore();
1744            }
1745            r
1746        })
1747    }
1748}
1749
1750#[cfg(test)]
1751#[path = "kit_tests.rs"]
1752mod tests;
1753
1754// -- DOM trees ----------------------------------------------------------------
1755
1756/// Sense of a custom-paint slot: clicks, hover, the mouse drag and the wheel, and it
1757/// captures its fingers (`Sense::touch` + gestures).
1758fn paint_slot_sense() -> Sense {
1759    Sense::CLICK_AND_DRAG.union(Sense::SCROLL).with_touch().with_gesture()
1760}
1761
1762/// The mouse part of a slot frame for `wid`: the held pointer and the wheel.
1763fn slot_mouse(v: &dyn crate::handle::VisualQuery, wid: &WidgetId) -> (Option<(f64, f64)>, (f64, f64)) {
1764    let pressed = if v.is_pressed(wid) && !v.coarse_pointer() { v.raw_pointer() } else { None };
1765    let wheel = if v.scroll_touch() { (0.0, 0.0) } else { v.scroll_over(wid) };
1766    (pressed, wheel)
1767}
1768
1769/// A DOM tree ([`uzor::ui::dom`]) inside a kit panel. Start with [`dom`].
1770pub struct DomBuilder<'a> {
1771    rect: Rect,
1772    sheet: &'a uzor::ui::style::Sheet,
1773    root: uzor::ui::dom::El,
1774    scroll: f64,
1775    viewport: Option<Rect>,
1776    slots: Option<&'a mut dyn FnMut(&mut dyn RenderContext, &SlotFrame<'_>)>,
1777    registry: Option<&'a mut dyn SlotHooks>,
1778    numbers: Vec<(String, uzor::ui::domkit::NumberSpec)>,
1779    key: Option<&'a KeyInput>,
1780    /// Framework-owned `overflow: auto | scroll` containers ([`DomBuilder::dom_scroll`]).
1781    own_scroll: bool,
1782    /// Elements whose press-drag deltas are reported ([`DomBuilder::draggable`]).
1783    drag: Vec<String>,
1784    /// Grips whose press-drag deltas are reported as size ([`DomBuilder::resizable`]).
1785    resize: Vec<String>,
1786}
1787
1788fn number_char(c: char) -> bool {
1789    uzor::ui::domkit::NumberSpec::new().accepts(c)
1790}
1791
1792fn integer_char(c: char) -> bool {
1793    uzor::ui::domkit::NumberSpec::integer().accepts(c)
1794}
1795
1796/// Whether a number field had focus last frame (to tidy it on blur).
1797#[derive(Default)]
1798struct NumberFocus(bool);
1799
1800/// One custom-paint slot as the host paints it this frame ([`DomBuilder::paint_slots`],
1801/// [`paint_slot`]).
1802#[derive(Clone, Debug)]
1803pub struct SlotFrame<'k> {
1804    /// The slot key ([`uzor::ui::dom::El::slot`] / [`uzor::ui::dom::El::paint_slot`]).
1805    pub key: &'k str,
1806    /// The content box to paint into (window coordinates); painting is clipped to it
1807    /// and to the element's scroll containers.
1808    pub rect: Rect,
1809    /// The gestures of the fingers the slot captured since the last frame, oldest
1810    /// first, in window coordinates ([`SlotFrame::local`] maps a point into the slot).
1811    pub gestures: Vec<crate::types::gesture::Gesture>,
1812    /// The pointer (mouse, or the finger on the slot) over the slot, z-order safe:
1813    /// `None` under a popover or a sheet.
1814    pub pointer: Option<(f64, f64)>,
1815    /// The slot was clicked or tapped this frame.
1816    pub clicked: bool,
1817    /// The pointer while a mouse button holds the slot (a mouse drag), `None` otherwise.
1818    /// Fingers never set it: their drags are [`SlotFrame::gestures`].
1819    pub pressed: Option<(f64, f64)>,
1820    /// Mouse-wheel / trackpad scroll over the slot this frame, `(dx, dy)`; a finger's
1821    /// scroll is not reported here.
1822    pub wheel: (f64, f64),
1823}
1824
1825impl SlotFrame<'_> {
1826    /// `(x, y)` relative to the slot's top-left corner.
1827    pub fn local(&self, x: f64, y: f64) -> (f64, f64) {
1828        (x - self.rect.x, y - self.rect.y)
1829    }
1830}
1831
1832impl Default for SlotFrame<'static> {
1833    fn default() -> Self {
1834        Self {
1835            key: "",
1836            rect: Rect::default(),
1837            gestures: Vec::new(),
1838            pointer: None,
1839            clicked: false,
1840            pressed: None,
1841            wheel: (0.0, 0.0),
1842        }
1843    }
1844}
1845
1846/// What a [`dom`] tree did this frame.
1847#[derive(Clone, Debug, Default)]
1848pub struct DomResponse {
1849    /// The laid-out tree (rects by id, embed slots, a11y nodes).
1850    pub dom: uzor::ui::dom::Dom,
1851    /// The element id clicked this frame (topmost first).
1852    pub clicked: Option<String>,
1853    /// Gestures captured by the tree's touch targets (`touch-action: none`, paint
1854    /// slots) since the last frame: `(element id, gesture)`, oldest first.
1855    pub captured: Vec<(String, crate::types::gesture::Gesture)>,
1856    /// The element id under the pointer.
1857    pub hovered: Option<String>,
1858    /// The focused element id.
1859    pub focused: Option<String>,
1860    /// Text inputs whose value the user changed this frame: `(id, new value)`.
1861    pub edited: Vec<(String, String)>,
1862    /// The framework-owned scroll containers of the tree (`overflow: auto | scroll` with
1863    /// an id, after [`DomBuilder::dom_scroll`]) and their `scrollTop` after this frame,
1864    /// in tree order. Empty when that opt-in is off.
1865    pub scrolls: Vec<(String, f64)>,
1866    /// The key given to [`DomBuilder::key`] was used (an arrow key stepped a number field,
1867    /// or a focused registered paint slot got it).
1868    pub key_used: bool,
1869    /// What the registered slot painters reported this frame
1870    /// ([`DomBuilder::slot_registry`]), in paint order.
1871    pub slot_actions: Vec<uzor::ui::dom::SlotAction>,
1872    /// Opt-in dialog drag ([`DomBuilder::draggable`]): `(id, dx, dy)` pointer deltas
1873    /// this frame while the element holds the press; the app moves its own dialog.
1874    /// Empty unless the opt-in is used.
1875    pub moved: Vec<(String, f64, f64)>,
1876    /// Opt-in dialog resize ([`DomBuilder::resizable`]): `(id, dw, dh)` pointer deltas
1877    /// this frame while the grip holds the press; the app resizes its own dialog.
1878    /// Empty unless the opt-in is used.
1879    pub resized: Vec<(String, f64, f64)>,
1880}
1881
1882/// The last pointer position of an opt-in drag / resize ([`DomBuilder::draggable`],
1883/// [`DomBuilder::resizable`]); `None` while the element does not hold the press.
1884#[derive(Default)]
1885struct DomDrag {
1886    last: Option<(f64, f64)>,
1887}
1888
1889/// The scroll state of one framework-owned DOM scroll container.
1890#[derive(Default)]
1891struct DomScroll {
1892    sv: crate::types::scroll::ScrollView,
1893}
1894
1895fn dom_scroll_key(id: &str) -> WidgetId {
1896    WidgetId::from(format!("{id}:dom-scroll"))
1897}
1898
1899/// Scroll the framework-owned DOM scroll container `id` to `y` (CSS `el.scrollTop = y`,
1900/// clamped to its range on the next frame); `smooth` glides there.
1901pub fn dom_scroll_to<'c, C: ContentCx<'c>>(cx: &mut C, id: &str, y: f64, smooth: bool) {
1902    cx.with_paint(|_, widgets, _, _| {
1903        let st = widgets.states.get_or_insert_with(dom_scroll_key(id), DomScroll::default);
1904        if smooth {
1905            st.sv.scroll_into_view(y, 0.0, crate::types::scroll::ScrollAlign::Start, true);
1906        } else {
1907            st.sv.scroll_to(y.max(0.0));
1908        }
1909    });
1910    cx.request_frame();
1911}
1912
1913/// The `scrollTop` of the framework-owned DOM scroll container `id` (0 before its first frame).
1914pub fn dom_scroll_top<'c, C: ContentCx<'c>>(cx: &mut C, id: &str) -> f64 {
1915    cx.with_paint(|_, widgets, _, _| widgets.states.get::<DomScroll>(&dom_scroll_key(id)).map_or(0.0, |s| s.sv.offset))
1916}
1917
1918/// Lay out `root` with `sheet` in `rect` (scrolled up by [`DomBuilder::scroll`]),
1919/// paint it, and register every element with an id: buttons, switches, checkboxes and
1920/// rows become focusable click targets named by their accessible name ([`El::name`]
1921/// first, then text) with their checked state; DOM text inputs
1922/// ([`uzor::ui::dom::Control::Input`]) become text-store fields, so caret, selection,
1923/// drag, clipboard and IME work as in [`field`]. `position: fixed` elements (a select
1924/// popover, a side panel) are placed against the panel and stay put while it scrolls.
1925///
1926/// Kit widgets go *inside* the tree through embed slots: call them at
1927/// `resp.dom.slots()` after `build`.
1928///
1929/// Opt in with [`DomBuilder::dom_scroll`] to let elements with an id and
1930/// `overflow: auto | scroll` scroll themselves, as in a browser: the wheel, a
1931/// touchpad (1:1 with fling), a finger, keyboard steps queued with
1932/// [`queue_scroll_key`](crate::widgets::queue_scroll_key), a draggable thumb,
1933/// nested chaining at the edges (`overscroll-behavior: auto`). Their offset lives
1934/// in the widget state store under the id; read it from [`DomResponse::scrolls`]
1935/// or [`dom_scroll_top`], move it with [`dom_scroll_to`]. An element given a
1936/// non-zero [`El::scroll_top`](uzor::ui::dom::El::scroll_top) by the app is the
1937/// app's to scroll, as is `overflow: hidden`. Off by default: an app that already
1938/// scrolls those boxes itself (HQ's `@body`) must not have them taken over.
1939///
1940/// [`El::name`]: uzor::ui::dom::El::name
1941pub fn dom<'a>(rect: Rect, sheet: &'a uzor::ui::style::Sheet, root: uzor::ui::dom::El) -> DomBuilder<'a> {
1942    DomBuilder { rect, sheet, root, scroll: 0.0, viewport: None, slots: None, registry: None, numbers: Vec::new(), key: None, own_scroll: false, drag: Vec::new(), resize: Vec::new() }
1943}
1944
1945impl<'a> DomBuilder<'a> {
1946    /// Scroll the tree up by `y` (fixed elements do not move).
1947    pub fn scroll(mut self, y: f64) -> Self {
1948        self.scroll = y;
1949        self
1950    }
1951    /// The viewport fixed elements are placed against (the panel rect by default).
1952    pub fn viewport(mut self, r: Rect) -> Self {
1953        self.viewport = Some(r);
1954        self
1955    }
1956    /// Paint the tree's embed slots with `paint` *in paint order*: each slot's content
1957    /// is drawn right after its box, clipped to it and to its scroll containers, so a
1958    /// popover, a fixed sheet or a toast declared later stays on top. A paint slot
1959    /// ([`uzor::ui::dom::El::paint_slot`]) also gets the gestures it captured.
1960    pub fn paint_slots(mut self, paint: &'a mut dyn FnMut(&mut dyn RenderContext, &SlotFrame<'_>)) -> Self {
1961        self.slots = Some(paint);
1962        self
1963    }
1964    /// Paint slots by registered painters ([`uzor::ui::dom::SlotRegistry`]): a slot
1965    /// whose key has a painter is painted by it in paint order, gets its pointer, drag,
1966    /// wheel, click, gestures and (when focused) the [`DomBuilder::key`] as
1967    /// [`uzor::ui::dom::SlotEvent`]s in slot-local coordinates, is a Tab stop when the
1968    /// painter is focusable, and takes the painter's accessible name and role. What the
1969    /// painters return is [`DomResponse::slot_actions`]. Slots without a painter still go
1970    /// to [`DomBuilder::paint_slots`], if given.
1971    pub fn slot_registry(mut self, reg: &'a mut uzor::ui::dom::SlotRegistry) -> Self {
1972        // Through a trait object made only here: a tree that never calls this does
1973        // not link the registry's dispatch (HQ's wasm stays as it was).
1974        self.registry = Some(reg as &mut dyn SlotHooks);
1975        self
1976    }
1977
1978    /// Make the text input `id` a number field ([`uzor::ui::domkit::number_input`]):
1979    /// only what `spec` accepts can be typed, `{id}:inc` / `{id}:dec`, ArrowUp / ArrowDown
1980    /// (with [`DomBuilder::key`]) and the wheel over the focused field step it, and
1981    /// leaving it tidies the text ([`NumberSpec::normalized`]). Every change comes back in
1982    /// [`DomResponse::edited`]; read the value with [`NumberSpec::parse`].
1983    ///
1984    /// [`NumberSpec::normalized`]: uzor::ui::domkit::NumberSpec::normalized
1985    /// [`NumberSpec::parse`]: uzor::ui::domkit::NumberSpec::parse
1986    pub fn number(mut self, id: impl Into<String>, spec: uzor::ui::domkit::NumberSpec) -> Self {
1987        self.numbers.push((id.into(), spec));
1988        self
1989    }
1990    /// This frame's key press, if any (the app forwards keys it did not use): the arrow
1991    /// keys step a focused number field ([`DomResponse::key_used`]).
1992    pub fn key(mut self, k: Option<&'a KeyInput>) -> Self {
1993        self.key = k.filter(|k| k.state != crate::KeyState::Up);
1994        self
1995    }
1996    /// Let elements with an id and `overflow: auto | scroll` be framework-owned
1997    /// scroll containers (see [`dom`]). Off by default, so an app that already
1998    /// scrolls those boxes itself is unchanged.
1999    pub fn dom_scroll(mut self) -> Self {
2000        self.own_scroll = true;
2001        self
2002    }
2003    /// Report pointer deltas while element `id` holds the press as
2004    /// [`DomResponse::moved`] `(id, dx, dy)`, so the app can move its own dialog by
2005    /// its header. Off unless asked; the framework never moves the tree itself.
2006    pub fn draggable(mut self, id: impl Into<String>) -> Self {
2007        self.drag.push(id.into());
2008        self
2009    }
2010    /// The same for a resize grip: [`DomResponse::resized`] `(id, dw, dh)` while the
2011    /// grip holds the press; the app applies the delta to its own dialog size.
2012    pub fn resizable(mut self, id: impl Into<String>) -> Self {
2013        self.resize.push(id.into());
2014        self
2015    }
2016
2017    /// Paint the tree and register its hit targets and fields.
2018    pub fn build<'c, C: ContentCx<'c>>(self, cx: &mut C) -> DomResponse {
2019        let now_ms = cx.time_ms();
2020        let frame_now = cx.frame_now_ms();
2021        let overlay = cx.is_overlay();
2022        let DomBuilder { rect, sheet, mut root, scroll, viewport, slots, registry, numbers, key, own_scroll, drag, resize } = self;
2023        let (resp, ime, more) = cx.with_paint(|render, widgets, v, _| {
2024            build_paint(render, widgets, v, now_ms, frame_now, overlay, rect, sheet, &mut root, scroll, viewport, slots, registry, &numbers, key, own_scroll, &drag, &resize)
2025        });
2026        if let Some(at) = ime {
2027            cx.ime_area(at);
2028        }
2029        if more {
2030            cx.request_frame();
2031        }
2032        resp
2033    }
2034}
2035
2036
2037/// One non-generic paint of a [`dom`] tree: number fields, optional framework-owned
2038/// scroll containers, layout, slots and hit targets. Kept off the generic
2039/// [`DomBuilder::build`] so it is not copied for every content type.
2040#[inline(never)]
2041fn build_paint(
2042    render: &mut dyn RenderContext,
2043    widgets: &mut crate::handle::Widgets<'_>,
2044    v: &dyn crate::handle::VisualQuery,
2045    now_ms: u64,
2046    frame_now: f64,
2047    overlay: bool,
2048    rect: Rect,
2049    sheet: &uzor::ui::style::Sheet,
2050    root: &mut uzor::ui::dom::El,
2051    scroll: f64,
2052    viewport: Option<Rect>,
2053    mut slots: Option<&mut dyn FnMut(&mut dyn RenderContext, &SlotFrame<'_>)>,
2054    mut registry: Option<&mut dyn SlotHooks>,
2055    numbers: &[(String, uzor::ui::domkit::NumberSpec)],
2056    key: Option<&KeyInput>,
2057    own_scroll: bool,
2058    drag: &[String],
2059    resize: &[String],
2060) -> (DomResponse, Option<Rect>, bool) {
2061    use uzor::ui::dom::{Control, El};
2062    use uzor::ui::style::State;
2063    // Number fields: steps (buttons, arrow keys, wheel over the focused field), what
2064    // could not be typed (a paste) and the tidy-up on blur go into the text store,
2065    // so the walk below reports them as edits.
2066    let mut key_used = false;
2067    let mut num_edits: Vec<(String, String)> = Vec::new();
2068    if !numbers.is_empty() {
2069        for (id, spec) in numbers {
2070            let wid = WidgetId::from(id.as_str());
2071            let Some(text) = widgets.coord.text_fields().field_state(&wid).map(|s| s.text.clone()) else { continue };
2072            let focused = v.is_focused(&wid);
2073            let mut n = 0i32;
2074            if v.clicked(&WidgetId::from(format!("{id}:inc"))) {
2075                n += 1;
2076            }
2077            if v.clicked(&WidgetId::from(format!("{id}:dec"))) {
2078                n -= 1;
2079            }
2080            if focused {
2081                use uzor::input::keyboard::KeyCode as Kc;
2082                match key.map(|k| k.code) {
2083                    Some(Kc::ArrowUp) => {
2084                        n += 1;
2085                        key_used = true;
2086                    }
2087                    Some(Kc::ArrowDown) => {
2088                        n -= 1;
2089                        key_used = true;
2090                    }
2091                    _ => {}
2092                }
2093                let dy = v.scroll_over(&wid).1;
2094                if dy != 0.0 && !v.scroll_touch() {
2095                    n += if dy > 0.0 { 1 } else { -1 };
2096                }
2097            }
2098            let was = std::mem::replace(&mut widgets.states.get_or_insert_with(WidgetId::from(format!("{id}:num-focus")), NumberFocus::default).0, focused);
2099            let next = if n != 0 {
2100                spec.stepped(&text, n)
2101            } else if was && !focused {
2102                spec.normalized(&text)
2103            } else {
2104                spec.sanitize(&text)
2105            };
2106            if next != text {
2107                widgets.coord.text_fields_mut().set_text(&wid, &next);
2108                num_edits.push((id.clone(), next));
2109            }
2110        }
2111    }
2112    // Framework-owned scroll containers: their stored offsets go into the tree,
2113    // this frame's wheel / keys / thumb move them (relaid out when they did).
2114    fn app_scrolled(e: &El, out: &mut Vec<String>) {
2115        if let (Some(id), true) = (e.id.as_deref(), e.scroll_top != 0.0) {
2116            out.push(id.to_string());
2117        }
2118        for c in &e.children {
2119            app_scrolled(c, out);
2120        }
2121    }
2122    fn apply(e: &mut El, offs: &[(String, f64)]) {
2123        if let Some(id) = e.id.as_deref() {
2124            if let Some((_, y)) = offs.iter().find(|(i, _)| i == id) {
2125                e.scroll_top = *y;
2126            }
2127        }
2128        for c in &mut e.children {
2129            apply(c, offs);
2130        }
2131    }
2132    let mut app_owned = Vec::new();
2133    let mut offs: Vec<(String, f64)> = Vec::new();
2134    if own_scroll {
2135        app_scrolled(root, &mut app_owned);
2136        fn ids(e: &El, out: &mut Vec<String>) {
2137            if let Some(id) = &e.id {
2138                out.push(id.clone());
2139            }
2140            for c in &e.children {
2141                ids(c, out);
2142            }
2143        }
2144        let mut all = Vec::new();
2145        ids(root, &mut all);
2146        for id in all.into_iter().filter(|i| !app_owned.contains(i)) {
2147            if let Some(st) = widgets.states.get::<DomScroll>(&dom_scroll_key(&id)) {
2148                offs.push((id, st.sv.offset));
2149            }
2150        }
2151        apply(root, &offs);
2152    }
2153    let mut edited = Vec::new();
2154    let mut seed: Vec<(WidgetId, String)> = Vec::new();
2155    // Feed the text store's state into the tree's inputs (seeding new fields).
2156    fn walk(e: &mut El, f: &mut dyn FnMut(&str, &mut uzor::ui::dom::Edit)) {
2157        if let (Some(id), Some(Control::Input(ed))) = (e.id.as_deref(), e.control.as_mut()) {
2158            f(id, ed);
2159        }
2160        for c in &mut e.children {
2161            walk(c, f);
2162        }
2163    }
2164    walk(root, &mut |id, ed| {
2165        let wid = WidgetId::from(id);
2166        if widgets.coord.text_fields().field_state(&wid).is_none() {
2167            seed.push((wid.clone(), ed.value.clone()));
2168        }
2169        let focused = v.is_focused(&wid);
2170        if let Some(s) = widgets.coord.text_fields().field_state(&wid) {
2171            let text = s.text.clone();
2172            if text != ed.value {
2173                edited.push((id.to_string(), text.clone()));
2174                ed.value = text;
2175            }
2176            let caret = s.cursor.min(ed.value.chars().count());
2177            let composing = !s.preedit.is_empty();
2178            let sel = (!composing).then(|| s.selection_range()).flatten();
2179            ed.caret = focused.then_some(caret);
2180            ed.anchor = sel.filter(|_| focused).map(|(a, b)| if b == caret { a } else { b });
2181            ed.preedit = (focused && composing).then(|| s.preedit.clone());
2182            ed.caret_on = focused && s.engaged && widgets.coord.text_fields().cursor_visible(now_ms);
2183        } else {
2184            ed.caret = None;
2185        }
2186    });
2187    let state = |id: &str| {
2188        let w = WidgetId::from(id);
2189        let mut s = State::NONE;
2190        if v.is_hovered(&w) {
2191            s = s | State::HOVER;
2192        }
2193        if v.is_pressed(&w) {
2194            s = s | State::ACTIVE;
2195        }
2196        if v.is_focused(&w) {
2197            // `:focus-visible` like the browser: keyboard focus only, not a click.
2198            s = s | State::FOCUS;
2199            if v.focus_visible() {
2200                s = s | State::FOCUS_VISIBLE;
2201            }
2202        }
2203        s
2204    };
2205    let vp = viewport.unwrap_or(rect);
2206    let lay = |render: &mut dyn RenderContext, root: &El| {
2207        let d = uzor::ui::dom::lay_out_in(render, sheet, root, rect.x, rect.y, rect.width, Some(vp), &state);
2208        if scroll != 0.0 { d.moved(0.0, -scroll) } else { d }
2209    };
2210    let mut d = lay(render, root);
2211    let mut more = false;
2212    // (id, visible viewport, scroll view, whether the host paints its bar)
2213    let mut scrollers: Vec<(String, Rect, crate::types::scroll::ScrollView, bool)> = Vec::new();
2214    let sst = crate::types::scroll::ScrollStyle::default();
2215    if own_scroll {
2216        // (id, viewport, scroll view) of each owned container, tree order.
2217        for b in &d.boxes {
2218            let Some(id) = b.id.as_deref() else { continue };
2219            if !matches!(b.style.overflow.as_deref(), Some("auto" | "scroll")) || app_owned.iter().any(|a| a == id) {
2220                continue;
2221            }
2222            let e = b.style.border_edges();
2223            let pad = Rect::new(b.rect.x + e[3], b.rect.y + e[0], (b.rect.width - e[1] - e[3]).max(0.0), (b.rect.height - e[0] - e[2]).max(0.0));
2224            let mut vis = b.clip.map_or(pad, |c| c.intersect(pad));
2225            if !b.fixed {
2226                vis = vis.intersect(rect);
2227            }
2228            let mut sv = widgets.states.get_or_insert_with(dom_scroll_key(id), DomScroll::default).sv.clone();
2229            // The wheel goes to the visible part; the extent is the padding box's.
2230            let wheel = vis.width > 0.0 && vis.height > 0.0;
2231            more |= crate::widgets::scroll::begin_parts(widgets.states, v, frame_now, id, vis, &mut sv, b.scroll_height, wheel, &sst);
2232            sv.set_extent(b.scroll_height, pad.height);
2233            sv.offset = sv.offset.clamp(0.0, sv.max());
2234            widgets.states.get_or_insert_with(dom_scroll_key(id), DomScroll::default).sv = sv.clone();
2235            let bar = b.style.scrollbar_width.as_deref() != Some("none");
2236            scrollers.push((id.to_string(), vis, sv, bar));
2237        }
2238        let now_offs: Vec<(String, f64)> = scrollers.iter().map(|(i, _, sv, _)| (i.clone(), sv.offset)).collect();
2239        let changed = now_offs.iter().any(|(i, y)| offs.iter().find(|(j, _)| j == i).map_or(*y != 0.0, |(_, o)| (o - y).abs() > 0.01));
2240        if changed {
2241            apply(root, &now_offs);
2242            d = lay(render, root);
2243        }
2244    }
2245    let (coord, _, layer) = parts(widgets);
2246    render.save();
2247    render.begin_path();
2248    render.rect(rect.x, rect.y, rect.width, rect.height);
2249    render.clip();
2250    let key_in = key;
2251    let mut slot_actions = Vec::new();
2252    let mut slot_key_used = false;
2253    if slots.is_some() || registry.is_some() {
2254        uzor::ui::dom::paint_slots(render, &d, &mut |ctx, key, content| {
2255            let id = d.boxes.iter().find(|b| b.slot.as_deref() == Some(key)).and_then(|b| b.id.as_deref()).unwrap_or(key);
2256            let wid = WidgetId::from(id);
2257            let (pressed, wheel) = slot_mouse(v, &wid);
2258            if let Some(reg) = registry.as_deref_mut() {
2259                let style = d.boxes.iter().find(|b| b.slot.as_deref() == Some(key)).map(|b| &b.style);
2260                if reg.slot(ctx, v, &wid, key, content, style, key_in, &mut slot_actions, &mut slot_key_used) {
2261                    return;
2262                }
2263            }
2264            let Some(paint) = slots.as_mut() else { return };
2265            let frame = SlotFrame { key, rect: content, gestures: v.captured_gestures(&wid), pointer: v.pointer_over(&wid), clicked: v.clicked(&wid), pressed, wheel };
2266            ctx.save();
2267            ctx.begin_path();
2268            ctx.rect(content.x, content.y, content.width, content.height);
2269            ctx.clip();
2270            paint(ctx, &frame);
2271            ctx.restore();
2272        });
2273    } else {
2274        uzor::ui::dom::paint(render, &d);
2275    }
2276    render.restore();
2277    coord.set_default_layer(Some(layer.clone()));
2278    let mut ime = None;
2279    for b in &d.boxes {
2280        let Some(id) = b.id.as_deref() else { continue };
2281        // What is visible of it: inside the panel (unless fixed) and its clips.
2282        let mut vis = b.clip.map_or(b.rect, |c| c.intersect(b.rect));
2283        if !b.fixed {
2284            vis = vis.intersect(rect);
2285        }
2286        if vis.width <= 0.0 || vis.height <= 0.0 {
2287            continue;
2288        }
2289        let wid = WidgetId::from(id);
2290        let name = b.accessible_name().unwrap_or_default().to_string();
2291        if let Some(Control::Input(e)) = &b.control {
2292            let cfg = match numbers.iter().find(|(n, _)| n == id) {
2293                Some((_, spec)) => uzor::TextFieldConfig::text().with_filter(if spec.decimals == Some(0) { integer_char } else { number_char }),
2294                None if e.masked => uzor::TextFieldConfig::password(),
2295                None => uzor::TextFieldConfig::text(),
2296            };
2297            coord.register_text_field(wid.clone(), vis, cfg);
2298            if let Some((_, v)) = seed.iter().find(|(s, _)| *s == wid) {
2299                coord.text_fields_mut().set_text(&wid, v);
2300            }
2301            coord.set_a11y(&wid, &name, None);
2302            let c = uzor::ui::dom::content_box(b);
2303            let sx = c.x - b.input_scroll();
2304            // Boundaries of the shown text (value + composition), mapped back to the buffer.
2305            let pos: Vec<f64> = b.bounds.iter().map(|x| sx + x).collect();
2306            let _ = e;
2307            let fields = coord.text_fields_mut();
2308            let pos = match fields.field_state(&wid) {
2309                Some(s) => s.buffer_positions(pos),
2310                None => pos,
2311            };
2312            fields.update_field(&wid, (c.x, c.y, c.width, c.height), pos);
2313            if e.caret.is_some() {
2314                ime = b.caret_rect();
2315            }
2316        } else if b.tab || b.id.is_some() {
2317            let painter = b.slot.as_deref().and_then(|k| registry.as_deref().and_then(|r| r.info(k)));
2318            let tab = b.tab || painter.as_ref().is_some_and(|p| p.0);
2319            let mut sense = if tab { focusable() } else { Sense::CLICK | Sense::HOVER };
2320            if b.slot.is_some() && b.captures_touch() {
2321                // A paint slot (a chart): its fingers, and the mouse drag and
2322                // wheel too (`SlotFrame::pressed`, `SlotFrame::wheel`).
2323                sense = sense.union(paint_slot_sense());
2324            } else if b.captures_touch() {
2325                // `touch-action: none`: the element takes its fingers whole
2326                // (`VisualView::captured_gestures`).
2327                sense = sense.with_touch().with_gesture();
2328            }
2329            if scrollers.iter().any(|(i, _, _, _)| i == id) {
2330                sense = sense.union(Sense::SCROLL);
2331            }
2332            if painter.as_ref().is_some_and(|p| p.0) {
2333                // Arrows and the like reach the painter (with `DomBuilder::key`).
2334                sense = sense.with_keyboard();
2335            }
2336            let (kind, name) = match painter {
2337                Some((_, kind, pname)) => (kind, pname.unwrap_or(name)),
2338                None => (WidgetKind::Button, name),
2339            };
2340            coord.register_atomic(wid.clone(), kind, vis, sense, layer);
2341            coord.set_a11y(&wid, &name, b.control.as_ref().and_then(Control::checked));
2342        }
2343    }
2344    coord.set_default_layer(None);
2345    if registry.as_deref().is_some_and(|r| r.wants_frame()) {
2346        more = true;
2347    }
2348    // Thumbs over the content, and this frame's entries in the scroll chain.
2349    render.save();
2350    render.begin_path();
2351    render.rect(rect.x, rect.y, rect.width, rect.height);
2352    render.clip();
2353    for (id, vis, sv, bar) in &scrollers {
2354        crate::widgets::scroll::end_parts(widgets, render, v, frame_now, id, *vis, sv, &sst, overlay, *bar);
2355    }
2356    render.restore();
2357    let ids: Vec<&str> = d.boxes.iter().rev().filter_map(|b| b.id.as_deref()).collect();
2358    let clicked = ids.iter().find(|i| v.clicked(&WidgetId::from(**i))).map(|s| s.to_string());
2359    let hovered = ids.iter().find(|i| v.is_hovered(&WidgetId::from(**i))).map(|s| s.to_string());
2360    let focused = ids.iter().find(|i| v.is_focused(&WidgetId::from(**i))).map(|s| s.to_string());
2361    let captured = d
2362        .touch_targets()
2363        .flat_map(|(id, _)| v.captured_gestures(&WidgetId::from(id)).into_iter().map(move |g| (id.to_string(), g)))
2364        .collect();
2365    let scrolls = scrollers.into_iter().map(|(i, _, sv, _)| (i, sv.offset)).collect();
2366    // A number field's change counts even when the app's tree already shows it.
2367    for (id, text) in num_edits {
2368        match edited.iter_mut().find(|(i, _)| *i == id) {
2369            Some(e) => e.1 = text,
2370            None => edited.push((id, text)),
2371        }
2372    }
2373    let key_used = key_used || slot_key_used;
2374    // Opt-in dialog drag / resize: pointer deltas while the element holds the press.
2375    // The first pressed frame only seeds the position; release forgets it.
2376    let mut moved = Vec::new();
2377    let mut resized = Vec::new();
2378    for (ids, out) in [(drag, &mut moved), (resize, &mut resized)] {
2379        for id in ids {
2380            let wid = WidgetId::from(id.as_str());
2381            let st = widgets.states.get_or_insert_with(WidgetId::from(format!("{id}:dom-drag")), DomDrag::default);
2382            if v.is_pressed(&wid) {
2383                if let Some(p) = v.raw_pointer() {
2384                    if let Some(last) = st.last {
2385                        let (dx, dy) = (p.0 - last.0, p.1 - last.1);
2386                        if dx != 0.0 || dy != 0.0 {
2387                            out.push((id.clone(), dx, dy));
2388                        }
2389                    }
2390                    st.last = Some(p);
2391                }
2392            } else {
2393                st.last = None;
2394            }
2395        }
2396    }
2397    (DomResponse { dom: d, clicked, captured, hovered, focused, edited, scrolls, key_used, slot_actions, moved, resized }, ime, more)
2398}
2399
2400/// What a [`dom`] tree needs from a [`uzor::ui::dom::SlotRegistry`]. A trait object
2401/// built only by [`DomBuilder::slot_registry`], so trees that never call it do not
2402/// link the registry.
2403trait SlotHooks {
2404    /// Feed slot `key` its input and paint it; `false` when nobody is registered.
2405    #[allow(clippy::too_many_arguments)]
2406    fn slot(
2407        &mut self,
2408        ctx: &mut dyn RenderContext,
2409        v: &dyn crate::handle::VisualQuery,
2410        wid: &WidgetId,
2411        key: &str,
2412        content: Rect,
2413        style: Option<&uzor::ui::style::Style>,
2414        key_in: Option<&KeyInput>,
2415        actions: &mut Vec<uzor::ui::dom::SlotAction>,
2416        key_used: &mut bool,
2417    ) -> bool;
2418    /// `(focusable, widget kind, name)` of `key`'s painter.
2419    fn info(&self, key: &str) -> Option<(bool, WidgetKind, Option<String>)>;
2420    fn wants_frame(&self) -> bool;
2421}
2422
2423impl SlotHooks for uzor::ui::dom::SlotRegistry {
2424    fn slot(
2425        &mut self,
2426        ctx: &mut dyn RenderContext,
2427        v: &dyn crate::handle::VisualQuery,
2428        wid: &WidgetId,
2429        key: &str,
2430        content: Rect,
2431        style: Option<&uzor::ui::style::Style>,
2432        key_in: Option<&KeyInput>,
2433        actions: &mut Vec<uzor::ui::dom::SlotAction>,
2434        key_used: &mut bool,
2435    ) -> bool {
2436        if !self.contains(key) {
2437            return false;
2438        }
2439        let (pressed, wheel) = slot_mouse(v, wid);
2440        let focused = v.is_focused(wid);
2441        let input = uzor::ui::dom::SlotInput {
2442            pointer: v.pointer_over(wid),
2443            pressed,
2444            clicked: v.clicked(wid),
2445            wheel,
2446            focused,
2447            key: if focused { key_in.map(|k| (k.code, k.text.clone())) } else { None },
2448            events: v.captured_gestures(wid).iter().filter_map(|g| slot_gesture(g, content)).collect(),
2449        };
2450        *key_used |= input.key.is_some();
2451        actions.extend(self.input(key, content, &input));
2452        self.paint_slot(ctx, key, content, style);
2453        true
2454    }
2455    fn info(&self, key: &str) -> Option<(bool, WidgetKind, Option<String>)> {
2456        let p = self.painter(key)?;
2457        Some((p.focusable(), slot_widget_kind(p.role()), p.name()))
2458    }
2459    fn wants_frame(&self) -> bool {
2460        uzor::ui::dom::SlotRegistry::wants_frame(self)
2461    }
2462}
2463
2464/// A captured gesture (window coordinates) as a slot event (slot-local).
2465fn slot_gesture(g: &crate::types::gesture::Gesture, r: Rect) -> Option<uzor::ui::dom::SlotEvent> {
2466    use crate::types::gesture::Gesture as G;
2467    use uzor::ui::dom::SlotEvent as E;
2468    let l = |p: &crate::types::window::Point| (p.x - r.x, p.y - r.y);
2469    Some(match g {
2470        G::Pan { pos, delta, .. } | G::LongPressDrag { pos, delta } => {
2471            let (x, y) = l(pos);
2472            E::Pan { x, y, dx: delta.0, dy: delta.1 }
2473        }
2474        G::PanEnd { pos, .. } | G::LongPressEnd { pos } => {
2475            let (x, y) = l(pos);
2476            E::PanEnd { x, y }
2477        }
2478        G::Pinch { center, scale } => {
2479            let (x, y) = l(center);
2480            E::Pinch { x, y, scale: *scale }
2481        }
2482        G::PinchPan { center, delta, .. } => {
2483            let (x, y) = l(center);
2484            E::PinchPan { x, y, dx: delta.0, dy: delta.1 }
2485        }
2486        G::PinchEnd { scale } => E::PinchEnd { scale: *scale },
2487        G::LongPress { pos } => {
2488            let (x, y) = l(pos);
2489            E::LongPress { x, y }
2490        }
2491        G::DoubleTap { pos } => {
2492            let (x, y) = l(pos);
2493            E::DoubleTap { x, y }
2494        }
2495        // A tap is the slot's click; a pan's start is its first `Pan`.
2496        G::Tap { .. } | G::PanStart { .. } | G::Swipe { .. } => return None,
2497    })
2498}
2499
2500/// The widget kind (and so the platform accessibility role) of a registered paint
2501/// slot with ARIA role `role`.
2502fn slot_widget_kind(role: &str) -> WidgetKind {
2503    match role {
2504        "slider" => WidgetKind::Slider,
2505        "checkbox" => WidgetKind::Checkbox,
2506        "switch" => WidgetKind::Toggle,
2507        "link" => WidgetKind::Link,
2508        _ => WidgetKind::Button,
2509    }
2510}
2511
2512// -- custom-paint slots outside a DOM tree --------------------------------------
2513
2514/// A custom-paint area (a chart, an order book) outside a DOM tree. Start with
2515/// [`paint_slot`]. Inside a DOM tree use [`uzor::ui::dom::El::paint_slot`] with
2516/// [`DomBuilder::paint_slots`] instead.
2517pub struct PaintSlot<'k> {
2518    id: &'k str,
2519    rect: Rect,
2520}
2521
2522/// What a [`paint_slot`] reported this frame.
2523#[derive(Clone, Debug, Default)]
2524pub struct SlotResponse {
2525    /// The gestures the slot captured since the last frame (window coordinates).
2526    pub gestures: Vec<crate::types::gesture::Gesture>,
2527    /// The pointer over the slot (z-order safe).
2528    pub pointer: Option<(f64, f64)>,
2529    /// Clicked or tapped.
2530    pub clicked: bool,
2531    /// The pointer while a mouse button holds the slot ([`SlotFrame::pressed`]).
2532    pub pressed: Option<(f64, f64)>,
2533    /// Wheel scroll over the slot this frame ([`SlotFrame::wheel`]).
2534    pub wheel: (f64, f64),
2535}
2536
2537/// A custom-paint slot `id` at `rect`: registered as a click, drag and wheel target
2538/// that also captures touch (`Sense::touch`, so a finger on it pans / pinches it and
2539/// never scrolls what is under it), painted by the closure given to [`PaintSlot::paint`],
2540/// clipped to `rect`. The mouse drag and the wheel are [`SlotFrame::pressed`] and
2541/// [`SlotFrame::wheel`]. Widgets registered after it (buttons drawn over a chart) stay
2542/// ordinary targets.
2543pub fn paint_slot(id: &str, rect: Rect) -> PaintSlot<'_> {
2544    PaintSlot { id, rect }
2545}
2546
2547impl PaintSlot<'_> {
2548    /// Register the slot and paint it with `paint`.
2549    pub fn paint<'c, C: ContentCx<'c>>(self, cx: &mut C, paint: impl FnOnce(&mut dyn RenderContext, &SlotFrame<'_>)) -> SlotResponse {
2550        let PaintSlot { id, rect } = self;
2551        cx.with_paint(|render, widgets, v, _| {
2552            let (coord, _, layer) = parts(widgets);
2553            let wid = WidgetId::from(id);
2554            coord.register_atomic(wid.clone(), WidgetKind::Button, rect, paint_slot_sense(), layer);
2555            let (pressed, wheel) = slot_mouse(v, &wid);
2556            let frame = SlotFrame { key: id, rect, gestures: v.captured_gestures(&wid), pointer: v.pointer_over(&wid), clicked: v.clicked(&wid), pressed, wheel };
2557            render.save();
2558            render.begin_path();
2559            render.rect(rect.x, rect.y, rect.width, rect.height);
2560            render.clip();
2561            paint(render, &frame);
2562            render.restore();
2563            SlotResponse { gestures: frame.gestures, pointer: frame.pointer, clicked: frame.clicked, pressed: frame.pressed, wheel: frame.wheel }
2564        })
2565    }
2566}