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, 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 || render(&view.get(), &send_for_view)}
213 </div>
214 }
215}
216
217fn drive<A: WebApp>(core: &Arc<Core<A>>, set_view: WriteSignal<Widget>, effects: Vec<Effect>)
219where
220 A::Model: Default + Send + Sync,
221{
222 for effect in effects {
223 match effect {
224 Effect::Render(_) => set_view.set(core.view()),
225 Effect::PluginNotify(notify) => perform_notify(¬ify.operation),
226 Effect::Plugin(mut request) => {
227 let core = core.clone();
228 spawn_local(async move {
229 let response = perform(&request.operation).await;
230 if let Ok(next) = core.resolve(&mut request, response) {
231 drive(&core, set_view, next);
232 }
233 });
234 }
235 Effect::PluginStream(request) => start_stream(core, set_view, request),
238 }
239 }
240}
241
242fn start_stream<A: WebApp>(
251 core: &Arc<Core<A>>,
252 set_view: WriteSignal<Widget>,
253 request: Request<PluginStreamCall>,
254) where
255 A::Model: Default + Send + Sync,
256{
257 use wasm_bindgen::{closure::Closure, JsCast};
258
259 let call = request.operation.clone();
260
261 let request = Rc::new(RefCell::new(request));
264 let core = core.clone();
265 let emit = move |resp: PluginResponse| {
266 if let Ok(next) = core.resolve(&mut *request.borrow_mut(), resp) {
267 drive(&core, set_view, next);
268 }
269 };
270
271 let handle = match (call.plugin.as_str(), call.op.as_str()) {
272 ("ticker", "start") => {
275 let ms: u32 = call.input.parse().unwrap_or(1000);
276 let count = std::cell::Cell::new(0u32);
277 let interval = gloo_timers::callback::Interval::new(ms, move || {
278 count.set(count.get() + 1);
279 emit(PluginResponse::text(true, count.get().to_string()));
280 });
281 StreamHandle::Ticker { _interval: interval }
282 }
283 ("websocket", "stream") => {
284 let Ok(ws) = web_sys::WebSocket::new(&call.input) else { return };
285 let onmessage = {
286 let emit = emit.clone();
287 Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |e: web_sys::MessageEvent| {
288 emit(PluginResponse::text(true, e.data().as_string().unwrap_or_default()));
289 })
290 };
291 let onclose = Closure::<dyn FnMut(web_sys::CloseEvent)>::new(move |_e| {
292 emit(PluginResponse::text(false, "closed"));
293 });
294 ws.set_onmessage(Some(onmessage.as_ref().unchecked_ref()));
295 ws.set_onclose(Some(onclose.as_ref().unchecked_ref()));
296 StreamHandle::Ws(WsStream { ws, _onmessage: onmessage, _onclose: onclose })
297 }
298 ("system", "events") => {
302 let win = web_sys::window().expect("window");
303 let doc = win.document().expect("document");
304 if let Ok(href) = win.location().href() {
306 emit(PluginResponse::text(true, system_deeplink(&href)));
307 }
308 emit(PluginResponse::text(true, system_lifecycle(&doc)));
309 let onpop = {
310 let (emit, win) = (emit.clone(), win.clone());
311 Closure::<dyn FnMut(web_sys::Event)>::new(move |_e: web_sys::Event| {
312 if let Ok(href) = win.location().href() {
313 emit(PluginResponse::text(true, system_deeplink(&href)));
314 }
315 })
316 };
317 let onvis = {
318 let (emit, doc) = (emit.clone(), doc.clone());
319 Closure::<dyn FnMut(web_sys::Event)>::new(move |_e: web_sys::Event| {
320 emit(PluginResponse::text(true, system_lifecycle(&doc)));
321 })
322 };
323 let _ = win.add_event_listener_with_callback("popstate", onpop.as_ref().unchecked_ref());
324 let _ = doc.add_event_listener_with_callback("visibilitychange", onvis.as_ref().unchecked_ref());
325 StreamHandle::System(SystemStream { win, doc, _onpop: onpop, _onvis: onvis })
326 }
327 ("transfer", op @ ("upload" | "download")) => {
332 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap_or(serde_json::Value::Null);
333 let url = v.get("url").and_then(|x| x.as_str()).unwrap_or("").to_string();
334 let headers: Vec<(String, String)> = v
335 .get("headers")
336 .and_then(|x| x.as_array())
337 .map(|hs| {
338 hs.iter()
339 .filter_map(|h| Some((h.get("name")?.as_str()?.to_string(), h.get("value")?.as_str()?.to_string())))
340 .collect()
341 })
342 .unwrap_or_default();
343
344 if op == "upload" {
345 let method = v.get("method").and_then(|x| x.as_str()).unwrap_or("PUT").to_string();
346 let source = v.get("source").and_then(|x| x.as_str()).unwrap_or("").to_string();
347 start_web_upload(url, method, headers, source, emit.clone())
348 } else {
349 start_web_download(url, headers, emit.clone())
350 }
351 }
352 _ => return, };
354
355 STREAMS.with(|m| {
356 m.borrow_mut().insert(call.key.clone(), handle);
357 });
358}
359
360fn js_now() -> f64 {
362 web_sys::window().and_then(|w| w.performance()).map(|p| p.now()).unwrap_or(0.0)
363}
364
365fn start_web_upload(
373 url: String,
374 method: String,
375 headers: Vec<(String, String)>,
376 source: String,
377 emit: impl Fn(PluginResponse) + Clone + 'static,
378) -> StreamHandle {
379 use wasm_bindgen::{closure::Closure, JsCast};
380 let xhr = web_sys::XmlHttpRequest::new().expect("xhr");
381 let _ = xhr.open_with_async(&method, &url, true);
382 for (n, val) in &headers {
383 let _ = xhr.set_request_header(n, val);
384 }
385
386 let last = std::rc::Rc::new(std::cell::Cell::new(0.0f64));
392 let on_prog = {
393 let (emit, last) = (emit.clone(), last.clone());
394 Closure::<dyn FnMut(web_sys::ProgressEvent)>::new(move |e: web_sys::ProgressEvent| {
395 let now = js_now();
396 if now - last.get() < 100.0 {
397 return;
398 }
399 last.set(now);
400 let total = if e.length_computable() { Some(e.total() as u64) } else { None };
401 emit(transfer_response(&TransferEvent::Progress { transferred: e.loaded() as u64, total }));
402 })
403 };
404 if let Ok(upload) = xhr.upload() {
405 upload.set_onprogress(Some(on_prog.as_ref().unchecked_ref()));
406 }
407
408 let on_done = {
411 let (emit, xhr_c) = (emit.clone(), xhr.clone());
412 Closure::<dyn FnMut()>::new(move || {
413 let status = xhr_c.status().unwrap_or(0);
414 let outcome = if status == 0 {
415 HttpOutcome::TransportError { message: "upload failed".into() }
416 } else {
417 HttpOutcome::Response { status, headers: vec![], body: vec![] }
418 };
419 emit(transfer_response(&TransferEvent::Done { outcome, handle: None }));
420 })
421 };
422 xhr.set_onload(Some(on_done.as_ref().unchecked_ref()));
423 let on_err = {
424 let emit = emit.clone();
425 Closure::<dyn FnMut()>::new(move || {
426 emit(transfer_response(&TransferEvent::Done {
427 outcome: HttpOutcome::TransportError { message: "upload error".into() },
428 handle: None,
429 }));
430 })
431 };
432 xhr.set_onerror(Some(on_err.as_ref().unchecked_ref()));
433 let on_abort = {
434 let emit = emit.clone();
435 Closure::<dyn FnMut()>::new(move || {
436 emit(transfer_response(&TransferEvent::Done {
437 outcome: HttpOutcome::TransportError { message: "upload aborted".into() },
438 handle: None,
439 }));
440 })
441 };
442 xhr.set_onabort(Some(on_abort.as_ref().unchecked_ref()));
443
444 let xhr_send = xhr.clone();
456 let cancelled = std::rc::Rc::new(std::cell::Cell::new(false));
457 let cancelled_send = cancelled.clone();
458 wasm_bindgen_futures::spawn_local(async move {
459 let blob = fetch_blob(&source).await;
460 if cancelled_send.get() {
461 return;
462 }
463 if let Some(blob) = blob {
464 let _ = xhr_send.send_with_opt_blob(Some(&blob));
465 } else {
466 let _ = xhr_send.send();
467 }
468 });
469
470 StreamHandle::Transfer(TransferHandle {
471 xhr: Some(xhr),
472 abort: None,
473 cancelled: Some(cancelled),
474 _on_prog: Some(on_prog),
475 _on_done: Some(on_done),
476 _on_err: Some(on_err),
477 _on_abort: Some(on_abort),
478 })
479}
480
481async fn fetch_blob(url: &str) -> Option<web_sys::Blob> {
485 use wasm_bindgen::JsCast;
486 let win = web_sys::window()?;
487 let resp_value = wasm_bindgen_futures::JsFuture::from(win.fetch_with_str(url)).await.ok()?;
488 let resp: web_sys::Response = resp_value.dyn_into().ok()?;
489 let blob_promise = resp.blob().ok()?;
490 let blob_value = wasm_bindgen_futures::JsFuture::from(blob_promise).await.ok()?;
491 blob_value.dyn_into().ok()
492}
493
494fn start_web_download(
503 url: String,
504 headers: Vec<(String, String)>,
505 emit: impl Fn(PluginResponse) + Clone + 'static,
506) -> StreamHandle {
507 let ctrl = web_sys::AbortController::new().expect("abortcontroller");
508 let signal = ctrl.signal();
509 let emit2 = emit.clone();
510 wasm_bindgen_futures::spawn_local(async move {
511 match fetch_stream(&url, &headers, &signal).await {
512 Ok((status, resp_headers, total, mut reader)) => {
513 let mut got: u64 = 0;
514 let mut chunks: Vec<u8> = Vec::new();
515 let mut last = js_now();
516 loop {
517 match reader.next().await {
518 Ok(Some(chunk)) => {
519 got += chunk.len() as u64;
520 chunks.extend_from_slice(&chunk);
521 let now = js_now();
522 if now - last >= 100.0 {
524 last = now;
525 emit2(transfer_response(&TransferEvent::Progress { transferred: got, total }));
526 }
527 }
528 Ok(None) => break, Err(msg) => {
530 emit2(transfer_response(&TransferEvent::Done {
531 outcome: HttpOutcome::TransportError { message: msg },
532 handle: None,
533 }));
534 return;
535 }
536 }
537 }
538 let handle = make_blob_url(&chunks);
539 let outcome = HttpOutcome::Response { status, headers: resp_headers, body: vec![] };
540 emit2(transfer_response(&TransferEvent::Done { outcome, handle: Some(handle) }));
541 }
542 Err(msg) => emit2(transfer_response(&TransferEvent::Done {
543 outcome: HttpOutcome::TransportError { message: msg },
544 handle: None,
545 })),
546 }
547 });
548 StreamHandle::Transfer(TransferHandle {
549 xhr: None,
550 abort: Some(ctrl),
551 cancelled: None,
552 _on_prog: None,
553 _on_done: None,
554 _on_err: None,
555 _on_abort: None,
556 })
557}
558
559async fn fetch_stream(
563 url: &str,
564 headers: &[(String, String)],
565 signal: &web_sys::AbortSignal,
566) -> Result<(u16, Vec<HttpHeader>, Option<u64>, Reader), String> {
567 use wasm_bindgen::JsCast;
568 let win = web_sys::window().ok_or_else(|| "no window".to_string())?;
569 let js_headers = web_sys::Headers::new().map_err(|e| js_err(&e))?;
570 for (n, v) in headers {
571 js_headers.append(n, v).map_err(|e| js_err(&e))?;
572 }
573 let init = web_sys::RequestInit::new();
574 init.set_method("GET");
575 init.set_headers_headers(&js_headers);
576 init.set_signal(Some(signal));
577 let request = web_sys::Request::new_with_str_and_init(url, &init).map_err(|e| js_err(&e))?;
578
579 let resp_value = wasm_bindgen_futures::JsFuture::from(win.fetch_with_request(&request))
580 .await
581 .map_err(|e| js_err(&e))?;
582 let resp: web_sys::Response = resp_value.dyn_into().map_err(|_| "fetch: not a Response".to_string())?;
583 let status = resp.status();
584 let resp_headers = response_headers(&resp.headers());
585 let total = resp_headers
586 .iter()
587 .find(|h| h.name.eq_ignore_ascii_case("content-length"))
588 .and_then(|h| h.value.parse().ok());
589
590 let Some(stream) = resp.body() else {
591 return Ok((status, resp_headers, total, Reader::empty()));
594 };
595 let reader = web_sys::ReadableStreamDefaultReader::new(&stream).map_err(|e| js_err(&e))?;
596 Ok((status, resp_headers, total, Reader::new(reader)))
597}
598
599fn response_headers(headers: &web_sys::Headers) -> Vec<HttpHeader> {
602 use wasm_bindgen::JsCast;
603 let mut out = Vec::new();
604 if let Ok(Some(iter)) = js_sys::try_iter(headers) {
605 for entry in iter.flatten() {
606 let arr: js_sys::Array = entry.unchecked_into();
607 let name = arr.get(0).as_string().unwrap_or_default();
608 let value = arr.get(1).as_string().unwrap_or_default();
609 out.push(HttpHeader { name, value });
610 }
611 }
612 out
613}
614
615fn js_err(e: &wasm_bindgen::JsValue) -> String {
618 use wasm_bindgen::JsCast;
619 e.as_string()
620 .or_else(|| e.dyn_ref::<js_sys::Error>().map(|err| String::from(err.message())))
621 .unwrap_or_else(|| "transfer error".to_string())
622}
623
624struct Reader(Option<web_sys::ReadableStreamDefaultReader>);
628impl Reader {
629 fn new(reader: web_sys::ReadableStreamDefaultReader) -> Self {
630 Self(Some(reader))
631 }
632 fn empty() -> Self {
634 Self(None)
635 }
636 async fn next(&mut self) -> Result<Option<Vec<u8>>, String> {
637 use wasm_bindgen::JsCast;
638 let Some(reader) = &self.0 else { return Ok(None) };
639 let result = wasm_bindgen_futures::JsFuture::from(reader.read()).await.map_err(|e| js_err(&e))?;
640 let result: web_sys::ReadableStreamReadResult = result.unchecked_into();
641 if result.get_done().unwrap_or(true) {
642 return Ok(None);
643 }
644 let value = result.get_value();
645 let bytes = js_sys::Uint8Array::new(&value).to_vec();
646 Ok(Some(bytes))
647 }
648}
649
650fn make_blob_url(bytes: &[u8]) -> String {
654 let array = js_sys::Uint8Array::from(bytes);
655 let parts = js_sys::Array::new();
656 parts.push(&array);
657 web_sys::Blob::new_with_u8_array_sequence(&parts)
658 .ok()
659 .and_then(|blob| web_sys::Url::create_object_url_with_blob(&blob).ok())
660 .unwrap_or_default()
661}
662
663fn system_deeplink(url: &str) -> String {
665 format!("{{\"type\":\"deeplink\",\"url\":{}}}", serde_json::to_string(url).unwrap_or_else(|_| "\"\"".into()))
666}
667fn system_lifecycle(doc: &web_sys::Document) -> String {
669 let state = if doc.visibility_state() == web_sys::VisibilityState::Visible { "active" } else { "background" };
670 format!("{{\"type\":\"lifecycle\",\"state\":\"{state}\"}}")
671}
672
673enum StreamHandle {
677 Ticker { _interval: gloo_timers::callback::Interval },
679 Ws(WsStream),
680 #[allow(dead_code)]
683 System(SystemStream),
684 #[allow(dead_code)]
687 Transfer(TransferHandle),
688}
689
690struct TransferHandle {
694 xhr: Option<web_sys::XmlHttpRequest>,
695 abort: Option<web_sys::AbortController>,
696 cancelled: Option<std::rc::Rc<std::cell::Cell<bool>>>,
701 _on_prog: Option<wasm_bindgen::closure::Closure<dyn FnMut(web_sys::ProgressEvent)>>,
706 _on_done: Option<wasm_bindgen::closure::Closure<dyn FnMut()>>,
707 _on_err: Option<wasm_bindgen::closure::Closure<dyn FnMut()>>,
708 _on_abort: Option<wasm_bindgen::closure::Closure<dyn FnMut()>>,
709}
710impl Drop for TransferHandle {
711 fn drop(&mut self) {
712 if let Some(c) = &self.cancelled {
713 c.set(true);
714 }
715 if let Some(x) = &self.xhr {
716 let _ = x.abort();
717 }
718 if let Some(a) = &self.abort {
719 a.abort();
720 }
721 }
722}
723
724fn transfer_response(ev: &TransferEvent) -> PluginResponse {
726 PluginResponse {
727 ok: matches!(ev, TransferEvent::Done { outcome, .. } if outcome.is_success()),
728 output: ev.encode(),
729 }
730}
731
732struct SystemStream {
734 win: web_sys::Window,
735 doc: web_sys::Document,
736 _onpop: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::Event)>,
737 _onvis: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::Event)>,
738}
739impl Drop for SystemStream {
740 fn drop(&mut self) {
741 use wasm_bindgen::JsCast;
742 let _ = self.win.remove_event_listener_with_callback("popstate", self._onpop.as_ref().unchecked_ref());
743 let _ = self.doc.remove_event_listener_with_callback("visibilitychange", self._onvis.as_ref().unchecked_ref());
744 }
745}
746
747struct WsStream {
749 ws: web_sys::WebSocket,
750 _onmessage: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::MessageEvent)>,
751 _onclose: wasm_bindgen::closure::Closure<dyn FnMut(web_sys::CloseEvent)>,
752}
753
754async fn perform(call: &PluginCall) -> PluginResponse {
757 if call.plugin == "device" {
758 let nav = web_sys::window().map(|w| w.navigator());
759 let output = if call.op == "locale" {
760 nav.and_then(|n| n.language()).unwrap_or_else(|| "en-US".into())
762 } else {
763 nav.and_then(|n| n.user_agent().ok()).unwrap_or_default()
764 };
765 return PluginResponse::text(true, output);
766 }
767 if call.plugin == "photo" && call.op == "pick" {
768 return take_image(false).await;
769 }
770 if call.plugin == "camera" && call.op == "capture" {
771 return take_image(true).await;
772 }
773 if call.plugin == "datetime" {
774 return match call.op.as_str() {
775 "date" => take_datetime("date").await,
776 "time" => take_datetime("time").await,
777 other => PluginResponse::text(false, format!("unknown datetime op '{other}'")),
778 };
779 }
780 if call.plugin == "dialog" && call.op == "confirm" {
781 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap_or(serde_json::Value::Null);
782 let title = v.get("title").and_then(serde_json::Value::as_str).unwrap_or("");
783 let message = v.get("message").and_then(serde_json::Value::as_str).unwrap_or("");
784 let prompt = if title.is_empty() { message.to_string() } else { format!("{title}\n\n{message}") };
785 let ok = web_sys::window()
786 .and_then(|w| w.confirm_with_message(&prompt).ok())
787 .unwrap_or(false);
788 return PluginResponse::text(ok, if ok { "ok" } else { "cancel" });
789 }
790 if call.plugin != "http" {
791 return PluginResponse::text(false, format!("plugin '{}' not available", call.plugin));
792 }
793 let v: serde_json::Value = serde_json::from_str(&call.input).unwrap_or(serde_json::Value::Null);
794 let url = v.get("url").and_then(serde_json::Value::as_str).unwrap_or("");
795 let body = v.get("body").and_then(serde_json::Value::as_str);
796 let req_headers: Vec<(String, String)> = v
797 .get("headers")
798 .and_then(serde_json::Value::as_array)
799 .map(|hs| {
800 hs.iter()
801 .filter_map(|h| {
802 Some((
803 h.get("name")?.as_str()?.to_string(),
804 h.get("value")?.as_str()?.to_string(),
805 ))
806 })
807 .collect()
808 })
809 .unwrap_or_default();
810
811 use gloo_net::http::{Method, Request};
812
813 let builder = match call.op.as_str() {
816 "GET" => Request::get(url),
817 "POST" => Request::post(url),
818 "PUT" => Request::put(url),
819 "PATCH" => Request::patch(url),
820 "DELETE" => Request::delete(url),
821 "HEAD" => Request::get(url).method(Method::HEAD),
822 "OPTIONS" => Request::get(url).method(Method::OPTIONS),
823 other => return http_transport_error(format!("unsupported HTTP method '{other}'")),
824 };
825
826 let caller_set_content_type =
828 req_headers.iter().any(|(n, _)| n.eq_ignore_ascii_case("content-type"));
829
830 let gloo_headers = gloo_net::http::Headers::new();
836 for (name, value) in &req_headers {
837 gloo_headers.append(name, value);
838 }
839 if body.is_some() && !caller_set_content_type {
840 gloo_headers.append("Content-Type", "application/json");
841 }
842 let builder = builder.headers(gloo_headers);
843
844 let request = match body {
845 Some(b) => builder.body(b),
846 None => builder.build(),
847 };
848 let request = match request {
849 Ok(r) => r,
850 Err(e) => return http_transport_error(e.to_string()),
851 };
852
853 match request.send().await {
854 Ok(resp) => {
855 let status = resp.status();
856 let headers = resp
857 .headers()
858 .entries()
859 .map(|(name, value)| HttpHeader { name, value })
860 .collect();
861 match resp.binary().await {
862 Ok(bytes) => {
863 let outcome = HttpOutcome::Response { status, headers, body: bytes };
864 PluginResponse { ok: (200..300).contains(&status), output: outcome.encode() }
865 }
866 Err(e) => http_transport_error(e.to_string()),
869 }
870 }
871 Err(e) => http_transport_error(e.to_string()),
872 }
873}
874
875fn http_transport_error(message: String) -> PluginResponse {
877 PluginResponse { ok: false, output: HttpOutcome::TransportError { message }.encode() }
878}
879
880async fn take_image(capture: bool) -> PluginResponse {
887 use wasm_bindgen::{closure::Closure, JsCast};
888 let Some(doc) = web_sys::window().and_then(|w| w.document()) else {
889 return PluginResponse::text(false, "no document");
890 };
891 let Some(input) = doc.create_element("input").ok().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()) else {
892 return PluginResponse::text(false, "no input element");
893 };
894 input.set_type("file");
895 input.set_accept("image/*");
896 if capture {
897 let _ = input.set_attribute("capture", "environment");
899 }
900
901 let (tx, rx) = futures_channel::oneshot::channel::<Option<String>>();
902 let tx = std::cell::RefCell::new(Some(tx));
903 let input_for_cb = input.clone();
904 let on_change = Closure::wrap(Box::new(move || {
905 let url = input_for_cb
906 .files()
907 .and_then(|files| files.get(0))
908 .and_then(|file| web_sys::Url::create_object_url_with_blob(&file).ok());
909 if let Some(tx) = tx.borrow_mut().take() {
910 let _ = tx.send(url);
911 }
912 }) as Box<dyn FnMut()>);
913 input.set_onchange(Some(on_change.as_ref().unchecked_ref()));
914 input.click();
915 on_change.forget(); match rx.await {
918 Ok(Some(url)) => PluginResponse::text(true, url),
919 _ => PluginResponse::text(false, "cancelled"),
920 }
921}
922
923async fn take_datetime(kind: &str) -> PluginResponse {
928 use wasm_bindgen::{closure::Closure, JsCast};
929 let Some(doc) = web_sys::window().and_then(|w| w.document()) else {
930 return PluginResponse::text(false, "no document");
931 };
932 let Some(input) = doc.create_element("input").ok().and_then(|e| e.dyn_into::<web_sys::HtmlInputElement>().ok()) else {
933 return PluginResponse::text(false, "no input element");
934 };
935 input.set_type(kind); let _ = input.set_attribute("style", "position:fixed;left:-9999px;opacity:0");
938 if let Some(body) = doc.body() {
939 let _ = body.append_child(&input);
940 }
941
942 let (tx, rx) = futures_channel::oneshot::channel::<Option<String>>();
943 let tx = std::rc::Rc::new(std::cell::RefCell::new(Some(tx)));
944 let input_for_change = input.clone();
945 let tx_change = tx.clone();
946 let on_change = Closure::wrap(Box::new(move || {
947 let v = input_for_change.value();
948 if let Some(tx) = tx_change.borrow_mut().take() {
949 let _ = tx.send(if v.is_empty() { None } else { Some(v) });
950 }
951 }) as Box<dyn FnMut()>);
952 let tx_cancel = tx.clone();
953 let on_cancel = Closure::wrap(Box::new(move || {
954 if let Some(tx) = tx_cancel.borrow_mut().take() {
955 let _ = tx.send(None);
956 }
957 }) as Box<dyn FnMut()>);
958 let _ = input.add_event_listener_with_callback("change", on_change.as_ref().unchecked_ref());
959 let _ = input.add_event_listener_with_callback("cancel", on_cancel.as_ref().unchecked_ref());
960 if input.show_picker().is_err() {
961 input.click(); }
963 on_change.forget(); on_cancel.forget();
965
966 let result = rx.await;
967 input.remove();
968 match result {
969 Ok(Some(v)) => PluginResponse::text(true, v),
970 _ => PluginResponse::text(false, "cancelled"),
971 }
972}
973
974const STORAGE_KEY: &str = "mobiler.state";
975
976fn local_storage() -> Option<web_sys::Storage> {
978 web_sys::window()?.local_storage().ok().flatten()
979}
980
981fn perform_notify(notify: &PluginNotify) {
985 let win = match web_sys::window() {
986 Some(w) => w,
987 None => return,
988 };
989 match (notify.plugin.as_str(), notify.op.as_str()) {
990 ("storage", "save") => {
992 if let Some(s) = local_storage() {
993 let _ = s.set_item(STORAGE_KEY, ¬ify.input);
994 }
995 }
996 ("clipboard", "copy") => {
998 let _ = win.navigator().clipboard().write_text(¬ify.input);
999 }
1000 ("browser", "open") => {
1002 let _ = win.open_with_url_and_target(¬ify.input, "_blank");
1003 }
1004 ("share", _) => {
1007 let _ = win.navigator().clipboard().write_text(¬ify.input);
1008 }
1009 ("stream", "unsubscribe") => {
1013 if let Some(StreamHandle::Ws(ws)) = STREAMS.with(|m| m.borrow_mut().remove(¬ify.input)) {
1016 let _ = ws.ws.close();
1017 }
1018 }
1019 ("toast", _) => show_toast(¬ify.input),
1021 ("haptics", style) => {
1023 let ms = match style {
1024 "light" => 15,
1025 "heavy" => 50,
1026 _ => 30, };
1028 let _ = win.navigator().vibrate_with_duration(ms);
1029 }
1030 _ => {} }
1032}
1033
1034fn show_toast(text: &str) {
1037 let Some(doc) = web_sys::window().and_then(|w| w.document()) else { return };
1038 let (Ok(el), Some(body)) = (doc.create_element("div"), doc.body()) else { return };
1039 el.set_class_name("toast");
1040 el.set_text_content(Some(text));
1041 let _ = body.append_child(&el);
1042 gloo_timers::callback::Timeout::new(2600, move || el.remove()).forget();
1043}
1044
1045fn render(widget: &Widget, send: &Dispatch) -> AnyView {
1052 match widget {
1053 Widget::Text { content, style } => {
1055 let (class, content) = (text_class(*style), content.clone());
1056 view! { <p class=class>{content}</p> }.into_any()
1057 }
1058 Widget::Image { source, shape, ratio } => {
1059 let (class, source) = (image_class(*shape, *ratio), source.clone());
1060 view! { <img class=class src=source /> }.into_any()
1061 }
1062 Widget::Badge { label, tone } => {
1063 let (class, label) = (format!("badge {}", tone_class(*tone)), label.clone());
1064 view! { <span class=class>{label}</span> }.into_any()
1065 }
1066 Widget::ColorDot { color } => {
1067 view! { <span class=format!("dot {}", dot_class(*color))></span> }.into_any()
1068 }
1069 Widget::Avatar { source, status } => {
1070 let dot = status.map(|t| view! { <span class=format!("avatar-status {}", tone_class(t))></span> });
1071 view! {
1072 <span class="avatar">
1073 <img class="avatar-img" src=source.clone() />
1074 {dot}
1075 </span>
1076 }
1077 .into_any()
1078 }
1079 Widget::PdfView { url } => {
1080 view! { <iframe class="pdfview" src=url.clone() title="PDF"></iframe> }.into_any()
1082 }
1083 Widget::WebView { url } => {
1084 view! {
1087 <iframe
1088 class="webview"
1089 src=url.clone()
1090 title="Web"
1091 allow="autoplay; fullscreen; picture-in-picture; encrypted-media"
1092 allowfullscreen=true
1093 ></iframe>
1094 }.into_any()
1095 }
1096 Widget::Map { id, center_lat, center_lng, zoom, markers, style_url, interactive } => {
1100 let send = send.clone();
1101 let id = id.clone();
1102 let center = format!("{center_lat},{center_lng}");
1103 let markers_json = serde_json::to_string(markers).unwrap_or_else(|_| "[]".to_string());
1104 let style = style_url.clone().unwrap_or_default();
1105 view! {
1106 <div class="mobiler-map-wrap">
1107 <div
1108 class="mobiler-map"
1109 data-map="1"
1110 data-center=center
1111 data-zoom=zoom.to_string()
1112 data-style=style
1113 data-markers=markers_json
1114 data-interactive=interactive.to_string()
1115 ></div>
1116 <input
1117 class="mobiler-map-sink"
1118 type="text"
1119 tabindex="-1"
1120 aria-hidden="true"
1121 on:input=move |ev| {
1122 let raw = event_target_value(&ev);
1123 if let Some((suffix, value)) = raw.split_once('|') {
1124 send(Action::Input {
1125 id: format!("{id}.{suffix}"),
1126 value: InputValue::Text(value.to_string()),
1127 });
1128 }
1129 }
1130 />
1131 </div>
1132 }.into_any()
1133 }
1134 Widget::Video { url, playing, controls, looping, muted, on_ended, poster, start_at_ms, captions, rate, volume, urls, start_index, .. } => {
1135 use wasm_bindgen::JsCast;
1143 let (send, ended) = (send.clone(), on_ended.clone());
1144 let autoplay = *playing && *muted;
1145 let playlist = urls.clone();
1146 let start_index = (*start_index).max(0) as usize;
1147 let effective = if playlist.is_empty() { url.clone() }
1148 else { playlist.get(start_index).cloned().unwrap_or_else(|| url.clone()) };
1149 let is_hls = effective.to_ascii_lowercase().ends_with(".m3u8");
1150 let src = (!is_hls).then(|| effective.clone());
1151 let hls_src = is_hls.then(|| effective.clone());
1152 let poster_attr = poster.clone();
1153 let start_at = *start_at_ms;
1154 let rate = *rate as f64;
1155 let volume = (*volume as f64).clamp(0.0, 1.0);
1156 let tracks: Vec<_> = captions.iter().map(|c| view! {
1157 <track kind="subtitles" src=c.url.clone() srclang=c.language.clone() label=c.label.clone() default=c.default_on />
1158 }).collect();
1159 let next_idx = std::rc::Rc::new(std::cell::Cell::new(start_index));
1160 view! {
1161 <video
1162 class="video"
1163 src=src
1164 data-hls-src=hls_src
1165 poster=poster_attr
1166 controls=*controls
1167 autoplay=autoplay
1168 prop:loop=*looping
1169 prop:playbackRate=rate
1170 prop:volume=volume
1171 muted=*muted
1172 playsinline=true
1173 on:loadedmetadata=move |ev| {
1174 if start_at >= 0 {
1175 if let Some(v) = ev.target().and_then(|t| t.dyn_into::<web_sys::HtmlVideoElement>().ok()) {
1176 v.set_current_time(start_at as f64 / 1000.0);
1177 }
1178 }
1179 }
1180 on:ended=move |ev| {
1181 let nxt = next_idx.get() + 1;
1182 if !playlist.is_empty() && nxt < playlist.len() {
1183 next_idx.set(nxt);
1184 if let Some(v) = ev.target().and_then(|t| t.dyn_into::<web_sys::HtmlVideoElement>().ok()) {
1185 v.set_src(&playlist[nxt]);
1186 let _ = v.play();
1187 }
1188 } else if let Some(t) = ended.clone() {
1189 send(Action::Fired { token: t });
1190 }
1191 }
1192 >{tracks}</video>
1193 }.into_any()
1194 }
1195 Widget::Rating { value, max, on_rate } => {
1196 let value = *value;
1197 let stars: Vec<AnyView> = (1..=*max)
1198 .map(|i| {
1199 let threshold = u32::from(i) * 10;
1200 let glyph = if value >= threshold { "★" } else if value + 5 >= threshold { "⯨" } else { "☆" };
1202 match on_rate {
1203 Some(tokens) => {
1204 let (send, token) = (send.clone(), tokens.get(usize::from(i - 1)).cloned().unwrap_or_default());
1205 view! {
1206 <button class="star star-tappable" on:click=move |_| send(Action::Fired { token: token.clone() })>
1207 {glyph}
1208 </button>
1209 }
1210 .into_any()
1211 }
1212 None => view! { <span class="star">{glyph}</span> }.into_any(),
1213 }
1214 })
1215 .collect();
1216 view! { <span class="rating">{stars}</span> }.into_any()
1217 }
1218 Widget::Divider => view! { <hr class="divider" /> }.into_any(),
1219 Widget::Progress { value } => match value {
1220 Some(v) => {
1221 let pct = (v.clamp(0.0, 1.0) * 100.0) as u32;
1222 view! { <div class="progress"><div class="progress-bar" style=format!("width:{pct}%")></div></div> }.into_any()
1223 }
1224 None => view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> }.into_any(),
1225 },
1226 Widget::Skeleton => view! { <div class="skeleton"></div> }.into_any(),
1227 Widget::Chart { series, labels, style, axis, legend } => {
1228 chart_view(series, labels, *style, *axis, *legend)
1229 }
1230 Widget::RegionChart { regions, ticks, x_max, y_max, ref_lines, bracket, legend } => {
1231 region_chart_view(regions, ticks, *x_max, *y_max, ref_lines, bracket, legend)
1232 }
1233 Widget::Calendar { year, month, first_weekday, selected, on_day } => {
1234 const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June",
1235 "July", "August", "September", "October", "November", "December"];
1236 let head_label = format!("{} {year}", MONTHS.get((*month as usize).saturating_sub(1)).copied().unwrap_or(""));
1237 let weekdays = ["S", "M", "T", "W", "T", "F", "S"];
1238 let heads: Vec<_> = weekdays.iter().map(|w| view! { <div class="cal-head">{*w}</div> }).collect();
1239 let blanks: Vec<_> = (0..*first_weekday).map(|_| view! { <div class="cal-blank"></div> }).collect();
1240 let selected = *selected;
1241 let days: Vec<_> = on_day.iter().enumerate().map(|(i, token)| {
1242 let day = (i + 1) as u8;
1243 let token = token.clone();
1244 let send = send.clone();
1245 let cls = if selected == Some(day) { "cal-day cal-sel" } else { "cal-day" };
1246 view! { <button class=cls on:click=move |_| send(Action::Fired { token: token.clone() })>{day.to_string()}</button> }
1247 }).collect();
1248 view! {
1249 <div class="calendar">
1250 <div class="cal-title">{head_label}</div>
1251 <div class="cal-grid">{heads}{blanks}{days}</div>
1252 </div>
1253 }.into_any()
1254 }
1255 Widget::SwipeAction { child, actions } => {
1256 let acts: Vec<_> = actions.iter().map(|a| {
1258 let token = a.on_tap.clone();
1259 let send = send.clone();
1260 let cls = format!("swipe-act {}", tone_class(a.tone));
1261 let label = a.label.clone();
1262 view! { <button class=cls on:click=move |_| send(Action::Fired { token: token.clone() })>{label}</button> }
1263 }).collect();
1264 view! {
1265 <div class="swipe-row">
1266 <div class="swipe-content">{render(child, send)}</div>
1267 <div class="swipe-actions">{acts}</div>
1268 </div>
1269 }.into_any()
1270 }
1271 Widget::Spacer { size } => {
1272 view! { <div class=format!("spacer {}", spacer_class(*size))></div> }.into_any()
1273 }
1274
1275 Widget::Row { children } => {
1277 let kids = render_all(children, send);
1278 view! { <div class="row">{kids}</div> }.into_any()
1279 }
1280 Widget::Column { children } => {
1281 let kids = render_all(children, send);
1282 view! { <div class="col">{kids}</div> }.into_any()
1283 }
1284 Widget::Card { child, style, on_press, on_long_press } => {
1285 let class = format!("card {}", card_class(*style));
1286 let body = render(child, send);
1287 match (on_press, on_long_press) {
1288 (None, None) => view! { <div class=class>{body}</div> }.into_any(),
1290 (tap, long) => {
1292 let send = send.clone();
1293 let timer: Rc<RefCell<Option<gloo_timers::callback::Timeout>>> =
1297 Rc::new(RefCell::new(None));
1298 let long_fired = Rc::new(RefCell::new(false));
1299
1300 let on_pointerdown = {
1301 let (send, long, timer, long_fired) =
1302 (send.clone(), long.clone(), timer.clone(), long_fired.clone());
1303 move |_: web_sys::PointerEvent| {
1304 let Some(token) = long.clone() else { return };
1305 *long_fired.borrow_mut() = false;
1306 let (send, long_fired) = (send.clone(), long_fired.clone());
1307 *timer.borrow_mut() = Some(gloo_timers::callback::Timeout::new(
1308 500,
1309 move || {
1310 *long_fired.borrow_mut() = true;
1311 send(Action::Fired { token: token.clone() });
1312 },
1313 ));
1314 }
1315 };
1316 let cancel = {
1317 let timer = timer.clone();
1318 move |_: web_sys::PointerEvent| { timer.borrow_mut().take(); }
1320 };
1321 let on_click = {
1322 let (send, tap, long_fired) = (send.clone(), tap.clone(), long_fired.clone());
1323 move |_| {
1324 if std::mem::take(&mut *long_fired.borrow_mut()) {
1326 return;
1327 }
1328 if let Some(token) = tap.clone() {
1329 send(Action::Fired { token });
1330 }
1331 }
1332 };
1333 view! {
1334 <button
1335 class=format!("{class} card-tappable")
1336 on:pointerdown=on_pointerdown
1337 on:pointerup=cancel.clone()
1338 on:pointerleave=cancel.clone()
1339 on:pointercancel=cancel
1340 on:click=on_click
1341 >
1342 {body}
1343 </button>
1344 }
1345 .into_any()
1346 }
1347 }
1348 }
1349 Widget::Box { children, align, scrim } => {
1353 let acls = align_class(*align);
1354 if *scrim && children.len() > 1 {
1355 let bg = render(&children[0], send);
1356 let content = render_all(&children[1..], send);
1357 view! {
1358 <div class=format!("box box-scrim {acls}")>
1359 {bg}
1360 <div class="scrim"></div>
1361 <div class="box-content">{content}</div>
1362 </div>
1363 }
1364 .into_any()
1365 } else {
1366 let kids = render_all(children, send);
1367 view! { <div class=format!("box {acls}")>{kids}</div> }.into_any()
1368 }
1369 }
1370 Widget::Grid { children } => {
1371 let kids = render_all(children, send);
1372 view! { <div class="grid">{kids}</div> }.into_any()
1373 }
1374 Widget::Scroller { children } => {
1375 let kids = render_all(children, send);
1376 view! { <div class="scroller">{kids}</div> }.into_any()
1377 }
1378 Widget::Split { primary, detail, show_detail, on_back } => {
1382 let p = render(primary, send);
1383 let d = render(detail, send);
1384 let back_btn = on_back.clone().map(|t| {
1385 let send = send.clone();
1386 view! { <button class="split-back" on:click=move |_| send(Action::Fired { token: t.clone() })>"‹ Back"</button> }
1387 });
1388 view! {
1389 <div class="split" data-detail=show_detail.then_some("1")>
1390 <div class="split-primary">{p}</div>
1391 <div class="split-detail">{back_btn}{d}</div>
1392 </div>
1393 }.into_any()
1394 }
1395 Widget::A11y { child, label, hint, role } => {
1398 let body = render(child, send);
1399 let role_attr = role.map(a11y_role_aria).unwrap_or("group");
1400 view! {
1401 <div class="a11y" role=role_attr aria-label=label.clone() title=hint.clone()>
1402 {body}
1403 </div>
1404 }.into_any()
1405 }
1406 Widget::LazyList { children, on_load_more, loading, has_more, on_refresh, refreshing } => {
1411 let kids = render_all(children, send);
1412 let refresh_btn = on_refresh.clone().map(|token| {
1413 let send = send.clone();
1414 view! { <button class="refresh-btn" on:click=move |_| send(Action::Fired { token: token.clone() })>"↻ Refresh"</button> }
1415 });
1416 let refresh_bar = refreshing.then(|| view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> });
1417 let loading_bar = loading.then(|| view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> });
1418 let load_more_btn = (!*loading && *has_more)
1419 .then(|| on_load_more.clone())
1420 .flatten()
1421 .map(|token| {
1422 let send = send.clone();
1423 view! { <button class="btn btn-outlined lazylist-more" on:click=move |_| send(Action::Fired { token: token.clone() })>"Load more"</button> }
1424 });
1425 let end_cap = (!*has_more && on_load_more.is_some()).then(|| view! { <div class="lazylist-end">"End of list"</div> });
1426 view! {
1427 <div class="lazylist">
1428 {refresh_btn}
1429 {refresh_bar}
1430 {kids}
1431 {loading_bar}
1432 {load_more_btn}
1433 {end_cap}
1434 </div>
1435 }.into_any()
1436 }
1437
1438 Widget::Button { label, style, on_press } => {
1440 let (send, token, label) = (send.clone(), on_press.clone(), label.clone());
1441 let class = format!("btn {}", button_class(*style));
1442 view! {
1443 <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1444 {label}
1445 </button>
1446 }
1447 .into_any()
1448 }
1449 Widget::IconButton { icon, on_press } => {
1450 let (send, token) = (send.clone(), on_press.clone());
1451 let glyph = icon_glyph(*icon);
1452 view! {
1453 <button class="iconbtn" on:click=move |_| send(Action::Fired { token: token.clone() })>
1454 {glyph}
1455 </button>
1456 }
1457 .into_any()
1458 }
1459 Widget::Chip { label, selected, on_press } => {
1460 let (send, token, label) = (send.clone(), on_press.clone(), label.clone());
1461 let class = if *selected { "chip selected" } else { "chip" };
1462 view! {
1463 <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1464 {label}
1465 </button>
1466 }
1467 .into_any()
1468 }
1469 Widget::TextField { id, placeholder, value, kind, error } => {
1470 let (send, id) = (send.clone(), id.clone());
1471 let (placeholder, value) = (placeholder.clone(), value.clone());
1472 let invalid = error.is_some();
1473 let err_view = error.clone().map(|m| view! { <div class="field-error">{m}</div> });
1474 let (itype, imode): (&str, &str) = match kind {
1476 FieldKind::Secure => ("password", ""),
1477 FieldKind::Email => ("email", "email"),
1478 FieldKind::Number => ("text", "numeric"),
1479 FieldKind::Decimal => ("text", "decimal"),
1480 FieldKind::Phone => ("tel", "tel"),
1481 FieldKind::Url => ("url", "url"),
1482 FieldKind::Text | FieldKind::Multiline => ("text", ""),
1483 };
1484 let field_class = if invalid { "field field-invalid" } else { "field" };
1485 let control = if matches!(kind, FieldKind::Multiline) {
1486 view! {
1487 <textarea
1488 class=field_class
1489 rows="3"
1490 placeholder=placeholder
1491 prop:value=value
1492 on:input=move |ev| send(Action::Input {
1493 id: id.clone(),
1494 value: InputValue::Text(event_target_value(&ev)),
1495 })
1496 ></textarea>
1497 }
1498 .into_any()
1499 } else {
1500 view! {
1501 <input
1502 class=field_class
1503 r#type=itype
1504 inputmode=imode
1505 placeholder=placeholder
1506 prop:value=value
1507 on:input=move |ev| send(Action::Input {
1508 id: id.clone(),
1509 value: InputValue::Text(event_target_value(&ev)),
1510 })
1511 />
1512 }
1513 .into_any()
1514 };
1515 view! { <div class="field-wrap">{control}{err_view}</div> }.into_any()
1516 }
1517 Widget::SearchField { id, placeholder, value } => {
1518 let (send, id) = (send.clone(), id.clone());
1519 let (placeholder, value) = (placeholder.clone(), value.clone());
1520 view! {
1521 <div class="searchfield">
1522 <span class="search-icon">{icon_glyph(Icon::Search)}</span>
1523 <input
1524 class="search-input"
1525 placeholder=placeholder
1526 prop:value=value
1527 on:input=move |ev| send(Action::Input {
1528 id: id.clone(),
1529 value: InputValue::Text(event_target_value(&ev)),
1530 })
1531 />
1532 </div>
1533 }
1534 .into_any()
1535 }
1536 Widget::Segmented { segments } => {
1537 let segs: Vec<AnyView> = segments
1538 .iter()
1539 .map(|s| {
1540 let (send, token) = (send.clone(), s.on_select.clone());
1541 let class = if s.selected { "segment selected" } else { "segment" };
1542 let label = s.label.clone();
1543 view! {
1544 <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1545 {label}
1546 </button>
1547 }
1548 .into_any()
1549 })
1550 .collect();
1551 view! { <div class="segmented">{segs}</div> }.into_any()
1552 }
1553 Widget::Toggle { id, label, value } => {
1554 let (send, id, label, checked) = (send.clone(), id.clone(), label.clone(), *value);
1555 view! {
1556 <label class="toggle">
1557 {label}
1558 <input
1559 type="checkbox"
1560 role="switch"
1561 prop:checked=checked
1562 on:change=move |ev| send(Action::Input {
1563 id: id.clone(),
1564 value: InputValue::Bool(event_target_checked(&ev)),
1565 })
1566 />
1567 </label>
1568 }
1569 .into_any()
1570 }
1571 Widget::Checkbox { id, label, value } => {
1572 let (send, id, label, checked) = (send.clone(), id.clone(), label.clone(), *value);
1573 view! {
1574 <label class="check">
1575 <input
1576 type="checkbox"
1577 prop:checked=checked
1578 on:change=move |ev| send(Action::Input {
1579 id: id.clone(),
1580 value: InputValue::Bool(event_target_checked(&ev)),
1581 })
1582 />
1583 {label}
1584 </label>
1585 }
1586 .into_any()
1587 }
1588 Widget::Slider { id, value, max } => {
1589 let (send, id, value, max) = (send.clone(), id.clone(), *value, *max);
1590 view! {
1591 <input
1592 class="slider"
1593 type="range"
1594 min="0"
1595 max=max
1596 prop:value=value
1597 on:input=move |ev| send(Action::Input {
1598 id: id.clone(),
1599 value: InputValue::Int(event_target_value(&ev).parse().unwrap_or(0)),
1600 })
1601 />
1602 }
1603 .into_any()
1604 }
1605 Widget::Stepper { value, on_decrement, on_increment } => {
1606 let send_dec = send.clone();
1607 let send_inc = send.clone();
1608 let (dec, inc) = (on_decrement.clone(), on_increment.clone());
1609 view! {
1610 <div class="stepper">
1611 <button on:click=move |_| send_dec(Action::Fired { token: dec.clone() })>"−"</button>
1612 <span class="stepper-value">{*value}</span>
1613 <button on:click=move |_| send_inc(Action::Fired { token: inc.clone() })>"+"</button>
1614 </div>
1615 }
1616 .into_any()
1617 }
1618
1619 Widget::Scaffold { title, body, tabs, back, dark_mode, theme, fab, sheet, on_refresh, refreshing, route, depth } => {
1621 let back_btn = back.clone().map(|token| {
1622 let send = send.clone();
1623 view! {
1624 <button class="back" on:click=move |_| send(Action::Fired { token: token.clone() })>
1625 "‹"
1626 </button>
1627 }
1628 });
1629 let tabbar = (!tabs.is_empty()).then(|| {
1630 let tabs: Vec<AnyView> = tabs
1631 .iter()
1632 .map(|tab| {
1633 let (send, token) = (send.clone(), tab.on_select.clone());
1634 let class = if tab.selected { "tab selected" } else { "tab" };
1635 let label = tab.label.clone();
1636 let icon = tab.icon.map(|i| view! { <span class="tab-icon">{icon_glyph(i)}</span> });
1638 view! {
1639 <button class=class on:click=move |_| send(Action::Fired { token: token.clone() })>
1640 {icon}
1641 <span class="tab-label">{label}</span>
1642 </button>
1643 }
1644 .into_any()
1645 })
1646 .collect();
1647 view! { <div class="tabbar">{tabs}</div> }
1648 });
1649 let fab_btn = fab.clone().map(|f| {
1651 let (send, token) = (send.clone(), f.on_press.clone());
1652 view! {
1653 <button class="fab" on:click=move |_| send(Action::Fired { token: token.clone() })>
1654 {icon_glyph(f.icon)}
1655 </button>
1656 }
1657 });
1658 let sheet_overlay = sheet.as_ref().map(|s| {
1660 let (send_scrim, dismiss) = (send.clone(), s.on_dismiss.clone());
1661 let (title, child) = (s.title.clone(), render(&s.child, send));
1662 view! {
1663 <div class="sheet-scrim" on:click=move |_| send_scrim(Action::Fired { token: dismiss.clone() })></div>
1664 <div class="sheet">
1665 <div class="sheet-handle"></div>
1666 <div class="sheet-title">{title}</div>
1667 {child}
1668 </div>
1669 }
1670 });
1671 let class = if *dark_mode { "scaffold theme-dark" } else { "scaffold" };
1674 let refresh_btn = on_refresh.clone().map(|token| {
1677 let send = send.clone();
1678 view! {
1679 <button class="refresh-btn" on:click=move |_| send(Action::Fired { token: token.clone() })>"↻"</button>
1680 }
1681 });
1682 let refresh_bar = refreshing.then(|| {
1683 view! { <div class="progress progress-indeterminate"><div class="progress-bar"></div></div> }
1684 });
1685 let body_class = format!("scaffold-body {}", nav_class(route, *depth));
1686 let theme_style = theme.as_ref().map(theme_css).unwrap_or_default();
1689 let (title, body) = (title.clone(), render(body, send));
1690 view! {
1691 <div class=class style=theme_style>
1692 <div class="topbar">
1693 {back_btn}
1694 <span class="title">{title}</span>
1695 {refresh_btn}
1696 </div>
1697 <div class=body_class data-route=route.clone()>{refresh_bar}{body}</div>
1698 {fab_btn}
1699 {tabbar}
1700 {sheet_overlay}
1701 </div>
1702 }
1703 .into_any()
1704 }
1705 }
1706}
1707
1708fn render_all(children: &[Widget], send: &Dispatch) -> Vec<AnyView> {
1710 children.iter().map(|c| render(c, send)).collect()
1711}
1712
1713thread_local! {
1714 static NAV: RefCell<(String, u32, bool)> = const { RefCell::new((String::new(), 0, false)) };
1719
1720 static STREAMS: RefCell<HashMap<String, StreamHandle>> = RefCell::new(HashMap::new());
1724}
1725
1726fn theme_css(t: &Theme) -> String {
1731 let (r, g, b) = (t.seed.r, t.seed.g, t.seed.b);
1732 let radius = match t.corner {
1733 Corner::None => "0px",
1734 Corner::Small => "8px",
1735 Corner::Medium => "14px",
1736 Corner::Large => "22px",
1737 };
1738 let (gap, pad) = match t.density {
1739 Density::Compact => ("8px", "10px"),
1740 Density::Comfortable => ("12px", "14px"),
1741 };
1742 let font = match t.font {
1743 FontFamily::System => "system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif",
1744 FontFamily::Rounded => "ui-rounded, \"SF Pro Rounded\", \"Segoe UI\", system-ui, sans-serif",
1745 FontFamily::Serif => "ui-serif, Georgia, \"Times New Roman\", serif",
1746 FontFamily::Monospace => "ui-monospace, \"SF Mono\", \"Cascadia Code\", Menlo, monospace",
1747 };
1748 let (ar, ag, ab) = t.accent.map_or((r, g, b), |a| (a.r, a.g, a.b));
1750 format!(
1751 "--primary:rgb({r},{g},{b});--accent:rgb({r},{g},{b});\
1752 --accent2:rgb({ar},{ag},{ab});\
1753 --accent-soft:rgba({r},{g},{b},0.16);--radius:{radius};\
1754 --gap:{gap};--pad:{pad};--font:{font};"
1755 )
1756}
1757
1758fn nav_class(route: &str, depth: u32) -> &'static str {
1765 NAV.with_borrow_mut(|(prev_route, prev_depth, toggle)| {
1766 if route == prev_route {
1767 return "";
1768 }
1769 let dir = if depth > *prev_depth {
1770 ["nav-push-a", "nav-push-b"]
1771 } else if depth < *prev_depth {
1772 ["nav-pop-a", "nav-pop-b"]
1773 } else {
1774 ["nav-fade-a", "nav-fade-b"]
1775 };
1776 *toggle = !*toggle;
1777 *prev_route = route.to_string();
1778 *prev_depth = depth;
1779 dir[usize::from(*toggle)]
1780 })
1781}
1782
1783fn text_class(s: TextStyle) -> &'static str {
1786 match s {
1787 TextStyle::Title => "t-title",
1788 TextStyle::Subtitle => "t-subtitle",
1789 TextStyle::Caption => "t-caption",
1790 TextStyle::Emphasis => "t-emphasis",
1791 TextStyle::Body => "t-body",
1792 }
1793}
1794
1795fn button_class(s: ButtonStyle) -> &'static str {
1796 match s {
1797 ButtonStyle::Filled => "btn-filled",
1798 ButtonStyle::Outlined => "btn-outlined",
1799 ButtonStyle::Text => "btn-text",
1800 }
1801}
1802
1803fn card_class(s: CardStyle) -> &'static str {
1804 match s {
1805 CardStyle::Elevated => "card-elevated",
1806 CardStyle::Outlined => "card-outlined",
1807 CardStyle::Filled => "card-filled",
1808 CardStyle::Brand => "card-brand",
1809 }
1810}
1811
1812fn a11y_role_aria(role: A11yRole) -> &'static str {
1813 match role {
1814 A11yRole::Button => "button",
1815 A11yRole::Link => "link",
1816 A11yRole::Image => "img",
1817 A11yRole::Header => "heading",
1818 A11yRole::Adjustable => "slider",
1819 }
1820}
1821
1822fn tone_class(t: Tone) -> &'static str {
1823 match t {
1824 Tone::Neutral => "tone-neutral",
1825 Tone::Success => "tone-success",
1826 Tone::Warning => "tone-warning",
1827 Tone::Danger => "tone-danger",
1828 Tone::Info => "tone-info",
1829 }
1830}
1831
1832fn spacer_class(s: Spacing) -> &'static str {
1833 match s {
1834 Spacing::Xs => "sp-xs",
1835 Spacing::Sm => "sp-sm",
1836 Spacing::Md => "sp-md",
1837 Spacing::Lg => "sp-lg",
1838 Spacing::Xl => "sp-xl",
1839 }
1840}
1841
1842fn icon_glyph(i: Icon) -> &'static str {
1843 match i {
1844 Icon::Delete => "🗑",
1845 Icon::Add => "+",
1846 Icon::Edit => "✏️",
1847 Icon::Close => "✕",
1848 Icon::Settings => "⚙",
1849 Icon::Check => "✓",
1850 Icon::Star => "★",
1851 Icon::Info => "ℹ",
1852 Icon::Home => "⌂",
1853 Icon::Search => "🔍",
1854 Icon::Menu => "☰",
1855 Icon::Filter => "⚟",
1856 Icon::Back => "‹",
1857 Icon::Forward => "›",
1858 Icon::Down => "⌄",
1859 Icon::Bell => "🔔",
1860 Icon::Cart => "🛒",
1861 Icon::Share => "↗",
1862 Icon::Heart => "♡",
1863 Icon::HeartFilled => "♥",
1864 Icon::Person => "👤",
1865 Icon::People => "👥",
1866 Icon::Phone => "📞",
1867 Icon::Mail => "✉",
1868 Icon::Calendar => "📅",
1869 Icon::Clock => "🕑",
1870 Icon::MapPin => "📍",
1871 Icon::Camera => "📷",
1872 Icon::Photo => "🖼",
1873 Icon::Play => "▶",
1874 Icon::Scissors => "✂",
1875 }
1876}
1877
1878fn image_class(shape: ImageShape, ratio: ImageRatio) -> String {
1879 let shape = match shape {
1880 ImageShape::Square => "img-square",
1881 ImageShape::Rounded => "img-rounded",
1882 ImageShape::Circle => "img-circle",
1883 };
1884 let ratio = match ratio {
1885 ImageRatio::Wide => "ratio-wide",
1886 ImageRatio::Square => "ratio-square",
1887 ImageRatio::Tall => "ratio-tall",
1888 };
1889 format!("img {shape} {ratio}")
1890}
1891
1892fn dot_class(c: ProjectColor) -> &'static str {
1893 match c {
1894 ProjectColor::Indigo => "dot-indigo",
1895 ProjectColor::Teal => "dot-teal",
1896 ProjectColor::Coral => "dot-coral",
1897 ProjectColor::Amber => "dot-amber",
1898 ProjectColor::Lime => "dot-lime",
1899 ProjectColor::Pink => "dot-pink",
1900 }
1901}
1902
1903fn align_class(a: BoxAlign) -> &'static str {
1904 match a {
1905 BoxAlign::TopStart => "align-top-start",
1906 BoxAlign::TopEnd => "align-top-end",
1907 BoxAlign::Center => "align-center",
1908 BoxAlign::BottomStart => "align-bottom-start",
1909 BoxAlign::BottomCenter => "align-bottom-center",
1910 BoxAlign::BottomEnd => "align-bottom-end",
1911 }
1912}
1913
1914const CHART_PALETTE: [&str; 6] = ["#E0772C", "#2EA06A", "#C0466B", "#8A5CC0", "#C9A227", "#3FA7D6"];
1918
1919fn hex(c: Rgb) -> String {
1920 format!("#{:02x}{:02x}{:02x}", c.r, c.g, c.b)
1921}
1922
1923fn chart_color(i: usize, s: &ChartSeries) -> String {
1925 match s.color {
1926 Some(c) => hex(c),
1927 None if i == 0 => "var(--accent, #5C6BC0)".to_string(),
1928 None => CHART_PALETTE[(i - 1) % CHART_PALETTE.len()].to_string(),
1929 }
1930}
1931
1932fn chart_mag(s: &ChartSeries) -> f32 {
1934 s.values.iter().copied().sum()
1935}
1936
1937fn polar(cx: f32, cy: f32, r: f32, ang: f32) -> (f32, f32) {
1939 (cx + r * ang.sin(), cy - r * ang.cos())
1940}
1941
1942fn arc_path(cx: f32, cy: f32, r: f32, a0: f32, a1: f32) -> String {
1944 let (x0, y0) = polar(cx, cy, r, a0);
1945 let (x1, y1) = polar(cx, cy, r, a1);
1946 let large = if (a1 - a0).abs() > std::f32::consts::PI { 1 } else { 0 };
1947 format!("M {x0:.2} {y0:.2} A {r:.2} {r:.2} 0 {large} 1 {x1:.2} {y1:.2}")
1948}
1949
1950fn wedge_path(cx: f32, cy: f32, r: f32, a0: f32, a1: f32) -> String {
1952 let (x0, y0) = polar(cx, cy, r, a0);
1953 let (x1, y1) = polar(cx, cy, r, a1);
1954 let large = if (a1 - a0).abs() > std::f32::consts::PI { 1 } else { 0 };
1955 format!("M {cx:.2} {cy:.2} L {x0:.2} {y0:.2} A {r:.2} {r:.2} 0 {large} 1 {x1:.2} {y1:.2} Z")
1956}
1957
1958fn fmt_tick(v: f32) -> String {
1959 if (v - v.round()).abs() < 0.05 { format!("{}", v.round() as i64) } else { format!("{v:.1}") }
1960}
1961
1962fn is_cartesian(style: ChartStyle) -> bool {
1963 matches!(style, ChartStyle::Bar | ChartStyle::Line | ChartStyle::StackedBar | ChartStyle::StackedBar100)
1964}
1965
1966fn cartesian_max(series: &[ChartSeries], style: ChartStyle, nslots: usize) -> f32 {
1968 match style {
1969 ChartStyle::StackedBar => (0..nslots)
1970 .map(|j| series.iter().map(|s| *s.values.get(j).unwrap_or(&0.0)).sum::<f32>())
1971 .fold(0.0, f32::max)
1972 .max(1e-6),
1973 ChartStyle::StackedBar100 => 1.0,
1974 _ => series.iter().flat_map(|s| s.values.iter().copied()).fold(0.0, f32::max).max(1e-6),
1975 }
1976}
1977
1978fn cartesian_svg(series: &[ChartSeries], style: ChartStyle, axis: bool, max: f32, nslots: usize) -> AnyView {
1979 let mut nodes: Vec<AnyView> = Vec::new();
1981 if axis {
1982 for k in 0..=4 {
1983 let y = 2.0 + k as f32 * (46.0 / 4.0);
1984 nodes.push(view! { <line x1="0" y1=format!("{y:.2}") x2="100" y2=format!("{y:.2}") class="chart-gridline"></line> }.into_any());
1985 }
1986 }
1987 match style {
1988 ChartStyle::Line => {
1989 for (i, s) in series.iter().enumerate() {
1990 let n = s.values.len().max(1);
1991 let pts = s.values.iter().enumerate().map(|(j, v)| {
1992 let x = if n == 1 { 50.0 } else { j as f32 * (100.0 / (n as f32 - 1.0)) };
1993 let y = 2.0 + (1.0 - (v / max).clamp(0.0, 1.0)) * 46.0;
1994 format!("{x:.2},{y:.2}")
1995 }).collect::<Vec<_>>().join(" ");
1996 let st = format!("fill:none;stroke:{};stroke-width:1.5;vector-effect:non-scaling-stroke", chart_color(i, s));
1997 nodes.push(view! { <polyline points=pts style=st></polyline> }.into_any());
1998 }
1999 }
2000 ChartStyle::Bar => {
2001 let sw = 100.0 / nslots as f32;
2002 let ns = series.len().max(1);
2003 for (i, s) in series.iter().enumerate() {
2004 let st = format!("fill:{}", chart_color(i, s));
2005 for (j, v) in s.values.iter().enumerate() {
2006 let h = (v / max).clamp(0.0, 1.0) * 46.0;
2007 let bw = sw * 0.8 / ns as f32;
2008 let x = j as f32 * sw + sw * 0.1 + i as f32 * bw;
2009 let y = 48.0 - h;
2010 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());
2011 }
2012 }
2013 }
2014 ChartStyle::StackedBar | ChartStyle::StackedBar100 => {
2015 let sw = 100.0 / nslots as f32;
2016 for j in 0..nslots {
2017 let slot_total = series.iter().map(|s| *s.values.get(j).unwrap_or(&0.0)).sum::<f32>().max(1e-6);
2018 let denom = if matches!(style, ChartStyle::StackedBar100) { slot_total } else { max };
2019 let mut acc = 0.0_f32;
2020 for (i, s) in series.iter().enumerate() {
2021 let v = *s.values.get(j).unwrap_or(&0.0);
2022 let h = (v / denom).clamp(0.0, 1.0) * 46.0;
2023 let x = j as f32 * sw + sw * 0.15;
2024 let bw = sw * 0.7;
2025 let y = 48.0 - acc - h;
2026 let st = format!("fill:{}", chart_color(i, s));
2027 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());
2028 acc += h;
2029 }
2030 }
2031 }
2032 _ => {}
2033 }
2034 view! { <svg viewBox="0 0 100 50" preserveAspectRatio="none" class="chart-svg">{nodes}</svg> }.into_any()
2035}
2036
2037fn circular_svg(series: &[ChartSeries], style: ChartStyle) -> AnyView {
2038 use std::f32::consts::PI;
2039 let mut nodes: Vec<AnyView> = Vec::new();
2040 match style {
2041 ChartStyle::Pie | ChartStyle::Donut => {
2042 let total = series.iter().map(chart_mag).sum::<f32>().max(1e-6);
2043 let mut a = 0.0_f32;
2044 for (i, s) in series.iter().enumerate() {
2045 let frac = chart_mag(s) / total;
2046 let st = format!("fill:{}", chart_color(i, s));
2047 if frac >= 0.999 {
2048 nodes.push(view! { <circle cx="50" cy="50" r="45" style=st></circle> }.into_any());
2049 } else if frac > 0.0 {
2050 let d = wedge_path(50.0, 50.0, 45.0, a, a + frac * 2.0 * PI);
2051 nodes.push(view! { <path d=d style=st></path> }.into_any());
2052 }
2053 a += frac * 2.0 * PI;
2054 }
2055 if matches!(style, ChartStyle::Donut) {
2056 nodes.push(view! { <circle cx="50" cy="50" r="24" style="fill:var(--surface, #ffffff)"></circle> }.into_any());
2057 }
2058 }
2059 ChartStyle::Rings => {
2060 let n = series.len().max(1);
2061 for (i, s) in series.iter().enumerate() {
2062 let r = 45.0 - i as f32 * (34.0 / n as f32);
2063 let goal = s.goal.unwrap_or_else(|| chart_mag(s)).max(1e-6);
2064 let prog = (chart_mag(s) / goal).clamp(0.0, 1.0);
2065 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());
2066 let st = format!("fill:none;stroke:{};stroke-width:6;stroke-linecap:round", chart_color(i, s));
2067 if prog >= 0.999 {
2068 nodes.push(view! { <circle cx="50" cy="50" r=format!("{r:.2}") style=st></circle> }.into_any());
2069 } else if prog > 0.0 {
2070 let d = arc_path(50.0, 50.0, r, 0.0, prog * 2.0 * PI);
2071 nodes.push(view! { <path d=d style=st></path> }.into_any());
2072 }
2073 }
2074 }
2075 ChartStyle::Gauge => {
2076 let s = match series.first() { Some(s) => s, None => return view! { <svg viewBox="0 0 100 100" class="chart-svg"></svg> }.into_any() };
2077 let goal = s.goal.unwrap_or_else(|| chart_mag(s)).max(1e-6);
2078 let prog = (chart_mag(s) / goal).clamp(0.0, 1.0);
2079 let a0 = -0.75 * PI; let a1 = 0.75 * PI;
2081 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());
2082 if prog > 0.0 {
2083 let st = format!("fill:none;stroke:{};stroke-width:8;stroke-linecap:round", chart_color(0, s));
2084 nodes.push(view! { <path d=arc_path(50.0, 50.0, 42.0, a0, a0 + prog * 1.5 * PI) style=st></path> }.into_any());
2085 }
2086 let pct = format!("{}%", (prog * 100.0).round() as i64);
2087 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());
2088 }
2089 _ => {}
2090 }
2091 view! { <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" class="chart-svg">{nodes}</svg> }.into_any()
2092}
2093
2094fn chart_view(series: &[ChartSeries], labels: &[String], style: ChartStyle, axis: bool, legend: bool) -> AnyView {
2095 let cartesian = is_cartesian(style);
2096 let nslots = series.iter().map(|s| s.values.len()).max().unwrap_or(0).max(1);
2097 let max = cartesian_max(series, style, nslots);
2098
2099 let plot = if cartesian {
2100 let svg = cartesian_svg(series, style, axis, max, nslots);
2101 let yaxis = if axis {
2102 let ticks: Vec<_> = [max, max / 2.0, 0.0].iter()
2103 .map(|t| view! { <span class="chart-tick">{fmt_tick(*t)}</span> })
2104 .collect();
2105 Some(view! { <div class="chart-yaxis">{ticks}</div> })
2106 } else {
2107 None
2108 };
2109 view! { <div class="chart-plot">{yaxis}{svg}</div> }.into_any()
2110 } else {
2111 circular_svg(series, style).into_any()
2112 };
2113
2114 let label_row = if cartesian && !labels.is_empty() {
2115 let items: Vec<_> = labels.iter().map(|l| view! { <span class="chart-label">{l.clone()}</span> }).collect();
2116 Some(view! { <div class="chart-labels">{items}</div> })
2117 } else {
2118 None
2119 };
2120
2121 let legend_row = if legend {
2122 let items: Vec<_> = series.iter().enumerate().map(|(i, s)| {
2123 let sw = format!("background:{}", chart_color(i, s));
2124 let name = s.name.clone();
2125 view! { <span class="chart-legend-item"><span class="chart-swatch" style=sw></span>{name}</span> }
2126 }).collect();
2127 Some(view! { <div class="chart-legend">{items}</div> })
2128 } else {
2129 None
2130 };
2131
2132 view! { <div class="chart">{plot}{label_row}{legend_row}</div> }.into_any()
2133}
2134
2135const CHART_PALETTE_RGB: [(u8, u8, u8); 6] =
2139 [(0xE0, 0x77, 0x2C), (0x2E, 0xA0, 0x6A), (0xC0, 0x46, 0x6B), (0x8A, 0x5C, 0xC0), (0xC9, 0xA2, 0x27), (0x3F, 0xA7, 0xD6)];
2140
2141fn region_rgb(i: usize, r: &ChartRegion) -> (u8, u8, u8) {
2143 match r.color {
2144 Some(c) => (c.r, c.g, c.b),
2145 None => CHART_PALETTE_RGB[i % CHART_PALETTE_RGB.len()],
2146 }
2147}
2148
2149fn contrast_text((r, g, b): (u8, u8, u8)) -> &'static str {
2151 let lum = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
2152 if lum > 140.0 { "#1a1a1a" } else { "#f5f5f5" }
2153}
2154
2155fn region_color(i: usize, r: &ChartRegion) -> String {
2156 let (r8, g8, b8) = region_rgb(i, r);
2157 format!("#{r8:02x}{g8:02x}{b8:02x}")
2158}
2159
2160fn region_chart_view(
2164 regions: &[ChartRegion],
2165 ticks: &[ChartTick],
2166 x_max: f32,
2167 y_max: f32,
2168 ref_lines: &[ChartRefLine],
2169 bracket: &Option<ChartBracket>,
2170 legend: &[ChartLegendItem],
2171) -> AnyView {
2172 let xm = x_max.max(1e-6);
2173 let ym = y_max.max(1e-6);
2174
2175 let region_divs: Vec<_> = regions.iter().enumerate().map(|(i, r)| {
2176 let left = (r.x0 / xm * 100.0).clamp(0.0, 100.0);
2177 let width = ((r.x1 - r.x0) / xm * 100.0).clamp(0.0, 100.0);
2178 let bottom = (r.y0 / ym * 100.0).clamp(0.0, 100.0);
2179 let height = ((r.y1 - r.y0) / ym * 100.0).clamp(0.0, 100.0);
2180 let style = format!("left:{left:.3}%;width:{width:.3}%;bottom:{bottom:.3}%;height:{height:.3}%;background:{}", region_color(i, r));
2181 let label_class = if r.vertical { "rchart-label rchart-label-v" } else { "rchart-label" };
2182 let label_style = format!("color:{}", contrast_text(region_rgb(i, r)));
2183 let label = r.label.clone();
2184 view! { <div class="rchart-region" style=style><span class=label_class style=label_style>{label}</span></div> }
2185 }).collect();
2186
2187 let ref_line_divs: Vec<_> = ref_lines.iter().map(|rl| {
2190 let style = format!("bottom:{:.3}%", (rl.value / ym * 100.0).clamp(0.0, 100.0));
2191 let cls = if rl.dashed { "rchart-refline rchart-refline-dashed" } else { "rchart-refline" };
2192 view! { <div class=cls style=style></div> }
2193 }).collect();
2194 let chip_divs: Vec<_> = ref_lines.iter().map(|rl| {
2195 let style = format!("bottom:{:.3}%", (rl.value / ym * 100.0).clamp(0.0, 100.0));
2196 let label = rl.label.clone();
2197 view! { <div class="rchart-chip" style=style>{label}</div> }
2198 }).collect();
2199
2200 let bracket_div = bracket.as_ref().map(|b| {
2201 let bottom = (b.y0 / ym * 100.0).clamp(0.0, 100.0);
2202 let height = ((b.y1 - b.y0) / ym * 100.0).clamp(0.0, 100.0);
2203 let style = format!("bottom:{bottom:.3}%;height:{height:.3}%");
2204 let label = if b.info { format!("ⓘ\n{}", b.label) } else { b.label.clone() };
2205 view! { <div class="rchart-bracket" style=style><span>{label}</span></div> }
2206 });
2207
2208 let yticks: Vec<_> = (0..=4).rev().map(|k| {
2209 let v = ym * k as f32 / 4.0;
2210 view! { <span class="chart-tick">{fmt_tick(v)}</span> }
2211 }).collect();
2212
2213 let xticks: Vec<_> = ticks.iter().map(|t| {
2214 let style = format!("left:{:.3}%", (t.at / xm * 100.0).clamp(0.0, 100.0));
2215 let label = t.label.clone();
2216 view! { <span class="rchart-xtick" style=style>{label}</span> }
2217 }).collect();
2218
2219 let ytick_marks: Vec<_> = (0..=4).map(|k| {
2222 let style = format!("bottom:{:.3}%", k as f32 * 25.0);
2223 view! { <div class="rchart-ytick" style=style></div> }
2224 }).collect();
2225 let xtick_marks: Vec<_> = ticks.iter().map(|t| {
2226 let style = format!("left:{:.3}%", (t.at / xm * 100.0).clamp(0.0, 100.0));
2227 view! { <div class="rchart-xtickmark" style=style></div> }
2228 }).collect();
2229
2230 let legend_row = if legend.is_empty() {
2231 None
2232 } else {
2233 let items: Vec<_> = legend.iter().map(|l| {
2234 let sw = format!("background:{}", hex(l.color));
2235 let name = l.label.clone();
2236 view! { <span class="chart-legend-item"><span class="chart-swatch" style=sw></span>{name}</span> }
2237 }).collect();
2238 Some(view! { <div class="chart-legend">{items}</div> })
2239 };
2240
2241 view! {
2242 <div class="rchart">
2243 <div class="rchart-row">
2244 <div class="rchart-yaxis">{yticks}</div>
2245 <div class="rchart-plotwrap">
2246 <div class="rchart-plot">{region_divs}{ytick_marks}{xtick_marks}{ref_line_divs}</div>
2247 {chip_divs}{bracket_div}
2248 </div>
2249 </div>
2250 <div class="rchart-xaxis">{xticks}</div>
2251 {legend_row}
2252 </div>
2253 }.into_any()
2254}