adam_web_ui/components/styles.rs
1//! Delivers immutable official styles without a bundler or deployment prefix.
2use dioxus::prelude::*;
3
4/// Contains the official styles transformed with public CSS-module exports.
5///
6/// Publish this exact stylesheet when a host stages shared control assets.
7///
8/// # Examples
9/// ```
10/// assert!(!adam_web_ui::components::CONTROL_CSS.is_empty());
11/// ```
12pub const CONTROL_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/adam-controls.css"));
13
14/// Returns an idempotent document-owned stylesheet installation script.
15///
16/// The stylesheet survives independent root removal and requires no asset fetch.
17/// - Complexity: O(stylesheet bytes) time and space.
18///
19/// # Examples
20/// ```
21/// let script = adam_web_ui::components::style_delivery_script();
22/// assert!(script.contains("createElement"));
23/// ```
24pub fn style_delivery_script() -> String {
25 format!(
26 "/* adam-control-styles */ if (!document.getElementById('stlab-adam-controls-v1')) {{ const style = document.createElement('style'); style.id = 'stlab-adam-controls-v1'; style.textContent = {}; document.head.appendChild(style); }} return null;",
27 serde_json::to_string(CONTROL_CSS).expect("static CSS encodes as JSON")
28 )
29}
30
31/// Installs document-owned styles once per component scope and reports delivery failure.
32///
33/// Renderers supply Dioxus's `Document` context. Missing context reports a
34/// delivery failure on the platform diagnostic channel rather than silently
35/// rendering without styles; no alternate stylesheet is assumed.
36/// - Complexity: O(stylesheet bytes) delivery on initialization; O(1) thereafter.
37pub(crate) fn use_control_styles() {
38 use_hook(|| {
39 if let Some(document) = try_consume_context::<std::rc::Rc<dyn dioxus::document::Document>>()
40 {
41 let evaluation = document.eval(style_delivery_script());
42 spawn(async move {
43 if let Err(error) = evaluation.await {
44 crate::diagnostics::report_error(&format!(
45 "Control stylesheet delivery failed: {error}"
46 ));
47 }
48 });
49 } else {
50 crate::diagnostics::report_error(
51 "Control stylesheet delivery failed: Document context unavailable",
52 );
53 }
54 });
55}