Skip to main content

uzor_framework/widgets/
kit.rs

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