Skip to main content

uzor/ui/
domkit.rs

1//! The DOM widget catalog: ready-made [`El`] trees for the common controls and chat
2//! building blocks, styled by [`KIT_CSS`] (every look is a CSS rule an app may override
3//! by appending its own sheet, see [`sheet_with`]).
4//!
5//! | widget | builder | element / classes | hit ids |
6//! |---|---|---|---|
7//! | button | [`button`] | `button.k-btn` (`.primary`, `.ghost`) | `id` |
8//! | switch | [`switch`] | `button.k-switch` + [`Control::Switch`] (`:checked`) | `id` |
9//! | checkbox | [`checkbox`] | `div.k-check` > `span.k-box` + [`Control::Checkbox`] | `id` |
10//! | text input | [`input`] | `div.k-input` + [`Control::Input`] (`:focus`) | `id` |
11//! | number field | [`number_input`] + [`NumberSpec`] | `div.k-num` > `div.k-input`, `div.k-steps` > `button.k-step` | `id`, `{id}:inc`, `{id}:dec` |
12//! | spinner | [`spinner`] | `span.k-spinner` + [`Control::Spinner`] | — |
13//! | select trigger | [`select_trigger`] | `select.k-select` (`.open`) | `id` |
14//! | select popover | [`select_popover`] | fixed `div.k-pop` > `div.k-opt` (`.sel`, `.dis`) > label + `div.k-sub` | `{id}:opt:{i}` (enabled rows only) |
15//! | message bubble | [`bubble`] | `div.k-msg.me` / `.them` > `div.k-who`, `div.k-body` (runs), `div.k-time` | `id` |
16//! | hover action row | [`action_row`] | `div.k-actions` > `button.k-act` | `{id}:{key}` |
17//! | collapsible card | [`card`] | `div.k-card` (`.open`) > `div.k-card-head` + `div.k-card-body` | `id` (the head) |
18//! | chip / filter | [`chip`] | `button.k-chip` (`.on`) | `id` |
19//! | banner | [`banner`] | `div.k-banner.info` / `.warn` / `.error` | `{id}:act`, `{id}:close` |
20//! | side panel | [`side_panel`] | fixed `div.k-side` > `div.k-side-head` + `div.k-side-body` | `{id}:close` |
21//! | tabs | [`tabs`] | `div.k-tabs` > `button.k-tab` (`.on`) | `{id}:tab:{i}` |
22//! | segmented | [`segmented`] | `div.k-seg` > `button.k-seg-btn` (`.on`) | `{id}:{i}` |
23//! | list | [`list`] | `div.k-list` > `div.k-li` (`.sel`) | `{id}:row:{i}` |
24//! | radio group | [`radio_group`] | `div.k-radio-group` > `div.k-radio` (`.sel`) > ring + dot | `{id}:{key}` |
25//! | table | [`table`] | `div.k-table` > grid `div.k-tr` (`.k-th`, `.sel`) > `div.k-td` (`.num`) | `{id}:row:{i}` |
26//! | menu | [`menu`] | fixed `div.k-menu` > `div.k-mi` (`.danger`, `.dis`), `div.k-sep` | `{id}:item:{i}` |
27//! | dialog | [`dialog`] | fixed `div.k-scrim` + `div.k-dialog` > head, body, foot | `{id}:scrim`, `{id}:close`, `{id}:foot:{i}` |
28//! | tooltip | [`tooltip`] | fixed `div.k-tip` | — |
29//! | toasts | [`toasts`] | fixed `div.k-toasts` > `div.k-toast` (`.ok`, `.warn`, `.error`) | `{id}:{i}:close` |
30//! | toolbar (opt-in [`TOOLBAR_CSS`]) | [`toolbar`] + [`ToolItem`] | `div.k-toolbar` (`.vert`) > `button.k-tool` (`.on`, `.dis`) > `span.k-tool-icon`, `div.k-tool-split` > `button.k-tool-chev`, `div.k-tool-sep`, `div.k-tool-fill` | `{id}:{key}`, `{id}:{key}:menu` |
31//! | flyout | [`menu`] at [`flyout_at`] | fixed `div.k-menu` beside its tool | `{id}:item:{i}` |
32//! | stat, progress, badge, kbd, field | [`stat`], [`progress`], [`badge`], [`kbd`], [`field`] | `div.k-stat`, `div.k-progress`, `span.k-badge`, `span.k-kbd`, `div.k-field` | `id` (stat) |
33//!
34//! The light look is [`LIGHT_VARS`] on the page root ([`theme_vars`]); every colour in
35//! [`KIT_CSS`] is a `--k-*` variable.
36//!
37//! Inline markdown for bubbles is [`inline_md`]; long lists render only their visible
38//! rows with [`VirtualList`]. Kit widgets from `uzor-framework` go *inside* a DOM tree
39//! through an embed slot ([`El::slot`] + [`Dom::slots`](super::dom::Dom::slots)); a
40//! DOM tree goes inside a kit panel by laying it out in the panel's rect.
41
42use super::dom::{Control, Dom, Edit, El, Run};
43use super::style::{Sheet, StyleError};
44use crate::types::Rect;
45
46/// The catalog's default look (dark, 13px Inter). Variables on `:root` theme it:
47/// `--k-accent`, `--k-bg`, `--k-fg`, `--k-muted`, `--k-line`, `--k-panel`.
48pub const KIT_CSS: &str = r#"
49:root { --k-accent: #3b82f6; --k-bg: #17181b; --k-panel: #1f2125; --k-fg: #e8e8ea; --k-muted: #9a9ca3; --k-line: #33363c;
50        --k-me: #2563eb; --k-them: #26282d; --k-warn: #f59e0b; --k-error: #ef4444; --k-info: #3b82f6; --k-ok: #22c55e;
51        --k-btn: #2b2e34; --k-btn-hover: #353840; --k-track: #4a4d55; --k-track-hover: #575b64; --k-accent-hover: #2f6fd8;
52        --k-field: #111214; --k-sunken: #141518; --k-hover: #2c2f36; --k-hi: #33363d; --k-sel: rgba(59,130,246,0.18);
53        --k-dis: #5d6068; --k-body: #c9cbd1; --k-on-accent: #ffffff; --k-scrim: rgba(0,0,0,0.55); --k-shadow: rgba(0,0,0,0.45) }
54div.k-root { color: var(--k-fg); font-size: 13px; font-family: Inter, sans-serif }
55button.k-btn { padding: 6px 14px; border-radius: 8px; background: var(--k-btn); color: var(--k-fg); font-weight: 500 }
56button.k-btn:hover { background: var(--k-btn-hover) }
57button.k-btn.primary { background: var(--k-accent); color: var(--k-on-accent) }
58button.k-btn.primary:hover { background: var(--k-accent-hover) }
59button.k-btn.ghost { background: transparent; border: 1px solid var(--k-line) }
60button.k-btn.ghost:hover { background: var(--k-hover) }
61button.k-btn.danger { background: transparent; border: 1px solid var(--k-error); color: var(--k-error) }
62button.k-btn:focus-visible { border: 2px solid var(--k-accent) }
63button.k-switch { width: 36px; height: 20px; padding: 2px; border-radius: 10px; background: var(--k-track); --knob: #ffffff }
64button.k-switch:checked { background: var(--k-accent) }
65button.k-switch:hover { background: var(--k-track-hover) }
66button.k-switch:checked:hover { background: var(--k-accent-hover) }
67div.k-check { display: flex; align-items: center; gap: 8px }
68span.k-box { width: 16px; height: 16px; padding: 1px; border-radius: 4px; border: 1.5px solid var(--k-track-hover); --check: #ffffff; --check-width: 2px }
69span.k-box:checked { background: var(--k-accent); border-color: var(--k-accent) }
70div.k-radio-group { display: flex; flex-direction: column; gap: 4px }
71div.k-radio { display: flex; align-items: center; height: 32px; padding: 0 6px 0 3.25px; border-radius: 6px; gap: 11.25px }
72div.k-radio:hover { background: var(--k-hover) }
73span.k-radio-ring { display: flex; align-items: center; justify-content: center; width: 15.5px; height: 15.5px; border: 1.5px solid var(--k-line); border-radius: 7.75px; flex: none }
74div.k-radio.sel span.k-radio-ring { border-color: var(--k-accent) }
75span.k-radio-dot { width: 8px; height: 8px; border-radius: 4px; background: var(--k-accent) }
76span.k-radio-label { font-size: 13px; color: var(--k-fg) }
77div.k-input { height: 32px; padding: 0 10px; border-radius: 8px; background: var(--k-field); border: 1px solid var(--k-line);
78              --placeholder: var(--k-muted); --selection: rgba(59,130,246,0.4); --caret: var(--k-fg) }
79div.k-input:hover { border-color: var(--k-track) }
80div.k-input:focus { border-color: var(--k-accent) }
81div.k-num { display: flex; align-items: stretch; height: 32px }
82div.k-num > div.k-input { flex-grow: 1; border-radius: 8px 0px 0px 8px }
83div.k-steps { display: flex; flex-direction: column; width: 22px; flex-shrink: 0; border: 1px solid var(--k-line); border-left: none;
84              border-radius: 0px 8px 8px 0px; background: var(--k-btn); overflow: hidden }
85button.k-step { flex-grow: 1; display: flex; align-items: center; justify-content: center; color: var(--k-muted); padding: 0px }
86button.k-step:hover { background: var(--k-btn-hover); color: var(--k-fg) }
87button.k-step > span { width: 12px; height: 12px }
88span.k-spinner { width: 18px; height: 18px; color: var(--k-accent); --spin-track: var(--k-line); --spin-speed: 1.2 }
89select.k-select { height: 32px; padding: 0 30px 0 12px; border-radius: 8px; background: var(--k-btn); color: var(--k-fg); --chevron: var(--k-muted) }
90select.k-select:hover { background: var(--k-btn-hover) }
91select.k-select.open { border: 1px solid var(--k-accent) }
92div.k-pop { position: fixed; z-index: 100; padding: 4px; border-radius: 10px; background: var(--k-panel); border: 1px solid var(--k-line);
93            box-shadow: 0 8px 24px var(--k-shadow); display: flex; flex-direction: column }
94div.k-opt { display: flex; align-items: center; gap: 8px; padding: 7px 10px; border-radius: 6px; color: var(--k-fg); flex-shrink: 0 }
95div.k-opt:hover { background: var(--k-hover) }
96div.k-opt.sel { background: var(--k-sel) }
97div.k-opt.hi { background: var(--k-hi) }
98span.k-tick { width: 14px; height: 14px; flex-shrink: 0; color: var(--k-accent) }
99div.k-optl { display: flex; flex-direction: column; flex-grow: 1; min-width: 0 }
100div.k-search { display: flex; align-items: center; gap: 8px; height: 28px; margin: 2px 2px 4px; padding: 0 8px; border-radius: 6px; background: var(--k-sunken); flex-shrink: 0 }
101span.k-mag { width: 14px; height: 14px; color: var(--k-muted) }
102div.k-ph { color: var(--k-muted) }
103div.k-empty { padding: 7px 14px; color: var(--k-muted) }
104div.k-thumb { position: absolute; right: 3px; width: 3px; border-radius: 2px; background: var(--k-track) }
105div.k-opt.dis { color: var(--k-dis) }
106div.k-opt .k-sub { color: var(--k-muted); font-size: 11px }
107div.k-opt.dis .k-sub { color: var(--k-dis) }
108div.k-msg { display: flex; flex-direction: column; max-width: 75%; padding: 8px 12px; border-radius: 14px; white-space: normal; gap: 2px }
109div.k-msg.me { align-self: flex-end; background: var(--k-me); color: #ffffff; border-radius: 14px 14px 4px 14px }
110div.k-msg.them { align-self: flex-start; background: var(--k-them); border-radius: 14px 14px 14px 4px }
111div.k-msg > div.k-who { font-weight: 600; font-size: 12px; color: var(--k-accent) }
112div.k-msg.me > div.k-who { color: #dbe7ff }
113div.k-msg div.k-time { font-size: 10px; color: var(--k-muted); text-align: right }
114div.k-msg.me div.k-time { color: #c7d7f7 }
115div.k-body code { font-family: monospace; background: rgba(0,0,0,0.3); padding: 0 5px; border-radius: 5px }
116div.k-body b { font-weight: 700 }
117div.k-body i { font-style: italic }
118div.k-body a.link { color: #93c5fd }
119div.k-body a.mention { color: #93c5fd; font-weight: 600 }
120div.k-msg.me div.k-body a.link { color: #ffffff }
121div.k-msg > div.k-actions { align-self: flex-end }
122div.k-actions { display: flex; gap: 2px; padding: 2px; border-radius: 8px; background: var(--k-panel); border: 1px solid var(--k-line) }
123button.k-act { width: 26px; height: 26px; padding: 5px; border-radius: 6px; color: var(--k-muted) }
124button.k-act:hover { background: var(--k-hover); color: var(--k-fg) }
125div.k-card { border-radius: 10px; border: 1px solid var(--k-line); background: var(--k-panel); display: flex; flex-direction: column }
126div.k-card-head { display: flex; align-items: center; gap: 6px; padding: 8px 10px; font-weight: 600 }
127div.k-card-head:hover { background: var(--k-hover); border-radius: 10px }
128div.k-card > div.k-card-head > span.k-chev { width: 14px; height: 14px; color: var(--k-muted) }
129div.k-card-body { padding: 4px 12px 10px; white-space: normal; color: var(--k-body) }
130button.k-chip { padding: 4px 10px; border-radius: 999px; border: 1px solid var(--k-line); color: var(--k-muted); font-size: 12px }
131button.k-chip:hover { color: var(--k-fg) }
132button.k-chip.on { background: var(--k-sel); border-color: var(--k-accent); color: var(--k-fg) }
133div.k-banner { display: flex; align-items: center; gap: 10px; padding: 8px 12px; border-radius: 8px; border-left: 3px solid var(--k-info); background: rgba(59,130,246,0.12) }
134div.k-banner.warn { border-left: 3px solid var(--k-warn); background: rgba(245,158,11,0.12) }
135div.k-banner.error { border-left: 3px solid var(--k-error); background: rgba(239,68,68,0.12) }
136div.k-banner.ok { border-left: 3px solid var(--k-ok); background: rgba(34,197,94,0.12) }
137div.k-banner > div.k-banner-text { flex-grow: 1; white-space: normal }
138div.k-banner button.k-act { width: 22px; height: 22px; padding: 4px }
139div.k-side { position: fixed; top: 0; right: 0; bottom: 0; width: 320px; z-index: 50; background: var(--k-panel); border-left: 1px solid var(--k-line);
140             display: flex; flex-direction: column }
141div.k-side-head { display: flex; align-items: center; padding: 12px 14px; border-bottom: 1px solid var(--k-line); font-weight: 600 }
142div.k-side-head > div.k-side-title { flex-grow: 1 }
143div.k-side-body { padding: 12px 14px; display: flex; flex-direction: column; gap: 10px; flex-grow: 1 }
144div.k-slot { border: 1px dashed var(--k-line); border-radius: 8px }
145div.k-tabs { display: flex; gap: 2px; padding: 3px; border-radius: 9px; background: var(--k-sunken); border: 1px solid var(--k-line) }
146button.k-tab { flex-grow: 1; padding: 5px 12px; border-radius: 6px; color: var(--k-muted); font-weight: 500; text-align: center }
147button.k-tab:hover { color: var(--k-fg); background: var(--k-hover) }
148button.k-tab.on { background: var(--k-btn-hover); color: var(--k-fg) }
149div.k-list { display: flex; flex-direction: column; padding: 4px; border-radius: 10px; border: 1px solid var(--k-line); background: var(--k-panel); overflow: hidden }
150div.k-li { display: flex; align-items: center; gap: 8px; height: 30px; padding: 0 10px; border-radius: 6px; flex-shrink: 0 }
151div.k-li:hover { background: var(--k-hover) }
152div.k-li.sel { background: var(--k-sel); color: var(--k-fg) }
153div.k-li > div.k-li-main { flex-grow: 1; min-width: 0 }
154div.k-li > div.k-li-side { color: var(--k-muted); font-size: 12px }
155div.k-table { display: flex; flex-direction: column; border-radius: 10px; border: 1px solid var(--k-line); background: var(--k-panel); overflow: hidden }
156div.k-tr { display: grid; align-items: center; height: 30px; padding: 0 12px; column-gap: 12px; border-bottom: 1px solid var(--k-line); flex-shrink: 0 }
157div.k-tr:hover { background: var(--k-hover) }
158div.k-tr.sel { background: var(--k-sel) }
159div.k-tr.k-th { color: var(--k-muted); font-size: 11px; font-weight: 600; background: var(--k-sunken) }
160div.k-td.num { text-align: right }
161div.k-menu { position: fixed; z-index: 120; padding: 4px; border-radius: 10px; background: var(--k-panel); border: 1px solid var(--k-line);
162             box-shadow: 0 8px 24px var(--k-shadow); display: flex; flex-direction: column }
163div.k-menu-title { padding: 6px 10px 4px; color: var(--k-muted); font-size: 11px; font-weight: 600 }
164div.k-mi { display: flex; align-items: center; gap: 8px; padding: 7px 10px; border-radius: 6px; flex-shrink: 0 }
165div.k-mi:hover { background: var(--k-hover) }
166div.k-mi.danger { color: var(--k-error) }
167div.k-mi.dis { color: var(--k-dis) }
168div.k-mi > span.k-mi-icon { width: 14px; height: 14px; color: var(--k-muted) }
169div.k-mi > div.k-mi-label { flex-grow: 1 }
170div.k-sep { height: 1px; margin: 4px 6px; background: var(--k-line); flex-shrink: 0 }
171span.k-kbd { padding: 1px 6px; border-radius: 5px; border: 1px solid var(--k-line); background: var(--k-sunken); color: var(--k-muted); font-size: 11px; font-family: monospace }
172span.k-badge { padding: 1px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; background: var(--k-sel); color: var(--k-accent) }
173span.k-badge.ok { background: rgba(34,197,94,0.15); color: var(--k-ok) }
174span.k-badge.warn { background: rgba(245,158,11,0.15); color: var(--k-warn) }
175span.k-badge.error { background: rgba(239,68,68,0.15); color: var(--k-error) }
176span.k-badge.muted { background: var(--k-hover); color: var(--k-muted) }
177div.k-scrim { position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 140; background: var(--k-scrim) }
178div.k-dialog { position: fixed; z-index: 150; border-radius: 14px; background: var(--k-panel); border: 1px solid var(--k-line);
179               box-shadow: 0 16px 48px var(--k-shadow); display: flex; flex-direction: column }
180div.k-dialog-head { display: flex; align-items: center; padding: 14px 16px 6px; font-size: 15px; font-weight: 600 }
181div.k-dialog-head > div.k-dialog-title { flex-grow: 1 }
182div.k-dialog-body { padding: 6px 16px 12px; flex-grow: 1; white-space: normal; color: var(--k-body); display: flex; flex-direction: column; gap: 10px }
183div.k-dialog-foot { display: flex; justify-content: flex-end; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--k-line) }
184div.k-tip { position: fixed; z-index: 160; padding: 5px 9px; border-radius: 6px; background: var(--k-fg); color: var(--k-bg); font-size: 12px }
185div.k-toasts { position: fixed; right: 16px; bottom: 16px; z-index: 170; width: 300px; display: flex; flex-direction: column; gap: 8px }
186div.k-toast { display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 10px; background: var(--k-panel); border: 1px solid var(--k-line);
187              border-left: 3px solid var(--k-info); box-shadow: 0 8px 24px var(--k-shadow) }
188div.k-toast.ok { border-left: 3px solid var(--k-ok) }
189div.k-toast.warn { border-left: 3px solid var(--k-warn) }
190div.k-toast.error { border-left: 3px solid var(--k-error) }
191div.k-toast > div.k-toast-text { flex-grow: 1; white-space: normal }
192div.k-seg { display: flex; padding: 3px; gap: 2px; border-radius: 9px; background: var(--k-sunken); border: 1px solid var(--k-line) }
193button.k-seg-btn { flex-grow: 1; padding: 5px 10px; border-radius: 6px; color: var(--k-muted); text-align: center; font-weight: 500 }
194button.k-seg-btn:hover { color: var(--k-fg) }
195button.k-seg-btn.on { background: var(--k-accent); color: var(--k-on-accent) }
196div.k-stat { display: flex; flex-direction: column; gap: 4px; padding: 12px 14px; border-radius: 12px; background: var(--k-panel); border: 1px solid var(--k-line) }
197div.k-stat > div.k-stat-label { color: var(--k-muted); font-size: 11px; font-weight: 600 }
198div.k-stat > div.k-stat-value { font-size: 24px; font-weight: 700 }
199div.k-stat > div.k-stat-note { color: var(--k-muted); font-size: 11px }
200div.k-progress { height: 6px; border-radius: 3px; background: var(--k-line); overflow: hidden }
201div.k-progress > div.k-bar { height: 6px; border-radius: 3px; background: var(--k-accent) }
202div.k-field { display: flex; flex-direction: column; gap: 6px }
203div.k-field > div.k-field-label { color: var(--k-muted); font-size: 11px; font-weight: 600 }
204"#;
205
206/// The toolbar's look, opt-in (not in [`KIT_CSS`], so apps without a toolbar do not
207/// carry it): append it with [`sheet_with`] (`sheet_with(TOOLBAR_CSS)`, or after
208/// the app's own rules to let them win).
209pub const TOOLBAR_CSS: &str = r#"
210div.k-toolbar { display: flex; align-items: center; gap: 4px; padding: 4px; background: var(--k-panel) }
211div.k-toolbar.vert { flex-direction: column }
212button.k-tool { display: flex; align-items: center; justify-content: center; gap: 6px; min-width: 32px; height: 32px; padding: 0 6px;
213                border-radius: 6px; color: var(--k-muted); flex-shrink: 0 }
214button.k-tool:hover { background: var(--k-hover); color: var(--k-fg) }
215button.k-tool.on { background: var(--k-sel); color: var(--k-accent) }
216button.k-tool.dis { color: var(--k-dis) }
217span.k-tool-icon { width: 20px; height: 20px }
218div.k-tool-split { display: flex; align-items: center; flex-shrink: 0 }
219div.k-tool-split > button.k-tool { border-radius: 6px 0px 0px 6px }
220button.k-tool-chev { display: flex; align-items: center; justify-content: center; width: 14px; height: 32px; padding: 0px;
221                     border-radius: 0px 6px 6px 0px; color: var(--k-muted) }
222button.k-tool-chev:hover { background: var(--k-hover); color: var(--k-fg) }
223button.k-tool-chev > span { width: 10px; height: 10px }
224div.k-tool-sep { width: 1px; height: 20px; background: var(--k-line); flex-shrink: 0 }
225div.k-toolbar.vert > div.k-tool-sep { width: 20px; height: 1px }
226div.k-tool-fill { flex-grow: 1 }
227"#;
228
229/// Touch-sized targets, applied under `@media (pointer: coarse)` (a finger: iOS /
230/// Android builds, or the last input was touch). Apple asks for 44 pt, Material
231/// for 48 dp: controls grow to 44 px, list rows to 48 px, text to 15 px. The look
232/// stays the same; only sizes change. [`sheet`] and [`sheet_with`] include it
233/// after [`KIT_CSS`]; the app's own rules still win.
234pub const KIT_TOUCH_CSS: &str = r#"
235@media (pointer: coarse) {
236div.k-root { font-size: 15px }
237button.k-btn { padding: 12px 18px; min-height: 44px; border-radius: 10px }
238button.k-switch { width: 44px; height: 26px; padding: 3px; border-radius: 13px }
239span.k-box { width: 22px; height: 22px; border-radius: 6px }
240div.k-check { gap: 12px; min-height: 44px }
241div.k-radio { min-height: 44px }
242div.k-input { height: 44px; padding: 0 12px; border-radius: 10px }
243select.k-select { height: 44px; padding: 0 34px 0 14px; border-radius: 10px }
244div.k-opt { padding: 12px 12px; border-radius: 8px }
245div.k-mi { padding: 12px 12px; border-radius: 8px }
246div.k-search { height: 40px }
247div.k-li { height: 48px; padding: 0 14px; border-radius: 8px }
248div.k-tr { height: 44px }
249button.k-act { width: 40px; height: 40px; padding: 10px; border-radius: 8px }
250button.k-tab { padding: 10px 14px }
251button.k-seg-btn { padding: 9px 12px }
252button.k-chip { padding: 8px 14px }
253div.k-card-head { padding: 12px 14px }
254div.k-dialog-foot { padding: 12px 16px 16px }
255}
256"#;
257
258/// Inline `:root` overrides for the light look: put them on the page root
259/// (`El::new("div.k-root").css(LIGHT_VARS)`); custom properties cascade to the subtree.
260pub const LIGHT_VARS: &str = "--k-bg: #f6f7f9; --k-panel: #ffffff; --k-fg: #1d1f24; --k-muted: #6b6f78; --k-line: #dfe1e6; \
261--k-them: #eceef2; --k-btn: #eceef2; --k-btn-hover: #e2e5ea; --k-track: #c9ccd3; --k-track-hover: #b7bbc4; --k-accent-hover: #2563eb; \
262--k-field: #ffffff; --k-sunken: #f0f1f4; --k-hover: #eef0f4; --k-hi: #e6e9ef; --k-sel: rgba(59,130,246,0.14); --k-dis: #b0b4bc; \
263--k-body: #3a3d45; --k-scrim: rgba(15,17,21,0.35); --k-shadow: rgba(15,17,21,0.18)";
264
265/// The page-root inline variables for the dark (`""`, the sheet's own `:root`) or light look.
266pub fn theme_vars(dark: bool) -> &'static str {
267    if dark {
268        ""
269    } else {
270        LIGHT_VARS
271    }
272}
273
274/// [`KIT_CSS`] (plus [`KIT_TOUCH_CSS`]) parsed against the current media environment.
275pub fn sheet() -> Sheet {
276    Sheet::parse(&[KIT_CSS, KIT_TOUCH_CSS].concat()).expect("KIT_CSS parses")
277}
278
279/// [`KIT_CSS`] followed by the app's own rules (later rules of equal specificity win).
280pub fn sheet_with(app_css: &str) -> Result<Sheet, StyleError> {
281    Sheet::parse(&[KIT_CSS, KIT_TOUCH_CSS, app_css].concat())
282}
283
284/// A 24×24 stroke icon (`currentColor`) from its path markup.
285pub fn icon(body: &str) -> String {
286    format!(r#"<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">{body}</svg>"#)
287}
288
289/// Icon bodies used by the catalog.
290pub mod icons {
291    pub const CLOSE: &str = r#"<path d="M6 6l12 12M18 6L6 18"/>"#;
292    pub const RIGHT: &str = r#"<path d="M9 6l6 6-6 6"/>"#;
293    pub const DOWN: &str = r#"<path d="M6 9l6 6 6-6"/>"#;
294    pub const UP: &str = r#"<path d="M6 15l6-6 6 6"/>"#;
295    pub const REPLY: &str = r#"<path d="M9 14L4 9l5-5"/><path d="M4 9h10a6 6 0 0 1 6 6v3"/>"#;
296    pub const COPY: &str = r#"<rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h8"/>"#;
297    pub const SMILE: &str = r#"<circle cx="12" cy="12" r="9"/><path d="M8.5 14.5a4.5 4.5 0 0 0 7 0M9 9.5h.01M15 9.5h.01"/>"#;
298    pub const MORE: &str = r#"<path d="M5 12h.01M12 12h.01M19 12h.01"/>"#;
299    pub const CHECK: &str = r#"<path d="M5 12.5l4.5 4.5L19 7.5"/>"#;
300    pub const SEARCH: &str = r#"<circle cx="11" cy="11" r="6.5"/><path d="M16 16l4 4"/>"#;
301    pub const LEFT: &str = r#"<path d="M15 6l-6 6 6 6"/>"#;
302    pub const PLUS: &str = r#"<path d="M12 5v14M5 12h14"/>"#;
303    pub const SETTINGS: &str = r#"<circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M4.9 19.1L7 17M17 7l2.1-2.1"/>"#;
304    pub const MENU: &str = r#"<path d="M4 6h16M4 12h16M4 18h16"/>"#;
305    pub const SUN: &str = r#"<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.4 1.4M17.6 17.6L19 19M5 19l1.4-1.4M17.6 6.4L19 5"/>"#;
306    pub const MOON: &str = r#"<path d="M20 14.5A8 8 0 1 1 9.5 4a6.5 6.5 0 0 0 10.5 10.5z"/>"#;
307    pub const SAVE: &str = r#"<path d="M5 3h11l3 3v15H5z"/><path d="M8 3v5h7V3M8 21v-7h8v7"/>"#;
308    pub const UNDO: &str = r#"<path d="M4 9h11a5 5 0 0 1 0 10H8"/><path d="M8 5L4 9l4 4"/>"#;
309    pub const EXPAND: &str = r#"<path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/>"#;
310    pub const PLAY: &str = r#"<path d="M7 4l13 8-13 8z"/>"#;
311    pub const GRID: &str = r#"<rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/>"#;
312    pub const IMAGE: &str = r#"<rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="9" cy="10" r="2"/><path d="M21 16l-5-5-9 9"/>"#;
313    pub const WINDOW: &str = r#"<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 9h18"/>"#;
314    pub const DOWNLOAD: &str = r#"<path d="M12 3v12M7 10l5 5 5-5M4 20h16"/>"#;
315    pub const CHART: &str = r#"<path d="M4 20V4M4 20h16M8 16v-5M12 16V8M16 16v-8"/>"#;
316    pub const LIST: &str = r#"<path d="M9 6h11M9 12h11M9 18h11M4 6h.01M4 12h.01M4 18h.01"/>"#;
317    pub const TERMINAL: &str = r#"<path d="M4 7l5 5-5 5M12 19h8"/>"#;
318    pub const TRASH: &str = r#"<path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"/>"#;
319    pub const EDIT: &str = r#"<path d="M4 20h4L19 9l-4-4L4 16z"/>"#;
320    pub const PIN: &str = r#"<path d="M9 4h6l-1 6 4 4H6l4-4zM12 14v6"/>"#;
321    pub const BOX: &str = r#"<path d="M21 8l-9-5-9 5 9 5 9-5zM3 8v8l9 5 9-5V8M12 13v8"/>"#;
322    pub const BOLT: &str = r#"<path d="M13 2L4 14h7l-1 8 9-12h-7z"/>"#;
323}
324
325/// A push button.
326pub fn button(id: &str, label: &str) -> El {
327    El::new("button.k-btn").id(id).tab().text(label)
328}
329
330/// A switch (`role="switch"`): the track is the button's box, the knob its control.
331pub fn switch(id: &str, on: bool, name: &str) -> El {
332    El::new("button.k-switch").id(id).tab().name(name).control(Control::switch(on))
333}
334
335/// A switch whose knob is at `pos` (0 … 1) while it slides.
336pub fn switch_at(id: &str, on: bool, pos: f64, name: &str) -> El {
337    El::new("button.k-switch").id(id).tab().name(name).control(Control::Switch { on, pos })
338}
339
340/// A checkbox with its label; the row is the hit.
341pub fn checkbox(id: &str, on: bool, label: &str) -> El {
342    El::new("div.k-check").id(id).tab().name(label).child(El::new("span.k-box").control(Control::checkbox(on))).child(El::new("span").text(label))
343}
344
345/// A radio group: one choice of many, compact 32 px rows 4 px apart (the mlc
346/// language-picker metrics: 15.5 px ring with a 1.5 px border, an 8 px dot when
347/// on, a 13 px label at x=30). Each row is a hit `{id}:{key}`; the selected row
348/// carries `.sel` (accent ring + dot). The hover highlight is
349/// `div.k-radio:hover` — set `--k-hover: transparent` to turn it off.
350pub fn radio_group(id: &str, opts: &[(&str, &str)], selected: usize) -> El {
351    El::new("div.k-radio-group").id(id).children(opts.iter().enumerate().map(|(i, (key, label))| {
352        El::new(if i == selected { "div.k-radio.sel" } else { "div.k-radio" })
353            .id(format!("{id}:{key}"))
354            .tab()
355            .name(*label)
356            .child(El::new("span.k-radio-ring").child_if(i == selected, || El::new("span.k-radio-dot")))
357            .child(El::new("span.k-radio-label").text(*label))
358    }))
359}
360
361/// The key of a radio row hit (`{id}:{key}`), if `hit` is one of this group's rows.
362pub fn picked_radio<'a>(id: &str, hit: &'a str) -> Option<&'a str> {
363    hit.strip_prefix(&format!("{id}:")).filter(|k| !k.is_empty())
364}
365
366/// A busy spinner at time `t` seconds.
367pub fn spinner(t: f64) -> El {
368    El::new("span.k-spinner").name("Loading").control(Control::spinner(t))
369}
370
371/// A single-line text input showing `edit`.
372pub fn input(id: &str, edit: Edit) -> El {
373    El::new("div.k-input").id(id).tab().control(Control::input(edit))
374}
375
376/// The rules of a number field ([`number_input`]): range, step, shown decimals. The
377/// value stays text while it is typed (`-`, `1.` and an empty field are fine); the app
378/// reads it with [`NumberSpec::parse`], the steppers and the arrow keys go through
379/// [`NumberSpec::stepped`], and leaving the field tidies it with
380/// [`NumberSpec::normalized`] (uzor-framework's `kit::dom` does all three).
381#[derive(Clone, Copy, Debug, PartialEq)]
382#[non_exhaustive]
383pub struct NumberSpec {
384    /// Smallest value (inclusive).
385    pub min: Option<f64>,
386    /// Largest value (inclusive).
387    pub max: Option<f64>,
388    /// One stepper / arrow-key step.
389    pub step: f64,
390    /// Decimals shown after a step or on leaving the field (`None`: as many as needed).
391    pub decimals: Option<u32>,
392}
393
394impl Default for NumberSpec {
395    fn default() -> Self {
396        NumberSpec { min: None, max: None, step: 1.0, decimals: None }
397    }
398}
399
400impl NumberSpec {
401    /// Any number, step 1.
402    pub fn new() -> Self {
403        Self::default()
404    }
405    /// Whole numbers only (no decimal point is typed), step 1.
406    pub fn integer() -> Self {
407        NumberSpec { decimals: Some(0), ..Self::default() }
408    }
409    /// The range `min..=max`.
410    pub fn range(mut self, min: f64, max: f64) -> Self {
411        self.min = Some(min.min(max));
412        self.max = Some(max.max(min));
413        self
414    }
415    /// The smallest value.
416    pub fn min(mut self, v: f64) -> Self {
417        self.min = Some(v);
418        self
419    }
420    /// The largest value.
421    pub fn max(mut self, v: f64) -> Self {
422        self.max = Some(v);
423        self
424    }
425    /// One step.
426    pub fn step(mut self, v: f64) -> Self {
427        if v.is_finite() && v > 0.0 {
428            self.step = v;
429        }
430        self
431    }
432    /// Decimals shown.
433    pub fn decimals(mut self, n: u32) -> Self {
434        self.decimals = Some(n);
435        self
436    }
437
438    /// Whether `c` may be typed: digits, a sign, a decimal point (`.` or `,`) unless whole
439    /// numbers only, and an exponent.
440    pub fn accepts(&self, c: char) -> bool {
441        c.is_ascii_digit() || matches!(c, '-' | '+' | 'e' | 'E') || (self.decimals != Some(0) && matches!(c, '.' | ','))
442    }
443
444    /// `text` with what may not be typed taken out (a paste of `"1 234,5 $"` → `"1234,5"`).
445    pub fn sanitize(&self, text: &str) -> String {
446        text.chars().filter(|c| self.accepts(*c)).collect()
447    }
448
449    /// The value `text` holds, inside the range; `None` while it is not a number yet.
450    /// A decimal comma reads as a point.
451    pub fn parse(&self, text: &str) -> Option<f64> {
452        let t: String = self.sanitize(text).replace(',', ".");
453        let v: f64 = t.parse().ok().filter(|v: &f64| v.is_finite())?;
454        Some(self.clamp(v))
455    }
456
457    /// `v` inside the range.
458    pub fn clamp(&self, v: f64) -> f64 {
459        let v = self.min.map_or(v, |m| v.max(m));
460        self.max.map_or(v, |m| v.min(m))
461    }
462
463    /// `v` as text: with [`NumberSpec::decimals`] places, else as short as it reads.
464    pub fn format(&self, v: f64) -> String {
465        match self.decimals {
466            Some(n) => format!("{v:.*}", n as usize),
467            None => {
468                // Up to the step's decimals and no float noise (0.1 + 0.2).
469                let places = decimals_of(self.step).max(decimals_of(v)).min(10);
470                let s = format!("{v:.places$}");
471                if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s }
472            }
473        }
474    }
475
476    /// The text after `n` steps from `text` (an unreadable text steps from the range's
477    /// start, or 0), snapped to the step grid and clamped.
478    pub fn stepped(&self, text: &str, n: i32) -> String {
479        let from = self.parse(text).unwrap_or_else(|| self.min.unwrap_or(0.0).max(self.max.map_or(f64::MIN, |m| m.min(0.0))));
480        let base = self.min.unwrap_or(0.0);
481        let k = ((from - base) / self.step).round();
482        let at_grid = (base + k * self.step - from).abs() < self.step * 1e-9;
483        let k = if at_grid { k + n as f64 } else if n > 0 { ((from - base) / self.step).floor() + n as f64 } else { ((from - base) / self.step).ceil() + n as f64 };
484        self.format(self.clamp(base + k * self.step))
485    }
486
487    /// The text tidied on leaving the field: the clamped value formatted, or the text
488    /// unchanged when it is not a number (empty stays empty).
489    pub fn normalized(&self, text: &str) -> String {
490        match self.parse(text) {
491            Some(v) => self.format(v),
492            None => text.to_string(),
493        }
494    }
495}
496
497fn decimals_of(v: f64) -> usize {
498    let s = format!("{}", v.abs());
499    s.split_once('.').map_or(0, |(_, f)| f.len())
500}
501
502/// A number field: a text input (`id`) with up / down steppers (`{id}:inc`, `{id}:dec`).
503/// The rules are a [`NumberSpec`]; in uzor-framework register them with
504/// `kit::dom(..).number(id, spec)`, which filters typing, steps on the buttons, the
505/// arrow keys and the wheel over the focused field, and tidies the text on blur.
506pub fn number_input(id: &str, edit: Edit, name: &str) -> El {
507    let step = |dir: &str, label: &str, body: &str| {
508        El::new("button.k-step").id(format!("{id}:{dir}")).name(format!("{name} {label}")).child(El::new("span").svg(icon(body)))
509    };
510    El::new("div.k-num")
511        .child(input(id, edit).name(name))
512        .child(El::new("div.k-steps").child(step("inc", "+", icons::UP)).child(step("dec", "−", icons::DOWN)))
513}
514
515/// One option of a select.
516#[derive(Clone, Debug, Default, PartialEq)]
517pub struct SelectOpt {
518    pub label: String,
519    /// A muted second line.
520    pub sub: Option<String>,
521    /// Shown greyed, not pickable (no hit id).
522    pub disabled: bool,
523}
524
525impl SelectOpt {
526    pub fn new(label: impl Into<String>) -> Self {
527        SelectOpt { label: label.into(), ..Default::default() }
528    }
529    pub fn sub(mut self, s: impl Into<String>) -> Self {
530        self.sub = Some(s.into());
531        self
532    }
533    pub fn disabled(mut self, on: bool) -> Self {
534        self.disabled = on;
535        self
536    }
537}
538
539/// The closed select: the chosen label and a chevron.
540pub fn select_trigger(id: &str, label: &str, open: bool, name: &str) -> El {
541    El::new(if open { "select.k-select.open" } else { "select.k-select" }).id(id).tab().name(name).text(label)
542}
543
544/// Where a popover `h` tall goes for a trigger at `anchor` in `viewport`: below it, or
545/// above when it does not fit below and fits better above; at least the trigger's width.
546pub fn popover_at(anchor: Rect, viewport: Rect, w: f64, h: f64) -> Rect {
547    let w = w.max(anchor.width);
548    let below = viewport.y + viewport.height - (anchor.y + anchor.height + 4.0);
549    let above = anchor.y - 4.0 - viewport.y;
550    let y = if h > below && above > below { (anchor.y - 4.0 - h).max(viewport.y) } else { anchor.y + anchor.height + 4.0 };
551    let x = anchor.x.min(viewport.x + viewport.width - w).max(viewport.x);
552    Rect::new(x, y, w, h.min(below.max(above)))
553}
554
555/// The open select's list as a `position: fixed` popover at `at` (see [`popover_at`]):
556/// it paints above the page and does not scroll with it. Enabled rows are hits
557/// `{id}:opt:{i}`; `chosen` is marked `.sel` (with a tick).
558pub fn select_popover(id: &str, opts: &[SelectOpt], chosen: Option<usize>, at: Rect) -> El {
559    select_list(id, opts, chosen, &ListView::all(), at)
560}
561
562/// What part of a long option list a popover shows. The select's own model (keyboard,
563/// wheel, type-to-filter) keeps it; the popover only draws it.
564#[derive(Clone, Copy, Debug, PartialEq)]
565pub struct ListView<'a> {
566    /// The keyboard-highlighted row (`.hi`).
567    pub hi: Option<usize>,
568    /// First shown row.
569    pub top: usize,
570    /// How many rows show (a scroll thumb appears when there are more).
571    pub rows: usize,
572    /// A search line with this query (`Some("")`: its placeholder).
573    pub query: Option<&'a str>,
574    /// Height of a row (sets the thumb's travel; rows are styled by CSS).
575    pub row_h: f64,
576}
577
578impl ListView<'_> {
579    /// Every row, no search line.
580    pub fn all() -> Self {
581        ListView { hi: None, top: 0, rows: usize::MAX, query: None, row_h: 0.0 }
582    }
583}
584
585/// [`select_popover`] for a windowed, searchable list: rows `view.top ..` of `opts` (the
586/// already filtered options; hits keep their index in `opts`), the highlighted row, a
587/// search line and a scroll thumb. "No matches" when `opts` is empty. The popover is
588/// `position: fixed` at `at`, so `at` is in the coordinates of the viewport given to
589/// [`lay_out_in`](crate::ui::dom::lay_out_in) (the window, origin 0,0). Its rows' `--k-accent`
590/// (the chosen row's tick) can be set inline on the returned element.
591pub fn select_list(id: &str, opts: &[SelectOpt], chosen: Option<usize>, view: &ListView<'_>, at: Rect) -> El {
592    let mut pop = El::new("div.k-pop").id(format!("{id}:pop")).css(format!("top: {}px; left: {}px; width: {}px", at.y, at.x, at.width));
593    if let Some(q) = view.query {
594        let line = El::new("div.k-search").child(El::new("span.k-mag").svg(icon(icons::SEARCH)));
595        pop = pop.child(if q.is_empty() { line.child(El::new("div.k-ph").text("Type to search")) } else { line.child(El::new("div.k-q").text(q)) });
596    }
597    if opts.is_empty() {
598        pop = pop.child(El::new("div.k-empty").text("No matches"));
599    }
600    let end = view.top.saturating_add(view.rows).min(opts.len());
601    for (i, o) in opts.iter().enumerate().take(end).skip(view.top) {
602        let mut spec = String::from("div.k-opt");
603        if chosen == Some(i) {
604            spec.push_str(".sel");
605        }
606        if view.hi == Some(i) {
607            spec.push_str(".hi");
608        }
609        if o.disabled {
610            spec.push_str(".dis");
611        }
612        let mut label = El::new("div.k-optl").child(El::new("div.k-label").text(&o.label));
613        if let Some(s) = &o.sub {
614            label = label.child(El::new("div.k-sub").text(s));
615        }
616        let tick = El::new("span.k-tick");
617        let tick = if chosen == Some(i) { tick.svg(icon(icons::CHECK)) } else { tick };
618        let mut row = El::new(spec).name(&o.label).child(tick).child(label);
619        if !o.disabled {
620            row = row.id(format!("{id}:opt:{i}")).tab();
621        }
622        pop = pop.child(row);
623    }
624    let n = opts.len();
625    if n > view.rows && view.row_h > 0.0 {
626        let track = view.row_h * view.rows as f64;
627        let th = (track * view.rows as f64 / n as f64).max(18.0);
628        let ty = (track - th) * view.top as f64 / (n - view.rows) as f64 + if view.query.is_some() { 34.0 } else { 0.0 } + 4.0;
629        pop = pop.child(El::new("div.k-thumb").css(format!("top: {ty}px; height: {th}px")));
630    }
631    pop
632}
633
634/// The option index a select popover hit id names (`{id}:opt:{i}`).
635pub fn picked_opt(id: &str, hit: &str) -> Option<usize> {
636    hit.strip_prefix(id)?.strip_prefix(":opt:")?.parse().ok()
637}
638
639/// A chat message bubble: optional sender line, markdown body ([`inline_md`]), time.
640pub fn bubble(id: &str, mine: bool, who: Option<&str>, body: &str, time: Option<&str>) -> El {
641    let mut b = El::new(if mine { "div.k-msg.me" } else { "div.k-msg.them" }).id(id);
642    if let Some(w) = who {
643        b = b.child(El::new("div.k-who").text(w));
644    }
645    b = b.child(El::new("div.k-body").runs(inline_md(body)));
646    if let Some(t) = time {
647        b = b.child(El::new("div.k-time").text(t));
648    }
649    b
650}
651
652/// A hover action row (reply, react, copy, more…): `(key, icon body, name)` per button,
653/// hits `{id}:{key}`.
654pub fn action_row(id: &str, actions: &[(&str, &str, &str)]) -> El {
655    El::new("div.k-actions").id(id).children(actions.iter().map(|(k, ic, n)| El::new("button.k-act").id(format!("{id}:{k}")).tab().name(*n).svg(icon(ic))))
656}
657
658/// A collapsible card: the head (hit `id`) toggles `open`; the body shows when open.
659pub fn card(id: &str, title: &str, open: bool, body: El) -> El {
660    let head = El::new("div.k-card-head")
661        .id(id)
662        .tab()
663        .name(title)
664        .child(El::new("span.k-chev").svg(icon(if open { icons::DOWN } else { icons::RIGHT })))
665        .child(El::new("span").text(title));
666    El::new(if open { "div.k-card.open" } else { "div.k-card" }).child(head).child_if(open, || El::new("div.k-card-body").child(body))
667}
668
669/// A filter chip.
670pub fn chip(id: &str, label: &str, on: bool) -> El {
671    El::new(if on { "button.k-chip.on" } else { "button.k-chip" }).id(id).tab().text(label)
672}
673
674/// A banner (`kind`: `info`, `warn`, `error`) with an optional action button
675/// (`{id}:act`) and a close button (`{id}:close`).
676pub fn banner(id: &str, kind: &str, text: &str, action: Option<&str>, closable: bool) -> El {
677    let mut b = El::new(format!("div.k-banner.{kind}")).id(id).name(text).child(El::new("div.k-banner-text").text(text));
678    if let Some(a) = action {
679        b = b.child(El::new("button.k-btn.ghost").id(format!("{id}:act")).tab().text(a));
680    }
681    if closable {
682        b = b.child(El::new("button.k-act").id(format!("{id}:close")).tab().name("Close").svg(icon(icons::CLOSE)));
683    }
684    b
685}
686
687/// A side panel docked right (`position: fixed`: it stays while the page scrolls), with a
688/// title row and a close button (`{id}:close`).
689pub fn side_panel(id: &str, title: &str, body: impl IntoIterator<Item = El>) -> El {
690    El::new("div.k-side")
691        .id(id)
692        .child(
693            El::new("div.k-side-head")
694                .child(El::new("div.k-side-title").text(title))
695                .child(El::new("button.k-act").id(format!("{id}:close")).tab().name("Close").svg(icon(icons::CLOSE))),
696        )
697        .child(El::new("div.k-side-body").children(body))
698}
699
700/// An embed slot box (`div.k-slot`) named `key`, `w` × `h`: a kit widget or canvas goes
701/// in its content box (see [`Dom::slots`]).
702pub fn slot(key: &str, w: f64, h: f64) -> El {
703    El::new("div.k-slot").slot(key).css(format!("width: {w}px; height: {h}px"))
704}
705
706/// A tab strip: one `button.k-tab` per label (`.on` for `active`), hits `{id}:tab:{i}`.
707pub fn tabs(id: &str, labels: &[&str], active: usize) -> El {
708    El::new("div.k-tabs").id(id).children(labels.iter().enumerate().map(|(i, l)| {
709        El::new(if i == active { "button.k-tab.on" } else { "button.k-tab" }).id(format!("{id}:tab:{i}")).tab().text(*l)
710    }))
711}
712
713/// A segmented control (one choice of a few, e.g. Dark / Light): hits `{id}:{i}`.
714pub fn segmented(id: &str, labels: &[&str], active: usize) -> El {
715    El::new("div.k-seg").id(id).children(labels.iter().enumerate().map(|(i, l)| {
716        El::new(if i == active { "button.k-seg-btn.on" } else { "button.k-seg-btn" }).id(format!("{id}:{i}")).tab().text(*l)
717    }))
718}
719
720/// The tab, segment, row or item index a hit id names (`{id}:{kind}:{i}`, or `{id}:{i}` for an empty `kind`).
721pub fn picked(id: &str, kind: &str, hit: &str) -> Option<usize> {
722    let rest = hit.strip_prefix(id)?.strip_prefix(':')?;
723    let rest = if kind.is_empty() { rest } else { rest.strip_prefix(kind)?.strip_prefix(':')? };
724    rest.parse().ok()
725}
726
727/// A list of rows (`div.k-li`, `.sel` for `selected`), each a main label and an optional
728/// muted side text; hits `{id}:row:{i}`.
729pub fn list(id: &str, rows: &[(&str, Option<&str>)], selected: Option<usize>) -> El {
730    El::new("div.k-list").id(id).children(rows.iter().enumerate().map(|(i, (main, side))| {
731        El::new(if selected == Some(i) { "div.k-li.sel" } else { "div.k-li" })
732            .id(format!("{id}:row:{i}"))
733            .tab()
734            .name(*main)
735            .child(El::new("div.k-li-main").text(*main))
736            .child_if(side.is_some(), || El::new("div.k-li-side").text(side.unwrap_or_default()))
737    }))
738}
739
740/// A table: a header row and data rows on one CSS grid track list (`columns`, e.g.
741/// `"1fr 80px"`); `num` columns align right. Rows are hits `{id}:row:{i}`, `.sel` for `selected`.
742pub fn table(id: &str, head: &[&str], columns: &str, num: &[usize], rows: &[Vec<String>], selected: Option<usize>) -> El {
743    let grid = format!("grid-template-columns: {columns}");
744    let cell = |c: usize, t: &str| El::new(if num.contains(&c) { "div.k-td.num" } else { "div.k-td" }).text(t);
745    let mut t = El::new("div.k-table").id(id).child(
746        El::new("div.k-tr.k-th").css(grid.clone()).children(head.iter().enumerate().map(|(c, h)| cell(c, h))),
747    );
748    for (i, r) in rows.iter().enumerate() {
749        t = t.child(
750            El::new(if selected == Some(i) { "div.k-tr.sel" } else { "div.k-tr" })
751                .id(format!("{id}:row:{i}"))
752                .tab()
753                .name(r.first().map(String::as_str).unwrap_or_default())
754                .css(grid.clone())
755                .children(r.iter().enumerate().map(|(c, v)| cell(c, v))),
756        );
757    }
758    t
759}
760
761/// One entry of a [`menu`].
762#[derive(Clone, Debug, Default, PartialEq)]
763pub struct MenuItem {
764    pub label: String,
765    /// An icon body ([`icons`]).
766    pub icon: Option<&'static str>,
767    /// A shortcut hint (`Ctrl+K`).
768    pub kbd: Option<String>,
769    /// Red (a destructive action).
770    pub danger: bool,
771    /// Greyed, not pickable (no hit id).
772    pub disabled: bool,
773    /// A divider line instead of an item.
774    pub separator: bool,
775}
776
777impl MenuItem {
778    pub fn new(label: impl Into<String>) -> Self {
779        MenuItem { label: label.into(), ..Default::default() }
780    }
781    pub fn separator() -> Self {
782        MenuItem { separator: true, ..Default::default() }
783    }
784    pub fn icon(mut self, body: &'static str) -> Self {
785        self.icon = Some(body);
786        self
787    }
788    pub fn kbd(mut self, k: impl Into<String>) -> Self {
789        self.kbd = Some(k.into());
790        self
791    }
792    pub fn danger(mut self, on: bool) -> Self {
793        self.danger = on;
794        self
795    }
796    pub fn disabled(mut self, on: bool) -> Self {
797        self.disabled = on;
798        self
799    }
800}
801
802/// A context menu / command list as a `position: fixed` box at `at` (viewport
803/// coordinates; see [`popover_at`]). Enabled items are hits `{id}:item:{i}` (`i` counts
804/// separators too, so it is the index into `items`).
805pub fn menu(id: &str, title: Option<&str>, items: &[MenuItem], at: Rect) -> El {
806    let mut m = El::new("div.k-menu").id(format!("{id}:menu")).css(format!("top: {}px; left: {}px; width: {}px", at.y, at.x, at.width));
807    if let Some(t) = title {
808        m = m.child(El::new("div.k-menu-title").text(t));
809    }
810    m.children(items.iter().enumerate().map(|(i, it)| {
811        if it.separator {
812            return El::new("div.k-sep");
813        }
814        let mut spec = String::from("div.k-mi");
815        if it.danger {
816            spec.push_str(".danger");
817        }
818        if it.disabled {
819            spec.push_str(".dis");
820        }
821        let mut row = El::new(spec).name(&it.label);
822        if let Some(ic) = it.icon {
823            row = row.child(El::new("span.k-mi-icon").svg(icon(ic)));
824        }
825        row = row.child(El::new("div.k-mi-label").text(&it.label));
826        if let Some(k) = &it.kbd {
827            row = row.child(kbd(k));
828        }
829        if !it.disabled {
830            row = row.id(format!("{id}:item:{i}")).tab();
831        }
832        row
833    }))
834}
835
836/// What a toolbar entry is.
837#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
838#[non_exhaustive]
839pub enum ToolKind {
840    /// An icon (and/or label) button: hit `{id}:{key}`.
841    #[default]
842    Button,
843    /// A button with a chevron beside it that opens its flyout: hits `{id}:{key}`
844    /// and `{id}:{key}:menu`.
845    Split,
846    /// A thin rule between groups.
847    Separator,
848    /// Takes the free space: what follows sits at the far end (an end group).
849    Fill,
850}
851
852/// One toolbar entry ([`toolbar`]).
853#[derive(Clone, Debug, Default)]
854#[non_exhaustive]
855pub struct ToolItem {
856    pub kind: ToolKind,
857    /// The hit key (`{id}:{key}`).
858    pub key: String,
859    /// The icon's SVG markup (e.g. [`icon`]`(body)` or an app's own icon set).
860    pub icon: Option<String>,
861    pub label: Option<String>,
862    /// The accessible name (and tooltip text); defaults to the label or the key.
863    pub name: Option<String>,
864    /// Lit: the active tool, or a toggled option.
865    pub on: bool,
866    /// Shown dimmed, no hit.
867    pub disabled: bool,
868}
869
870impl ToolItem {
871    /// An icon button.
872    pub fn button(key: impl Into<String>, icon_svg: impl Into<String>) -> Self {
873        ToolItem { key: key.into(), icon: Some(icon_svg.into()), ..Self::default() }
874    }
875    /// A button with a flyout chevron.
876    pub fn split(key: impl Into<String>, icon_svg: impl Into<String>) -> Self {
877        ToolItem { kind: ToolKind::Split, ..Self::button(key, icon_svg) }
878    }
879    /// A separator.
880    pub fn separator() -> Self {
881        ToolItem { kind: ToolKind::Separator, ..Self::default() }
882    }
883    /// The free space before an end group.
884    pub fn fill() -> Self {
885        ToolItem { kind: ToolKind::Fill, ..Self::default() }
886    }
887    pub fn label(mut self, l: impl Into<String>) -> Self {
888        self.label = Some(l.into());
889        self
890    }
891    pub fn name(mut self, n: impl Into<String>) -> Self {
892        self.name = Some(n.into());
893        self
894    }
895    pub fn on(mut self, on: bool) -> Self {
896        self.on = on;
897        self
898    }
899    pub fn disabled(mut self, on: bool) -> Self {
900        self.disabled = on;
901        self
902    }
903}
904
905/// A toolbar (style it with [`TOOLBAR_CSS`]): a row, or a column when `vertical`, of
906/// [`ToolItem`]s. Hits `{id}:{key}` per enabled button, `{id}:{key}:menu` per split
907/// chevron (open its flyout with [`menu`] at [`flyout_at`]); [`picked_tool`] reads them.
908pub fn toolbar(id: &str, items: &[ToolItem], vertical: bool) -> El {
909    let bar = El::new(if vertical { "div.k-toolbar.vert" } else { "div.k-toolbar" }).id(format!("{id}:bar"));
910    bar.children(items.iter().map(|it| match it.kind {
911        ToolKind::Separator => El::new("div.k-tool-sep"),
912        ToolKind::Fill => El::new("div.k-tool-fill"),
913        ToolKind::Button | ToolKind::Split => {
914            let mut spec = String::from("button.k-tool");
915            if it.on {
916                spec.push_str(".on");
917            }
918            if it.disabled {
919                spec.push_str(".dis");
920            }
921            let name = it.name.as_deref().or(it.label.as_deref()).unwrap_or(&it.key);
922            let mut b = El::new(spec).name(name);
923            if !it.disabled {
924                b = b.id(format!("{id}:{}", it.key)).tab();
925            }
926            if let Some(svg) = &it.icon {
927                b = b.child(El::new("span.k-tool-icon").svg(svg.clone()));
928            }
929            if let Some(l) = &it.label {
930                b = b.child(El::new("span").text(l.clone()));
931            }
932            if it.kind == ToolKind::Split {
933                let mut chev = El::new("button.k-tool-chev").name(format!("{name}: more"));
934                if !it.disabled {
935                    chev = chev.id(format!("{id}:{}:menu", it.key)).tab();
936                }
937                let chev = chev.child(El::new("span").svg(icon(if vertical { icons::RIGHT } else { icons::DOWN })));
938                El::new("div.k-tool-split").child(b).child(chev)
939            } else {
940                b
941            }
942        }
943    }))
944}
945
946/// The tool a toolbar hit names: `(key, false)` for the button, `(key, true)` for its
947/// flyout chevron.
948pub fn picked_tool<'a>(id: &str, hit: &'a str) -> Option<(&'a str, bool)> {
949    let rest = hit.strip_prefix(id)?.strip_prefix(':')?;
950    if rest == "bar" {
951        return None;
952    }
953    Some(match rest.strip_suffix(":menu") {
954        Some(key) => (key, true),
955        None => (rest, false),
956    })
957}
958
959/// Where a tool's flyout goes: beside the tool `anchor` (to its right on a vertical
960/// toolbar, below it on a horizontal one, 4 px off), `w` × `h`, kept inside `viewport`.
961pub fn flyout_at(anchor: Rect, viewport: Rect, w: f64, h: f64, vertical: bool) -> Rect {
962    let (mut x, mut y) = if vertical { (anchor.x + anchor.width + 4.0, anchor.y) } else { (anchor.x, anchor.y + anchor.height + 4.0) };
963    if x + w > viewport.x + viewport.width {
964        x = if vertical { anchor.x - 4.0 - w } else { viewport.x + viewport.width - w };
965    }
966    if y + h > viewport.y + viewport.height {
967        y = if vertical { viewport.y + viewport.height - h } else { anchor.y - 4.0 - h };
968    }
969    Rect::new(x.max(viewport.x), y.max(viewport.y), w, h)
970}
971
972/// A keyboard shortcut hint (`span.k-kbd`).
973pub fn kbd(text: &str) -> El {
974    El::new("span.k-kbd").text(text)
975}
976
977/// A small status pill (`kind`: `""`, `ok`, `warn`, `error`, `muted`).
978pub fn badge(text: &str, kind: &str) -> El {
979    El::new(if kind.is_empty() { "span.k-badge".to_string() } else { format!("span.k-badge.{kind}") }).text(text)
980}
981
982/// A `w × h` box centred in `viewport` (where a [`dialog`] goes).
983pub fn centered(viewport: Rect, w: f64, h: f64) -> Rect {
984    let (w, h) = (w.min(viewport.width), h.min(viewport.height));
985    Rect::new(viewport.x + (viewport.width - w) / 2.0, viewport.y + (viewport.height - h) / 2.0, w, h)
986}
987
988/// A modal dialog at `at` over a full-viewport scrim (`{id}:scrim`, a hit so a click
989/// outside can close it), with a title, a close button (`{id}:close`), `body` and footer
990/// buttons `{id}:foot:{i}` (the first is `.primary`).
991pub fn dialog(id: &str, title: &str, body: El, footer: &[&str], at: Rect) -> El {
992    let foot = El::new("div.k-dialog-foot").children(footer.iter().enumerate().map(|(i, l)| {
993        El::new(if i == 0 { "button.k-btn.primary" } else { "button.k-btn" }).id(format!("{id}:foot:{i}")).tab().text(*l)
994    }));
995    El::new("div.k-modal")
996        .child(El::new("div.k-scrim").id(format!("{id}:scrim")))
997        .child(
998            El::new("div.k-dialog")
999                .id(id)
1000                .name(title)
1001                .css(format!("top: {}px; left: {}px; width: {}px; height: {}px", at.y, at.x, at.width, at.height))
1002                .child(
1003                    El::new("div.k-dialog-head")
1004                        .child(El::new("div.k-dialog-title").text(title))
1005                        .child(El::new("button.k-act").id(format!("{id}:close")).tab().name("Close").svg(icon(icons::CLOSE))),
1006                )
1007                .child(El::new("div.k-dialog-body").child(body))
1008                .child_if(!footer.is_empty(), || foot),
1009        )
1010}
1011
1012/// A tooltip below `anchor` (fixed, viewport coordinates).
1013pub fn tooltip(text: &str, anchor: Rect) -> El {
1014    El::new("div.k-tip").text(text).css(format!("top: {}px; left: {}px", anchor.y + anchor.height + 6.0, anchor.x))
1015}
1016
1017/// A toast stack in the bottom-right corner of the viewport: `(kind, text)` per toast
1018/// (`kind` as for [`banner`]); each has a close hit `{id}:{i}:close`.
1019pub fn toasts(id: &str, items: &[(&str, &str)]) -> El {
1020    El::new("div.k-toasts").id(id).children(items.iter().enumerate().map(|(i, (kind, text))| {
1021        El::new(if kind.is_empty() { "div.k-toast".to_string() } else { format!("div.k-toast.{kind}") })
1022            .name(*text)
1023            .child(El::new("div.k-toast-text").text(*text))
1024            .child(El::new("button.k-act").id(format!("{id}:{i}:close")).tab().name("Close").svg(icon(icons::CLOSE)))
1025    }))
1026}
1027
1028/// A metric tile: a caption, a big value and a muted note.
1029pub fn stat(id: &str, label: &str, value: &str, note: &str) -> El {
1030    El::new("div.k-stat")
1031        .id(id)
1032        .name(label)
1033        .child(El::new("div.k-stat-label").text(label))
1034        .child(El::new("div.k-stat-value").text(value))
1035        .child_if(!note.is_empty(), || El::new("div.k-stat-note").text(note))
1036}
1037
1038/// A progress bar, `v` in 0 … 1.
1039pub fn progress(v: f64) -> El {
1040    let pct = (v.clamp(0.0, 1.0) * 100.0 * 10.0).round() / 10.0;
1041    El::new("div.k-progress").child(El::new("div.k-bar").css(format!("width: {pct}%")))
1042}
1043
1044/// A labelled form row: a small caption above `control`.
1045pub fn field(label: &str, control: El) -> El {
1046    El::new("div.k-field").child(El::new("div.k-field-label").text(label)).child(control)
1047}
1048
1049/// Inline markdown to DOM runs: `**bold**`, `*italic*` / `_italic_`, `***both***`,
1050/// `` `code` `` (verbatim), http(s) links (`a.link`, hit `url:…`) and `@nick` mentions
1051/// (`a.mention`, hit `nick:…`). Unclosed markers stay literal; `_` only opens at a word
1052/// start and closes at a word end (`snake_case` stays as is).
1053pub fn inline_md(text: &str) -> Vec<Run> {
1054    let cs: Vec<char> = text.chars().collect();
1055    let mut out: Vec<Run> = Vec::new();
1056    let (mut bold, mut ital) = (false, false);
1057    let mut cur = String::new();
1058    let flush = |out: &mut Vec<Run>, cur: &mut String, bold: bool, ital: bool| {
1059        if cur.is_empty() {
1060            return;
1061        }
1062        let spec = match (bold, ital) {
1063            (true, true) => "b.i",
1064            (true, false) => "b",
1065            (false, true) => "i",
1066            _ => "span",
1067        };
1068        for sp in crate::ui::widgets::composite::chat_thread::linkify(cur, "link", 400) {
1069            let r = match crate::ui::widgets::composite::chat_thread::span_link(&sp) {
1070                Some(crate::ui::widgets::composite::chat_thread::Link::Mention(n)) => Run::new("a.mention", sp.text.as_str()).id(format!("nick:{n}")),
1071                Some(crate::ui::widgets::composite::chat_thread::Link::Url(u)) => Run::new("a.link", sp.text.as_str()).id(format!("url:{u}")),
1072                None => Run::new(spec, sp.text.as_str()),
1073            };
1074            let r = if (bold || ital) && r.spec.starts_with('a') {
1075                r.css(format!("{}{}", if bold { "font-weight: 700;" } else { "" }, if ital { "font-style: italic" } else { "" }))
1076            } else if spec == "b.i" {
1077                r.css("font-weight: 700; font-style: italic")
1078            } else if spec == "i" {
1079                r.css("font-style: italic")
1080            } else if spec == "b" {
1081                r.css("font-weight: 700")
1082            } else {
1083                r
1084            };
1085            out.push(r);
1086        }
1087        cur.clear();
1088    };
1089    let closes = |from: usize, pat: &[char]| -> bool {
1090        let n = pat.len();
1091        (from..cs.len().saturating_sub(n - 1)).any(|j| cs[j..j + n] == *pat && j > from)
1092    };
1093    let mut i = 0;
1094    while i < cs.len() {
1095        let c = cs[i];
1096        if c == '`' {
1097            if let Some(j) = (i + 1..cs.len()).find(|&j| cs[j] == '`') {
1098                flush(&mut out, &mut cur, bold, ital);
1099                let code: String = cs[i + 1..j].iter().collect();
1100                if !code.is_empty() {
1101                    out.push(Run::new("code", code));
1102                }
1103                i = j + 1;
1104                continue;
1105            }
1106        }
1107        if c == '*' && i + 1 < cs.len() && cs[i + 1] == '*' && (bold || closes(i + 2, &['*', '*'])) {
1108            flush(&mut out, &mut cur, bold, ital);
1109            bold = !bold;
1110            i += 2;
1111            continue;
1112        }
1113        if c == '*' && (ital || (i + 1 < cs.len() && !cs[i + 1].is_whitespace() && closes(i + 1, &['*']))) {
1114            flush(&mut out, &mut cur, bold, ital);
1115            ital = !ital;
1116            i += 1;
1117            continue;
1118        }
1119        if c == '_' {
1120            let word_before = i > 0 && cs[i - 1].is_alphanumeric();
1121            let word_after = i + 1 < cs.len() && cs[i + 1].is_alphanumeric();
1122            let opens = !ital
1123                && !word_before
1124                && i + 1 < cs.len()
1125                && !cs[i + 1].is_whitespace()
1126                && (i + 2..cs.len()).any(|j| cs[j] == '_' && !cs[j - 1].is_whitespace() && (j + 1 == cs.len() || !cs[j + 1].is_alphanumeric()));
1127            if opens || (ital && !word_after) {
1128                flush(&mut out, &mut cur, bold, ital);
1129                ital = !ital;
1130                i += 1;
1131                continue;
1132            }
1133        }
1134        cur.push(c);
1135        i += 1;
1136    }
1137    flush(&mut out, &mut cur, bold, ital);
1138    out
1139}
1140
1141/// A virtualized list: only the rows in (or near) the viewport are built and laid out;
1142/// spacers stand for the rest. Row heights start at an estimate and are learned from
1143/// laid-out rows ([`VirtualList::measure`]), so long chats stay cheap.
1144#[derive(Clone, Debug, Default, PartialEq)]
1145pub struct VirtualList {
1146    heights: Vec<Option<f64>>,
1147    /// Height of a row not measured yet.
1148    pub estimate: f64,
1149    /// Gap between rows.
1150    pub gap: f64,
1151}
1152
1153/// The rows a [`VirtualList`] shows and the space around them.
1154#[derive(Clone, Copy, Debug, Default, PartialEq)]
1155pub struct Window {
1156    pub start: usize,
1157    /// One past the last shown row.
1158    pub end: usize,
1159    /// Height of the spacer above the first shown row.
1160    pub top: f64,
1161    /// Height of the spacer below the last shown row.
1162    pub bottom: f64,
1163}
1164
1165impl VirtualList {
1166    pub fn new(len: usize, estimate: f64) -> Self {
1167        VirtualList { heights: vec![None; len], estimate, gap: 0.0 }
1168    }
1169    pub fn len(&self) -> usize {
1170        self.heights.len()
1171    }
1172    pub fn is_empty(&self) -> bool {
1173        self.heights.is_empty()
1174    }
1175    /// Grow or shrink to `n` rows (new rows unmeasured; kept rows keep their height).
1176    pub fn set_len(&mut self, n: usize) {
1177        self.heights.resize(n, None);
1178    }
1179    /// Forget a row's height (its content changed).
1180    pub fn invalidate(&mut self, i: usize) {
1181        if let Some(h) = self.heights.get_mut(i) {
1182            *h = None;
1183        }
1184    }
1185    fn h(&self, i: usize) -> f64 {
1186        self.heights[i].unwrap_or(self.estimate)
1187    }
1188    /// Set row `i`'s height (a host that lays rows out itself, e.g. from a cache of
1189    /// laid trees, reports them here instead of [`VirtualList::measure`]).
1190    pub fn set_height(&mut self, i: usize, h: f64) {
1191        if let Some(x) = self.heights.get_mut(i) {
1192            *x = Some(h);
1193        }
1194    }
1195    /// Row `i`'s measured height (`None`: not measured, the estimate stands in).
1196    pub fn height(&self, i: usize) -> Option<f64> {
1197        self.heights.get(i).copied().flatten()
1198    }
1199    /// Every row's top in list coordinates in one pass (`len() + 1` entries; the last
1200    /// is the total without a trailing gap counted twice).
1201    pub fn tops(&self) -> Vec<f64> {
1202        let mut out = Vec::with_capacity(self.len() + 1);
1203        let mut y = 0.0;
1204        for i in 0..self.len() {
1205            out.push(y);
1206            y += self.h(i) + self.gap;
1207        }
1208        out.push(self.total());
1209        out
1210    }
1211    /// The whole list's height (measured rows plus estimates).
1212    pub fn total(&self) -> f64 {
1213        (0..self.len()).map(|i| self.h(i)).sum::<f64>() + self.gap * self.len().saturating_sub(1) as f64
1214    }
1215    /// Top of row `i` in list coordinates.
1216    pub fn offset_of(&self, i: usize) -> f64 {
1217        (0..i.min(self.len())).map(|k| self.h(k) + self.gap).sum()
1218    }
1219    /// The row at list `y`.
1220    pub fn index_at(&self, y: f64) -> usize {
1221        let mut acc = 0.0;
1222        for i in 0..self.len() {
1223            acc += self.h(i) + self.gap;
1224            if y < acc {
1225                return i;
1226            }
1227        }
1228        self.len().saturating_sub(1)
1229    }
1230    /// The rows covering `scroll .. scroll + view`, plus `overscan` pixels each way.
1231    pub fn window(&self, scroll: f64, view: f64, overscan: f64) -> Window {
1232        if self.is_empty() {
1233            return Window::default();
1234        }
1235        let a = (scroll - overscan).max(0.0);
1236        let b = scroll + view + overscan;
1237        let start = self.index_at(a);
1238        let mut end = start;
1239        let mut y = self.offset_of(start);
1240        while end < self.len() && y < b {
1241            y += self.h(end) + self.gap;
1242            end += 1;
1243        }
1244        let top = self.offset_of(start);
1245        let bottom = (self.total() - self.offset_of(end)).max(0.0);
1246        Window { start, end, top, bottom }
1247    }
1248    /// The list element: `container` holding spacers and the rows `row(i)` for `w`.
1249    /// A container column `gap` must equal [`VirtualList::gap`] (spacers are emitted
1250    /// only when they stand for rows, so the gap is not doubled).
1251    pub fn el(&self, container: El, w: Window, mut row: impl FnMut(usize) -> El) -> El {
1252        let mut c = container;
1253        if w.start > 0 {
1254            c = c.child(El::new("div.k-vspace").css(format!("height: {}px", (w.top - self.gap).max(0.0))));
1255        }
1256        for i in w.start..w.end {
1257            c = c.child(row(i));
1258        }
1259        if w.end < self.len() {
1260            c = c.child(El::new("div.k-vspace").css(format!("height: {}px", w.bottom)));
1261        }
1262        c
1263    }
1264    /// Learn the shown rows' heights from a laid-out tree: row `i`'s element has id
1265    /// `id_of(i)`. Returns whether any height changed (re-lay out to settle).
1266    pub fn measure(&mut self, dom: &Dom, w: Window, id_of: impl Fn(usize) -> String) -> bool {
1267        let mut changed = false;
1268        for i in w.start..w.end.min(self.len()) {
1269            if let Some(r) = dom.rect(&id_of(i)) {
1270                if self.heights[i].is_none_or(|h| (h - r.height).abs() > 0.25) {
1271                    self.heights[i] = Some(r.height);
1272                    changed = true;
1273                }
1274            }
1275        }
1276        changed
1277    }
1278}
1279
1280#[cfg(all(test, feature = "flow-flex"))]
1281mod tests {
1282    use super::*;
1283    use crate::testing::NullRenderContext;
1284    use crate::ui::dom::lay_out_in;
1285    use crate::ui::style::State;
1286
1287    #[test]
1288    fn number_spec_parses_steps_and_tidies() {
1289        let s = NumberSpec::new().range(0.0, 10.0).step(0.5);
1290        assert_eq!(s.parse("3,5"), Some(3.5), "a decimal comma reads as a point");
1291        assert_eq!(s.parse("42"), Some(10.0), "clamped");
1292        assert_eq!(s.parse("-"), None, "not a number yet");
1293        assert_eq!(s.sanitize("1 234,5 $"), "1234,5");
1294        assert_eq!(s.stepped("3.5", 1), "4");
1295        assert_eq!(s.stepped("3.2", 1), "3.5", "off the grid: up to the next step");
1296        assert_eq!(s.stepped("3.2", -1), "3", "and down to the previous one");
1297        assert_eq!(s.stepped("9.8", 3), "10", "clamped at the top");
1298        assert_eq!(s.stepped("", 1), "0.5", "an empty field steps from the start");
1299        assert_eq!(s.normalized("7,25"), "7.25");
1300        assert_eq!(s.normalized("abc"), "abc");
1301        let i = NumberSpec::integer().min(1.0);
1302        assert!(!i.accepts('.') && i.accepts('7'));
1303        assert_eq!(i.stepped("0", 1), "2", "from below the range: clamped, then a step");
1304        assert_eq!(NumberSpec::new().step(0.1).stepped("0.2", 1), "0.3", "no float noise");
1305        assert_eq!(NumberSpec::new().decimals(2).format(1.0), "1.00");
1306    }
1307
1308    #[test]
1309    fn toolbar_lays_out_groups_hits_and_an_end_group() {
1310        let mut ctx = NullRenderContext::default();
1311        let sheet = sheet_with(TOOLBAR_CSS).unwrap();
1312        let items = [
1313            ToolItem::button("cursor", icon(icons::PLUS)).on(true),
1314            ToolItem::split("line", icon(icons::EDIT)),
1315            ToolItem::separator(),
1316            ToolItem::button("lock", icon(icons::PIN)).disabled(true),
1317            ToolItem::fill(),
1318            ToolItem::button("trash", icon(icons::TRASH)),
1319        ];
1320        let row = El::new("div").css("width: 400px").child(toolbar("tb", &items, false));
1321        let dom = lay_out_in(&mut ctx, &sheet, &row, 0.0, 0.0, 400.0, None, &|_| State::NONE);
1322        let ids: Vec<&str> = dom.hits().map(|(id, _)| id).collect();
1323        assert_eq!(ids, ["tb:bar", "tb:cursor", "tb:line", "tb:line:menu", "tb:trash"], "no hit for the disabled tool");
1324        let (c, l, m, t) = (dom.rect("tb:cursor").unwrap(), dom.rect("tb:line").unwrap(), dom.rect("tb:line:menu").unwrap(), dom.rect("tb:trash").unwrap());
1325        assert_eq!((c.x, c.y, c.width, c.height), (4.0, 4.0, 32.0, 32.0));
1326        assert_eq!(l.x, 40.0, "one gap after the first tool");
1327        assert_eq!(m.x, l.x + l.width, "the chevron hugs its button");
1328        assert_eq!(t.x + t.width, 396.0, "the end group sits at the far edge, inside the padding");
1329        assert_eq!(dom.get("tb:cursor").and_then(|p| p.style.background.as_deref()), Some("rgba(59,130,246,0.18)"), "lit");
1330        assert_eq!(picked_tool("tb", "tb:line:menu"), Some(("line", true)));
1331        assert_eq!(picked_tool("tb", "tb:trash"), Some(("trash", false)));
1332        assert_eq!(picked_tool("tb", "tb:bar"), None);
1333
1334        let col = El::new("div").css("height: 300px; display: flex; flex-direction: column").child(toolbar("v", &items, true).css("flex-grow: 1"));
1335        let dom = lay_out_in(&mut ctx, &sheet, &col, 0.0, 0.0, 48.0, None, &|_| State::NONE);
1336        let (c, l, t) = (dom.rect("v:cursor").unwrap(), dom.rect("v:line").unwrap(), dom.rect("v:trash").unwrap());
1337        assert_eq!((c.x, c.y), (8.0, 4.0), "a column, tools centred across it");
1338        assert_eq!(l.y, 40.0);
1339        assert_eq!(t.y + t.height, 296.0, "the end group at the bottom");
1340    }
1341
1342    #[test]
1343    fn flyouts_open_beside_their_tool_and_stay_on_screen() {
1344        let vp = Rect::new(0.0, 0.0, 800.0, 600.0);
1345        let r = flyout_at(Rect::new(4.0, 100.0, 32.0, 32.0), vp, 200.0, 150.0, true);
1346        assert_eq!((r.x, r.y), (40.0, 100.0), "right of a vertical toolbar's tool");
1347        let r = flyout_at(Rect::new(700.0, 4.0, 32.0, 32.0), vp, 200.0, 150.0, false);
1348        assert_eq!((r.x, r.y), (600.0, 40.0), "below, pulled back inside");
1349        let r = flyout_at(Rect::new(4.0, 560.0, 32.0, 32.0), vp, 200.0, 150.0, true);
1350        assert_eq!(r.y, 450.0, "lifted to fit");
1351    }
1352
1353    #[test]
1354    fn radio_group_rows_are_hits_with_a_sel_ring_and_dot() {
1355        let opts = [("en", "English"), ("ru", "Russian"), ("de", "German")];
1356        let g = radio_group("lang", &opts, 1);
1357        assert_eq!(g.children.len(), 3);
1358        assert_eq!(g.children[0].spec, "div.k-radio");
1359        assert_eq!(g.children[1].spec, "div.k-radio.sel");
1360        let dots = |row: &El| {
1361            row.children
1362                .iter()
1363                .filter(|c| c.spec == "span.k-radio-ring")
1364                .flat_map(|r| r.children.iter())
1365                .filter(|d| d.spec == "span.k-radio-dot")
1366                .count()
1367        };
1368        assert_eq!(dots(&g.children[0]), 0, "no dot off");
1369        assert_eq!(dots(&g.children[1]), 1, "dot on the selected row");
1370        assert_eq!(picked_radio("lang", "lang:ru"), Some("ru"));
1371        assert_eq!(picked_radio("lang", "lang:en"), Some("en"));
1372        assert_eq!(picked_radio("lang", "other:ru"), None);
1373
1374        let mut ctx = NullRenderContext::default();
1375        let sheet = sheet();
1376        let row = El::new("div").css("width: 300px").child(g);
1377        let dom = lay_out_in(&mut ctx, &sheet, &row, 0.0, 0.0, 300.0, None, &|_| State::NONE);
1378        let ids: Vec<&str> = dom.hits().map(|(id, _)| id).collect();
1379        // the group container is a hit too (like a toolbar bar); rows sit on top
1380        assert_eq!(ids, ["lang", "lang:en", "lang:ru", "lang:de"]);
1381        let (a, b) = (dom.rect("lang:en").unwrap(), dom.rect("lang:ru").unwrap());
1382        assert_eq!((a.height, b.height), (32.0, 32.0), "compact rows");
1383        assert_eq!(b.y - a.y, 36.0, "32 px row + 4 px gap");
1384    }
1385
1386    #[test]
1387    fn number_input_has_the_field_and_steppers() {
1388        fn walk(e: &El, out: &mut Vec<String>) {
1389            if let Some(i) = &e.id {
1390                out.push(i.clone());
1391            }
1392            for c in &e.children {
1393                walk(c, out);
1394            }
1395        }
1396        let mut ids = Vec::new();
1397        walk(&number_input("qty", Edit::new("3"), "Quantity"), &mut ids);
1398        assert_eq!(ids, ["qty", "qty:inc", "qty:dec"]);
1399    }
1400
1401    #[test]
1402    fn markdown_bold_italic_code_links() {
1403        let r = inline_md("a **b** *i* _u_ snake_case ***bi*** `x*y` see https://e.x @bob");
1404        let specs: Vec<(&str, &str)> = r.iter().map(|r| (r.spec.as_str(), r.text.as_str())).collect();
1405        assert!(specs.contains(&("b", "b")));
1406        assert!(specs.contains(&("i", "i")));
1407        assert!(specs.contains(&("i", "u")));
1408        assert!(specs.contains(&("b.i", "bi")));
1409        assert!(specs.contains(&("code", "x*y")));
1410        assert!(specs.iter().any(|(s, t)| *s == "span" && t.contains("snake_case")));
1411        assert!(r.iter().any(|r| r.spec == "a.link" && r.id.as_deref() == Some("url:https://e.x")));
1412        assert!(r.iter().any(|r| r.spec == "a.mention" && r.id.as_deref() == Some("nick:bob")));
1413        // unclosed markers stay literal
1414        let r = inline_md("2 * 3 and *open");
1415        assert_eq!(r.iter().map(|r| r.text.as_str()).collect::<String>(), "2 * 3 and *open");
1416    }
1417
1418    #[test]
1419    fn virtual_list_windows_and_learns() {
1420        let mut v = VirtualList::new(1000, 40.0);
1421        let w = v.window(4000.0, 400.0, 0.0);
1422        assert_eq!((w.start, w.end), (100, 110));
1423        assert_eq!(w.top, 4000.0);
1424        assert_eq!(w.top + (w.end - w.start) as f64 * 40.0 + w.bottom, v.total());
1425        let mut ctx = NullRenderContext::default();
1426        let el = v.el(El::new("div").css("display:flex;flex-direction:column"), w, |i| El::new("div").id(format!("r{i}")).css(if i % 2 == 0 { "height:60px" } else { "height:40px" }));
1427        let dom = crate::ui::dom::lay_out(&mut ctx, &sheet(), &el, 0.0, 0.0, 300.0, &|_| State::NONE);
1428        assert!(v.measure(&dom, w, |i| format!("r{i}")));
1429        assert_eq!(v.total(), 990.0 * 40.0 + 5.0 * 60.0 + 5.0 * 40.0);
1430        // Hosts that lay rows out themselves report heights directly.
1431        let mut v = VirtualList::new(3, 10.0);
1432        v.set_height(1, 30.0);
1433        assert_eq!((v.height(0), v.height(1)), (None, Some(30.0)));
1434        assert_eq!(v.tops(), vec![0.0, 10.0, 40.0, 50.0]);
1435    }
1436
1437    #[test]
1438    fn select_popover_is_fixed_and_skips_disabled() {
1439        let opts = [SelectOpt::new("Auto").sub("follow the system"), SelectOpt::new("Dark"), SelectOpt::new("Light").disabled(true)];
1440        let page = El::new("div.k-root")
1441            .css("height: 2000px")
1442            .child(select_trigger("theme", "Auto", true, "Theme"))
1443            .child(select_popover("theme", &opts, Some(0), Rect::new(10.0, 50.0, 200.0, 120.0)));
1444        let mut ctx = NullRenderContext::default();
1445        let vp = Rect::new(0.0, 0.0, 800.0, 600.0);
1446        let dom = lay_out_in(&mut ctx, &sheet(), &page, 0.0, 0.0, 800.0, Some(vp), &|_| State::NONE);
1447        assert!(dom.rect("theme:opt:0").is_some() && dom.rect("theme:opt:1").is_some());
1448        assert!(dom.rect("theme:opt:2").is_none());
1449        let pop = dom.rect("theme:pop").unwrap();
1450        assert_eq!((pop.x, pop.y, pop.width), (10.0, 50.0, 200.0));
1451        // scrolling the page leaves the popover in place and on top
1452        let moved = dom.clone().moved(0.0, -300.0);
1453        assert_eq!(moved.rect("theme:pop"), Some(pop));
1454        assert_eq!(moved.rect("theme").map(|r| r.y), dom.rect("theme").map(|r| r.y - 300.0));
1455        assert_eq!(moved.hit(20.0, 60.0), Some("theme:opt:0"));
1456        assert_eq!(picked_opt("theme", "theme:opt:1"), Some(1));
1457    }
1458
1459    #[test]
1460    fn select_list_windows_highlights_and_searches() {
1461        let opts: Vec<SelectOpt> = (0..20).map(|i| SelectOpt::new(format!("Zone {i}"))).collect();
1462        let view = ListView { hi: Some(6), top: 5, rows: 4, query: Some("zo"), row_h: 30.0 };
1463        let pop = select_list("tz", &opts, Some(7), &view, Rect::new(0.0, 0.0, 240.0, 200.0));
1464        let mut ctx = NullRenderContext::default();
1465        let vp = Rect::new(0.0, 0.0, 800.0, 600.0);
1466        let dom = lay_out_in(&mut ctx, &sheet(), &pop, 0.0, 0.0, 800.0, Some(vp), &|_| State::NONE);
1467        let shown: Vec<&str> = dom.hits().map(|(id, _)| id).filter(|id| id.starts_with("tz:opt:")).collect();
1468        assert_eq!(shown, ["tz:opt:5", "tz:opt:6", "tz:opt:7", "tz:opt:8"]);
1469        assert_eq!(dom.get("tz:opt:6").and_then(|p| p.style.background.as_deref()), Some("#33363d"));
1470        assert!(dom.get("tz:opt:5").is_some_and(|p| p.style.background.is_none()));
1471        let row = dom.rect("tz:opt:5").unwrap();
1472        assert!(row.y > 30.0, "below the search line");
1473        let none = select_list("tz", &[], None, &ListView { query: Some(""), ..ListView::all() }, Rect::new(0.0, 0.0, 240.0, 80.0));
1474        let dom = lay_out_in(&mut ctx, &sheet(), &none, 0.0, 0.0, 800.0, Some(vp), &|_| State::NONE);
1475        assert!(dom.hits().all(|(id, _)| !id.contains(":opt:")));
1476    }
1477
1478    #[test]
1479    fn controls_are_css_styled_and_named() {
1480        let page = El::new("div.k-root")
1481            .child(switch("wifi", true, "Wi-Fi"))
1482            .child(checkbox("agree", false, "I agree"))
1483            .child(input("q", Edit::new("hello").placeholder("Search").caret(5)))
1484            .child(spinner(0.3));
1485        let mut ctx = NullRenderContext::default();
1486        let dom = crate::ui::dom::lay_out(&mut ctx, &sheet(), &page, 0.0, 0.0, 400.0, &|_| State::NONE);
1487        let sw = dom.get("wifi").unwrap();
1488        assert_eq!((sw.rect.width, sw.rect.height), (36.0, 20.0));
1489        // :checked picked the accent background
1490        assert_eq!(sw.style.background.as_deref(), Some("#3b82f6"));
1491        // :focus while the input has a caret
1492        assert_eq!(dom.get("q").unwrap().style.border_color.as_deref(), Some("#3b82f6"));
1493        let a = dom.a11y();
1494        assert!(a.iter().any(|n| n.id == "wifi" && n.role == "switch" && n.name == "Wi-Fi" && n.checked == Some(true)));
1495        assert!(a.iter().any(|n| n.id == "q" && n.role == "textbox" && n.name == "hello"));
1496        assert!(a.iter().any(|n| n.id == "agree" && n.name == "I agree"));
1497        assert!(dom.get("q").unwrap().caret_rect().is_some());
1498    }
1499
1500    #[test]
1501    fn light_vars_retheme_the_whole_kit() {
1502        let page = |vars: &str| {
1503            El::new("div.k-root")
1504                .css(vars)
1505                .child(button("b", "Save"))
1506                .child(input("q", Edit::new("x")))
1507                .child(tabs("t", &["A", "B"], 1))
1508        };
1509        let mut ctx = NullRenderContext::default();
1510        let dark = crate::ui::dom::lay_out(&mut ctx, &sheet(), &page(theme_vars(true)), 0.0, 0.0, 400.0, &|_| State::NONE);
1511        let light = crate::ui::dom::lay_out(&mut ctx, &sheet(), &page(theme_vars(false)), 0.0, 0.0, 400.0, &|_| State::NONE);
1512        assert_eq!(dark.get("b").and_then(|p| p.style.background.as_deref()), Some("#2b2e34"));
1513        assert_eq!(light.get("b").and_then(|p| p.style.background.as_deref()), Some("#eceef2"));
1514        assert_eq!(light.get("q").and_then(|p| p.style.background.as_deref()), Some("#ffffff"));
1515        assert_eq!(light.get("t:tab:1").and_then(|p| p.style.color.as_deref()), Some("#1d1f24"));
1516        // No colour literal is left outside :root except the fixed bubble/link tints and knobs.
1517        for line in KIT_CSS.lines().filter(|l| !l.starts_with(":root") && !l.starts_with("        --")) {
1518            if line.contains("k-msg") || line.contains("k-body") || line.contains("k-banner") || line.contains("k-badge") || line.contains("k-toast") {
1519                continue;
1520            }
1521            let rest = line.replace("--knob: #ffffff", "").replace("--check: #ffffff", "");
1522            assert!(!rest.contains(": #") && !rest.contains(" #"), "hard-coded colour in {line}");
1523        }
1524    }
1525
1526    #[test]
1527    fn tabs_segmented_list_table_hits() {
1528        let rows = vec![vec!["alpha".to_string(), "7".to_string()], vec!["beta".to_string(), "14".to_string()]];
1529        let page = El::new("div.k-root")
1530            .child(tabs("tb", &["One", "Two", "Three"], 0))
1531            .child(segmented("theme", &["Dark", "Light"], 1))
1532            .child(list("ls", &[("alpha", Some("3")), ("beta", None)], Some(1)))
1533            .child(table("tt", &["Name", "Count"], "1fr 80px", &[1], &rows, Some(0)));
1534        let mut ctx = NullRenderContext::default();
1535        let dom = crate::ui::dom::lay_out(&mut ctx, &sheet(), &page, 0.0, 0.0, 400.0, &|_| State::NONE);
1536        let (a, b) = (dom.rect("tb:tab:0").unwrap(), dom.rect("tb:tab:2").unwrap());
1537        assert!(b.x > a.x && (a.y - b.y).abs() < 0.01, "tabs share a row");
1538        assert!(dom.get("theme:1").is_some_and(|p| p.style.background.as_deref() == Some("#3b82f6")));
1539        assert_eq!(picked("theme", "", "theme:1"), Some(1));
1540        assert_eq!(picked("tb", "tab", "tb:tab:2"), Some(2));
1541        assert_eq!(picked("tt", "row", "tb:tab:2"), None);
1542        assert!(dom.get("ls:row:1").is_some_and(|p| p.style.background.is_some()));
1543        // Table cells sit on the grid: the count column is 80px at the right.
1544        let row = dom.rect("tt:row:0").unwrap();
1545        assert!(row.height >= 30.0);
1546        assert!(dom.get("tt:row:0").is_some_and(|p| p.style.background.is_some()), ".sel row tinted");
1547    }
1548
1549    #[test]
1550    fn menu_dialog_toasts_are_fixed_layers() {
1551        let vp = Rect::new(0.0, 0.0, 800.0, 600.0);
1552        let items = [MenuItem::new("Rename").kbd("F2"), MenuItem::separator(), MenuItem::new("Locked").disabled(true), MenuItem::new("Delete").danger(true)];
1553        let page = El::new("div.k-root")
1554            .css("height: 2000px")
1555            .child(menu("m", Some("Row"), &items, Rect::new(100.0, 100.0, 200.0, 0.0)))
1556            .child(dialog("d", "Details", El::new("div").text("Body"), &["OK", "Cancel"], centered(vp, 360.0, 200.0)))
1557            .child(toasts("ts", &[("ok", "Saved"), ("", "Synced")]))
1558            .child(tooltip("Saves the name", Rect::new(10.0, 10.0, 80.0, 30.0)));
1559        let mut ctx = NullRenderContext::default();
1560        let dom = lay_out_in(&mut ctx, &sheet(), &page, 0.0, 0.0, 800.0, Some(vp), &|_| State::NONE);
1561        assert!(dom.rect("m:item:0").is_some() && dom.rect("m:item:3").is_some());
1562        assert!(dom.rect("m:item:2").is_none(), "disabled item is not a hit");
1563        assert_eq!(dom.rect("m:menu").map(|r| (r.x, r.y)), Some((100.0, 100.0)));
1564        let d = dom.rect("d").unwrap();
1565        assert_eq!((d.x, d.y, d.width, d.height), (220.0, 200.0, 360.0, 200.0));
1566        assert_eq!(dom.rect("d:scrim"), Some(vp), "scrim covers the viewport");
1567        // The dialog is above the scrim, the scrim above the page.
1568        assert_eq!(dom.hit(400.0, 300.0).map(|s| s.starts_with("d")), Some(true));
1569        assert_eq!(dom.hit(10.0, 590.0), Some("d:scrim"));
1570        let t = dom.rect("ts").unwrap();
1571        assert!((t.x + t.width - 784.0).abs() < 0.5 && (t.y + t.height - 584.0).abs() < 0.5, "toasts sit 16px from the bottom-right: {t:?}");
1572        assert!(dom.rect("ts:1:close").is_some());
1573        let moved = dom.clone().moved(0.0, -500.0);
1574        assert_eq!(moved.rect("d"), Some(d), "fixed layers do not scroll");
1575    }
1576
1577    #[test]
1578    fn stat_progress_badge_field() {
1579        let page = El::new("div.k-root").css("width: 300px")
1580            .child(stat("s", "FRAMES", "1 204", "+12 / s"))
1581            .child(progress(0.25))
1582            .child(badge("live", "ok"))
1583            .child(field("Name", input("n", Edit::new(""))));
1584        let mut ctx = NullRenderContext::default();
1585        let dom = crate::ui::dom::lay_out(&mut ctx, &sheet(), &page, 0.0, 0.0, 300.0, &|_| State::NONE);
1586        assert!(dom.rect("s").is_some_and(|r| r.height > 40.0));
1587        let bar = dom.boxes.iter().find(|b| b.style.background.as_deref() == Some("#3b82f6") && b.rect.height == 6.0).expect("bar");
1588        assert!((bar.rect.width - 75.0).abs() < 0.5, "25% of 300: {:?}", bar.rect);
1589        assert!(dom.rect("n").is_some());
1590    }
1591
1592    #[test]
1593    fn coarse_pointer_grows_targets_to_touch_size() {
1594        use crate::ui::media::{Edges, MediaEnv};
1595        let css = [KIT_CSS, KIT_TOUCH_CSS].concat();
1596        let touch = Sheet::parse_with(&css, &MediaEnv::touch(390.0, 844.0, Edges::ZERO)).unwrap();
1597        let mouse = Sheet::parse_with(&css, &MediaEnv::default()).unwrap();
1598        assert_eq!(mouse.el("div.k-li").height, Some(30.0));
1599        assert_eq!(touch.el("div.k-li").height, Some(48.0));
1600        assert_eq!(touch.el("div.k-input").height, Some(44.0));
1601        assert_eq!(touch.el("select.k-select").height, Some(44.0));
1602        assert_eq!(touch.el("button.k-btn").min_height, Some(44.0));
1603        assert_eq!(mouse.el("button.k-btn").min_height, None);
1604        // The look is the same: colours come from KIT_CSS in both.
1605        assert_eq!(touch.el("button.k-btn").background, mouse.el("button.k-btn").background);
1606    }
1607
1608}