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//! | spinner | [`spinner`] | `span.k-spinner` + [`Control::Spinner`] | — |
12//! | select trigger | [`select_trigger`] | `select.k-select` (`.open`) | `id` |
13//! | select popover | [`select_popover`] | fixed `div.k-pop` > `div.k-opt` (`.sel`, `.dis`) > label + `div.k-sub` | `{id}:opt:{i}` (enabled rows only) |
14//! | message bubble | [`bubble`] | `div.k-msg.me` / `.them` > `div.k-who`, `div.k-body` (runs), `div.k-time` | `id` |
15//! | hover action row | [`action_row`] | `div.k-actions` > `button.k-act` | `{id}:{key}` |
16//! | collapsible card | [`card`] | `div.k-card` (`.open`) > `div.k-card-head` + `div.k-card-body` | `id` (the head) |
17//! | chip / filter | [`chip`] | `button.k-chip` (`.on`) | `id` |
18//! | banner | [`banner`] | `div.k-banner.info` / `.warn` / `.error` | `{id}:act`, `{id}:close` |
19//! | side panel | [`side_panel`] | fixed `div.k-side` > `div.k-side-head` + `div.k-side-body` | `{id}:close` |
20//! | tabs | [`tabs`] | `div.k-tabs` > `button.k-tab` (`.on`) | `{id}:tab:{i}` |
21//! | segmented | [`segmented`] | `div.k-seg` > `button.k-seg-btn` (`.on`) | `{id}:{i}` |
22//! | list | [`list`] | `div.k-list` > `div.k-li` (`.sel`) | `{id}:row:{i}` |
23//! | table | [`table`] | `div.k-table` > grid `div.k-tr` (`.k-th`, `.sel`) > `div.k-td` (`.num`) | `{id}:row:{i}` |
24//! | menu | [`menu`] | fixed `div.k-menu` > `div.k-mi` (`.danger`, `.dis`), `div.k-sep` | `{id}:item:{i}` |
25//! | dialog | [`dialog`] | fixed `div.k-scrim` + `div.k-dialog` > head, body, foot | `{id}:scrim`, `{id}:close`, `{id}:foot:{i}` |
26//! | tooltip | [`tooltip`] | fixed `div.k-tip` | — |
27//! | toasts | [`toasts`] | fixed `div.k-toasts` > `div.k-toast` (`.ok`, `.warn`, `.error`) | `{id}:{i}:close` |
28//! | 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) |
29//!
30//! The light look is [`LIGHT_VARS`] on the page root ([`theme_vars`]); every colour in
31//! [`KIT_CSS`] is a `--k-*` variable.
32//!
33//! Inline markdown for bubbles is [`inline_md`]; long lists render only their visible
34//! rows with [`VirtualList`]. Kit widgets from `uzor-framework` go *inside* a DOM tree
35//! through an embed slot ([`El::slot`] + [`Dom::slots`](super::dom::Dom::slots)); a
36//! DOM tree goes inside a kit panel by laying it out in the panel's rect.
37
38use super::dom::{Control, Dom, Edit, El, Run};
39use super::style::{Sheet, StyleError};
40use crate::types::Rect;
41
42/// The catalog's default look (dark, 13px Inter). Variables on `:root` theme it:
43/// `--k-accent`, `--k-bg`, `--k-fg`, `--k-muted`, `--k-line`, `--k-panel`.
44pub const KIT_CSS: &str = r#"
45:root { --k-accent: #3b82f6; --k-bg: #17181b; --k-panel: #1f2125; --k-fg: #e8e8ea; --k-muted: #9a9ca3; --k-line: #33363c;
46        --k-me: #2563eb; --k-them: #26282d; --k-warn: #f59e0b; --k-error: #ef4444; --k-info: #3b82f6; --k-ok: #22c55e;
47        --k-btn: #2b2e34; --k-btn-hover: #353840; --k-track: #4a4d55; --k-track-hover: #575b64; --k-accent-hover: #2f6fd8;
48        --k-field: #111214; --k-sunken: #141518; --k-hover: #2c2f36; --k-hi: #33363d; --k-sel: rgba(59,130,246,0.18);
49        --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) }
50div.k-root { color: var(--k-fg); font-size: 13px; font-family: Inter, sans-serif }
51button.k-btn { padding: 6px 14px; border-radius: 8px; background: var(--k-btn); color: var(--k-fg); font-weight: 500 }
52button.k-btn:hover { background: var(--k-btn-hover) }
53button.k-btn.primary { background: var(--k-accent); color: var(--k-on-accent) }
54button.k-btn.primary:hover { background: var(--k-accent-hover) }
55button.k-btn.ghost { background: transparent; border: 1px solid var(--k-line) }
56button.k-btn.ghost:hover { background: var(--k-hover) }
57button.k-btn.danger { background: transparent; border: 1px solid var(--k-error); color: var(--k-error) }
58button.k-btn:focus-visible { border: 2px solid var(--k-accent) }
59button.k-switch { width: 36px; height: 20px; padding: 2px; border-radius: 10px; background: var(--k-track); --knob: #ffffff }
60button.k-switch:checked { background: var(--k-accent) }
61button.k-switch:hover { background: var(--k-track-hover) }
62button.k-switch:checked:hover { background: var(--k-accent-hover) }
63div.k-check { display: flex; align-items: center; gap: 8px }
64span.k-box { width: 16px; height: 16px; padding: 1px; border-radius: 4px; border: 1.5px solid var(--k-track-hover); --check: #ffffff; --check-width: 2px }
65span.k-box:checked { background: var(--k-accent); border-color: var(--k-accent) }
66div.k-input { height: 32px; padding: 0 10px; border-radius: 8px; background: var(--k-field); border: 1px solid var(--k-line);
67              --placeholder: var(--k-muted); --selection: rgba(59,130,246,0.4); --caret: var(--k-fg) }
68div.k-input:hover { border-color: var(--k-track) }
69div.k-input:focus { border-color: var(--k-accent) }
70span.k-spinner { width: 18px; height: 18px; color: var(--k-accent); --spin-track: var(--k-line); --spin-speed: 1.2 }
71select.k-select { height: 32px; padding: 0 30px 0 12px; border-radius: 8px; background: var(--k-btn); color: var(--k-fg); --chevron: var(--k-muted) }
72select.k-select:hover { background: var(--k-btn-hover) }
73select.k-select.open { border: 1px solid var(--k-accent) }
74div.k-pop { position: fixed; z-index: 100; padding: 4px; border-radius: 10px; background: var(--k-panel); border: 1px solid var(--k-line);
75            box-shadow: 0 8px 24px var(--k-shadow); display: flex; flex-direction: column }
76div.k-opt { display: flex; align-items: center; gap: 8px; padding: 7px 10px; border-radius: 6px; color: var(--k-fg); flex-shrink: 0 }
77div.k-opt:hover { background: var(--k-hover) }
78div.k-opt.sel { background: var(--k-sel) }
79div.k-opt.hi { background: var(--k-hi) }
80span.k-tick { width: 14px; height: 14px; flex-shrink: 0; color: var(--k-accent) }
81div.k-optl { display: flex; flex-direction: column; flex-grow: 1; min-width: 0 }
82div.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 }
83span.k-mag { width: 14px; height: 14px; color: var(--k-muted) }
84div.k-ph { color: var(--k-muted) }
85div.k-empty { padding: 7px 14px; color: var(--k-muted) }
86div.k-thumb { position: absolute; right: 3px; width: 3px; border-radius: 2px; background: var(--k-track) }
87div.k-opt.dis { color: var(--k-dis) }
88div.k-opt .k-sub { color: var(--k-muted); font-size: 11px }
89div.k-opt.dis .k-sub { color: var(--k-dis) }
90div.k-msg { display: flex; flex-direction: column; max-width: 75%; padding: 8px 12px; border-radius: 14px; white-space: normal; gap: 2px }
91div.k-msg.me { align-self: flex-end; background: var(--k-me); color: #ffffff; border-radius: 14px 14px 4px 14px }
92div.k-msg.them { align-self: flex-start; background: var(--k-them); border-radius: 14px 14px 14px 4px }
93div.k-msg > div.k-who { font-weight: 600; font-size: 12px; color: var(--k-accent) }
94div.k-msg.me > div.k-who { color: #dbe7ff }
95div.k-msg div.k-time { font-size: 10px; color: var(--k-muted); text-align: right }
96div.k-msg.me div.k-time { color: #c7d7f7 }
97div.k-body code { font-family: monospace; background: rgba(0,0,0,0.3); padding: 0 5px; border-radius: 5px }
98div.k-body b { font-weight: 700 }
99div.k-body i { font-style: italic }
100div.k-body a.link { color: #93c5fd }
101div.k-body a.mention { color: #93c5fd; font-weight: 600 }
102div.k-msg.me div.k-body a.link { color: #ffffff }
103div.k-msg > div.k-actions { align-self: flex-end }
104div.k-actions { display: flex; gap: 2px; padding: 2px; border-radius: 8px; background: var(--k-panel); border: 1px solid var(--k-line) }
105button.k-act { width: 26px; height: 26px; padding: 5px; border-radius: 6px; color: var(--k-muted) }
106button.k-act:hover { background: var(--k-hover); color: var(--k-fg) }
107div.k-card { border-radius: 10px; border: 1px solid var(--k-line); background: var(--k-panel); display: flex; flex-direction: column }
108div.k-card-head { display: flex; align-items: center; gap: 6px; padding: 8px 10px; font-weight: 600 }
109div.k-card-head:hover { background: var(--k-hover); border-radius: 10px }
110div.k-card > div.k-card-head > span.k-chev { width: 14px; height: 14px; color: var(--k-muted) }
111div.k-card-body { padding: 4px 12px 10px; white-space: normal; color: var(--k-body) }
112button.k-chip { padding: 4px 10px; border-radius: 999px; border: 1px solid var(--k-line); color: var(--k-muted); font-size: 12px }
113button.k-chip:hover { color: var(--k-fg) }
114button.k-chip.on { background: var(--k-sel); border-color: var(--k-accent); color: var(--k-fg) }
115div.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) }
116div.k-banner.warn { border-left: 3px solid var(--k-warn); background: rgba(245,158,11,0.12) }
117div.k-banner.error { border-left: 3px solid var(--k-error); background: rgba(239,68,68,0.12) }
118div.k-banner.ok { border-left: 3px solid var(--k-ok); background: rgba(34,197,94,0.12) }
119div.k-banner > div.k-banner-text { flex-grow: 1; white-space: normal }
120div.k-banner button.k-act { width: 22px; height: 22px; padding: 4px }
121div.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);
122             display: flex; flex-direction: column }
123div.k-side-head { display: flex; align-items: center; padding: 12px 14px; border-bottom: 1px solid var(--k-line); font-weight: 600 }
124div.k-side-head > div.k-side-title { flex-grow: 1 }
125div.k-side-body { padding: 12px 14px; display: flex; flex-direction: column; gap: 10px; flex-grow: 1 }
126div.k-slot { border: 1px dashed var(--k-line); border-radius: 8px }
127div.k-tabs { display: flex; gap: 2px; padding: 3px; border-radius: 9px; background: var(--k-sunken); border: 1px solid var(--k-line) }
128button.k-tab { flex-grow: 1; padding: 5px 12px; border-radius: 6px; color: var(--k-muted); font-weight: 500; text-align: center }
129button.k-tab:hover { color: var(--k-fg); background: var(--k-hover) }
130button.k-tab.on { background: var(--k-btn-hover); color: var(--k-fg) }
131div.k-list { display: flex; flex-direction: column; padding: 4px; border-radius: 10px; border: 1px solid var(--k-line); background: var(--k-panel); overflow: hidden }
132div.k-li { display: flex; align-items: center; gap: 8px; height: 30px; padding: 0 10px; border-radius: 6px; flex-shrink: 0 }
133div.k-li:hover { background: var(--k-hover) }
134div.k-li.sel { background: var(--k-sel); color: var(--k-fg) }
135div.k-li > div.k-li-main { flex-grow: 1; min-width: 0 }
136div.k-li > div.k-li-side { color: var(--k-muted); font-size: 12px }
137div.k-table { display: flex; flex-direction: column; border-radius: 10px; border: 1px solid var(--k-line); background: var(--k-panel); overflow: hidden }
138div.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 }
139div.k-tr:hover { background: var(--k-hover) }
140div.k-tr.sel { background: var(--k-sel) }
141div.k-tr.k-th { color: var(--k-muted); font-size: 11px; font-weight: 600; background: var(--k-sunken) }
142div.k-td.num { text-align: right }
143div.k-menu { position: fixed; z-index: 120; padding: 4px; border-radius: 10px; background: var(--k-panel); border: 1px solid var(--k-line);
144             box-shadow: 0 8px 24px var(--k-shadow); display: flex; flex-direction: column }
145div.k-menu-title { padding: 6px 10px 4px; color: var(--k-muted); font-size: 11px; font-weight: 600 }
146div.k-mi { display: flex; align-items: center; gap: 8px; padding: 7px 10px; border-radius: 6px; flex-shrink: 0 }
147div.k-mi:hover { background: var(--k-hover) }
148div.k-mi.danger { color: var(--k-error) }
149div.k-mi.dis { color: var(--k-dis) }
150div.k-mi > span.k-mi-icon { width: 14px; height: 14px; color: var(--k-muted) }
151div.k-mi > div.k-mi-label { flex-grow: 1 }
152div.k-sep { height: 1px; margin: 4px 6px; background: var(--k-line); flex-shrink: 0 }
153span.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 }
154span.k-badge { padding: 1px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; background: var(--k-sel); color: var(--k-accent) }
155span.k-badge.ok { background: rgba(34,197,94,0.15); color: var(--k-ok) }
156span.k-badge.warn { background: rgba(245,158,11,0.15); color: var(--k-warn) }
157span.k-badge.error { background: rgba(239,68,68,0.15); color: var(--k-error) }
158span.k-badge.muted { background: var(--k-hover); color: var(--k-muted) }
159div.k-scrim { position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 140; background: var(--k-scrim) }
160div.k-dialog { position: fixed; z-index: 150; border-radius: 14px; background: var(--k-panel); border: 1px solid var(--k-line);
161               box-shadow: 0 16px 48px var(--k-shadow); display: flex; flex-direction: column }
162div.k-dialog-head { display: flex; align-items: center; padding: 14px 16px 6px; font-size: 15px; font-weight: 600 }
163div.k-dialog-head > div.k-dialog-title { flex-grow: 1 }
164div.k-dialog-body { padding: 6px 16px 12px; flex-grow: 1; white-space: normal; color: var(--k-body); display: flex; flex-direction: column; gap: 10px }
165div.k-dialog-foot { display: flex; justify-content: flex-end; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--k-line) }
166div.k-tip { position: fixed; z-index: 160; padding: 5px 9px; border-radius: 6px; background: var(--k-fg); color: var(--k-bg); font-size: 12px }
167div.k-toasts { position: fixed; right: 16px; bottom: 16px; z-index: 170; width: 300px; display: flex; flex-direction: column; gap: 8px }
168div.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);
169              border-left: 3px solid var(--k-info); box-shadow: 0 8px 24px var(--k-shadow) }
170div.k-toast.ok { border-left: 3px solid var(--k-ok) }
171div.k-toast.warn { border-left: 3px solid var(--k-warn) }
172div.k-toast.error { border-left: 3px solid var(--k-error) }
173div.k-toast > div.k-toast-text { flex-grow: 1; white-space: normal }
174div.k-seg { display: flex; padding: 3px; gap: 2px; border-radius: 9px; background: var(--k-sunken); border: 1px solid var(--k-line) }
175button.k-seg-btn { flex-grow: 1; padding: 5px 10px; border-radius: 6px; color: var(--k-muted); text-align: center; font-weight: 500 }
176button.k-seg-btn:hover { color: var(--k-fg) }
177button.k-seg-btn.on { background: var(--k-accent); color: var(--k-on-accent) }
178div.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) }
179div.k-stat > div.k-stat-label { color: var(--k-muted); font-size: 11px; font-weight: 600 }
180div.k-stat > div.k-stat-value { font-size: 24px; font-weight: 700 }
181div.k-stat > div.k-stat-note { color: var(--k-muted); font-size: 11px }
182div.k-progress { height: 6px; border-radius: 3px; background: var(--k-line); overflow: hidden }
183div.k-progress > div.k-bar { height: 6px; border-radius: 3px; background: var(--k-accent) }
184div.k-field { display: flex; flex-direction: column; gap: 6px }
185div.k-field > div.k-field-label { color: var(--k-muted); font-size: 11px; font-weight: 600 }
186"#;
187
188/// Touch-sized targets, applied under `@media (pointer: coarse)` (a finger: iOS /
189/// Android builds, or the last input was touch). Apple asks for 44 pt, Material
190/// for 48 dp: controls grow to 44 px, list rows to 48 px, text to 15 px. The look
191/// stays the same; only sizes change. [`sheet`] and [`sheet_with`] include it
192/// after [`KIT_CSS`]; the app's own rules still win.
193pub const KIT_TOUCH_CSS: &str = r#"
194@media (pointer: coarse) {
195div.k-root { font-size: 15px }
196button.k-btn { padding: 12px 18px; min-height: 44px; border-radius: 10px }
197button.k-switch { width: 44px; height: 26px; padding: 3px; border-radius: 13px }
198span.k-box { width: 22px; height: 22px; border-radius: 6px }
199div.k-check { gap: 12px; min-height: 44px }
200div.k-input { height: 44px; padding: 0 12px; border-radius: 10px }
201select.k-select { height: 44px; padding: 0 34px 0 14px; border-radius: 10px }
202div.k-opt { padding: 12px 12px; border-radius: 8px }
203div.k-mi { padding: 12px 12px; border-radius: 8px }
204div.k-search { height: 40px }
205div.k-li { height: 48px; padding: 0 14px; border-radius: 8px }
206div.k-tr { height: 44px }
207button.k-act { width: 40px; height: 40px; padding: 10px; border-radius: 8px }
208button.k-tab { padding: 10px 14px }
209button.k-seg-btn { padding: 9px 12px }
210button.k-chip { padding: 8px 14px }
211div.k-card-head { padding: 12px 14px }
212div.k-dialog-foot { padding: 12px 16px 16px }
213}
214"#;
215
216/// Inline `:root` overrides for the light look: put them on the page root
217/// (`El::new("div.k-root").css(LIGHT_VARS)`); custom properties cascade to the subtree.
218pub const LIGHT_VARS: &str = "--k-bg: #f6f7f9; --k-panel: #ffffff; --k-fg: #1d1f24; --k-muted: #6b6f78; --k-line: #dfe1e6; \
219--k-them: #eceef2; --k-btn: #eceef2; --k-btn-hover: #e2e5ea; --k-track: #c9ccd3; --k-track-hover: #b7bbc4; --k-accent-hover: #2563eb; \
220--k-field: #ffffff; --k-sunken: #f0f1f4; --k-hover: #eef0f4; --k-hi: #e6e9ef; --k-sel: rgba(59,130,246,0.14); --k-dis: #b0b4bc; \
221--k-body: #3a3d45; --k-scrim: rgba(15,17,21,0.35); --k-shadow: rgba(15,17,21,0.18)";
222
223/// The page-root inline variables for the dark (`""`, the sheet's own `:root`) or light look.
224pub fn theme_vars(dark: bool) -> &'static str {
225    if dark {
226        ""
227    } else {
228        LIGHT_VARS
229    }
230}
231
232/// [`KIT_CSS`] (plus [`KIT_TOUCH_CSS`]) parsed against the current media environment.
233pub fn sheet() -> Sheet {
234    Sheet::parse(&[KIT_CSS, KIT_TOUCH_CSS].concat()).expect("KIT_CSS parses")
235}
236
237/// [`KIT_CSS`] followed by the app's own rules (later rules of equal specificity win).
238pub fn sheet_with(app_css: &str) -> Result<Sheet, StyleError> {
239    Sheet::parse(&[KIT_CSS, KIT_TOUCH_CSS, app_css].concat())
240}
241
242/// A 24×24 stroke icon (`currentColor`) from its path markup.
243pub fn icon(body: &str) -> String {
244    format!(r#"<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">{body}</svg>"#)
245}
246
247/// Icon bodies used by the catalog.
248pub mod icons {
249    pub const CLOSE: &str = r#"<path d="M6 6l12 12M18 6L6 18"/>"#;
250    pub const RIGHT: &str = r#"<path d="M9 6l6 6-6 6"/>"#;
251    pub const DOWN: &str = r#"<path d="M6 9l6 6 6-6"/>"#;
252    pub const REPLY: &str = r#"<path d="M9 14L4 9l5-5"/><path d="M4 9h10a6 6 0 0 1 6 6v3"/>"#;
253    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"/>"#;
254    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"/>"#;
255    pub const MORE: &str = r#"<path d="M5 12h.01M12 12h.01M19 12h.01"/>"#;
256    pub const CHECK: &str = r#"<path d="M5 12.5l4.5 4.5L19 7.5"/>"#;
257    pub const SEARCH: &str = r#"<circle cx="11" cy="11" r="6.5"/><path d="M16 16l4 4"/>"#;
258    pub const LEFT: &str = r#"<path d="M15 6l-6 6 6 6"/>"#;
259    pub const PLUS: &str = r#"<path d="M12 5v14M5 12h14"/>"#;
260    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"/>"#;
261    pub const MENU: &str = r#"<path d="M4 6h16M4 12h16M4 18h16"/>"#;
262    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"/>"#;
263    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"/>"#;
264    pub const SAVE: &str = r#"<path d="M5 3h11l3 3v15H5z"/><path d="M8 3v5h7V3M8 21v-7h8v7"/>"#;
265    pub const UNDO: &str = r#"<path d="M4 9h11a5 5 0 0 1 0 10H8"/><path d="M8 5L4 9l4 4"/>"#;
266    pub const EXPAND: &str = r#"<path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/>"#;
267    pub const PLAY: &str = r#"<path d="M7 4l13 8-13 8z"/>"#;
268    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"/>"#;
269    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"/>"#;
270    pub const WINDOW: &str = r#"<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 9h18"/>"#;
271    pub const DOWNLOAD: &str = r#"<path d="M12 3v12M7 10l5 5 5-5M4 20h16"/>"#;
272    pub const CHART: &str = r#"<path d="M4 20V4M4 20h16M8 16v-5M12 16V8M16 16v-8"/>"#;
273    pub const LIST: &str = r#"<path d="M9 6h11M9 12h11M9 18h11M4 6h.01M4 12h.01M4 18h.01"/>"#;
274    pub const TERMINAL: &str = r#"<path d="M4 7l5 5-5 5M12 19h8"/>"#;
275    pub const TRASH: &str = r#"<path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"/>"#;
276    pub const EDIT: &str = r#"<path d="M4 20h4L19 9l-4-4L4 16z"/>"#;
277    pub const PIN: &str = r#"<path d="M9 4h6l-1 6 4 4H6l4-4zM12 14v6"/>"#;
278    pub const BOX: &str = r#"<path d="M21 8l-9-5-9 5 9 5 9-5zM3 8v8l9 5 9-5V8M12 13v8"/>"#;
279    pub const BOLT: &str = r#"<path d="M13 2L4 14h7l-1 8 9-12h-7z"/>"#;
280}
281
282/// A push button.
283pub fn button(id: &str, label: &str) -> El {
284    El::new("button.k-btn").id(id).tab().text(label)
285}
286
287/// A switch (`role="switch"`): the track is the button's box, the knob its control.
288pub fn switch(id: &str, on: bool, name: &str) -> El {
289    El::new("button.k-switch").id(id).tab().name(name).control(Control::switch(on))
290}
291
292/// A switch whose knob is at `pos` (0 … 1) while it slides.
293pub fn switch_at(id: &str, on: bool, pos: f64, name: &str) -> El {
294    El::new("button.k-switch").id(id).tab().name(name).control(Control::Switch { on, pos })
295}
296
297/// A checkbox with its label; the row is the hit.
298pub fn checkbox(id: &str, on: bool, label: &str) -> El {
299    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))
300}
301
302/// A busy spinner at time `t` seconds.
303pub fn spinner(t: f64) -> El {
304    El::new("span.k-spinner").name("Loading").control(Control::spinner(t))
305}
306
307/// A single-line text input showing `edit`.
308pub fn input(id: &str, edit: Edit) -> El {
309    El::new("div.k-input").id(id).tab().control(Control::input(edit))
310}
311
312/// One option of a select.
313#[derive(Clone, Debug, Default, PartialEq)]
314pub struct SelectOpt {
315    pub label: String,
316    /// A muted second line.
317    pub sub: Option<String>,
318    /// Shown greyed, not pickable (no hit id).
319    pub disabled: bool,
320}
321
322impl SelectOpt {
323    pub fn new(label: impl Into<String>) -> Self {
324        SelectOpt { label: label.into(), ..Default::default() }
325    }
326    pub fn sub(mut self, s: impl Into<String>) -> Self {
327        self.sub = Some(s.into());
328        self
329    }
330    pub fn disabled(mut self, on: bool) -> Self {
331        self.disabled = on;
332        self
333    }
334}
335
336/// The closed select: the chosen label and a chevron.
337pub fn select_trigger(id: &str, label: &str, open: bool, name: &str) -> El {
338    El::new(if open { "select.k-select.open" } else { "select.k-select" }).id(id).tab().name(name).text(label)
339}
340
341/// Where a popover `h` tall goes for a trigger at `anchor` in `viewport`: below it, or
342/// above when it does not fit below and fits better above; at least the trigger's width.
343pub fn popover_at(anchor: Rect, viewport: Rect, w: f64, h: f64) -> Rect {
344    let w = w.max(anchor.width);
345    let below = viewport.y + viewport.height - (anchor.y + anchor.height + 4.0);
346    let above = anchor.y - 4.0 - viewport.y;
347    let y = if h > below && above > below { (anchor.y - 4.0 - h).max(viewport.y) } else { anchor.y + anchor.height + 4.0 };
348    let x = anchor.x.min(viewport.x + viewport.width - w).max(viewport.x);
349    Rect::new(x, y, w, h.min(below.max(above)))
350}
351
352/// The open select's list as a `position: fixed` popover at `at` (see [`popover_at`]):
353/// it paints above the page and does not scroll with it. Enabled rows are hits
354/// `{id}:opt:{i}`; `chosen` is marked `.sel` (with a tick).
355pub fn select_popover(id: &str, opts: &[SelectOpt], chosen: Option<usize>, at: Rect) -> El {
356    select_list(id, opts, chosen, &ListView::all(), at)
357}
358
359/// What part of a long option list a popover shows. The select's own model (keyboard,
360/// wheel, type-to-filter) keeps it; the popover only draws it.
361#[derive(Clone, Copy, Debug, PartialEq)]
362pub struct ListView<'a> {
363    /// The keyboard-highlighted row (`.hi`).
364    pub hi: Option<usize>,
365    /// First shown row.
366    pub top: usize,
367    /// How many rows show (a scroll thumb appears when there are more).
368    pub rows: usize,
369    /// A search line with this query (`Some("")`: its placeholder).
370    pub query: Option<&'a str>,
371    /// Height of a row (sets the thumb's travel; rows are styled by CSS).
372    pub row_h: f64,
373}
374
375impl ListView<'_> {
376    /// Every row, no search line.
377    pub fn all() -> Self {
378        ListView { hi: None, top: 0, rows: usize::MAX, query: None, row_h: 0.0 }
379    }
380}
381
382/// [`select_popover`] for a windowed, searchable list: rows `view.top ..` of `opts` (the
383/// already filtered options; hits keep their index in `opts`), the highlighted row, a
384/// search line and a scroll thumb. "No matches" when `opts` is empty. The popover is
385/// `position: fixed` at `at`, so `at` is in the coordinates of the viewport given to
386/// [`lay_out_in`](crate::ui::dom::lay_out_in) (the window, origin 0,0). Its rows' `--k-accent`
387/// (the chosen row's tick) can be set inline on the returned element.
388pub fn select_list(id: &str, opts: &[SelectOpt], chosen: Option<usize>, view: &ListView<'_>, at: Rect) -> El {
389    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));
390    if let Some(q) = view.query {
391        let line = El::new("div.k-search").child(El::new("span.k-mag").svg(icon(icons::SEARCH)));
392        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)) });
393    }
394    if opts.is_empty() {
395        pop = pop.child(El::new("div.k-empty").text("No matches"));
396    }
397    let end = view.top.saturating_add(view.rows).min(opts.len());
398    for (i, o) in opts.iter().enumerate().take(end).skip(view.top) {
399        let mut spec = String::from("div.k-opt");
400        if chosen == Some(i) {
401            spec.push_str(".sel");
402        }
403        if view.hi == Some(i) {
404            spec.push_str(".hi");
405        }
406        if o.disabled {
407            spec.push_str(".dis");
408        }
409        let mut label = El::new("div.k-optl").child(El::new("div.k-label").text(&o.label));
410        if let Some(s) = &o.sub {
411            label = label.child(El::new("div.k-sub").text(s));
412        }
413        let tick = El::new("span.k-tick");
414        let tick = if chosen == Some(i) { tick.svg(icon(icons::CHECK)) } else { tick };
415        let mut row = El::new(spec).name(&o.label).child(tick).child(label);
416        if !o.disabled {
417            row = row.id(format!("{id}:opt:{i}")).tab();
418        }
419        pop = pop.child(row);
420    }
421    let n = opts.len();
422    if n > view.rows && view.row_h > 0.0 {
423        let track = view.row_h * view.rows as f64;
424        let th = (track * view.rows as f64 / n as f64).max(18.0);
425        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;
426        pop = pop.child(El::new("div.k-thumb").css(format!("top: {ty}px; height: {th}px")));
427    }
428    pop
429}
430
431/// The option index a select popover hit id names (`{id}:opt:{i}`).
432pub fn picked_opt(id: &str, hit: &str) -> Option<usize> {
433    hit.strip_prefix(id)?.strip_prefix(":opt:")?.parse().ok()
434}
435
436/// A chat message bubble: optional sender line, markdown body ([`inline_md`]), time.
437pub fn bubble(id: &str, mine: bool, who: Option<&str>, body: &str, time: Option<&str>) -> El {
438    let mut b = El::new(if mine { "div.k-msg.me" } else { "div.k-msg.them" }).id(id);
439    if let Some(w) = who {
440        b = b.child(El::new("div.k-who").text(w));
441    }
442    b = b.child(El::new("div.k-body").runs(inline_md(body)));
443    if let Some(t) = time {
444        b = b.child(El::new("div.k-time").text(t));
445    }
446    b
447}
448
449/// A hover action row (reply, react, copy, more…): `(key, icon body, name)` per button,
450/// hits `{id}:{key}`.
451pub fn action_row(id: &str, actions: &[(&str, &str, &str)]) -> El {
452    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))))
453}
454
455/// A collapsible card: the head (hit `id`) toggles `open`; the body shows when open.
456pub fn card(id: &str, title: &str, open: bool, body: El) -> El {
457    let head = El::new("div.k-card-head")
458        .id(id)
459        .tab()
460        .name(title)
461        .child(El::new("span.k-chev").svg(icon(if open { icons::DOWN } else { icons::RIGHT })))
462        .child(El::new("span").text(title));
463    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))
464}
465
466/// A filter chip.
467pub fn chip(id: &str, label: &str, on: bool) -> El {
468    El::new(if on { "button.k-chip.on" } else { "button.k-chip" }).id(id).tab().text(label)
469}
470
471/// A banner (`kind`: `info`, `warn`, `error`) with an optional action button
472/// (`{id}:act`) and a close button (`{id}:close`).
473pub fn banner(id: &str, kind: &str, text: &str, action: Option<&str>, closable: bool) -> El {
474    let mut b = El::new(format!("div.k-banner.{kind}")).id(id).name(text).child(El::new("div.k-banner-text").text(text));
475    if let Some(a) = action {
476        b = b.child(El::new("button.k-btn.ghost").id(format!("{id}:act")).tab().text(a));
477    }
478    if closable {
479        b = b.child(El::new("button.k-act").id(format!("{id}:close")).tab().name("Close").svg(icon(icons::CLOSE)));
480    }
481    b
482}
483
484/// A side panel docked right (`position: fixed`: it stays while the page scrolls), with a
485/// title row and a close button (`{id}:close`).
486pub fn side_panel(id: &str, title: &str, body: impl IntoIterator<Item = El>) -> El {
487    El::new("div.k-side")
488        .id(id)
489        .child(
490            El::new("div.k-side-head")
491                .child(El::new("div.k-side-title").text(title))
492                .child(El::new("button.k-act").id(format!("{id}:close")).tab().name("Close").svg(icon(icons::CLOSE))),
493        )
494        .child(El::new("div.k-side-body").children(body))
495}
496
497/// An embed slot box (`div.k-slot`) named `key`, `w` × `h`: a kit widget or canvas goes
498/// in its content box (see [`Dom::slots`]).
499pub fn slot(key: &str, w: f64, h: f64) -> El {
500    El::new("div.k-slot").slot(key).css(format!("width: {w}px; height: {h}px"))
501}
502
503/// A tab strip: one `button.k-tab` per label (`.on` for `active`), hits `{id}:tab:{i}`.
504pub fn tabs(id: &str, labels: &[&str], active: usize) -> El {
505    El::new("div.k-tabs").id(id).children(labels.iter().enumerate().map(|(i, l)| {
506        El::new(if i == active { "button.k-tab.on" } else { "button.k-tab" }).id(format!("{id}:tab:{i}")).tab().text(*l)
507    }))
508}
509
510/// A segmented control (one choice of a few, e.g. Dark / Light): hits `{id}:{i}`.
511pub fn segmented(id: &str, labels: &[&str], active: usize) -> El {
512    El::new("div.k-seg").id(id).children(labels.iter().enumerate().map(|(i, l)| {
513        El::new(if i == active { "button.k-seg-btn.on" } else { "button.k-seg-btn" }).id(format!("{id}:{i}")).tab().text(*l)
514    }))
515}
516
517/// The tab, segment, row or item index a hit id names (`{id}:{kind}:{i}`, or `{id}:{i}` for an empty `kind`).
518pub fn picked(id: &str, kind: &str, hit: &str) -> Option<usize> {
519    let rest = hit.strip_prefix(id)?.strip_prefix(':')?;
520    let rest = if kind.is_empty() { rest } else { rest.strip_prefix(kind)?.strip_prefix(':')? };
521    rest.parse().ok()
522}
523
524/// A list of rows (`div.k-li`, `.sel` for `selected`), each a main label and an optional
525/// muted side text; hits `{id}:row:{i}`.
526pub fn list(id: &str, rows: &[(&str, Option<&str>)], selected: Option<usize>) -> El {
527    El::new("div.k-list").id(id).children(rows.iter().enumerate().map(|(i, (main, side))| {
528        El::new(if selected == Some(i) { "div.k-li.sel" } else { "div.k-li" })
529            .id(format!("{id}:row:{i}"))
530            .tab()
531            .name(*main)
532            .child(El::new("div.k-li-main").text(*main))
533            .child_if(side.is_some(), || El::new("div.k-li-side").text(side.unwrap_or_default()))
534    }))
535}
536
537/// A table: a header row and data rows on one CSS grid track list (`columns`, e.g.
538/// `"1fr 80px"`); `num` columns align right. Rows are hits `{id}:row:{i}`, `.sel` for `selected`.
539pub fn table(id: &str, head: &[&str], columns: &str, num: &[usize], rows: &[Vec<String>], selected: Option<usize>) -> El {
540    let grid = format!("grid-template-columns: {columns}");
541    let cell = |c: usize, t: &str| El::new(if num.contains(&c) { "div.k-td.num" } else { "div.k-td" }).text(t);
542    let mut t = El::new("div.k-table").id(id).child(
543        El::new("div.k-tr.k-th").css(grid.clone()).children(head.iter().enumerate().map(|(c, h)| cell(c, h))),
544    );
545    for (i, r) in rows.iter().enumerate() {
546        t = t.child(
547            El::new(if selected == Some(i) { "div.k-tr.sel" } else { "div.k-tr" })
548                .id(format!("{id}:row:{i}"))
549                .tab()
550                .name(r.first().map(String::as_str).unwrap_or_default())
551                .css(grid.clone())
552                .children(r.iter().enumerate().map(|(c, v)| cell(c, v))),
553        );
554    }
555    t
556}
557
558/// One entry of a [`menu`].
559#[derive(Clone, Debug, Default, PartialEq)]
560pub struct MenuItem {
561    pub label: String,
562    /// An icon body ([`icons`]).
563    pub icon: Option<&'static str>,
564    /// A shortcut hint (`Ctrl+K`).
565    pub kbd: Option<String>,
566    /// Red (a destructive action).
567    pub danger: bool,
568    /// Greyed, not pickable (no hit id).
569    pub disabled: bool,
570    /// A divider line instead of an item.
571    pub separator: bool,
572}
573
574impl MenuItem {
575    pub fn new(label: impl Into<String>) -> Self {
576        MenuItem { label: label.into(), ..Default::default() }
577    }
578    pub fn separator() -> Self {
579        MenuItem { separator: true, ..Default::default() }
580    }
581    pub fn icon(mut self, body: &'static str) -> Self {
582        self.icon = Some(body);
583        self
584    }
585    pub fn kbd(mut self, k: impl Into<String>) -> Self {
586        self.kbd = Some(k.into());
587        self
588    }
589    pub fn danger(mut self, on: bool) -> Self {
590        self.danger = on;
591        self
592    }
593    pub fn disabled(mut self, on: bool) -> Self {
594        self.disabled = on;
595        self
596    }
597}
598
599/// A context menu / command list as a `position: fixed` box at `at` (viewport
600/// coordinates; see [`popover_at`]). Enabled items are hits `{id}:item:{i}` (`i` counts
601/// separators too, so it is the index into `items`).
602pub fn menu(id: &str, title: Option<&str>, items: &[MenuItem], at: Rect) -> El {
603    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));
604    if let Some(t) = title {
605        m = m.child(El::new("div.k-menu-title").text(t));
606    }
607    m.children(items.iter().enumerate().map(|(i, it)| {
608        if it.separator {
609            return El::new("div.k-sep");
610        }
611        let mut spec = String::from("div.k-mi");
612        if it.danger {
613            spec.push_str(".danger");
614        }
615        if it.disabled {
616            spec.push_str(".dis");
617        }
618        let mut row = El::new(spec).name(&it.label);
619        if let Some(ic) = it.icon {
620            row = row.child(El::new("span.k-mi-icon").svg(icon(ic)));
621        }
622        row = row.child(El::new("div.k-mi-label").text(&it.label));
623        if let Some(k) = &it.kbd {
624            row = row.child(kbd(k));
625        }
626        if !it.disabled {
627            row = row.id(format!("{id}:item:{i}")).tab();
628        }
629        row
630    }))
631}
632
633/// A keyboard shortcut hint (`span.k-kbd`).
634pub fn kbd(text: &str) -> El {
635    El::new("span.k-kbd").text(text)
636}
637
638/// A small status pill (`kind`: `""`, `ok`, `warn`, `error`, `muted`).
639pub fn badge(text: &str, kind: &str) -> El {
640    El::new(if kind.is_empty() { "span.k-badge".to_string() } else { format!("span.k-badge.{kind}") }).text(text)
641}
642
643/// A `w × h` box centred in `viewport` (where a [`dialog`] goes).
644pub fn centered(viewport: Rect, w: f64, h: f64) -> Rect {
645    let (w, h) = (w.min(viewport.width), h.min(viewport.height));
646    Rect::new(viewport.x + (viewport.width - w) / 2.0, viewport.y + (viewport.height - h) / 2.0, w, h)
647}
648
649/// A modal dialog at `at` over a full-viewport scrim (`{id}:scrim`, a hit so a click
650/// outside can close it), with a title, a close button (`{id}:close`), `body` and footer
651/// buttons `{id}:foot:{i}` (the first is `.primary`).
652pub fn dialog(id: &str, title: &str, body: El, footer: &[&str], at: Rect) -> El {
653    let foot = El::new("div.k-dialog-foot").children(footer.iter().enumerate().map(|(i, l)| {
654        El::new(if i == 0 { "button.k-btn.primary" } else { "button.k-btn" }).id(format!("{id}:foot:{i}")).tab().text(*l)
655    }));
656    El::new("div.k-modal")
657        .child(El::new("div.k-scrim").id(format!("{id}:scrim")))
658        .child(
659            El::new("div.k-dialog")
660                .id(id)
661                .name(title)
662                .css(format!("top: {}px; left: {}px; width: {}px; height: {}px", at.y, at.x, at.width, at.height))
663                .child(
664                    El::new("div.k-dialog-head")
665                        .child(El::new("div.k-dialog-title").text(title))
666                        .child(El::new("button.k-act").id(format!("{id}:close")).tab().name("Close").svg(icon(icons::CLOSE))),
667                )
668                .child(El::new("div.k-dialog-body").child(body))
669                .child_if(!footer.is_empty(), || foot),
670        )
671}
672
673/// A tooltip below `anchor` (fixed, viewport coordinates).
674pub fn tooltip(text: &str, anchor: Rect) -> El {
675    El::new("div.k-tip").text(text).css(format!("top: {}px; left: {}px", anchor.y + anchor.height + 6.0, anchor.x))
676}
677
678/// A toast stack in the bottom-right corner of the viewport: `(kind, text)` per toast
679/// (`kind` as for [`banner`]); each has a close hit `{id}:{i}:close`.
680pub fn toasts(id: &str, items: &[(&str, &str)]) -> El {
681    El::new("div.k-toasts").id(id).children(items.iter().enumerate().map(|(i, (kind, text))| {
682        El::new(if kind.is_empty() { "div.k-toast".to_string() } else { format!("div.k-toast.{kind}") })
683            .name(*text)
684            .child(El::new("div.k-toast-text").text(*text))
685            .child(El::new("button.k-act").id(format!("{id}:{i}:close")).tab().name("Close").svg(icon(icons::CLOSE)))
686    }))
687}
688
689/// A metric tile: a caption, a big value and a muted note.
690pub fn stat(id: &str, label: &str, value: &str, note: &str) -> El {
691    El::new("div.k-stat")
692        .id(id)
693        .name(label)
694        .child(El::new("div.k-stat-label").text(label))
695        .child(El::new("div.k-stat-value").text(value))
696        .child_if(!note.is_empty(), || El::new("div.k-stat-note").text(note))
697}
698
699/// A progress bar, `v` in 0 … 1.
700pub fn progress(v: f64) -> El {
701    let pct = (v.clamp(0.0, 1.0) * 100.0 * 10.0).round() / 10.0;
702    El::new("div.k-progress").child(El::new("div.k-bar").css(format!("width: {pct}%")))
703}
704
705/// A labelled form row: a small caption above `control`.
706pub fn field(label: &str, control: El) -> El {
707    El::new("div.k-field").child(El::new("div.k-field-label").text(label)).child(control)
708}
709
710/// Inline markdown to DOM runs: `**bold**`, `*italic*` / `_italic_`, `***both***`,
711/// `` `code` `` (verbatim), http(s) links (`a.link`, hit `url:…`) and `@nick` mentions
712/// (`a.mention`, hit `nick:…`). Unclosed markers stay literal; `_` only opens at a word
713/// start and closes at a word end (`snake_case` stays as is).
714pub fn inline_md(text: &str) -> Vec<Run> {
715    let cs: Vec<char> = text.chars().collect();
716    let mut out: Vec<Run> = Vec::new();
717    let (mut bold, mut ital) = (false, false);
718    let mut cur = String::new();
719    let flush = |out: &mut Vec<Run>, cur: &mut String, bold: bool, ital: bool| {
720        if cur.is_empty() {
721            return;
722        }
723        let spec = match (bold, ital) {
724            (true, true) => "b.i",
725            (true, false) => "b",
726            (false, true) => "i",
727            _ => "span",
728        };
729        for sp in crate::ui::widgets::composite::chat_thread::linkify(cur, "link", 400) {
730            let r = match crate::ui::widgets::composite::chat_thread::span_link(&sp) {
731                Some(crate::ui::widgets::composite::chat_thread::Link::Mention(n)) => Run::new("a.mention", sp.text.as_str()).id(format!("nick:{n}")),
732                Some(crate::ui::widgets::composite::chat_thread::Link::Url(u)) => Run::new("a.link", sp.text.as_str()).id(format!("url:{u}")),
733                None => Run::new(spec, sp.text.as_str()),
734            };
735            let r = if (bold || ital) && r.spec.starts_with('a') {
736                r.css(format!("{}{}", if bold { "font-weight: 700;" } else { "" }, if ital { "font-style: italic" } else { "" }))
737            } else if spec == "b.i" {
738                r.css("font-weight: 700; font-style: italic")
739            } else if spec == "i" {
740                r.css("font-style: italic")
741            } else if spec == "b" {
742                r.css("font-weight: 700")
743            } else {
744                r
745            };
746            out.push(r);
747        }
748        cur.clear();
749    };
750    let closes = |from: usize, pat: &[char]| -> bool {
751        let n = pat.len();
752        (from..cs.len().saturating_sub(n - 1)).any(|j| cs[j..j + n] == *pat && j > from)
753    };
754    let mut i = 0;
755    while i < cs.len() {
756        let c = cs[i];
757        if c == '`' {
758            if let Some(j) = (i + 1..cs.len()).find(|&j| cs[j] == '`') {
759                flush(&mut out, &mut cur, bold, ital);
760                let code: String = cs[i + 1..j].iter().collect();
761                if !code.is_empty() {
762                    out.push(Run::new("code", code));
763                }
764                i = j + 1;
765                continue;
766            }
767        }
768        if c == '*' && i + 1 < cs.len() && cs[i + 1] == '*' && (bold || closes(i + 2, &['*', '*'])) {
769            flush(&mut out, &mut cur, bold, ital);
770            bold = !bold;
771            i += 2;
772            continue;
773        }
774        if c == '*' && (ital || (i + 1 < cs.len() && !cs[i + 1].is_whitespace() && closes(i + 1, &['*']))) {
775            flush(&mut out, &mut cur, bold, ital);
776            ital = !ital;
777            i += 1;
778            continue;
779        }
780        if c == '_' {
781            let word_before = i > 0 && cs[i - 1].is_alphanumeric();
782            let word_after = i + 1 < cs.len() && cs[i + 1].is_alphanumeric();
783            let opens = !ital
784                && !word_before
785                && i + 1 < cs.len()
786                && !cs[i + 1].is_whitespace()
787                && (i + 2..cs.len()).any(|j| cs[j] == '_' && !cs[j - 1].is_whitespace() && (j + 1 == cs.len() || !cs[j + 1].is_alphanumeric()));
788            if opens || (ital && !word_after) {
789                flush(&mut out, &mut cur, bold, ital);
790                ital = !ital;
791                i += 1;
792                continue;
793            }
794        }
795        cur.push(c);
796        i += 1;
797    }
798    flush(&mut out, &mut cur, bold, ital);
799    out
800}
801
802/// A virtualized list: only the rows in (or near) the viewport are built and laid out;
803/// spacers stand for the rest. Row heights start at an estimate and are learned from
804/// laid-out rows ([`VirtualList::measure`]), so long chats stay cheap.
805#[derive(Clone, Debug, Default, PartialEq)]
806pub struct VirtualList {
807    heights: Vec<Option<f64>>,
808    /// Height of a row not measured yet.
809    pub estimate: f64,
810    /// Gap between rows.
811    pub gap: f64,
812}
813
814/// The rows a [`VirtualList`] shows and the space around them.
815#[derive(Clone, Copy, Debug, Default, PartialEq)]
816pub struct Window {
817    pub start: usize,
818    /// One past the last shown row.
819    pub end: usize,
820    /// Height of the spacer above the first shown row.
821    pub top: f64,
822    /// Height of the spacer below the last shown row.
823    pub bottom: f64,
824}
825
826impl VirtualList {
827    pub fn new(len: usize, estimate: f64) -> Self {
828        VirtualList { heights: vec![None; len], estimate, gap: 0.0 }
829    }
830    pub fn len(&self) -> usize {
831        self.heights.len()
832    }
833    pub fn is_empty(&self) -> bool {
834        self.heights.is_empty()
835    }
836    /// Grow or shrink to `n` rows (new rows unmeasured; kept rows keep their height).
837    pub fn set_len(&mut self, n: usize) {
838        self.heights.resize(n, None);
839    }
840    /// Forget a row's height (its content changed).
841    pub fn invalidate(&mut self, i: usize) {
842        if let Some(h) = self.heights.get_mut(i) {
843            *h = None;
844        }
845    }
846    fn h(&self, i: usize) -> f64 {
847        self.heights[i].unwrap_or(self.estimate)
848    }
849    /// Set row `i`'s height (a host that lays rows out itself, e.g. from a cache of
850    /// laid trees, reports them here instead of [`VirtualList::measure`]).
851    pub fn set_height(&mut self, i: usize, h: f64) {
852        if let Some(x) = self.heights.get_mut(i) {
853            *x = Some(h);
854        }
855    }
856    /// Row `i`'s measured height (`None`: not measured, the estimate stands in).
857    pub fn height(&self, i: usize) -> Option<f64> {
858        self.heights.get(i).copied().flatten()
859    }
860    /// Every row's top in list coordinates in one pass (`len() + 1` entries; the last
861    /// is the total without a trailing gap counted twice).
862    pub fn tops(&self) -> Vec<f64> {
863        let mut out = Vec::with_capacity(self.len() + 1);
864        let mut y = 0.0;
865        for i in 0..self.len() {
866            out.push(y);
867            y += self.h(i) + self.gap;
868        }
869        out.push(self.total());
870        out
871    }
872    /// The whole list's height (measured rows plus estimates).
873    pub fn total(&self) -> f64 {
874        (0..self.len()).map(|i| self.h(i)).sum::<f64>() + self.gap * self.len().saturating_sub(1) as f64
875    }
876    /// Top of row `i` in list coordinates.
877    pub fn offset_of(&self, i: usize) -> f64 {
878        (0..i.min(self.len())).map(|k| self.h(k) + self.gap).sum()
879    }
880    /// The row at list `y`.
881    pub fn index_at(&self, y: f64) -> usize {
882        let mut acc = 0.0;
883        for i in 0..self.len() {
884            acc += self.h(i) + self.gap;
885            if y < acc {
886                return i;
887            }
888        }
889        self.len().saturating_sub(1)
890    }
891    /// The rows covering `scroll .. scroll + view`, plus `overscan` pixels each way.
892    pub fn window(&self, scroll: f64, view: f64, overscan: f64) -> Window {
893        if self.is_empty() {
894            return Window::default();
895        }
896        let a = (scroll - overscan).max(0.0);
897        let b = scroll + view + overscan;
898        let start = self.index_at(a);
899        let mut end = start;
900        let mut y = self.offset_of(start);
901        while end < self.len() && y < b {
902            y += self.h(end) + self.gap;
903            end += 1;
904        }
905        let top = self.offset_of(start);
906        let bottom = (self.total() - self.offset_of(end)).max(0.0);
907        Window { start, end, top, bottom }
908    }
909    /// The list element: `container` holding spacers and the rows `row(i)` for `w`.
910    /// A container column `gap` must equal [`VirtualList::gap`] (spacers are emitted
911    /// only when they stand for rows, so the gap is not doubled).
912    pub fn el(&self, container: El, w: Window, mut row: impl FnMut(usize) -> El) -> El {
913        let mut c = container;
914        if w.start > 0 {
915            c = c.child(El::new("div.k-vspace").css(format!("height: {}px", (w.top - self.gap).max(0.0))));
916        }
917        for i in w.start..w.end {
918            c = c.child(row(i));
919        }
920        if w.end < self.len() {
921            c = c.child(El::new("div.k-vspace").css(format!("height: {}px", w.bottom)));
922        }
923        c
924    }
925    /// Learn the shown rows' heights from a laid-out tree: row `i`'s element has id
926    /// `id_of(i)`. Returns whether any height changed (re-lay out to settle).
927    pub fn measure(&mut self, dom: &Dom, w: Window, id_of: impl Fn(usize) -> String) -> bool {
928        let mut changed = false;
929        for i in w.start..w.end.min(self.len()) {
930            if let Some(r) = dom.rect(&id_of(i)) {
931                if self.heights[i].is_none_or(|h| (h - r.height).abs() > 0.25) {
932                    self.heights[i] = Some(r.height);
933                    changed = true;
934                }
935            }
936        }
937        changed
938    }
939}
940
941#[cfg(all(test, feature = "flow-flex"))]
942mod tests {
943    use super::*;
944    use crate::testing::NullRenderContext;
945    use crate::ui::dom::lay_out_in;
946    use crate::ui::style::State;
947
948    #[test]
949    fn markdown_bold_italic_code_links() {
950        let r = inline_md("a **b** *i* _u_ snake_case ***bi*** `x*y` see https://e.x @bob");
951        let specs: Vec<(&str, &str)> = r.iter().map(|r| (r.spec.as_str(), r.text.as_str())).collect();
952        assert!(specs.contains(&("b", "b")));
953        assert!(specs.contains(&("i", "i")));
954        assert!(specs.contains(&("i", "u")));
955        assert!(specs.contains(&("b.i", "bi")));
956        assert!(specs.contains(&("code", "x*y")));
957        assert!(specs.iter().any(|(s, t)| *s == "span" && t.contains("snake_case")));
958        assert!(r.iter().any(|r| r.spec == "a.link" && r.id.as_deref() == Some("url:https://e.x")));
959        assert!(r.iter().any(|r| r.spec == "a.mention" && r.id.as_deref() == Some("nick:bob")));
960        // unclosed markers stay literal
961        let r = inline_md("2 * 3 and *open");
962        assert_eq!(r.iter().map(|r| r.text.as_str()).collect::<String>(), "2 * 3 and *open");
963    }
964
965    #[test]
966    fn virtual_list_windows_and_learns() {
967        let mut v = VirtualList::new(1000, 40.0);
968        let w = v.window(4000.0, 400.0, 0.0);
969        assert_eq!((w.start, w.end), (100, 110));
970        assert_eq!(w.top, 4000.0);
971        assert_eq!(w.top + (w.end - w.start) as f64 * 40.0 + w.bottom, v.total());
972        let mut ctx = NullRenderContext::default();
973        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" }));
974        let dom = crate::ui::dom::lay_out(&mut ctx, &sheet(), &el, 0.0, 0.0, 300.0, &|_| State::NONE);
975        assert!(v.measure(&dom, w, |i| format!("r{i}")));
976        assert_eq!(v.total(), 990.0 * 40.0 + 5.0 * 60.0 + 5.0 * 40.0);
977        // Hosts that lay rows out themselves report heights directly.
978        let mut v = VirtualList::new(3, 10.0);
979        v.set_height(1, 30.0);
980        assert_eq!((v.height(0), v.height(1)), (None, Some(30.0)));
981        assert_eq!(v.tops(), vec![0.0, 10.0, 40.0, 50.0]);
982    }
983
984    #[test]
985    fn select_popover_is_fixed_and_skips_disabled() {
986        let opts = [SelectOpt::new("Auto").sub("follow the system"), SelectOpt::new("Dark"), SelectOpt::new("Light").disabled(true)];
987        let page = El::new("div.k-root")
988            .css("height: 2000px")
989            .child(select_trigger("theme", "Auto", true, "Theme"))
990            .child(select_popover("theme", &opts, Some(0), Rect::new(10.0, 50.0, 200.0, 120.0)));
991        let mut ctx = NullRenderContext::default();
992        let vp = Rect::new(0.0, 0.0, 800.0, 600.0);
993        let dom = lay_out_in(&mut ctx, &sheet(), &page, 0.0, 0.0, 800.0, Some(vp), &|_| State::NONE);
994        assert!(dom.rect("theme:opt:0").is_some() && dom.rect("theme:opt:1").is_some());
995        assert!(dom.rect("theme:opt:2").is_none());
996        let pop = dom.rect("theme:pop").unwrap();
997        assert_eq!((pop.x, pop.y, pop.width), (10.0, 50.0, 200.0));
998        // scrolling the page leaves the popover in place and on top
999        let moved = dom.clone().moved(0.0, -300.0);
1000        assert_eq!(moved.rect("theme:pop"), Some(pop));
1001        assert_eq!(moved.rect("theme").map(|r| r.y), dom.rect("theme").map(|r| r.y - 300.0));
1002        assert_eq!(moved.hit(20.0, 60.0), Some("theme:opt:0"));
1003        assert_eq!(picked_opt("theme", "theme:opt:1"), Some(1));
1004    }
1005
1006    #[test]
1007    fn select_list_windows_highlights_and_searches() {
1008        let opts: Vec<SelectOpt> = (0..20).map(|i| SelectOpt::new(format!("Zone {i}"))).collect();
1009        let view = ListView { hi: Some(6), top: 5, rows: 4, query: Some("zo"), row_h: 30.0 };
1010        let pop = select_list("tz", &opts, Some(7), &view, Rect::new(0.0, 0.0, 240.0, 200.0));
1011        let mut ctx = NullRenderContext::default();
1012        let vp = Rect::new(0.0, 0.0, 800.0, 600.0);
1013        let dom = lay_out_in(&mut ctx, &sheet(), &pop, 0.0, 0.0, 800.0, Some(vp), &|_| State::NONE);
1014        let shown: Vec<&str> = dom.hits().map(|(id, _)| id).filter(|id| id.starts_with("tz:opt:")).collect();
1015        assert_eq!(shown, ["tz:opt:5", "tz:opt:6", "tz:opt:7", "tz:opt:8"]);
1016        assert_eq!(dom.get("tz:opt:6").and_then(|p| p.style.background.as_deref()), Some("#33363d"));
1017        assert!(dom.get("tz:opt:5").is_some_and(|p| p.style.background.is_none()));
1018        let row = dom.rect("tz:opt:5").unwrap();
1019        assert!(row.y > 30.0, "below the search line");
1020        let none = select_list("tz", &[], None, &ListView { query: Some(""), ..ListView::all() }, Rect::new(0.0, 0.0, 240.0, 80.0));
1021        let dom = lay_out_in(&mut ctx, &sheet(), &none, 0.0, 0.0, 800.0, Some(vp), &|_| State::NONE);
1022        assert!(dom.hits().all(|(id, _)| !id.contains(":opt:")));
1023    }
1024
1025    #[test]
1026    fn controls_are_css_styled_and_named() {
1027        let page = El::new("div.k-root")
1028            .child(switch("wifi", true, "Wi-Fi"))
1029            .child(checkbox("agree", false, "I agree"))
1030            .child(input("q", Edit::new("hello").placeholder("Search").caret(5)))
1031            .child(spinner(0.3));
1032        let mut ctx = NullRenderContext::default();
1033        let dom = crate::ui::dom::lay_out(&mut ctx, &sheet(), &page, 0.0, 0.0, 400.0, &|_| State::NONE);
1034        let sw = dom.get("wifi").unwrap();
1035        assert_eq!((sw.rect.width, sw.rect.height), (36.0, 20.0));
1036        // :checked picked the accent background
1037        assert_eq!(sw.style.background.as_deref(), Some("#3b82f6"));
1038        // :focus while the input has a caret
1039        assert_eq!(dom.get("q").unwrap().style.border_color.as_deref(), Some("#3b82f6"));
1040        let a = dom.a11y();
1041        assert!(a.iter().any(|n| n.id == "wifi" && n.role == "switch" && n.name == "Wi-Fi" && n.checked == Some(true)));
1042        assert!(a.iter().any(|n| n.id == "q" && n.role == "textbox" && n.name == "hello"));
1043        assert!(a.iter().any(|n| n.id == "agree" && n.name == "I agree"));
1044        assert!(dom.get("q").unwrap().caret_rect().is_some());
1045    }
1046
1047    #[test]
1048    fn light_vars_retheme_the_whole_kit() {
1049        let page = |vars: &str| {
1050            El::new("div.k-root")
1051                .css(vars)
1052                .child(button("b", "Save"))
1053                .child(input("q", Edit::new("x")))
1054                .child(tabs("t", &["A", "B"], 1))
1055        };
1056        let mut ctx = NullRenderContext::default();
1057        let dark = crate::ui::dom::lay_out(&mut ctx, &sheet(), &page(theme_vars(true)), 0.0, 0.0, 400.0, &|_| State::NONE);
1058        let light = crate::ui::dom::lay_out(&mut ctx, &sheet(), &page(theme_vars(false)), 0.0, 0.0, 400.0, &|_| State::NONE);
1059        assert_eq!(dark.get("b").and_then(|p| p.style.background.as_deref()), Some("#2b2e34"));
1060        assert_eq!(light.get("b").and_then(|p| p.style.background.as_deref()), Some("#eceef2"));
1061        assert_eq!(light.get("q").and_then(|p| p.style.background.as_deref()), Some("#ffffff"));
1062        assert_eq!(light.get("t:tab:1").and_then(|p| p.style.color.as_deref()), Some("#1d1f24"));
1063        // No colour literal is left outside :root except the fixed bubble/link tints and knobs.
1064        for line in KIT_CSS.lines().filter(|l| !l.starts_with(":root") && !l.starts_with("        --")) {
1065            if line.contains("k-msg") || line.contains("k-body") || line.contains("k-banner") || line.contains("k-badge") || line.contains("k-toast") {
1066                continue;
1067            }
1068            let rest = line.replace("--knob: #ffffff", "").replace("--check: #ffffff", "");
1069            assert!(!rest.contains(": #") && !rest.contains(" #"), "hard-coded colour in {line}");
1070        }
1071    }
1072
1073    #[test]
1074    fn tabs_segmented_list_table_hits() {
1075        let rows = vec![vec!["alpha".to_string(), "7".to_string()], vec!["beta".to_string(), "14".to_string()]];
1076        let page = El::new("div.k-root")
1077            .child(tabs("tb", &["One", "Two", "Three"], 0))
1078            .child(segmented("theme", &["Dark", "Light"], 1))
1079            .child(list("ls", &[("alpha", Some("3")), ("beta", None)], Some(1)))
1080            .child(table("tt", &["Name", "Count"], "1fr 80px", &[1], &rows, Some(0)));
1081        let mut ctx = NullRenderContext::default();
1082        let dom = crate::ui::dom::lay_out(&mut ctx, &sheet(), &page, 0.0, 0.0, 400.0, &|_| State::NONE);
1083        let (a, b) = (dom.rect("tb:tab:0").unwrap(), dom.rect("tb:tab:2").unwrap());
1084        assert!(b.x > a.x && (a.y - b.y).abs() < 0.01, "tabs share a row");
1085        assert!(dom.get("theme:1").is_some_and(|p| p.style.background.as_deref() == Some("#3b82f6")));
1086        assert_eq!(picked("theme", "", "theme:1"), Some(1));
1087        assert_eq!(picked("tb", "tab", "tb:tab:2"), Some(2));
1088        assert_eq!(picked("tt", "row", "tb:tab:2"), None);
1089        assert!(dom.get("ls:row:1").is_some_and(|p| p.style.background.is_some()));
1090        // Table cells sit on the grid: the count column is 80px at the right.
1091        let row = dom.rect("tt:row:0").unwrap();
1092        assert!(row.height >= 30.0);
1093        assert!(dom.get("tt:row:0").is_some_and(|p| p.style.background.is_some()), ".sel row tinted");
1094    }
1095
1096    #[test]
1097    fn menu_dialog_toasts_are_fixed_layers() {
1098        let vp = Rect::new(0.0, 0.0, 800.0, 600.0);
1099        let items = [MenuItem::new("Rename").kbd("F2"), MenuItem::separator(), MenuItem::new("Locked").disabled(true), MenuItem::new("Delete").danger(true)];
1100        let page = El::new("div.k-root")
1101            .css("height: 2000px")
1102            .child(menu("m", Some("Row"), &items, Rect::new(100.0, 100.0, 200.0, 0.0)))
1103            .child(dialog("d", "Details", El::new("div").text("Body"), &["OK", "Cancel"], centered(vp, 360.0, 200.0)))
1104            .child(toasts("ts", &[("ok", "Saved"), ("", "Synced")]))
1105            .child(tooltip("Saves the name", Rect::new(10.0, 10.0, 80.0, 30.0)));
1106        let mut ctx = NullRenderContext::default();
1107        let dom = lay_out_in(&mut ctx, &sheet(), &page, 0.0, 0.0, 800.0, Some(vp), &|_| State::NONE);
1108        assert!(dom.rect("m:item:0").is_some() && dom.rect("m:item:3").is_some());
1109        assert!(dom.rect("m:item:2").is_none(), "disabled item is not a hit");
1110        assert_eq!(dom.rect("m:menu").map(|r| (r.x, r.y)), Some((100.0, 100.0)));
1111        let d = dom.rect("d").unwrap();
1112        assert_eq!((d.x, d.y, d.width, d.height), (220.0, 200.0, 360.0, 200.0));
1113        assert_eq!(dom.rect("d:scrim"), Some(vp), "scrim covers the viewport");
1114        // The dialog is above the scrim, the scrim above the page.
1115        assert_eq!(dom.hit(400.0, 300.0).map(|s| s.starts_with("d")), Some(true));
1116        assert_eq!(dom.hit(10.0, 590.0), Some("d:scrim"));
1117        let t = dom.rect("ts").unwrap();
1118        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:?}");
1119        assert!(dom.rect("ts:1:close").is_some());
1120        let moved = dom.clone().moved(0.0, -500.0);
1121        assert_eq!(moved.rect("d"), Some(d), "fixed layers do not scroll");
1122    }
1123
1124    #[test]
1125    fn stat_progress_badge_field() {
1126        let page = El::new("div.k-root").css("width: 300px")
1127            .child(stat("s", "FRAMES", "1 204", "+12 / s"))
1128            .child(progress(0.25))
1129            .child(badge("live", "ok"))
1130            .child(field("Name", input("n", Edit::new(""))));
1131        let mut ctx = NullRenderContext::default();
1132        let dom = crate::ui::dom::lay_out(&mut ctx, &sheet(), &page, 0.0, 0.0, 300.0, &|_| State::NONE);
1133        assert!(dom.rect("s").is_some_and(|r| r.height > 40.0));
1134        let bar = dom.boxes.iter().find(|b| b.style.background.as_deref() == Some("#3b82f6") && b.rect.height == 6.0).expect("bar");
1135        assert!((bar.rect.width - 75.0).abs() < 0.5, "25% of 300: {:?}", bar.rect);
1136        assert!(dom.rect("n").is_some());
1137    }
1138
1139    #[test]
1140    fn coarse_pointer_grows_targets_to_touch_size() {
1141        use crate::ui::media::{Edges, MediaEnv};
1142        let css = [KIT_CSS, KIT_TOUCH_CSS].concat();
1143        let touch = Sheet::parse_with(&css, &MediaEnv::touch(390.0, 844.0, Edges::ZERO)).unwrap();
1144        let mouse = Sheet::parse_with(&css, &MediaEnv::default()).unwrap();
1145        assert_eq!(mouse.el("div.k-li").height, Some(30.0));
1146        assert_eq!(touch.el("div.k-li").height, Some(48.0));
1147        assert_eq!(touch.el("div.k-input").height, Some(44.0));
1148        assert_eq!(touch.el("select.k-select").height, Some(44.0));
1149        assert_eq!(touch.el("button.k-btn").min_height, Some(44.0));
1150        assert_eq!(mouse.el("button.k-btn").min_height, None);
1151        // The look is the same: colours come from KIT_CSS in both.
1152        assert_eq!(touch.el("button.k-btn").background, mouse.el("button.k-btn").background);
1153    }
1154
1155}