1use super::dom::{Control, Dom, Edit, El, Run};
43use super::style::{Sheet, StyleError};
44use crate::types::Rect;
45
46pub 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
206pub 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
229pub 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
258pub 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
265pub fn theme_vars(dark: bool) -> &'static str {
267 if dark {
268 ""
269 } else {
270 LIGHT_VARS
271 }
272}
273
274pub fn sheet() -> Sheet {
276 Sheet::parse(&[KIT_CSS, KIT_TOUCH_CSS].concat()).expect("KIT_CSS parses")
277}
278
279pub fn sheet_with(app_css: &str) -> Result<Sheet, StyleError> {
281 Sheet::parse(&[KIT_CSS, KIT_TOUCH_CSS, app_css].concat())
282}
283
284pub 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
289pub 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
325pub fn button(id: &str, label: &str) -> El {
327 El::new("button.k-btn").id(id).tab().text(label)
328}
329
330pub 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
335pub 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
340pub 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
345pub 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
361pub 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
366pub fn spinner(t: f64) -> El {
368 El::new("span.k-spinner").name("Loading").control(Control::spinner(t))
369}
370
371pub fn input(id: &str, edit: Edit) -> El {
373 El::new("div.k-input").id(id).tab().control(Control::input(edit))
374}
375
376#[derive(Clone, Copy, Debug, PartialEq)]
382#[non_exhaustive]
383pub struct NumberSpec {
384 pub min: Option<f64>,
386 pub max: Option<f64>,
388 pub step: f64,
390 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 pub fn new() -> Self {
403 Self::default()
404 }
405 pub fn integer() -> Self {
407 NumberSpec { decimals: Some(0), ..Self::default() }
408 }
409 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 pub fn min(mut self, v: f64) -> Self {
417 self.min = Some(v);
418 self
419 }
420 pub fn max(mut self, v: f64) -> Self {
422 self.max = Some(v);
423 self
424 }
425 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 pub fn decimals(mut self, n: u32) -> Self {
434 self.decimals = Some(n);
435 self
436 }
437
438 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 pub fn sanitize(&self, text: &str) -> String {
446 text.chars().filter(|c| self.accepts(*c)).collect()
447 }
448
449 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 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 pub fn format(&self, v: f64) -> String {
465 match self.decimals {
466 Some(n) => format!("{v:.*}", n as usize),
467 None => {
468 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 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 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
502pub 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#[derive(Clone, Debug, Default, PartialEq)]
517pub struct SelectOpt {
518 pub label: String,
519 pub sub: Option<String>,
521 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
539pub 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
544pub 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
555pub 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#[derive(Clone, Copy, Debug, PartialEq)]
565pub struct ListView<'a> {
566 pub hi: Option<usize>,
568 pub top: usize,
570 pub rows: usize,
572 pub query: Option<&'a str>,
574 pub row_h: f64,
576}
577
578impl ListView<'_> {
579 pub fn all() -> Self {
581 ListView { hi: None, top: 0, rows: usize::MAX, query: None, row_h: 0.0 }
582 }
583}
584
585pub 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
634pub fn picked_opt(id: &str, hit: &str) -> Option<usize> {
636 hit.strip_prefix(id)?.strip_prefix(":opt:")?.parse().ok()
637}
638
639pub 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
652pub 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
658pub 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
669pub 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
674pub 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
687pub 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
700pub 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
706pub 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
713pub 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
720pub 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
727pub 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
740pub 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#[derive(Clone, Debug, Default, PartialEq)]
763pub struct MenuItem {
764 pub label: String,
765 pub icon: Option<&'static str>,
767 pub kbd: Option<String>,
769 pub danger: bool,
771 pub disabled: bool,
773 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
802pub 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
838#[non_exhaustive]
839pub enum ToolKind {
840 #[default]
842 Button,
843 Split,
846 Separator,
848 Fill,
850}
851
852#[derive(Clone, Debug, Default)]
854#[non_exhaustive]
855pub struct ToolItem {
856 pub kind: ToolKind,
857 pub key: String,
859 pub icon: Option<String>,
861 pub label: Option<String>,
862 pub name: Option<String>,
864 pub on: bool,
866 pub disabled: bool,
868}
869
870impl ToolItem {
871 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 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 pub fn separator() -> Self {
881 ToolItem { kind: ToolKind::Separator, ..Self::default() }
882 }
883 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
905pub 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
946pub 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
959pub 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
972pub fn kbd(text: &str) -> El {
974 El::new("span.k-kbd").text(text)
975}
976
977pub 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
982pub 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
988pub 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
1012pub 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
1017pub 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
1028pub 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
1038pub 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
1044pub 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
1049pub 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#[derive(Clone, Debug, Default, PartialEq)]
1145pub struct VirtualList {
1146 heights: Vec<Option<f64>>,
1147 pub estimate: f64,
1149 pub gap: f64,
1151}
1152
1153#[derive(Clone, Copy, Debug, Default, PartialEq)]
1155pub struct Window {
1156 pub start: usize,
1157 pub end: usize,
1159 pub top: f64,
1161 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 pub fn set_len(&mut self, n: usize) {
1177 self.heights.resize(n, None);
1178 }
1179 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 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 pub fn height(&self, i: usize) -> Option<f64> {
1197 self.heights.get(i).copied().flatten()
1198 }
1199 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 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 pub fn offset_of(&self, i: usize) -> f64 {
1217 (0..i.min(self.len())).map(|k| self.h(k) + self.gap).sum()
1218 }
1219 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 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 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 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 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 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 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 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 assert_eq!(sw.style.background.as_deref(), Some("#3b82f6"));
1491 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 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 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 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 assert_eq!(touch.el("button.k-btn").background, mouse.el("button.k-btn").background);
1606 }
1607
1608}