1#![allow(non_snake_case)]
4
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::Mutex;
7use strata_dom::{NodeBlueprint, Signal, View};
8use strata_icons::prelude::{Icon, IconName};
9use strata_macro::{component, rsx};
10
11use crate::primitives::{DismissableLayer, FocusTrap};
12
13pub fn count_focusable_elements(nodes: &[NodeBlueprint]) -> usize {
15 let mut count = 0;
16 for node in nodes {
17 match node {
18 NodeBlueprint::Element {
19 tag,
20 attributes,
21 children,
22 ..
23 } => {
24 let is_focusable_tag = matches!(
25 tag,
26 strata_dom::Tag::Button
27 | strata_dom::Tag::Input
28 | strata_dom::Tag::Select
29 | strata_dom::Tag::Textarea
30 | strata_dom::Tag::A
31 );
32 let has_tabindex = attributes.iter().any(|a| match a {
33 strata_dom::Attribute::Property { key, value } => {
34 key == "tabindex" && value != "-1"
35 }
36 _ => false,
37 });
38 if is_focusable_tag || has_tabindex {
39 count += 1;
40 }
41 count += count_focusable_elements(children);
42 }
43 NodeBlueprint::Fragment(children) => {
44 count += count_focusable_elements(children);
45 }
46 _ => {}
47 }
48 }
49 count
50}
51
52#[component]
54pub fn Modal(
55 open: Signal<bool>,
56 title: &'static str,
57 description: Option<&'static str>,
58 children: Option<Vec<NodeBlueprint>>,
59 class: Option<&'static str>,
60) -> View {
61 if !open.get() {
62 return rsx! { <></> };
63 }
64
65 let op = open.clone();
66 let op_backdrop = open.clone();
67 let op_key = open.clone();
68 let custom = class.unwrap_or("");
69
70 static MODAL_COUNTER: AtomicU64 = AtomicU64::new(1);
71 let modal_id = MODAL_COUNTER.fetch_add(1, Ordering::Relaxed);
72 let title_id = format!("strata-modal-title-{modal_id}");
73 let desc_id = format!("strata-modal-desc-{modal_id}");
74
75 let inner_children = children.unwrap_or_default();
76 let child_focus_count = count_focusable_elements(&inner_children);
77 let total_focusable = (1 + child_focus_count).max(1);
78
79 let focus_trap = std::rc::Rc::new(std::cell::RefCell::new(FocusTrap::new(total_focusable)));
80 let trap_clone = focus_trap.clone();
81
82 let on_keydown = move |e: strata_dom::Event| {
83 if DismissableLayer::should_dismiss_on_escape(&e.key)
84 || DismissableLayer::should_dismiss_on_escape(&e.code)
85 {
86 op_key.set(false);
87 e.prevent_default();
88 e.stop_propagation();
89 } else if e.key == "Tab" {
90 e.prevent_default();
91 e.stop_propagation();
92 let mut trap = trap_clone.borrow_mut();
93 if e.shift_key {
94 trap.prev();
95 } else {
96 trap.next();
97 }
98 }
99 };
100
101 rsx! {
102 <div
103 class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4 animate-in fade-in duration-200"
104 role="dialog"
105 aria-modal="true"
106 aria-labelledby={title_id.clone()}
107 aria-describedby={if description.is_some() { desc_id.clone() } else { String::new() }}
108 tabindex="0"
109 data-focus-trap="true"
110 onkeydown={on_keydown}
111 >
112 <div
113 class="fixed inset-0"
114 onclick={move |_| op_backdrop.set(false)}
115 />
116 <div class={format!("relative z-10 w-full max-w-lg rounded-2xl bg-neutral-900 border border-neutral-800 shadow-2xl p-6 flex flex-col gap-5 {}", custom)}>
117 <div class="flex items-start justify-between border-b border-neutral-800/80 pb-4">
118 <div class="flex flex-col gap-1">
119 <h2 id={title_id} class="text-lg font-bold text-white tracking-tight">{title}</h2>
120 {if let Some(desc) = description {
121 rsx! { <p id={desc_id} class="text-xs text-neutral-400">{desc}</p> }
122 } else {
123 rsx! { <></> }
124 }}
125 </div>
126 <button
127 type="button"
128 class="text-neutral-400 hover:text-white p-1 rounded-lg hover:bg-neutral-800/60 transition-colors cursor-pointer select-none"
129 onclick={move |_| op.set(false)}
130 aria-label="Close dialog"
131 >
132 {Icon(IconName::X, Some("w-4 h-4 text-current")).root}
133 </button>
134 </div>
135 <div class="text-sm text-neutral-300">
136 {inner_children}
137 </div>
138 </div>
139 </div>
140 }
141}
142
143#[component]
145pub fn Drawer(
146 open: Signal<bool>,
147 side: Option<&'static str>,
148 title: Option<&'static str>,
149 children: Option<Vec<NodeBlueprint>>,
150 class: Option<&'static str>,
151) -> View {
152 if !open.get() {
153 return rsx! { <></> };
154 }
155
156 let op = open.clone();
157 let op_backdrop = open.clone();
158 let op_key = open.clone();
159 let s = side.unwrap_or("right");
160
161 static DRAWER_COUNTER: AtomicU64 = AtomicU64::new(1);
162 let drawer_id = DRAWER_COUNTER.fetch_add(1, Ordering::Relaxed);
163 let title_id = format!("strata-drawer-title-{drawer_id}");
164
165 let inner_children = children.unwrap_or_default();
166 let child_focus_count = count_focusable_elements(&inner_children);
167 let total_focusable = (1 + child_focus_count).max(1);
168
169 let focus_trap = std::rc::Rc::new(std::cell::RefCell::new(FocusTrap::new(total_focusable)));
170 let trap_clone = focus_trap.clone();
171
172 let on_keydown = move |e: strata_dom::Event| {
173 if DismissableLayer::should_dismiss_on_escape(&e.key)
174 || DismissableLayer::should_dismiss_on_escape(&e.code)
175 {
176 op_key.set(false);
177 e.prevent_default();
178 e.stop_propagation();
179 } else if e.key == "Tab" {
180 e.prevent_default();
181 e.stop_propagation();
182 let mut trap = trap_clone.borrow_mut();
183 if e.shift_key {
184 trap.prev();
185 } else {
186 trap.next();
187 }
188 }
189 };
190
191 let placement_classes = match s {
192 "left" => "top-0 bottom-0 left-0 w-80 border-r",
193 "top" => "top-0 left-0 right-0 h-80 border-b",
194 "bottom" => "bottom-0 left-0 right-0 h-80 border-t",
195 _ => "top-0 bottom-0 right-0 w-80 border-l",
196 };
197
198 let custom = class.unwrap_or("");
199
200 rsx! {
201 <div
202 class="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm"
203 role="dialog"
204 aria-modal="true"
205 aria-labelledby={if title.is_some() { title_id.clone() } else { String::new() }}
206 tabindex="0"
207 data-focus-trap="true"
208 onkeydown={on_keydown}
209 >
210 <div
211 class="fixed inset-0"
212 onclick={move |_| op_backdrop.set(false)}
213 />
214 <div class={format!("fixed z-10 bg-neutral-900 border-neutral-800 shadow-2xl p-6 flex flex-col gap-4 overflow-y-auto {} {}", placement_classes, custom)}>
215 <div class="flex items-center justify-between border-b border-neutral-800 pb-3">
216 {if let Some(t) = title {
217 rsx! { <h3 id={title_id} class="text-base font-semibold text-white">{t}</h3> }
218 } else {
219 rsx! { <></> }
220 }}
221 <button
222 type="button"
223 class="text-neutral-400 hover:text-white cursor-pointer select-none"
224 onclick={move |_| op.set(false)}
225 aria-label="Close drawer"
226 >
227 {Icon(IconName::X, Some("w-4 h-4 text-current")).root}
228 </button>
229 </div>
230 <div class="flex-1 text-sm text-neutral-300">
231 {inner_children}
232 </div>
233 </div>
234 </div>
235 }
236}
237
238#[component]
240pub fn Tooltip(
241 content: &'static str,
242 children: Option<Vec<NodeBlueprint>>,
243 class: Option<&'static str>,
244) -> View {
245 let custom = class.unwrap_or("");
246 rsx! {
247 <div class="relative group inline-flex">
248 {children.unwrap_or_default()}
249 <div class={format!("absolute bottom-full left-1/2 -translate-x-1/2 mb-2 hidden group-hover:flex items-center px-2.5 py-1 rounded-md bg-neutral-800 border border-neutral-700 text-xs font-medium text-white shadow-lg pointer-events-none whitespace-nowrap z-50 {}", custom)}>
250 {content}
251 </div>
252 </div>
253 }
254}
255
256#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
258pub enum AlertVariant {
259 #[default]
260 Info,
261 Success,
262 Warning,
263 Destructive,
264}
265
266#[component]
268pub fn Alert(
269 variant: Option<AlertVariant>,
270 title: &'static str,
271 description: Option<&'static str>,
272 children: Option<Vec<NodeBlueprint>>,
273 class: Option<&'static str>,
274) -> View {
275 let var = variant.unwrap_or_default();
276 let (border, bg, text, icon) = match var {
277 AlertVariant::Info => (
278 "border-indigo-500/20",
279 "bg-indigo-500/10",
280 "text-indigo-400",
281 IconName::Info,
282 ),
283 AlertVariant::Success => (
284 "border-emerald-500/20",
285 "bg-emerald-500/10",
286 "text-emerald-400",
287 IconName::CheckCircle2,
288 ),
289 AlertVariant::Warning => (
290 "border-amber-500/20",
291 "bg-amber-500/10",
292 "text-amber-400",
293 IconName::AlertTriangle,
294 ),
295 AlertVariant::Destructive => (
296 "border-rose-500/20",
297 "bg-rose-500/10",
298 "text-rose-400",
299 IconName::AlertOctagon,
300 ),
301 };
302
303 let custom = class.unwrap_or("");
304
305 rsx! {
306 <div class={format!("w-full rounded-xl border p-4 flex gap-3.5 {} {} {}", border, bg, custom)}>
307 <div class={format!("flex-shrink-0 mt-0.5 {}", text)}>
308 {Icon(icon, Some("w-5 h-5 text-current")).root}
309 </div>
310 <div class="flex flex-col gap-1 flex-1">
311 <h4 class={format!("text-sm font-semibold {}", text)}>{title}</h4>
312 {if let Some(desc) = description {
313 rsx! { <p class="text-xs text-neutral-300 leading-relaxed">{desc}</p> }
314 } else {
315 rsx! { <></> }
316 }}
317 {children.unwrap_or_default()}
318 </div>
319 </div>
320 }
321}
322
323#[component]
325pub fn Progress(value: Option<f32>, class: Option<&'static str>) -> View {
326 let custom = class.unwrap_or("");
327 let base = "w-full h-2 rounded-full bg-neutral-800 overflow-hidden relative";
328
329 rsx! {
330 <div class={format!("{} {}", base, custom)}>
331 {if let Some(val) = value {
332 let clamped = val.clamp(0.0, 100.0);
333 rsx! {
334 <div
335 class="h-full bg-indigo-600 rounded-full transition-all duration-300"
336 style={format!("width: {clamped:.1}%;")}
337 />
338 }
339 } else {
340 rsx! {
341 <div class="h-full w-1/3 bg-indigo-600 rounded-full animate-pulse" />
342 }
343 }}
344 </div>
345 }
346}
347
348#[component]
350pub fn Spinner(size: Option<&'static str>, class: Option<&'static str>) -> View {
351 let sz = size.unwrap_or("w-5 h-5");
352 let custom = class.unwrap_or("text-indigo-500");
353
354 rsx! {
355 <div class={format!("animate-spin {}", custom)}>
356 {Icon(IconName::Loader2, Some(sz)).root}
357 </div>
358 }
359}
360
361#[component]
363pub fn Skeleton(class: Option<&'static str>) -> View {
364 let custom = class.unwrap_or("w-full h-4");
365 rsx! {
366 <div class={format!("rounded-lg bg-neutral-800/80 animate-pulse {}", custom)} />
367 }
368}
369
370#[component]
372pub fn EmptyState(
373 icon: Option<IconName>,
374 title: &'static str,
375 description: Option<&'static str>,
376 children: Option<Vec<NodeBlueprint>>,
377 class: Option<&'static str>,
378) -> View {
379 let ic = icon.unwrap_or(IconName::Box);
380 let custom = class.unwrap_or("");
381
382 rsx! {
383 <div class={format!("flex flex-col items-center justify-center p-8 text-center rounded-2xl border border-dashed border-neutral-800 bg-neutral-900/40 gap-3 {}", custom)}>
384 <div class="p-3 rounded-xl bg-neutral-800/60 text-neutral-400">
385 {Icon(ic, Some("w-8 h-8 text-current")).root}
386 </div>
387 <div class="flex flex-col gap-1 max-w-sm">
388 <h3 class="text-sm font-semibold text-white">{title}</h3>
389 {if let Some(desc) = description {
390 rsx! { <p class="text-xs text-neutral-400 leading-relaxed">{desc}</p> }
391 } else {
392 rsx! { <></> }
393 }}
394 </div>
395 {if let Some(ch) = children {
396 rsx! { <div class="mt-2 flex items-center gap-2">{ch}</div> }
397 } else {
398 rsx! { <></> }
399 }}
400 </div>
401 }
402}
403
404#[derive(Debug, Clone, Copy, PartialEq, Eq)]
406pub enum ToastKind {
407 Success,
408 Error,
409 Warning,
410 Info,
411}
412
413#[derive(Debug, Clone, PartialEq, Eq)]
415pub struct ToastMessage {
416 pub id: u64,
417 pub kind: ToastKind,
418 pub title: String,
419 pub description: Option<String>,
420}
421
422static TOAST_ID_GEN: AtomicU64 = AtomicU64::new(1);
423static TOAST_QUEUE: Mutex<Vec<ToastMessage>> = Mutex::new(Vec::new());
424
425pub struct Toast;
427
428impl Toast {
429 pub fn success(title: impl Into<String>) -> u64 {
430 Self::push(ToastKind::Success, title, None)
431 }
432
433 pub fn error(title: impl Into<String>) -> u64 {
434 Self::push(ToastKind::Error, title, None)
435 }
436
437 pub fn warning(title: impl Into<String>) -> u64 {
438 Self::push(ToastKind::Warning, title, None)
439 }
440
441 pub fn info(title: impl Into<String>) -> u64 {
442 Self::push(ToastKind::Info, title, None)
443 }
444
445 pub fn push(kind: ToastKind, title: impl Into<String>, description: Option<String>) -> u64 {
446 let id = TOAST_ID_GEN.fetch_add(1, Ordering::Relaxed);
447 let msg = ToastMessage {
448 id,
449 kind,
450 title: title.into(),
451 description,
452 };
453 if let Ok(mut q) = TOAST_QUEUE.lock() {
454 q.push(msg);
455 }
456 id
457 }
458
459 pub fn dismiss(id: u64) {
460 if let Ok(mut q) = TOAST_QUEUE.lock() {
461 q.retain(|m| m.id != id);
462 }
463 }
464
465 pub fn get_all() -> Vec<ToastMessage> {
466 if let Ok(q) = TOAST_QUEUE.lock() {
467 q.clone()
468 } else {
469 Vec::new()
470 }
471 }
472
473 pub fn clear() {
474 if let Ok(mut q) = TOAST_QUEUE.lock() {
475 q.clear();
476 }
477 }
478}
479
480#[component]
482pub fn ToastContainer(class: Option<&'static str>) -> View {
483 let items = Toast::get_all();
484 let custom = class.unwrap_or("bottom-4 right-4");
485
486 rsx! {
487 <div class={format!("fixed z-50 flex flex-col gap-2 pointer-events-none {}", custom)}>
488 {items.into_iter().map(|item| {
489 let (border, icon, text_color) = match item.kind {
490 ToastKind::Success => ("border-emerald-500/20 bg-emerald-950/60", IconName::CheckCircle2, "text-emerald-400"),
491 ToastKind::Error => ("border-rose-500/20 bg-rose-950/60", IconName::AlertOctagon, "text-rose-400"),
492 ToastKind::Warning => ("border-amber-500/20 bg-amber-950/60", IconName::AlertTriangle, "text-amber-400"),
493 ToastKind::Info => ("border-indigo-500/20 bg-indigo-950/60", IconName::Info, "text-indigo-400"),
494 };
495 let id = item.id;
496 rsx! {
497 <div class={format!("pointer-events-auto flex items-center gap-3 px-4 py-3 rounded-xl border backdrop-blur-md shadow-2xl min-w-[280px] max-w-sm text-sm text-white animate-in slide-in-from-bottom-2 {}", border)}>
498 <span class={text_color}>
499 {Icon(icon, Some("w-4 h-4 text-current")).root}
500 </span>
501 <div class="flex-1 flex flex-col">
502 <span class="font-medium">{item.title}</span>
503 {if let Some(desc) = item.description {
504 rsx! { <span class="text-xs text-neutral-400">{desc}</span> }
505 } else {
506 rsx! { <></> }
507 }}
508 </div>
509 <button
510 type="button"
511 class="text-neutral-400 hover:text-white cursor-pointer"
512 onclick={move |_| Toast::dismiss(id)}
513 >
514 {Icon(IconName::X, Some("w-3.5 h-3.5 text-current")).root}
515 </button>
516 </div>
517 }
518 })}
519 </div>
520 }
521}