1use std::cell::RefCell;
18use std::collections::HashMap;
19use std::rc::Rc;
20use std::sync::Arc;
21
22use crux_core::{App, Core, Request};
23use leptos::prelude::*;
24use mobiler_core::{
25 A11yRole, Action, BoxAlign, ButtonStyle, CardStyle, ChartBracket, ChartLegendItem, ChartRefLine, ChartRegion,
26 ChartSeries, ChartStyle, ChartTick, Corner, Density, Effect, FieldKind, FontFamily, HttpHeader, HttpOutcome, Icon,
27 ImageRatio, ImageShape, InputValue, PluginCall, PluginNotify, PluginResponse, PluginStreamCall, ProjectColor,
28 Rgb, ShellLabels, Spacing, TextStyle, Theme, Tone, TransferEvent, Widget,
29};
30use wasm_bindgen_futures::spawn_local;
31
32const STYLE: &str = include_str!("mobiler.css");
38
39type Dispatch = Arc<dyn Fn(Action) + Send + Sync>;
42
43pub trait WebApp:
47 App<Event = Action, ViewModel = Widget, Effect = Effect> + Default + Send + Sync + 'static
48where
49 Self::Model: Default + Send + Sync,
50{
51}
52impl<T> WebApp for T
53where
54 T: App<Event = Action, ViewModel = Widget, Effect = Effect> + Default + Send + Sync + 'static,
55 T::Model: Default + Send + Sync,
56{
57}
58
59pub fn run<A: WebApp>()
61where
62 A::Model: Default + Send + Sync,
63{
64 console_error_panic_hook::set_once();
65 inject_default_style();
66 inject_hls_support();
67 inject_maplibre_support();
68 leptos::mount::mount_to_body(shell::<A>);
69}
70
71fn inject_hls_support() {
81 const BOOTSTRAP: &str = r#"(function(){
82 function ensureHls(cb){
83 if(window.Hls){return cb();}
84 if(window.__mobilerHlsLoading){(window.__mobilerHlsCbs=window.__mobilerHlsCbs||[]).push(cb);return;}
85 window.__mobilerHlsLoading=true;window.__mobilerHlsCbs=[cb];
86 var s=document.createElement('script');
87 s.src='https://cdn.jsdelivr.net/npm/hls.js@1';
88 var flush=function(){var cbs=window.__mobilerHlsCbs||[];window.__mobilerHlsCbs=[];cbs.forEach(function(f){f();});};
89 s.onload=flush;s.onerror=flush;
90 document.head.appendChild(s);
91 }
92 function attach(v){
93 if(v.__mobilerHlsDone){return;}v.__mobilerHlsDone=true;
94 var url=v.getAttribute('data-hls-src');if(!url){return;}
95 if(v.canPlayType('application/vnd.apple.mpegurl')){v.src=url;return;}
96 ensureHls(function(){
97 if(window.Hls&&window.Hls.isSupported()){var h=new window.Hls();h.loadSource(url);h.attachMedia(v);v.__mobilerHls=h;}
98 else{v.src=url;}
99 });
100 }
101 function scan(root){if(root&&root.querySelectorAll){root.querySelectorAll('video[data-hls-src]').forEach(attach);}}
102 new MutationObserver(function(muts){muts.forEach(function(m){m.addedNodes.forEach(function(n){if(n.nodeType===1){if(n.matches&&n.matches('video[data-hls-src]')){attach(n);}scan(n);}});});}).observe(document.documentElement,{childList:true,subtree:true});
103 scan(document);
104})();"#;
105 let document = leptos::prelude::document();
106 let Some(head) = document.head() else { return };
107 let Ok(script) = document.create_element("script") else { return };
108 script.set_text_content(Some(BOOTSTRAP));
109 let _ = head.append_child(&script);
110}
111
112fn inject_maplibre_support() {
121 const BOOTSTRAP: &str = r#"(function(){
122 function ensureML(cb){
123 if(window.maplibregl){return cb();}
124 if(window.__mobilerMlLoading){(window.__mobilerMlCbs=window.__mobilerMlCbs||[]).push(cb);return;}
125 window.__mobilerMlLoading=true;window.__mobilerMlCbs=[cb];
126 var l=document.createElement('link');l.rel='stylesheet';l.href='https://cdn.jsdelivr.net/npm/maplibre-gl@4/dist/maplibre-gl.css';document.head.appendChild(l);
127 var s=document.createElement('script');s.src='https://cdn.jsdelivr.net/npm/maplibre-gl@4/dist/maplibre-gl.js';
128 var flush=function(){var cbs=window.__mobilerMlCbs||[];window.__mobilerMlCbs=[];cbs.forEach(function(f){f();});};
129 s.onload=flush;s.onerror=flush;document.head.appendChild(s);
130 }
131 function emit(el,payload){
132 var sink=el.parentElement&&el.parentElement.querySelector('.mobiler-map-sink');
133 if(sink){sink.value=payload;sink.dispatchEvent(new Event('input',{bubbles:true}));}
134 }
135 function init(el){
136 if(el.__mobilerMap){return;}el.__mobilerMap=true;
137 ensureML(function(){
138 try{
139 var c=(el.getAttribute('data-center')||'0,0').split(',');
140 var center=[parseFloat(c[1])||0,parseFloat(c[0])||0];
141 var zoom=parseFloat(el.getAttribute('data-zoom'))||2;
142 var style=el.getAttribute('data-style')||'https://tiles.openfreemap.org/styles/liberty';
143 var interactive=el.getAttribute('data-interactive')!=='false';
144 var map=new maplibregl.Map({container:el,style:style,center:center,zoom:zoom,interactive:interactive});
145 el.__mobilerMapInstance=map;
146 map.on('click',function(e){emit(el,'tap|'+e.lngLat.lat.toFixed(6)+','+e.lngLat.lng.toFixed(6));});
147 var markers=[];try{markers=JSON.parse(el.getAttribute('data-markers')||'[]');}catch(_){}
148 markers.forEach(function(mk){
149 var m=new maplibregl.Marker().setLngLat([mk.lng,mk.lat]);
150 if(mk.title){m.setPopup(new maplibregl.Popup({offset:24}).setText(mk.title));}
151 m.addTo(map);
152 m.getElement().addEventListener('click',function(ev){ev.stopPropagation();emit(el,'marker|'+mk.id);});
153 });
154 }catch(_){}
155 });
156 }
157 function scan(root){if(root&&root.querySelectorAll){root.querySelectorAll('.mobiler-map[data-map]').forEach(init);}}
158 new MutationObserver(function(muts){muts.forEach(function(m){
159 m.addedNodes.forEach(function(n){if(n.nodeType===1){if(n.matches&&n.matches('.mobiler-map[data-map]')){init(n);}scan(n);}});
160 m.removedNodes.forEach(function(n){if(n.nodeType===1){
161 if(n.__mobilerMapInstance){try{n.__mobilerMapInstance.remove();}catch(_){}}
162 if(n.querySelectorAll){n.querySelectorAll('.mobiler-map').forEach(function(x){if(x.__mobilerMapInstance){try{x.__mobilerMapInstance.remove();}catch(_){}}});}
163 }});
164 });}).observe(document.documentElement,{childList:true,subtree:true});
165 scan(document);
166})();"#;
167 let document = leptos::prelude::document();
168 let Some(head) = document.head() else { return };
169 let Ok(script) = document.create_element("script") else { return };
170 script.set_text_content(Some(BOOTSTRAP));
171 let _ = head.append_child(&script);
172}
173
174fn inject_default_style() {
178 let document = leptos::prelude::document();
179 let Some(head) = document.head() else { return };
180 let Ok(style) = document.create_element("style") else { return };
181 let _ = style.set_attribute("data-mobiler", "shell");
182 style.set_text_content(Some(STYLE));
183 let _ = head.insert_before(&style, head.first_child().as_ref());
184}
185
186fn shell<A: WebApp>() -> impl IntoView
187where
188 A::Model: Default + Send + Sync,
189{
190 let core = Arc::new(Core::<A>::new());
191 let (view, set_view) = signal(core.view());
192
193 let send: Dispatch = {
194 let core = core.clone();
195 Arc::new(move |action: Action| {
196 let effects = core.process_event(action);
197 drive(&core, set_view, effects);
198 })
199 };
200
201 let saved = local_storage().and_then(|s| s.get_item(STORAGE_KEY).ok().flatten()).unwrap_or_default();
204 if !saved.is_empty() {
205 send(Action::Restore { data: saved });
206 }
207 send(Action::Start);
208
209 let send_for_view = send.clone();
210 view! {
211 <div class="app">
212 {move || {
213 let widget = view.get();
214 ACTIVE_LABELS.with(|l| {
219 *l.borrow_mut() = match &widget {
220 Widget::Scaffold { labels, .. } => labels.clone(),
221 _ => None,
222 };
223 });
224 render(&widget, &send_for_view)
225 }}
226 </div>
227 }
228}
229
230fn drive<A: WebApp>(core: &Arc<Core<A>>, set_view: WriteSignal<Widget>, effects: Vec<Effect>)
232where
233 A::Model: Default + Send + Sync,
234{
235 for effect in effects {
236 match effect {
237 Effect::Render(_) => set_view.set(core.view()),
238 Effect::PluginNotify(notify) => perform_notify(¬ify.operation),
239 Effect::Plugin(mut request) => {
240 let core = core.clone();
241 spawn_local(async move {
242 let response = perform(&request.operation).await;
243 if let Ok(next) = core.resolve(&mut request, response) {
244 drive(&core, set_view, next);
245 }
246 });
247 }
248 Effect::PluginStream(request) => start_stream(core, set_view, request),
251 }
252 }
253}
254
255fn start_stream<A: WebApp>(
264 core: &Arc<Core<A>>,
265 set_view: WriteSignal<Widget>,
266 request: Request<PluginStreamCall>,
267) where
268 A::Model: Default + Send + Sync,
269{
270 use wasm_bindgen::{closure::Closure, JsCast};
271
272 let call = request.operation.clone();
273
274 let request = Rc::new(RefCell::new(request));
277 let core = core.clone();
278 let emit = move |resp: PluginResponse| {
279 if let Ok(next) = core.resolve(&mut *request.borrow_mut(), resp) {
280 drive(&core, set_view, next);
281 }
282 };
283
284 let handle = match (call.plugin.as_str(), call.op.as_str()) {
285 ("ticker", "start") => {
288 let ms: u32 = call.input.parse().unwrap_or(1000);
289 let count = std::cell::Cell::new(0u32);
290 let interval = gloo_timers::callback::Interval::new(ms, move || {
291 count.set(count.get() + 1);
292 emit(PluginResponse::text(true, count.get().to_string()));
293 });
294 StreamHandle::Ticker { _interval: interval }
295 }
296 ("websocket", "stream") => {
297 let Ok(ws) = web_sys::WebSocket::new(&call.input) else { return };
298 let onmessage = {
299 let emit = emit.clone();
300 Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |e: web_sys::MessageEvent| {
301 emit(PluginResponse::text(true, e.data().as_string().unwrap_or_default()));
302 })
303 };
304 let onclose = Closure::<dyn FnMut(web_sys::CloseEvent)>::new(move |_e| {
305 emit(PluginResponse::text(false, "closed"));
306 });
307 ws.set_onmessage(Some(onmessage.as_ref().unchecked_ref()));
308 ws.set_onclose(Some(onclose.as_ref().unchecked_ref()));
309 StreamHandle::Ws(WsStream { ws, _onmessage: onmessage, _onclose: onclose })
310 }
311 ("system", "events") => {
315 let win = web_sys::window().expect("window");
316 let doc = win.document().expect("document");
317 if let Ok(href) = win.location().href() {
319 emit(PluginResponse::text(true, system_deeplink(&href)));
320 }
321 emit(PluginResponse::text(true, system_lifecycle(&doc)));
322 let onpop = {
323 let (emit, win) = (emit.clone(), win.clone());
324 Closure::<dyn FnMut(web_sys::Event)>::new(move |_e: web_sys::Event| {
325 if let Ok(href) = win.location().href() {
326 emit(PluginResponse::text(true, system_deeplink(&href)));
327 }
328 })
329 };
330 let onvis = {
331 let (emit, doc) = (emit.clone(), doc.clone());
332 Closure::<dyn FnMut(web_sys::Event)>::new(move |_e: web_sys::Event| {
333 emit(PluginResponse::text(true, system_lifecycle(&doc)));
334 })
335 };
336 let _ = win.add_event_listener_with_callback("popstate", onpop.as_ref().unchecked_ref());
337 let _ = doc.add_event_listener_with_callback("visibilitychange", onvis.as_ref().unchecked_ref());
338 StreamHandle::System(SystemStream { win, doc, _onpop: onpop, _onvis: onvis })
339 }
340 ("transfer", op @ ("upload" | "download")) => {
345 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap_or(serde_json::Value::Null);
346 let url = v.get("url").and_then(|x| x.as_str()).unwrap_or("").to_string();
347 let headers: Vec<(String, String)> = v
348 .get("headers")
349 .and_then(|x| x.as_array())
350 .map(|hs| {
351 hs.iter()
352 .filter_map(|h| Some((h.get("name")?.as_str()?.to_string(), h.get("value")?.as_str()?.to_string())))
353 .collect()
354 })
355 .unwrap_or_default();
356
357 if op == "upload" {
358 let method = v.get("method").and_then(|x| x.as_str()).unwrap_or("PUT").to_string();
359 let source = v.get("source").and_then(|x| x.as_str()).unwrap_or("").to_string();
360 let multipart = v.get("multipart").map(|m| WebMultipart {
361 field: m.get("field").and_then(|x| x.as_str()).unwrap_or("").to_string(),
362 filename: m.get("filename").and_then(|x| x.as_str()).map(|s| s.to_string()),
363 fields: m
364 .get("fields")
365 .and_then(|x| x.as_array())
366 .map(|fs| {
367 fs.iter()
368 .filter_map(|f| Some((f.get("name")?.as_str()?.to_string(), f.get("value")?.as_str()?.to_string())))
369 .collect()
370 })
371 .unwrap_or_default(),
372 });
373 start_web_upload(url, method, headers, source, multipart, emit.clone())
374 } else {
375 start_web_download(url, headers, emit.clone())
376 }
377 }
378 _ => return, };
380
381 STREAMS.with(|m| {
382 m.borrow_mut().insert(call.key.clone(), handle);
383 });
384}
385
386fn js_now() -> f64 {
388 web_sys::window().and_then(|w| w.performance()).map(|p| p.now()).unwrap_or(0.0)
389}
390
391struct WebMultipart {
396 field: String,
398 filename: Option<String>,
400 fields: Vec<(String, String)>,
402}
403
404fn infer_filename(source: &str) -> String {
406 let s = source.split(['?', '#']).next().unwrap_or(source);
407 let name = s.rsplit('/').next().unwrap_or("");
408 if name.is_empty() {
409 "file".to_string()
410 } else {
411 name.to_string()
412 }
413}
414
415fn parse_header_block(raw: &str) -> Vec<HttpHeader> {
419 raw.split("\r\n")
420 .filter_map(|line| {
421 let (name, value) = line.split_once(':')?;
422 let name = name.trim();
423 if name.is_empty() {
424 return None;
425 }
426 Some(HttpHeader { name: name.to_string(), value: value.trim().to_string() })
427 })
428 .collect()
429}
430
431fn start_web_upload(
439 url: String,
440 method: String,
441 headers: Vec<(String, String)>,
442 source: String,
443 multipart: Option<WebMultipart>,
444 emit: impl Fn(PluginResponse) + Clone + 'static,
445) -> StreamHandle {
446 use wasm_bindgen::{closure::Closure, JsCast};
447 let xhr = web_sys::XmlHttpRequest::new().expect("xhr");
448 let _ = xhr.open_with_async(&method, &url, true);
449 for (n, val) in &headers {
450 if multipart.is_some() && n.eq_ignore_ascii_case("content-type") {
455 continue;
456 }
457 let _ = xhr.set_request_header(n, val);
458 }
459
460 let last = std::rc::Rc::new(std::cell::Cell::new(0.0f64));
466 let on_prog = {
467 let (emit, last) = (emit.clone(), last.clone());
468 Closure::<dyn FnMut(web_sys::ProgressEvent)>::new(move |e: web_sys::ProgressEvent| {
469 let now = js_now();
470 if now - last.get() < 100.0 {
471 return;
472 }
473 last.set(now);
474 let total = if e.length_computable() { Some(e.total() as u64) } else { None };
475 emit(transfer_response(&TransferEvent::Progress { transferred: e.loaded() as u64, total }));
476 })
477 };
478 if let Ok(upload) = xhr.upload() {
479 upload.set_onprogress(Some(on_prog.as_ref().unchecked_ref()));
480 }
481
482 let on_done = {
485 let (emit, xhr_c) = (emit.clone(), xhr.clone());
486 Closure::<dyn FnMut()>::new(move || {
487 let status = xhr_c.status().unwrap_or(0);
488 let outcome = if status == 0 {
489 HttpOutcome::TransportError { message: "upload failed".into() }
490 } else {
491 let headers = xhr_c
497 .get_all_response_headers()
498 .ok()
499 .map(|raw| parse_header_block(&raw))
500 .unwrap_or_default();
501 HttpOutcome::Response { status, headers, body: vec![] }
502 };
503 emit(transfer_response(&TransferEvent::Done { outcome, handle: None }));
504 })
505 };
506 xhr.set_onload(Some(on_done.as_ref().unchecked_ref()));
507 let on_err = {
508 let emit = emit.clone();
509 Closure::<dyn FnMut()>::new(move || {
510 emit(transfer_response(&TransferEvent::Done {
511 outcome: HttpOutcome::TransportError { message: "upload error".into() },
512 handle: None,
513 }));
514 })
515 };
516 xhr.set_onerror(Some(on_err.as_ref().unchecked_ref()));
517 let on_abort = {
518 let emit = emit.clone();
519 Closure::<dyn FnMut()>::new(move || {
520 emit(transfer_response(&TransferEvent::Done {
521 outcome: HttpOutcome::TransportError { message: "upload aborted".into() },
522 handle: None,
523 }));
524 })
525 };
526 xhr.set_onabort(Some(on_abort.as_ref().unchecked_ref()));
527
528 let xhr_send = xhr.clone();
540 let cancelled = std::rc::Rc::new(std::cell::Cell::new(false));
541 let cancelled_send = cancelled.clone();
542 wasm_bindgen_futures::spawn_local(async move {
543 let blob = fetch_blob(&source).await;
544 if cancelled_send.get() {
545 return;
546 }
547 match (blob, &multipart) {
548 (Some(blob), Some(mp)) => {
549 let form = web_sys::FormData::new().expect("FormData");
551 for (name, value) in &mp.fields {
552 let _ = form.append_with_str(name, value);
553 }
554 let filename = mp.filename.clone().unwrap_or_else(|| infer_filename(&source));
555 let _ = form.append_with_blob_and_filename(&mp.field, &blob, &filename);
556 let _ = xhr_send.send_with_opt_form_data(Some(&form));
557 }
558 (Some(blob), None) => {
559 let _ = xhr_send.send_with_opt_blob(Some(&blob));
560 }
561 (None, _) => {
562 let _ = xhr_send.send();
563 }
564 }
565 });
566
567 StreamHandle::Transfer(TransferHandle {
568 xhr: Some(xhr),
569 abort: None,
570 cancelled: Some(cancelled),
571 _on_prog: Some(on_prog),
572 _on_done: Some(on_done),
573 _on_err: Some(on_err),
574 _on_abort: Some(on_abort),
575 })
576}
577
578async fn fetch_blob(url: &str) -> Option<web_sys::Blob> {
582 use wasm_bindgen::JsCast;
583 let win = web_sys::window()?;
584 let resp_value = wasm_bindgen_futures::JsFuture::from(win.fetch_with_str(url)).await.ok()?;
585 let resp: web_sys::Response = resp_value.dyn_into().ok()?;
586 let blob_promise = resp.blob().ok()?;
587 let blob_value = wasm_bindgen_futures::JsFuture::from(blob_promise).await.ok()?;
588 blob_value.dyn_into().ok()
589}
590
591fn start_web_download(
600 url: String,
601 headers: Vec<(String, String)>,
602 emit: impl Fn(PluginResponse) + Clone + 'static,
603) -> StreamHandle {
604 let ctrl = web_sys::AbortController::new().expect("abortcontroller");
605 let signal = ctrl.signal();
606 let emit2 = emit.clone();
607 wasm_bindgen_futures::spawn_local(async move {
608 match fetch_stream(&url, &headers, &signal).await {
609 Ok((status, resp_headers, total, mut reader)) => {
610 let mut got: u64 = 0;
611 let mut chunks: Vec<u8> = Vec::new();
612 let mut last = js_now();
613 loop {
614 match reader.next().await {
615 Ok(Some(chunk)) => {
616 got += chunk.len() as u64;
617 chunks.extend_from_slice(&chunk);
618 let now = js_now();
619 if now - last >= 100.0 {
621 last = now;
622 emit2(transfer_response(&TransferEvent::Progress { transferred: got, total }));
623 }
624 }
625 Ok(None) => break, Err(msg) => {
627 emit2(transfer_response(&TransferEvent::Done {
628 outcome: HttpOutcome::TransportError { message: msg },
629 handle: None,
630 }));
631 return;
632 }
633 }
634 }
635 let handle = make_blob_url(&chunks);
636 let outcome = HttpOutcome::Response { status, headers: resp_headers, body: vec![] };
637 emit2(transfer_response(&TransferEvent::Done { outcome, handle: Some(handle) }));
638 }
639 Err(msg) => emit2(transfer_response(&TransferEvent::Done {
640 outcome: HttpOutcome::TransportError { message: msg },
641 handle: None,
642 })),
643 }
644 });
645 StreamHandle::Transfer(TransferHandle {
646 xhr: None,
647 abort: Some(ctrl),
648 cancelled: None,
649 _on_prog: None,
650 _on_done: None,
651 _on_err: None,
652 _on_abort: None,
653 })
654}
655
656async fn fetch_stream(
660 url: &str,
661 headers: &[(String, String)],
662 signal: &web_sys::AbortSignal,
663) -> Result<(u16, Vec<HttpHeader>, Option<u64>, Reader), String> {
664 use wasm_bindgen::JsCast;
665 let win = web_sys::window().ok_or_else(|| "no window".to_string())?;
666 let js_headers = web_sys::Headers::new().map_err(|e| js_err(&e))?;
667 for (n, v) in headers {
668 js_headers.append(n, v).map_err(|e| js_err(&e))?;
669 }
670 let init = web_sys::RequestInit::new();
671 init.set_method("GET");
672 init.set_headers_headers(&js_headers);
673 init.set_signal(Some(signal));
674 let request = web_sys::Request::new_with_str_and_init(url, &init).map_err(|e| js_err(&e))?;
675
676 let resp_value = wasm_bindgen_futures::JsFuture::from(win.fetch_with_request(&request))
677 .await
678 .map_err(|e| js_err(&e))?;
679 let resp: web_sys::Response = resp_value.dyn_into().map_err(|_| "fetch: not a Response".to_string())?;
680 let status = resp.status();
681 let resp_headers = response_headers(&resp.headers());
682 let total = resp_headers
683 .iter()
684 .find(|h| h.name.eq_ignore_ascii_case("content-length"))
685 .and_then(|h| h.value.parse().ok());
686
687 let Some(stream) = resp.body() else {
688 return Ok((status, resp_headers, total, Reader::empty()));
691 };
692 let reader = web_sys::ReadableStreamDefaultReader::new(&stream).map_err(|e| js_err(&e))?;
693 Ok((status, resp_headers, total, Reader::new(reader)))
694}
695
696fn response_headers(headers: &web_sys::Headers) -> Vec<HttpHeader> {
699 use wasm_bindgen::JsCast;
700 let mut out = Vec::new();
701 if let Ok(Some(iter)) = js_sys::try_iter(headers) {
702 for entry in iter.flatten() {
703 let arr: js_sys::Array = entry.unchecked_into();
704 let name = arr.get(0).as_string().unwrap_or_default();
705 let value = arr.get(1).as_string().unwrap_or_default();
706 out.push(HttpHeader { name, value });
707 }
708 }
709 out
710}
711
712fn js_err(e: &wasm_bindgen::JsValue) -> String {
715 use wasm_bindgen::JsCast;
716 e.as_string()
717 .or_else(|| e.dyn_ref::<js_sys::Error>().map(|err| String::from(err.message())))
718 .unwrap_or_else(|| "transfer error".to_string())
719}
720
721struct Reader(Option<web_sys::ReadableStreamDefaultReader>);
725impl Reader {
726 fn new(reader: web_sys::ReadableStreamDefaultReader) -> Self {
727 Self(Some(reader))
728 }
729 fn empty() -> Self {
731 Self(None)
732 }
733 async fn next(&mut self) -> Result<Option<Vec<u8>>, String> {
734 use wasm_bindgen::JsCast;
735 let Some(reader) = &self.0 else { return Ok(None) };
736 let result = wasm_bindgen_futures::JsFuture::from(reader.read()).await.map_err(|e| js_err(&e))?;
737 let result: web_sys::ReadableStreamReadResult = result.unchecked_into();
738 if result.get_done().unwrap_or(true) {
739 return Ok(None);
740 }
741 let value = result.get_value();
742 let bytes = js_sys::Uint8Array::new(&value).to_vec();
743 Ok(Some(bytes))
744 }
745}
746
747fn make_blob_url(bytes: &[u8]) -> String {
751 let array = js_sys::Uint8Array::from(bytes);
752 let parts = js_sys::Array::new();
753 parts.push(&array);
754 web_sys::Blob::new_with_u8_array_sequence(&parts)
755 .ok()
756 .and_then(|blob| web_sys::Url::create_object_url_with_blob(&blob).ok())
757 .unwrap_or_default()
758}
759
760fn system_deeplink(url: &str) -> String {
762 format!("{{\"type\":\"deeplink\",\"url\":{}}}", serde_json::to_string(url).unwrap_or_else(|_| "\"\"".into()))
763}
764fn system_lifecycle(doc: &web_sys::Document) -> String {
766 let state = if doc.visibility_state() == web_sys::VisibilityState::Visible { "active" } else { "background" };
767 format!("{{\"type\":\"lifecycle\",\"state\":\"{state}\"}}")
768}
769
770enum StreamHandle {
774 Ticker { _interval: gloo_timers::callback::Interval },
776 Ws(WsStream),
777 #[allow(dead_code)]
780 System(SystemStream),
781 #[allow(dead_code)]
784 Transfer(TransferHandle),
785}
786
787struct TransferHandle {
791 xhr: Option<web_sys::XmlHttpRequest>,
792 abort: Option<web_sys::AbortController>,
793 cancelled: Option<std::rc::Rc<std::cell::Cell<bool>>>,
798 _on_prog: Option<wasm_bindgen::closure::Closure<dyn FnMut(web_sys::ProgressEvent)>>,
803 _on_done: Option<wasm_bindgen::closure::Closure<dyn FnMut()>>,
804 _on_err: Option<wasm_bindgen::closure::Closure<dyn FnMut()>>,
805 _on_abort: Option<wasm_bindgen::closure::Closure<dyn FnMut()>>,
806}
807impl Drop for TransferHandle {
808 fn drop(&mut self) {
809 if let Some(c) = &self.cancelled {
810 c.set(true);
811 }
812 if let Some(x) = &self.xhr {
813 let _ = x.abort();
814 }
815 if let Some(a) = &self.abort {
816 a.abort();
817 }
818 }
819}
820
821fn transfer_response(ev: &TransferEvent) -> PluginResponse {
823 PluginResponse {
824 ok: matches!(ev, TransferEvent::Done { outcome, .. } if outcome.is_success()),
825 output: ev.encode(),
826 }
827}
828
829struct SystemStream {
831 win: web_sys::Window,
832 doc: web_sys::Document,
833 _onpop: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::Event)>,
834 _onvis: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::Event)>,
835}
836impl Drop for SystemStream {
837 fn drop(&mut self) {
838 use wasm_bindgen::JsCast;
839 let _ = self.win.remove_event_listener_with_callback("popstate", self._onpop.as_ref().unchecked_ref());
840 let _ = self.doc.remove_event_listener_with_callback("visibilitychange", self._onvis.as_ref().unchecked_ref());
841 }
842}
843
844struct WsStream {
846 ws: web_sys::WebSocket,
847 _onmessage: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::MessageEvent)>,
848 _onclose: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::CloseEvent)>,
849}
850
851async fn perform(call: &PluginCall) -> PluginResponse {
854 if call.plugin == "device" {
855 let nav = web_sys::window().map(|w| w.navigator());
856 let output = if call.op == "locale" {
857 nav.and_then(|n| n.language()).unwrap_or_else(|| "en-US".into())
859 } else {
860 nav.and_then(|n| n.user_agent().ok()).unwrap_or_default()
861 };
862 return PluginResponse::text(true, output);
863 }
864 if call.plugin == "photo" && call.op == "pick" {
865 return take_image(false).await;
866 }
867 if call.plugin == "camera" && call.op == "capture" {
868 return take_image(true).await;
869 }
870 if call.plugin == "datetime" {
871 return match call.op.as_str() {
872 "date" => take_datetime("date").await,
873 "time" => take_datetime("time").await,
874 other => PluginResponse::text(false, format!("unknown datetime op '{other}'")),
875 };
876 }
877 if call.plugin == "dialog" && call.op == "confirm" {
878 let ok = confirm_modal(ConfirmAsk::parse(&call.input)).await;
879 return PluginResponse::text(ok, if ok { "ok" } else { "cancel" });
880 }
881 if call.plugin != "http" {
882 return PluginResponse::text(false, format!("plugin '{}' not available", call.plugin));
883 }
884 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap_or(serde_json::Value::Null);
885 let url = v.get("url").and_then(serde_json::Value::as_str).unwrap_or("");
886 let body = v.get("body").and_then(serde_json::Value::as_str);
887 let req_headers: Vec<(String, String)> = v
888 .get("headers")
889 .and_then(serde_json::Value::as_array)
890 .map(|hs| {
891 hs.iter()
892 .filter_map(|h| {
893 Some((
894 h.get("name")?.as_str()?.to_string(),
895 h.get("value")?.as_str()?.to_string(),
896 ))
897 })
898 .collect()
899 })
900 .unwrap_or_default();
901
902 use gloo_net::http::{Method, Request};
903
904 let builder = match call.op.as_str() {
907 "GET" => Request::get(url),
908 "POST" => Request::post(url),
909 "PUT" => Request::put(url),
910 "PATCH" => Request::patch(url),
911 "DELETE" => Request::delete(url),
912 "HEAD" => Request::get(url).method(Method::HEAD),
913 "OPTIONS" => Request::get(url).method(Method::OPTIONS),
914 other => return http_transport_error(format!("unsupported HTTP method '{other}'")),
915 };
916
917 let caller_set_content_type =
919 req_headers.iter().any(|(n, _)| n.eq_ignore_ascii_case("content-type"));
920
921 let gloo_headers = gloo_net::http::Headers::new();
927 for (name, value) in &req_headers {
928 gloo_headers.append(name, value);
929 }
930 if body.is_some() && !caller_set_content_type {
931 gloo_headers.append("Content-Type", "application/json");
932 }
933 let builder = builder.headers(gloo_headers);
934
935 let request = match body {
936 Some(b) => builder.body(b),
937 None => builder.build(),
938 };
939 let request = match request {
940 Ok(r) => r,
941 Err(e) => return http_transport_error(e.to_string()),
942 };
943
944 match request.send().await {
945 Ok(resp) => {
946 let status = resp.status();
947 let headers = resp
948 .headers()
949 .entries()
950 .map(|(name, value)| HttpHeader { name, value })
951 .collect();
952 match resp.binary().await {
953 Ok(bytes) => {
954 let outcome = HttpOutcome::Response { status, headers, body: bytes };
955 PluginResponse { ok: (200..300).contains(&status), output: outcome.encode() }
956 }
957 Err(e) => http_transport_error(e.to_string()),
960 }
961 }
962 Err(e) => http_transport_error(e.to_string()),
963 }
964}
965
966fn http_transport_error(message: String) -> PluginResponse {
968 PluginResponse { ok: false, output: HttpOutcome::TransportError { message }.encode() }
969}
970
971async fn take_image(capture: bool) -> PluginResponse {
978 use wasm_bindgen::{closure::Closure, JsCast};
979 let Some(doc) = web_sys::window().and_then(|w| w.document()) else {
980 return PluginResponse::text(false, "no document");
981 };
982 let Some(input) = doc.create_element("input").ok().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()) else {
983 return PluginResponse::text(false, "no input element");
984 };
985 input.set_type("file");
986 input.set_accept("image/*");
987 if capture {
988 let _ = input.set_attribute("capture", "environment");
990 }
991
992 let (tx, rx) = futures_channel::oneshot::channel::<Option<String>>();
993 let tx = std::cell::RefCell::new(Some(tx));
994 let input_for_cb = input.clone();
995 let on_change = Closure::wrap(Box::new(move || {
996 let url = input_for_cb
997 .files()
998 .and_then(|files| files.get(0))
999 .and_then(|file| web_sys::Url::create_object_url_with_blob(&file).ok());
1000 if let Some(tx) = tx.borrow_mut().take() {
1001 let _ = tx.send(url);
1002 }
1003 }) as Box<dyn FnMut()>);
1004 input.set_onchange(Some(on_change.as_ref().unchecked_ref()));
1005 input.click();
1006 on_change.forget(); match rx.await {
1009 Ok(Some(url)) => PluginResponse::text(true, url),
1010 _ => PluginResponse::text(false, "cancelled"),
1011 }
1012}
1013
1014async fn take_datetime(kind: &str) -> PluginResponse {
1019 use wasm_bindgen::{closure::Closure, JsCast};
1020 let Some(doc) = web_sys::window().and_then(|w| w.document()) else {
1021 return PluginResponse::text(false, "no document");
1022 };
1023 let Some(input) = doc.create_element("input").ok().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()) else {
1024 return PluginResponse::text(false, "no input element");
1025 };
1026 input.set_type(kind); let _ = input.set_attribute("style", "position:fixed;left:-9999px;opacity:0");
1029 if let Some(body) = doc.body() {
1030 let _ = body.append_child(&input);
1031 }
1032
1033 let (tx, rx) = futures_channel::oneshot::channel::<Option<String>>();
1034 let tx = std::rc::Rc::new(std::cell::RefCell::new(Some(tx)));
1035 let input_for_change = input.clone();
1036 let tx_change = tx.clone();
1037 let on_change = Closure::wrap(Box::new(move || {
1038 let v = input_for_change.value();
1039 if let Some(tx) = tx_change.borrow_mut().take() {
1040 let _ = tx.send(if v.is_empty() { None } else { Some(v) });
1041 }
1042 }) as Box<dyn FnMut()>);
1043 let tx_cancel = tx.clone();
1044 let on_cancel = Closure::wrap(Box::new(move || {
1045 if let Some(tx) = tx_cancel.borrow_mut().take() {
1046 let _ = tx.send(None);
1047 }
1048 }) as Box<dyn FnMut()>);
1049 let _ = input.add_event_listener_with_callback("change", on_change.as_ref().unchecked_ref());
1050 let _ = input.add_event_listener_with_callback("cancel", on_cancel.as_ref().unchecked_ref());
1051 if input.show_picker().is_err() {
1052 input.click(); }
1054 on_change.forget(); on_cancel.forget();
1056
1057 let result = rx.await;
1058 input.remove();
1059 match result {
1060 Ok(Some(v)) => PluginResponse::text(true, v),
1061 _ => PluginResponse::text(false, "cancelled"),
1062 }
1063}
1064
1065const STORAGE_KEY: &str = "mobiler.state";
1066
1067fn local_storage() -> Option<web_sys::Storage> {
1069 web_sys::window()?.local_storage().ok().flatten()
1070}
1071
1072fn perform_notify(notify: &PluginNotify) {
1076 let win = match web_sys::window() {
1077 Some(w) => w,
1078 None => return,
1079 };
1080 match (notify.plugin.as_str(), notify.op.as_str()) {
1081 ("storage", "save") => {
1083 if let Some(s) = local_storage() {
1084 let _ = s.set_item(STORAGE_KEY, ¬ify.input);
1085 }
1086 }
1087 ("clipboard", "copy") => {
1089 let _ = win.navigator().clipboard().write_text(¬ify.input);
1090 }
1091 ("browser", "open") => {
1093 let _ = win.open_with_url_and_target(¬ify.input, "_blank");
1094 }
1095 ("share", _) => {
1098 let _ = win.navigator().clipboard().write_text(¬ify.input);
1099 }
1100 ("stream", "unsubscribe") => {
1104 if let Some(StreamHandle::Ws(ws)) = STREAMS.with(|m| m.borrow_mut().remove(¬ify.input)) {
1107 let _ = ws.ws.close();
1108 }
1109 }
1110 ("toast", _) => show_toast(¬ify.input),
1112 ("haptics", style) => {
1114 let ms = match style {
1115 "light" => 15,
1116 "heavy" => 50,
1117 _ => 30, };
1119 let _ = win.navigator().vibrate_with_duration(ms);
1120 }
1121 _ => {} }
1123}
1124
1125fn show_toast(text: &str) {
1128 let Some(doc) = web_sys::window().and_then(|w| w.document()) else { return };
1129 let (Ok(el), Some(body)) = (doc.create_element("div"), doc.body()) else { return };
1130 el.set_class_name("toast");
1131 el.set_text_content(Some(text));
1132 let _ = body.append_child(&el);
1133 gloo_timers::callback::Timeout::new(2600, move || el.remove()).forget();
1134}
1135
1136struct ConfirmAsk {
1139 title: String,
1140 message: String,
1141 confirm_label: String,
1142 cancel_label: String,
1143 destructive: bool,
1144}
1145
1146impl ConfirmAsk {
1147 fn parse(input: &str) -> Self {
1148 let v: serde_json::Value = serde_json::from_str(input).unwrap_or(serde_json::Value::Null);
1149 let s = |k: &str, d: &str| v.get(k).and_then(serde_json::Value::as_str).filter(|s| !s.is_empty()).unwrap_or(d).to_string();
1150 let ok_default = shell_label(|l| l.ok.clone(), "OK");
1153 let cancel_default = shell_label(|l| l.cancel.clone(), "Cancel");
1154 Self {
1155 title: s("title", ""),
1156 message: s("message", ""),
1157 confirm_label: s("confirm_label", &ok_default),
1158 cancel_label: s("cancel_label", &cancel_default),
1159 destructive: v.get("destructive").and_then(serde_json::Value::as_bool).unwrap_or(false),
1160 }
1161 }
1162}
1163
1164static CONFIRM_DIALOG_ID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
1167
1168struct OpenConfirm {
1172 tx: std::rc::Rc<std::cell::RefCell<Option<futures_channel::oneshot::Sender<bool>>>>,
1173 superseded: std::rc::Rc<std::cell::Cell<bool>>,
1174 restore_to: Option<web_sys::Element>,
1175}
1176thread_local! {
1177 static OPEN_CONFIRM: std::cell::RefCell<Option<OpenConfirm>> = const { std::cell::RefCell::new(None) };
1178}
1179
1180async fn confirm_modal(ask: ConfirmAsk) -> bool {
1191 use wasm_bindgen::{closure::Closure, JsCast};
1192 let Some(doc) = web_sys::window().and_then(|w| w.document()) else { return false };
1193 let Some(body) = doc.body() else { return false };
1194 let el = |tag: &str, class: &str| -> Option<web_sys::HtmlElement> {
1195 let e = doc.create_element(tag).ok()?.dyn_into::<web_sys::HtmlElement>().ok()?;
1196 e.set_class_name(class);
1197 Some(e)
1198 };
1199 let confirm_class = if ask.destructive { "btn btn-filled btn-danger" } else { "btn btn-filled" };
1200 let (Some(scrim), Some(card), Some(actions), Some(cancel), Some(confirm)) = (
1201 el("div", "confirm-scrim"),
1202 el("div", "confirm-card"),
1203 el("div", "confirm-actions"),
1204 el("button", "btn btn-text"),
1205 el("button", confirm_class),
1206 ) else {
1207 return false;
1208 };
1209
1210 if let Some(scaffold) = doc.query_selector(".scaffold").ok().flatten() {
1212 if let Some(style) = scaffold.get_attribute("style") {
1213 let _ = scrim.set_attribute("style", &style);
1214 }
1215 let classes = scaffold.class_list();
1216 for c in ["theme-dark", "density-large"] {
1217 if classes.contains(c) {
1218 let _ = scrim.class_list().add_1(c);
1219 }
1220 }
1221 }
1222
1223 let _ = card.set_attribute("role", "alertdialog");
1224 let _ = card.set_attribute("aria-modal", "true");
1225 let call_id = CONFIRM_DIALOG_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1226 if !ask.title.is_empty() {
1227 if let Some(title) = el("div", "confirm-title") {
1228 let title_id = format!("mobiler-confirm-title-{call_id}");
1229 title.set_text_content(Some(&ask.title));
1230 let _ = title.set_attribute("id", &title_id);
1231 let _ = card.append_child(&title);
1232 let _ = card.set_attribute("aria-labelledby", &title_id);
1233 }
1234 }
1235 if !ask.message.is_empty() {
1238 if let Some(message) = el("p", "confirm-message") {
1239 let msg_id = format!("mobiler-confirm-msg-{call_id}");
1240 message.set_text_content(Some(&ask.message));
1241 let _ = message.set_attribute("id", &msg_id);
1242 let _ = card.append_child(&message);
1243 let _ = card.set_attribute("aria-describedby", &msg_id);
1244 }
1245 }
1246 cancel.set_text_content(Some(&ask.cancel_label));
1247 confirm.set_text_content(Some(&ask.confirm_label));
1248 let _ = actions.append_child(&cancel);
1249 let _ = actions.append_child(&confirm);
1250 let _ = card.append_child(&actions);
1251 let _ = scrim.append_child(&card);
1252
1253 let previously_focused = OPEN_CONFIRM.with(|c| c.borrow_mut().take()).map(|old| {
1259 old.superseded.set(true);
1260 if let Some(tx) = old.tx.borrow_mut().take() {
1261 let _ = tx.send(false);
1262 }
1263 old.restore_to
1264 }).unwrap_or_else(|| doc.active_element());
1265
1266 let _ = body.append_child(&scrim);
1267 let _ = if ask.destructive { cancel.focus() } else { confirm.focus() };
1268
1269 let (tx, rx) = futures_channel::oneshot::channel::<bool>();
1270 let tx = std::rc::Rc::new(std::cell::RefCell::new(Some(tx)));
1271 let superseded = std::rc::Rc::new(std::cell::Cell::new(false));
1272 OPEN_CONFIRM.with(|c| {
1273 *c.borrow_mut() = Some(OpenConfirm { tx: tx.clone(), superseded: superseded.clone(), restore_to: previously_focused.clone() });
1274 });
1275 let answer = move |tx: &std::rc::Rc<std::cell::RefCell<Option<futures_channel::oneshot::Sender<bool>>>>, ok: bool| {
1276 if let Some(tx) = tx.borrow_mut().take() {
1277 let _ = tx.send(ok);
1278 }
1279 };
1280 let (t1, t2, t3, t4) = (tx.clone(), tx.clone(), tx.clone(), tx.clone());
1281 let on_cancel = Closure::wrap(Box::new(move || answer(&t1, false)) as Box<dyn FnMut()>);
1282 let on_confirm = Closure::wrap(Box::new(move || answer(&t2, true)) as Box<dyn FnMut()>);
1283
1284 let press_started_on_scrim = std::rc::Rc::new(std::cell::Cell::new(false));
1290 let scrim_node: web_sys::EventTarget = scrim.clone().into();
1291 let press_flag = press_started_on_scrim.clone();
1292 let pointerdown_target = scrim_node.clone();
1293 let on_pointerdown = Closure::wrap(Box::new(move |e: web_sys::Event| {
1294 press_flag.set(e.target().as_ref() == Some(&pointerdown_target));
1295 }) as Box<dyn FnMut(web_sys::Event)>);
1296 let on_backdrop = Closure::wrap(Box::new(move |e: web_sys::Event| {
1297 if press_started_on_scrim.get() && e.target().as_ref() == Some(&scrim_node) {
1298 answer(&t3, false);
1299 }
1300 }) as Box<dyn FnMut(web_sys::Event)>);
1301 let (doc_for_key, card_for_key, cancel_for_key, confirm_for_key) = (doc.clone(), card.clone(), cancel.clone(), confirm.clone());
1304 let on_key = Closure::wrap(Box::new(move |e: web_sys::KeyboardEvent| {
1305 if e.key() == "Escape" {
1306 answer(&t4, false);
1307 } else if e.key() == "Tab" {
1308 let first: web_sys::Element = cancel_for_key.clone().into();
1309 let last: web_sys::Element = confirm_for_key.clone().into();
1310 let active = doc_for_key.active_element();
1311 let inside = active.as_ref().is_some_and(|a| card_for_key.contains(a.dyn_ref::<web_sys::Node>()));
1312 let (at_first, at_last) = (active.as_ref() == Some(&first), active.as_ref() == Some(&last));
1313 if e.shift_key() {
1314 if at_first || !inside { e.prevent_default(); let _ = confirm_for_key.focus(); }
1315 } else if at_last || !inside {
1316 e.prevent_default();
1317 let _ = cancel_for_key.focus();
1318 }
1319 }
1320 }) as Box<dyn FnMut(web_sys::KeyboardEvent)>);
1321 cancel.set_onclick(Some(on_cancel.as_ref().unchecked_ref()));
1322 confirm.set_onclick(Some(on_confirm.as_ref().unchecked_ref()));
1323 let _ = scrim.add_event_listener_with_callback("pointerdown", on_pointerdown.as_ref().unchecked_ref());
1324 let _ = scrim.add_event_listener_with_callback("click", on_backdrop.as_ref().unchecked_ref());
1325 let _ = doc.add_event_listener_with_callback("keydown", on_key.as_ref().unchecked_ref());
1326
1327 let ok = rx.await.unwrap_or(false);
1328 let _ = doc.remove_event_listener_with_callback("keydown", on_key.as_ref().unchecked_ref());
1335 let _ = scrim.remove_event_listener_with_callback("click", on_backdrop.as_ref().unchecked_ref());
1336 let _ = scrim.remove_event_listener_with_callback("pointerdown", on_pointerdown.as_ref().unchecked_ref());
1337 cancel.set_onclick(None);
1338 confirm.set_onclick(None);
1339 scrim.remove();
1340 OPEN_CONFIRM.with(|c| {
1343 let mut open = c.borrow_mut();
1344 if open.as_ref().is_some_and(|o| std::rc::Rc::ptr_eq(&o.tx, &tx)) {
1345 *open = None;
1346 }
1347 });
1348 if !superseded.get() {
1351 if let Some(focus_target) = previously_focused.and_then(|e| e.dyn_into::<web_sys::HtmlElement>().ok()) {
1352 let _ = focus_target.focus();
1353 }
1354 }
1355 ok
1356}
1357
1358fn render(widget: &Widget, send: &Dispatch) -> AnyView {
1365 match widget {
1366 Widget::Text { content, style } => {
1368 let (class, content) = (text_class(*style), content.clone());
1369 view! { <p class=class>{content}</p> }.into_any()
1370 }
1371 Widget::Image { source, shape, ratio } => {
1372 let (class, source) = (image_class(*shape, *ratio), source.clone());
1373 view! { <img class=class src=source /> }.into_any()
1374 }
1375 Widget::Badge { label, tone } => {
1376 let (class, label) = (format!("badge {}", tone_class(*tone)), label.clone());
1377 view! { <span class=class>{label}</span> }.into_any()
1378 }
1379 Widget::ColorDot { color } => {
1380 view! { <span class=format!("dot {}", dot_class(*color))></span> }.into_any()
1381 }
1382 Widget::Avatar { source, status } => {
1383 let dot = status.map(|t| view! { <span class=format!("avatar-status {}", tone_class(t))></span> });
1384 view! {
1385 <span class="avatar">
1386 <img class="avatar-img" src=source.clone() />
1387 {dot}
1388 </span>
1389 }
1390 .into_any()
1391 }
1392 Widget::PdfView { url } => {
1393 view! { <iframe class="pdfview" src=url.clone() title="PDF"></iframe> }.into_any()
1395 }
1396 Widget::WebView { url } => {
1397 view! {
1400 <iframe
1401 class="webview"
1402 src=url.clone()
1403 title="Web"
1404 allow="autoplay; fullscreen; picture-in-picture; encrypted-media"
1405 allowfullscreen=true
1406 ></iframe>
1407 }.into_any()
1408 }
1409 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url, interactive } => {
1413 let send = send.clone();
1414 let id = id.clone();
1415 let center = format!("{center_lat},{center_lng}");
1416 let markers_json = serde_json::to_string(markers).unwrap_or_else(|_| "[]".to_string());
1417 let style = style_url.clone().unwrap_or_default();
1418 view! {
1419 <div class="mobiler-map-wrap">
1420 <div
1421 class="mobiler-map"
1422 data-map="1"
1423 data-center=center
1424 data-zoom=zoom.to_string()
1425 data-style=style
1426 data-markers=markers_json
1427 data-interactive=interactive.to_string()
1428 ></div>
1429 <input
1430 class="mobiler-map-sink"
1431 type="text"
1432 tabindex="-1"
1433 aria-hidden="true"
1434 on:input=move |ev| {
1435 let raw = event_target_value(&ev);
1436 if let Some((suffix, value)) = raw.split_once('|') {
1437 send(Action::Input {
1438 id: format!("{id}.{suffix}"),
1439 value: InputValue::Text(value.to_string()),
1440 });
1441 }
1442 }
1443 />
1444 </div>
1445 }.into_any()
1446 }
1447 Widget::Video { url, playing, controls, looping, muted, on_ended, poster, start_at_ms, captions, rate, volume, urls, start_index, .. } => {
1448 use wasm_bindgen::JsCast;
1456 let (send, ended) = (send.clone(), on_ended.clone());
1457 let autoplay = *playing && *muted;
1458 let playlist = urls.clone();
1459 let start_index = (*start_index).max(0) as usize;
1460 let effective = if playlist.is_empty() { url.clone() }
1461 else { playlist.get(start_index).cloned().unwrap_or_else(|| url.clone()) };
1462 let is_hls = effective.to_ascii_lowercase().ends_with(".m3u8");
1463 let src = (!is_hls).then(|| effective.clone());
1464 let hls_src = is_hls.then(|| effective.clone());
1465 let poster_attr = poster.clone();
1466 let start_at = *start_at_ms;
1467 let rate = *rate as f64;
1468 let volume = (*volume as f64).clamp(0.0, 1.0);
1469 let tracks: Vec<_> = captions.iter().map(|c| view! {
1470 <track kind="subtitles" src=c.url.clone() srclang=c.language.clone() label=c.label.clone() default=c.default_on />
1471 }).collect();
1472 let next_idx = std::rc::Rc::new(std::cell::Cell::new(start_index));
1473 view! {
1474 <video
1475 class="video"
1476 src=src
1477 data-hls-src=hls_src
1478 poster=poster_attr
1479 controls=*controls
1480 autoplay=autoplay
1481 prop:loop=*looping
1482 prop:playbackRate=rate
1483 prop:volume=volume
1484 muted=*muted
1485 playsinline=true
1486 on:loadedmetadata=move |ev| {
1487 if start_at >= 0 {
1488 if let Some(v) = ev.target().and_then(|t| t.dyn_into::<web_sys::HtmlVideoElement>().ok()) {
1489 v.set_current_time(start_at as f64 / 1000.0);
1490 }
1491 }
1492 }
1493 on:ended=move |ev| {
1494 let nxt = next_idx.get() + 1;
1495 if !playlist.is_empty() && nxt < playlist.len() {
1496 next_idx.set(nxt);
1497 if let Some(v) = ev.target().and_then(|t| t.dyn_into::<web_sys::HtmlVideoElement>().ok()) {
1498 v.set_src(&playlist[nxt]);
1499 let _ = v.play();
1500 }
1501 } else if let Some(t) = ended.clone() {
1502 send(Action::Fired { token: t });
1503 }
1504 }
1505 >{tracks}</video>
1506 }.into_any()
1507 }
1508 Widget::Rating { value, max, on_rate } => {
1509 let value = *value;
1510 let stars: Vec<AnyView> = (1..=*max)
1511 .map(|i| {
1512 let threshold = u32::from(i) * 10;
1513 let glyph = if value >= threshold { "★" } else if value + 5 >= threshold { "⯨" } else { "☆" };
1515 match on_rate {
1516 Some(tokens) => {
1517 let (send, token) = (send.clone(), tokens.get(usize::from(i - 1)).cloned().unwrap_or_default());
1518 view! {
1519 <button class="star star-tappable" on:click=move |_| send(Action::Fired { token: token.clone() })>
1520 {glyph}
1521 </button>
1522 }
1523 .into_any()
1524 }
1525 None => view! { <span class="star">{glyph}</span> }.into_any(),
1526 }
1527 })
1528 .collect();
1529 view! { <span class="rating">{stars}</span> }.into_any()
1530 }
1531 Widget::Divider => view! { <hr class="divider" /> }.into_any(),
1532 Widget::Progress { value } => match value {
1533 Some(v) => {
1534 let pct = (v.clamp(0.0, 1.0) * 100.0) as u32;
1535 view! { <div class="progress"><div class="progress-bar" style=format!("width:{pct}%")></div></div> }.into_any()
1536 }
1537 None => view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> }.into_any(),
1538 },
1539 Widget::Skeleton => view! { <div class="skeleton"></div> }.into_any(),
1540 Widget::Chart { series, labels, style, axis, legend } => {
1541 chart_view(series, labels, *style, *axis, *legend)
1542 }
1543 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket, legend } => {
1544 region_chart_view(regions, ticks, *x_max, *y_max, ref_lines, bracket, legend)
1545 }
1546 Widget::Calendar { title, weekday_labels, leading_blanks, selected, on_day, markers, .. } => {
1547 let heads: Vec<_> = weekday_labels.iter().map(|w| view! { <div class="cal-head">{w.clone()}</div> }).collect();
1548 let blanks: Vec<_> = (0..*leading_blanks).map(|_| view! { <div class="cal-blank"></div> }).collect();
1549 let selected = *selected;
1550 let days: Vec<_> = on_day.iter().enumerate().map(|(i, token)| {
1551 let day = (i + 1) as u8;
1552 let token = token.clone();
1553 let send = send.clone();
1554 let cls = if selected == Some(day) { "cal-day cal-sel" } else { "cal-day" };
1555 let level = markers.get(i).copied().unwrap_or(0).min(3);
1557 let dots = (level > 0).then(|| {
1558 let d: Vec<_> = (0..level).map(|_| view! { <span class="cal-dot"></span> }).collect();
1559 view! { <span class="cal-dots">{d}</span> }
1560 });
1561 view! { <button class=cls on:click=move |_| send(Action::Fired { token: token.clone() })>{day.to_string()}{dots}</button> }
1562 }).collect();
1563 view! {
1564 <div class="calendar">
1565 <div class="cal-title">{title.clone()}</div>
1566 <div class="cal-grid">{heads}{blanks}{days}</div>
1567 </div>
1568 }.into_any()
1569 }
1570 Widget::SwipeAction { child, actions } => {
1571 let acts: Vec<_> = actions.iter().map(|a| {
1573 let token = a.on_tap.clone();
1574 let send = send.clone();
1575 let cls = format!("swipe-act {}", tone_class(a.tone));
1576 let label = a.label.clone();
1577 view! { <button class=cls on:click=move |_| send(Action::Fired { token: token.clone() })>{label}</button> }
1578 }).collect();
1579 view! {
1580 <div class="swipe-row">
1581 <div class="swipe-content">{render(child, send)}</div>
1582 <div class="swipe-actions">{acts}</div>
1583 </div>
1584 }.into_any()
1585 }
1586 Widget::Spacer { size } => {
1587 view! { <div class=format!("spacer {}", spacer_class(*size))></div> }.into_any()
1588 }
1589
1590 Widget::Row { children } => {
1592 let kids = render_all(children, send);
1593 view! { <div class="row">{kids}</div> }.into_any()
1594 }
1595 Widget::Column { children } => {
1596 let kids = render_all(children, send);
1597 view! { <div class="col">{kids}</div> }.into_any()
1598 }
1599 Widget::Card { child, style, on_press, on_long_press } => {
1600 let class = format!("card {}", card_class(*style));
1601 let body = render(child, send);
1602 match (on_press, on_long_press) {
1603 (None, None) => view! { <div class=class>{body}</div> }.into_any(),
1605 (tap, long) => {
1607 let send = send.clone();
1608 let timer: Rc<RefCell<Option<gloo_timers::callback::Timeout>>> =
1612 Rc::new(RefCell::new(None));
1613 let long_fired = Rc::new(RefCell::new(false));
1614
1615 let on_pointerdown = {
1616 let (send, long, timer, long_fired) =
1617 (send.clone(), long.clone(), timer.clone(), long_fired.clone());
1618 move |_: web_sys::PointerEvent| {
1619 let Some(token) = long.clone() else { return };
1620 *long_fired.borrow_mut() = false;
1621 let (send, long_fired) = (send.clone(), long_fired.clone());
1622 *timer.borrow_mut() = Some(gloo_timers::callback::Timeout::new(
1623 500,
1624 move || {
1625 *long_fired.borrow_mut() = true;
1626 send(Action::Fired { token: token.clone() });
1627 },
1628 ));
1629 }
1630 };
1631 let cancel = {
1632 let timer = timer.clone();
1633 move |_: web_sys::PointerEvent| { timer.borrow_mut().take(); }
1635 };
1636 let on_click = {
1637 let (send, tap, long_fired) = (send.clone(), tap.clone(), long_fired.clone());
1638 move |_| {
1639 if std::mem::take(&mut *long_fired.borrow_mut()) {
1641 return;
1642 }
1643 if let Some(token) = tap.clone() {
1644 send(Action::Fired { token });
1645 }
1646 }
1647 };
1648 view! {
1649 <button
1650 class=format!("{class} card-tappable")
1651 on:pointerdown=on_pointerdown
1652 on:pointerup=cancel.clone()
1653 on:pointerleave=cancel.clone()
1654 on:pointercancel=cancel
1655 on:click=on_click
1656 >
1657 {body}
1658 </button>
1659 }
1660 .into_any()
1661 }
1662 }
1663 }
1664 Widget::Box { children, align, scrim } => {
1668 let acls = align_class(*align);
1669 if *scrim && children.len() > 1 {
1670 let bg = render(&children[0], send);
1671 let content = render_all(&children[1..], send);
1672 view! {
1673 <div class=format!("box box-scrim {acls}")>
1674 {bg}
1675 <div class="scrim"></div>
1676 <div class="box-content">{content}</div>
1677 </div>
1678 }
1679 .into_any()
1680 } else {
1681 let kids = render_all(children, send);
1682 view! { <div class=format!("box {acls}")>{kids}</div> }.into_any()
1683 }
1684 }
1685 Widget::Grid { children } => {
1686 let kids = render_all(children, send);
1687 view! { <div class="grid">{kids}</div> }.into_any()
1688 }
1689 Widget::Scroller { children, edge_fade } => {
1690 let kids = render_all(children, send);
1691 if *edge_fade {
1692 view! { <div class="scroller scroller-fade">{kids}<div class="scroller-end"></div></div> }.into_any()
1693 } else {
1694 view! { <div class="scroller">{kids}</div> }.into_any()
1695 }
1696 }
1697 Widget::Split { primary, detail, show_detail, on_back } => {
1701 let p = render(primary, send);
1702 let d = render(detail, send);
1703 let back_text = format!("‹ {}", shell_label(|l| l.back.clone(), "Back"));
1704 let back_btn = on_back.clone().map(|t| {
1705 let send = send.clone();
1706 view! { <button class="split-back" on:click=move |_| send(Action::Fired { token: t.clone() })>{back_text}</button> }
1707 });
1708 view! {
1709 <div class="split" data-detail=show_detail.then_some("1")>
1710 <div class="split-primary">{p}</div>
1711 <div class="split-detail">{back_btn}{d}</div>
1712 </div>
1713 }.into_any()
1714 }
1715 Widget::A11y { child, label, hint, role } => {
1718 let body = render(child, send);
1719 let role_attr = role.map(a11y_role_aria).unwrap_or("group");
1720 view! {
1721 <div class="a11y" role=role_attr aria-label=label.clone() title=hint.clone()>
1722 {body}
1723 </div>
1724 }.into_any()
1725 }
1726 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing, end_label } => {
1732 let kids = render_all(children, send);
1733 let refresh_text = format!("↻ {}", shell_label(|l| l.refresh.clone(), "Refresh"));
1734 let refresh_btn = on_refresh.clone().map(|token| {
1735 let send = send.clone();
1736 view! { <button class="refresh-btn" on:click=move |_| send(Action::Fired { token: token.clone() })>{refresh_text}</button> }
1737 });
1738 let refresh_bar = refreshing.then(|| view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> });
1739 let loading_bar = loading.then(|| view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> });
1740 let load_more_text = shell_label(|l| l.load_more.clone(), "Load more");
1741 let load_more_btn = (!*loading && *has_more)
1742 .then(|| on_load_more.clone())
1743 .flatten()
1744 .map(|token| {
1745 let send = send.clone();
1746 view! { <button class="btn btn-outlined lazylist-more" on:click=move |_| send(Action::Fired { token: token.clone() })>{load_more_text}</button> }
1747 });
1748 let end_cap = (!*has_more && on_load_more.is_some())
1750 .then(|| end_label.clone())
1751 .flatten()
1752 .map(|label| view! { <div class="lazylist-end">{label}</div> });
1753 view! {
1754 <div class="lazylist">
1755 {refresh_btn}
1756 {refresh_bar}
1757 {kids}
1758 {loading_bar}
1759 {load_more_btn}
1760 {end_cap}
1761 </div>
1762 }.into_any()
1763 }
1764
1765 Widget::Button { label, style, on_press, tone, icon, wide } => {
1767 let (send, token, label) = (send.clone(), on_press.clone(), label.clone());
1768 let mut class = format!("btn {}", button_class(*style));
1770 if *tone != Tone::Neutral {
1771 class.push(' ');
1772 class.push_str(button_tone_class(*tone));
1773 }
1774 if *wide {
1775 class.push_str(" btn-wide");
1776 }
1777 let glyph = icon.map(|i| view! { <span class="btn-icon">{icon_glyph(i)}</span> });
1778 view! {
1779 <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1780 {glyph}
1781 {label}
1782 </button>
1783 }
1784 .into_any()
1785 }
1786 Widget::IconButton { icon, on_press } => {
1787 let (send, token) = (send.clone(), on_press.clone());
1788 let glyph = icon_glyph(*icon);
1789 view! {
1790 <button class="iconbtn" on:click=move |_| send(Action::Fired { token: token.clone() })>
1791 {glyph}
1792 </button>
1793 }
1794 .into_any()
1795 }
1796 Widget::Chip { label, selected, on_press } => {
1797 let (send, token, label) = (send.clone(), on_press.clone(), label.clone());
1798 let class = if *selected { "chip selected" } else { "chip" };
1799 view! {
1800 <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1801 {label}
1802 </button>
1803 }
1804 .into_any()
1805 }
1806 Widget::TextField { id, placeholder, value, kind, error } => {
1807 let (send, id) = (send.clone(), id.clone());
1808 let (placeholder, value) = (placeholder.clone(), value.clone());
1809 let invalid = error.is_some();
1810 let err_view = error.clone().map(|m| view! { <div class="field-error">{m}</div> });
1811 let (itype, imode): (&str, &str) = match kind {
1813 FieldKind::Secure => ("password", ""),
1814 FieldKind::Email => ("email", "email"),
1815 FieldKind::Number => ("text", "numeric"),
1816 FieldKind::Decimal => ("text", "decimal"),
1817 FieldKind::Phone => ("tel", "tel"),
1818 FieldKind::Url => ("url", "url"),
1819 FieldKind::Text | FieldKind::Multiline => ("text", ""),
1820 };
1821 let field_class = if invalid { "field field-invalid" } else { "field" };
1822 let control = if matches!(kind, FieldKind::Multiline) {
1823 view! {
1824 <textarea
1825 class=field_class
1826 rows="3"
1827 placeholder=placeholder
1828 prop:value=value
1829 on:input=move |ev| send(Action::Input {
1830 id: id.clone(),
1831 value: InputValue::Text(event_target_value(&ev)),
1832 })
1833 ></textarea>
1834 }
1835 .into_any()
1836 } else {
1837 view! {
1838 <input
1839 class=field_class
1840 r#type=itype
1841 inputmode=imode
1842 placeholder=placeholder
1843 prop:value=value
1844 on:input=move |ev| send(Action::Input {
1845 id: id.clone(),
1846 value: InputValue::Text(event_target_value(&ev)),
1847 })
1848 />
1849 }
1850 .into_any()
1851 };
1852 view! { <div class="field-wrap">{control}{err_view}</div> }.into_any()
1853 }
1854 Widget::SearchField { id, placeholder, value } => {
1855 let (send, id) = (send.clone(), id.clone());
1856 let (placeholder, value) = (placeholder.clone(), value.clone());
1857 view! {
1858 <div class="searchfield">
1859 <span class="search-icon">{icon_glyph(Icon::Search)}</span>
1860 <input
1861 class="search-input"
1862 placeholder=placeholder
1863 prop:value=value
1864 on:input=move |ev| send(Action::Input {
1865 id: id.clone(),
1866 value: InputValue::Text(event_target_value(&ev)),
1867 })
1868 />
1869 </div>
1870 }
1871 .into_any()
1872 }
1873 Widget::Segmented { segments } => {
1874 let segs: Vec<AnyView> = segments
1875 .iter()
1876 .map(|s| {
1877 let (send, token) = (send.clone(), s.on_select.clone());
1878 let class = if s.selected { "segment selected" } else { "segment" };
1879 let label = s.label.clone();
1880 view! {
1881 <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1882 {label}
1883 </button>
1884 }
1885 .into_any()
1886 })
1887 .collect();
1888 view! { <div class="segmented">{segs}</div> }.into_any()
1889 }
1890 Widget::Toggle { id, label, value } => {
1891 let (send, id, label, checked) = (send.clone(), id.clone(), label.clone(), *value);
1892 view! {
1893 <label class="toggle">
1894 {label}
1895 <input
1896 type="checkbox"
1897 role="switch"
1898 prop:checked=checked
1899 on:change=move |ev| send(Action::Input {
1900 id: id.clone(),
1901 value: InputValue::Bool(event_target_checked(&ev)),
1902 })
1903 />
1904 </label>
1905 }
1906 .into_any()
1907 }
1908 Widget::Checkbox { id, label, value } => {
1909 let (send, id, label, checked) = (send.clone(), id.clone(), label.clone(), *value);
1910 view! {
1911 <label class="check">
1912 <input
1913 type="checkbox"
1914 prop:checked=checked
1915 on:change=move |ev| send(Action::Input {
1916 id: id.clone(),
1917 value: InputValue::Bool(event_target_checked(&ev)),
1918 })
1919 />
1920 {label}
1921 </label>
1922 }
1923 .into_any()
1924 }
1925 Widget::Slider { id, value, max } => {
1926 let (send, id, value, max) = (send.clone(), id.clone(), *value, *max);
1927 view! {
1928 <input
1929 class="slider"
1930 type="range"
1931 min="0"
1932 max=max
1933 prop:value=value
1934 on:input=move |ev| send(Action::Input {
1935 id: id.clone(),
1936 value: InputValue::Int(event_target_value(&ev).parse().unwrap_or(0)),
1937 })
1938 />
1939 }
1940 .into_any()
1941 }
1942 Widget::Stepper { value, on_decrement, on_increment } => {
1943 let send_dec = send.clone();
1944 let send_inc = send.clone();
1945 let (dec, inc) = (on_decrement.clone(), on_increment.clone());
1946 view! {
1947 <div class="stepper">
1948 <button on:click=move |_| send_dec(Action::Fired { token: dec.clone() })>"−"</button>
1949 <span class="stepper-value">{*value}</span>
1950 <button on:click=move |_| send_inc(Action::Fired { token: inc.clone() })>"+"</button>
1951 </div>
1952 }
1953 .into_any()
1954 }
1955
1956 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth, labels: _ } => {
1958 let back_aria = shell_label(|l| l.back.clone(), "Back");
1963 let back_btn = back.clone().map(|token| {
1964 let send = send.clone();
1965 view! {
1966 <button class="back" aria-label=back_aria on:click=move |_| send(Action::Fired { token: token.clone() })>
1967 "‹"
1968 </button>
1969 }
1970 });
1971 let tabbar = (!tabs.is_empty()).then(|| {
1972 let tabs: Vec<AnyView> = tabs
1973 .iter()
1974 .map(|tab| {
1975 let (send, token) = (send.clone(), tab.on_select.clone());
1976 let class = if tab.selected { "tab selected" } else { "tab" };
1977 let label = tab.label.clone();
1978 let icon = tab.icon.map(|i| view! { <span class="tab-icon">{icon_glyph(i)}</span> });
1980 view! {
1981 <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1982 {icon}
1983 <span class="tab-label">{label}</span>
1984 </button>
1985 }
1986 .into_any()
1987 })
1988 .collect();
1989 view! { <div class="tabbar">{tabs}</div> }
1990 });
1991 let fab_btn = fab.clone().map(|f| {
1993 let (send, token) = (send.clone(), f.on_press.clone());
1994 view! {
1995 <button class="fab" on:click=move |_| send(Action::Fired { token: token.clone() })>
1996 {icon_glyph(f.icon)}
1997 </button>
1998 }
1999 });
2000 let sheet_overlay = sheet.as_ref().map(|s| {
2002 let (send_scrim, dismiss) = (send.clone(), s.on_dismiss.clone());
2003 let (title, child) = (s.title.clone(), render(&s.child, send));
2004 view! {
2005 <div class="sheet-scrim" on:click=move |_| send_scrim(Action::Fired { token: dismiss.clone() })></div>
2006 <div class="sheet">
2007 <div class="sheet-handle"></div>
2008 <div class="sheet-title">{title}</div>
2009 {child}
2010 </div>
2011 }
2012 });
2013 let large = theme.as_ref().is_some_and(|t| t.density == Density::Large);
2017 let class = format!("scaffold{}{}", if *dark_mode { " theme-dark" } else { "" }, if large { " density-large" } else { "" });
2018 let refresh_aria = shell_label(|l| l.refresh.clone(), "Refresh");
2021 let refresh_btn = on_refresh.clone().map(|token| {
2022 let send = send.clone();
2023 view! {
2024 <button class="refresh-btn" aria-label=refresh_aria on:click=move |_| send(Action::Fired { token: token.clone() })>"↻"</button>
2025 }
2026 });
2027 let refresh_bar = refreshing.then(|| {
2028 view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> }
2029 });
2030 let body_class = format!("scaffold-body {}", nav_class(route, *depth));
2031 let theme_style = theme.as_ref().map(theme_css).unwrap_or_default();
2034 let (title, body) = (title.clone(), render(body, send));
2035 view! {
2036 <div class=class style=theme_style>
2037 <div class="topbar">
2038 {back_btn}
2039 <span class="title">{title}</span>
2040 {refresh_btn}
2041 </div>
2042 <div class=body_class data-route=route.clone()>{refresh_bar}{body}</div>
2043 {fab_btn}
2044 {tabbar}
2045 {sheet_overlay}
2046 </div>
2047 }
2048 .into_any()
2049 }
2050 }
2051}
2052
2053fn render_all(children: &[Widget], send: &Dispatch) -> Vec<AnyView> {
2055 children.iter().map(|c| render(c, send)).collect()
2056}
2057
2058thread_local! {
2059 static NAV: RefCell<(String, u32, bool)> = const { RefCell::new((String::new(), 0, false)) };
2064
2065 static STREAMS: RefCell<HashMap<String, StreamHandle>> = RefCell::new(HashMap::new());
2069
2070 static ACTIVE_LABELS: std::cell::RefCell<Option<ShellLabels>> = const { std::cell::RefCell::new(None) };
2074}
2075
2076fn shell_label(pick: impl Fn(&ShellLabels) -> Option<String>, default: &str) -> String {
2079 ACTIVE_LABELS.with(|l| {
2080 l.borrow()
2081 .as_ref()
2082 .and_then(pick)
2083 .filter(|s| !s.is_empty())
2084 .unwrap_or_else(|| default.to_string())
2085 })
2086}
2087
2088fn theme_css(t: &Theme) -> String {
2093 let (r, g, b) = (t.seed.r, t.seed.g, t.seed.b);
2094 let radius = match t.corner {
2095 Corner::None => "0px",
2096 Corner::Small => "8px",
2097 Corner::Medium => "14px",
2098 Corner::Large => "22px",
2099 };
2100 let (gap, pad) = match t.density {
2101 Density::Compact => ("8px", "10px"),
2102 Density::Comfortable => ("12px", "14px"),
2103 Density::Large => ("16px", "18px"),
2104 };
2105 let font = match t.font {
2106 FontFamily::System => "system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif",
2107 FontFamily::Rounded => "ui-rounded, \"SF Pro Rounded\", \"Segoe UI\", system-ui, sans-serif",
2108 FontFamily::Serif => "ui-serif, Georgia, \"Times New Roman\", serif",
2109 FontFamily::Monospace => "ui-monospace, \"SF Mono\", \"Cascadia Code\", Menlo, monospace",
2110 };
2111 let (ar, ag, ab) = t.accent.map_or((r, g, b), |a| (a.r, a.g, a.b));
2113 format!(
2114 "--primary:rgb({r},{g},{b});--accent:rgb({r},{g},{b});\
2115 --accent2:rgb({ar},{ag},{ab});\
2116 --accent-soft:rgba({r},{g},{b},0.16);--radius:{radius};\
2117 --gap:{gap};--pad:{pad};--font:{font};"
2118 )
2119}
2120
2121fn nav_class(route: &str, depth: u32) -> &'static str {
2128 NAV.with_borrow_mut(|(prev_route, prev_depth, toggle)| {
2129 if route == prev_route {
2130 return "";
2131 }
2132 let dir = if depth > *prev_depth {
2133 ["nav-push-a", "nav-push-b"]
2134 } else if depth < *prev_depth {
2135 ["nav-pop-a", "nav-pop-b"]
2136 } else {
2137 ["nav-fade-a", "nav-fade-b"]
2138 };
2139 *toggle = !*toggle;
2140 *prev_route = route.to_string();
2141 *prev_depth = depth;
2142 dir[usize::from(*toggle)]
2143 })
2144}
2145
2146fn text_class(s: TextStyle) -> &'static str {
2149 match s {
2150 TextStyle::Title => "t-title",
2151 TextStyle::Subtitle => "t-subtitle",
2152 TextStyle::Caption => "t-caption",
2153 TextStyle::Emphasis => "t-emphasis",
2154 TextStyle::Body => "t-body",
2155 }
2156}
2157
2158fn button_class(s: ButtonStyle) -> &'static str {
2159 match s {
2160 ButtonStyle::Filled => "btn-filled",
2161 ButtonStyle::Outlined => "btn-outlined",
2162 ButtonStyle::Text => "btn-text",
2163 ButtonStyle::Tonal => "btn-tonal",
2164 }
2165}
2166
2167fn button_tone_class(t: Tone) -> &'static str {
2168 match t {
2169 Tone::Neutral => "",
2170 Tone::Success => "btn-success",
2171 Tone::Warning => "btn-warning",
2172 Tone::Danger => "btn-danger",
2173 Tone::Info => "btn-info",
2174 }
2175}
2176
2177fn card_class(s: CardStyle) -> &'static str {
2178 match s {
2179 CardStyle::Elevated => "card-elevated",
2180 CardStyle::Outlined => "card-outlined",
2181 CardStyle::Filled => "card-filled",
2182 CardStyle::Brand => "card-brand",
2183 }
2184}
2185
2186fn a11y_role_aria(role: A11yRole) -> &'static str {
2187 match role {
2188 A11yRole::Button => "button",
2189 A11yRole::Link => "link",
2190 A11yRole::Image => "img",
2191 A11yRole::Header => "heading",
2192 A11yRole::Adjustable => "slider",
2193 }
2194}
2195
2196fn tone_class(t: Tone) -> &'static str {
2197 match t {
2198 Tone::Neutral => "tone-neutral",
2199 Tone::Success => "tone-success",
2200 Tone::Warning => "tone-warning",
2201 Tone::Danger => "tone-danger",
2202 Tone::Info => "tone-info",
2203 }
2204}
2205
2206fn spacer_class(s: Spacing) -> &'static str {
2207 match s {
2208 Spacing::Xs => "sp-xs",
2209 Spacing::Sm => "sp-sm",
2210 Spacing::Md => "sp-md",
2211 Spacing::Lg => "sp-lg",
2212 Spacing::Xl => "sp-xl",
2213 }
2214}
2215
2216fn icon_glyph(i: Icon) -> &'static str {
2217 match i {
2218 Icon::Delete => "🗑",
2219 Icon::Add => "+",
2220 Icon::Edit => "✏️",
2221 Icon::Close => "✕",
2222 Icon::Settings => "⚙",
2223 Icon::Check => "✓",
2224 Icon::Star => "★",
2225 Icon::Info => "ℹ",
2226 Icon::Home => "⌂",
2227 Icon::Search => "🔍",
2228 Icon::Menu => "☰",
2229 Icon::Filter => "⚟",
2230 Icon::Back => "‹",
2231 Icon::Forward => "›",
2232 Icon::Down => "⌄",
2233 Icon::Bell => "🔔",
2234 Icon::Cart => "🛒",
2235 Icon::Share => "↗",
2236 Icon::Heart => "♡",
2237 Icon::HeartFilled => "♥",
2238 Icon::Person => "👤",
2239 Icon::People => "👥",
2240 Icon::Phone => "📞",
2241 Icon::Mail => "✉",
2242 Icon::Calendar => "📅",
2243 Icon::Clock => "🕑",
2244 Icon::MapPin => "📍",
2245 Icon::Camera => "📷",
2246 Icon::Photo => "🖼",
2247 Icon::Play => "▶",
2248 Icon::Scissors => "✂",
2249 }
2250}
2251
2252fn image_class(shape: ImageShape, ratio: ImageRatio) -> String {
2253 let shape = match shape {
2254 ImageShape::Square => "img-square",
2255 ImageShape::Rounded => "img-rounded",
2256 ImageShape::Circle => "img-circle",
2257 };
2258 let ratio = match ratio {
2259 ImageRatio::Wide => "ratio-wide",
2260 ImageRatio::Square => "ratio-square",
2261 ImageRatio::Tall => "ratio-tall",
2262 };
2263 format!("img {shape} {ratio}")
2264}
2265
2266fn dot_class(c: ProjectColor) -> &'static str {
2267 match c {
2268 ProjectColor::Indigo => "dot-indigo",
2269 ProjectColor::Teal => "dot-teal",
2270 ProjectColor::Coral => "dot-coral",
2271 ProjectColor::Amber => "dot-amber",
2272 ProjectColor::Lime => "dot-lime",
2273 ProjectColor::Pink => "dot-pink",
2274 }
2275}
2276
2277fn align_class(a: BoxAlign) -> &'static str {
2278 match a {
2279 BoxAlign::TopStart => "align-top-start",
2280 BoxAlign::TopEnd => "align-top-end",
2281 BoxAlign::Center => "align-center",
2282 BoxAlign::BottomStart => "align-bottom-start",
2283 BoxAlign::BottomCenter => "align-bottom-center",
2284 BoxAlign::BottomEnd => "align-bottom-end",
2285 }
2286}
2287
2288const CHART_PALETTE: [&str; 6] = ["#E0772C", "#2EA06A", "#C0466B", "#8A5CC0", "#C9A227", "#3FA7D6"];
2292
2293fn hex(c: Rgb) -> String {
2294 format!("#{:02x}{:02x}{:02x}", c.r, c.g, c.b)
2295}
2296
2297fn chart_color(i: usize, s: &ChartSeries) -> String {
2299 match s.color {
2300 Some(c) => hex(c),
2301 None if i == 0 => "var(--accent, #5C6BC0)".to_string(),
2302 None => CHART_PALETTE[(i - 1) % CHART_PALETTE.len()].to_string(),
2303 }
2304}
2305
2306fn chart_mag(s: &ChartSeries) -> f32 {
2308 s.values.iter().copied().sum()
2309}
2310
2311fn polar(cx: f32, cy: f32, r: f32, ang: f32) -> (f32, f32) {
2313 (cx + r * ang.sin(), cy - r * ang.cos())
2314}
2315
2316fn arc_path(cx: f32, cy: f32, r: f32, a0: f32, a1: f32) -> String {
2318 let (x0, y0) = polar(cx, cy, r, a0);
2319 let (x1, y1) = polar(cx, cy, r, a1);
2320 let large = if (a1 - a0).abs() > std::f32::consts::PI { 1 } else { 0 };
2321 format!("M {x0:.2} {y0:.2} A {r:.2} {r:.2} 0 {large} 1 {x1:.2} {y1:.2}")
2322}
2323
2324fn wedge_path(cx: f32, cy: f32, r: f32, a0: f32, a1: f32) -> String {
2326 let (x0, y0) = polar(cx, cy, r, a0);
2327 let (x1, y1) = polar(cx, cy, r, a1);
2328 let large = if (a1 - a0).abs() > std::f32::consts::PI { 1 } else { 0 };
2329 format!("M {cx:.2} {cy:.2} L {x0:.2} {y0:.2} A {r:.2} {r:.2} 0 {large} 1 {x1:.2} {y1:.2} Z")
2330}
2331
2332fn fmt_tick(v: f32) -> String {
2333 if (v - v.round()).abs() < 0.05 { format!("{}", v.round() as i64) } else { format!("{v:.1}") }
2334}
2335
2336fn is_cartesian(style: ChartStyle) -> bool {
2337 matches!(style, ChartStyle::Bar | ChartStyle::Line | ChartStyle::StackedBar | ChartStyle::StackedBar100)
2338}
2339
2340fn cartesian_max(series: &[ChartSeries], style: ChartStyle, nslots: usize) -> f32 {
2342 match style {
2343 ChartStyle::StackedBar => (0..nslots)
2344 .map(|j| series.iter().map(|s| *s.values.get(j).unwrap_or(&0.0)).sum::<f32>())
2345 .fold(0.0, f32::max)
2346 .max(1e-6),
2347 ChartStyle::StackedBar100 => 1.0,
2348 _ => series.iter().flat_map(|s| s.values.iter().copied()).fold(0.0, f32::max).max(1e-6),
2349 }
2350}
2351
2352fn cartesian_svg(series: &[ChartSeries], style: ChartStyle, axis: bool, max: f32, nslots: usize) -> AnyView {
2353 let mut nodes: Vec<AnyView> = Vec::new();
2355 if axis {
2356 for k in 0..=4 {
2357 let y = 2.0 + k as f32 * (46.0 / 4.0);
2358 nodes.push(view! { <line x1="0" y1=format!("{y:.2}") x2="100" y2=format!("{y:.2}") class="chart-gridline"></line> }.into_any());
2359 }
2360 }
2361 match style {
2362 ChartStyle::Line => {
2363 for (i, s) in series.iter().enumerate() {
2364 let n = s.values.len().max(1);
2365 let pts = s.values.iter().enumerate().map(|(j, v)| {
2366 let x = if n == 1 { 50.0 } else { j as f32 * (100.0 / (n as f32 - 1.0)) };
2367 let y = 2.0 + (1.0 - (v / max).clamp(0.0, 1.0)) * 46.0;
2368 format!("{x:.2},{y:.2}")
2369 }).collect::<Vec<_>>().join(" ");
2370 let st = format!("fill:none;stroke:{};stroke-width:1.5;vector-effect:non-scaling-stroke", chart_color(i, s));
2371 nodes.push(view! { <polyline points=pts style=st></polyline> }.into_any());
2372 }
2373 }
2374 ChartStyle::Bar => {
2375 let sw = 100.0 / nslots as f32;
2376 let ns = series.len().max(1);
2377 for (i, s) in series.iter().enumerate() {
2378 let st = format!("fill:{}", chart_color(i, s));
2379 for (j, v) in s.values.iter().enumerate() {
2380 let h = (v / max).clamp(0.0, 1.0) * 46.0;
2381 let bw = sw * 0.8 / ns as f32;
2382 let x = j as f32 * sw + sw * 0.1 + i as f32 * bw;
2383 let y = 48.0 - h;
2384 nodes.push(view! { <rect x=format!("{x:.2}") y=format!("{y:.2}") width=format!("{bw:.2}") height=format!("{h:.2}") style=st.clone()></rect> }.into_any());
2385 }
2386 }
2387 }
2388 ChartStyle::StackedBar | ChartStyle::StackedBar100 => {
2389 let sw = 100.0 / nslots as f32;
2390 for j in 0..nslots {
2391 let slot_total = series.iter().map(|s| *s.values.get(j).unwrap_or(&0.0)).sum::<f32>().max(1e-6);
2392 let denom = if matches!(style, ChartStyle::StackedBar100) { slot_total } else { max };
2393 let mut acc = 0.0_f32;
2394 for (i, s) in series.iter().enumerate() {
2395 let v = *s.values.get(j).unwrap_or(&0.0);
2396 let h = (v / denom).clamp(0.0, 1.0) * 46.0;
2397 let x = j as f32 * sw + sw * 0.15;
2398 let bw = sw * 0.7;
2399 let y = 48.0 - acc - h;
2400 let st = format!("fill:{}", chart_color(i, s));
2401 nodes.push(view! { <rect x=format!("{x:.2}") y=format!("{y:.2}") width=format!("{bw:.2}") height=format!("{h:.2}") style=st></rect> }.into_any());
2402 acc += h;
2403 }
2404 }
2405 }
2406 _ => {}
2407 }
2408 view! { <svg viewBox="0 0 100 50" preserveAspectRatio="none" class="chart-svg">{nodes}</svg> }.into_any()
2409}
2410
2411fn circular_svg(series: &[ChartSeries], style: ChartStyle) -> AnyView {
2412 use std::f32::consts::PI;
2413 let mut nodes: Vec<AnyView> = Vec::new();
2414 match style {
2415 ChartStyle::Pie | ChartStyle::Donut => {
2416 let total = series.iter().map(chart_mag).sum::<f32>().max(1e-6);
2417 let mut a = 0.0_f32;
2418 for (i, s) in series.iter().enumerate() {
2419 let frac = chart_mag(s) / total;
2420 let st = format!("fill:{}", chart_color(i, s));
2421 if frac >= 0.999 {
2422 nodes.push(view! { <circle cx="50" cy="50" r="45" style=st></circle> }.into_any());
2423 } else if frac > 0.0 {
2424 let d = wedge_path(50.0, 50.0, 45.0, a, a + frac * 2.0 * PI);
2425 nodes.push(view! { <path d=d style=st></path> }.into_any());
2426 }
2427 a += frac * 2.0 * PI;
2428 }
2429 if matches!(style, ChartStyle::Donut) {
2430 nodes.push(view! { <circle cx="50" cy="50" r="24" style="fill:var(--surface, #ffffff)"></circle> }.into_any());
2431 }
2432 }
2433 ChartStyle::Rings => {
2434 let n = series.len().max(1);
2435 for (i, s) in series.iter().enumerate() {
2436 let r = 45.0 - i as f32 * (34.0 / n as f32);
2437 let goal = s.goal.unwrap_or_else(|| chart_mag(s)).max(1e-6);
2438 let prog = (chart_mag(s) / goal).clamp(0.0, 1.0);
2439 nodes.push(view! { <circle cx="50" cy="50" r=format!("{r:.2}") style="fill:none;stroke:var(--border, #e6e6e6);stroke-width:6"></circle> }.into_any());
2440 let st = format!("fill:none;stroke:{};stroke-width:6;stroke-linecap:round", chart_color(i, s));
2441 if prog >= 0.999 {
2442 nodes.push(view! { <circle cx="50" cy="50" r=format!("{r:.2}") style=st></circle> }.into_any());
2443 } else if prog > 0.0 {
2444 let d = arc_path(50.0, 50.0, r, 0.0, prog * 2.0 * PI);
2445 nodes.push(view! { <path d=d style=st></path> }.into_any());
2446 }
2447 }
2448 }
2449 ChartStyle::Gauge => {
2450 let s = match series.first() { Some(s) => s, None => return view! { <svg viewBox="0 0 100 100" class="chart-svg"></svg> }.into_any() };
2451 let goal = s.goal.unwrap_or_else(|| chart_mag(s)).max(1e-6);
2452 let prog = (chart_mag(s) / goal).clamp(0.0, 1.0);
2453 let a0 = -0.75 * PI; let a1 = 0.75 * PI;
2455 nodes.push(view! { <path d=arc_path(50.0, 50.0, 42.0, a0, a1) style="fill:none;stroke:var(--border, #e6e6e6);stroke-width:8;stroke-linecap:round"></path> }.into_any());
2456 if prog > 0.0 {
2457 let st = format!("fill:none;stroke:{};stroke-width:8;stroke-linecap:round", chart_color(0, s));
2458 nodes.push(view! { <path d=arc_path(50.0, 50.0, 42.0, a0, a0 + prog * 1.5 * PI) style=st></path> }.into_any());
2459 }
2460 let pct = format!("{}%", (prog * 100.0).round() as i64);
2461 nodes.push(view! { <text x="50" y="56" style="fill:var(--fg, #222);font-size:20px;font-weight:700;text-anchor:middle">{pct}</text> }.into_any());
2462 }
2463 _ => {}
2464 }
2465 view! { <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" class="chart-svg">{nodes}</svg> }.into_any()
2466}
2467
2468fn chart_view(series: &[ChartSeries], labels: &[String], style: ChartStyle, axis: bool, legend: bool) -> AnyView {
2469 let cartesian = is_cartesian(style);
2470 let nslots = series.iter().map(|s| s.values.len()).max().unwrap_or(0).max(1);
2471 let max = cartesian_max(series, style, nslots);
2472
2473 let plot = if cartesian {
2474 let svg = cartesian_svg(series, style, axis, max, nslots);
2475 let yaxis = if axis {
2476 let ticks: Vec<_> = [max, max / 2.0, 0.0].iter()
2477 .map(|t| view! { <span class="chart-tick">{fmt_tick(*t)}</span> })
2478 .collect();
2479 Some(view! { <div class="chart-yaxis">{ticks}</div> })
2480 } else {
2481 None
2482 };
2483 view! { <div class="chart-plot">{yaxis}{svg}</div> }.into_any()
2484 } else {
2485 circular_svg(series, style).into_any()
2486 };
2487
2488 let label_row = if cartesian && !labels.is_empty() {
2489 let items: Vec<_> = labels.iter().map(|l| view! { <span class="chart-label">{l.clone()}</span> }).collect();
2490 Some(view! { <div class="chart-labels">{items}</div> })
2491 } else {
2492 None
2493 };
2494
2495 let legend_row = if legend {
2496 let items: Vec<_> = series.iter().enumerate().map(|(i, s)| {
2497 let sw = format!("background:{}", chart_color(i, s));
2498 let name = s.name.clone();
2499 view! { <span class="chart-legend-item"><span class="chart-swatch" style=sw></span>{name}</span> }
2500 }).collect();
2501 Some(view! { <div class="chart-legend">{items}</div> })
2502 } else {
2503 None
2504 };
2505
2506 view! { <div class="chart">{plot}{label_row}{legend_row}</div> }.into_any()
2507}
2508
2509const CHART_PALETTE_RGB: [(u8, u8, u8); 6] =
2513 [(0xE0, 0x77, 0x2C), (0x2E, 0xA0, 0x6A), (0xC0, 0x46, 0x6B), (0x8A, 0x5C, 0xC0), (0xC9, 0xA2, 0x27), (0x3F, 0xA7, 0xD6)];
2514
2515fn region_rgb(i: usize, r: &ChartRegion) -> (u8, u8, u8) {
2517 match r.color {
2518 Some(c) => (c.r, c.g, c.b),
2519 None => CHART_PALETTE_RGB[i % CHART_PALETTE_RGB.len()],
2520 }
2521}
2522
2523fn contrast_text((r, g, b): (u8, u8, u8)) -> &'static str {
2525 let lum = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
2526 if lum > 140.0 { "#1a1a1a" } else { "#f5f5f5" }
2527}
2528
2529fn region_color(i: usize, r: &ChartRegion) -> String {
2530 let (r8, g8, b8) = region_rgb(i, r);
2531 format!("#{r8:02x}{g8:02x}{b8:02x}")
2532}
2533
2534fn region_chart_view(
2538 regions: &[ChartRegion],
2539 ticks: &[ChartTick],
2540 x_max: f32,
2541 y_max: f32,
2542 ref_lines: &[ChartRefLine],
2543 bracket: &Option<ChartBracket>,
2544 legend: &[ChartLegendItem],
2545) -> AnyView {
2546 let xm = x_max.max(1e-6);
2547 let ym = y_max.max(1e-6);
2548
2549 let region_divs: Vec<_> = regions.iter().enumerate().map(|(i, r)| {
2550 let left = (r.x0 / xm * 100.0).clamp(0.0, 100.0);
2551 let width = ((r.x1 - r.x0) / xm * 100.0).clamp(0.0, 100.0);
2552 let bottom = (r.y0 / ym * 100.0).clamp(0.0, 100.0);
2553 let height = ((r.y1 - r.y0) / ym * 100.0).clamp(0.0, 100.0);
2554 let style = format!("left:{left:.3}%;width:{width:.3}%;bottom:{bottom:.3}%;height:{height:.3}%;background:{}", region_color(i, r));
2555 let label_class = if r.vertical { "rchart-label rchart-label-v" } else { "rchart-label" };
2556 let label_style = format!("color:{}", contrast_text(region_rgb(i, r)));
2557 let label = r.label.clone();
2558 view! { <div class="rchart-region" style=style><span class=label_class style=label_style>{label}</span></div> }
2559 }).collect();
2560
2561 let ref_line_divs: Vec<_> = ref_lines.iter().map(|rl| {
2564 let style = format!("bottom:{:.3}%", (rl.value / ym * 100.0).clamp(0.0, 100.0));
2565 let cls = if rl.dashed { "rchart-refline rchart-refline-dashed" } else { "rchart-refline" };
2566 view! { <div class=cls style=style></div> }
2567 }).collect();
2568 let chip_divs: Vec<_> = ref_lines.iter().map(|rl| {
2569 let style = format!("bottom:{:.3}%", (rl.value / ym * 100.0).clamp(0.0, 100.0));
2570 let label = rl.label.clone();
2571 view! { <div class="rchart-chip" style=style>{label}</div> }
2572 }).collect();
2573
2574 let bracket_div = bracket.as_ref().map(|b| {
2575 let bottom = (b.y0 / ym * 100.0).clamp(0.0, 100.0);
2576 let height = ((b.y1 - b.y0) / ym * 100.0).clamp(0.0, 100.0);
2577 let style = format!("bottom:{bottom:.3}%;height:{height:.3}%");
2578 let label = if b.info { format!("ⓘ\n{}", b.label) } else { b.label.clone() };
2579 view! { <div class="rchart-bracket" style=style><span>{label}</span></div> }
2580 });
2581
2582 let yticks: Vec<_> = (0..=4).rev().map(|k| {
2583 let v = ym * k as f32 / 4.0;
2584 view! { <span class="chart-tick">{fmt_tick(v)}</span> }
2585 }).collect();
2586
2587 let xticks: Vec<_> = ticks.iter().map(|t| {
2588 let style = format!("left:{:.3}%", (t.at / xm * 100.0).clamp(0.0, 100.0));
2589 let label = t.label.clone();
2590 view! { <span class="rchart-xtick" style=style>{label}</span> }
2591 }).collect();
2592
2593 let ytick_marks: Vec<_> = (0..=4).map(|k| {
2596 let style = format!("bottom:{:.3}%", k as f32 * 25.0);
2597 view! { <div class="rchart-ytick" style=style></div> }
2598 }).collect();
2599 let xtick_marks: Vec<_> = ticks.iter().map(|t| {
2600 let style = format!("left:{:.3}%", (t.at / xm * 100.0).clamp(0.0, 100.0));
2601 view! { <div class="rchart-xtickmark" style=style></div> }
2602 }).collect();
2603
2604 let legend_row = if legend.is_empty() {
2605 None
2606 } else {
2607 let items: Vec<_> = legend.iter().map(|l| {
2608 let sw = format!("background:{}", hex(l.color));
2609 let name = l.label.clone();
2610 view! { <span class="chart-legend-item"><span class="chart-swatch" style=sw></span>{name}</span> }
2611 }).collect();
2612 Some(view! { <div class="chart-legend">{items}</div> })
2613 };
2614
2615 view! {
2616 <div class="rchart">
2617 <div class="rchart-row">
2618 <div class="rchart-yaxis">{yticks}</div>
2619 <div class="rchart-plotwrap">
2620 <div class="rchart-plot">{region_divs}{ytick_marks}{xtick_marks}{ref_line_divs}</div>
2621 {chip_divs}{bracket_div}
2622 </div>
2623 </div>
2624 <div class="rchart-xaxis">{xticks}</div>
2625 {legend_row}
2626 </div>
2627 }.into_any()
2628}