dioxus-theme 0.1.0-alpha.2

Dioxus components and native metadata for no-reload theme switching.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use dioxus::prelude::*;
pub use dioxus_theme_core::{
    DEFAULT_THEME_ANIMATION_SPEED, DEFAULT_THEME_ANIMATION_SPEED_STORAGE_KEY,
    DEFAULT_THEME_ANIMATION_STORAGE_KEY, DEFAULT_THEME_ATTRIBUTE, DEFAULT_THEME_DURATION_MS,
    DEFAULT_THEME_EASING, DEFAULT_THEME_RUNTIME_BASE_PATH, DEFAULT_THEME_RUNTIME_PATH,
    DEFAULT_THEME_RUNTIME_VERSION, DEFAULT_THEME_STORAGE_KEY, DEFAULT_THEME_TARGET,
    MAX_THEME_ANIMATION_SPEED, MIN_THEME_ANIMATION_SPEED, THEME_CHANGE_EVENT, THEME_TOKEN_ACCENT,
    THEME_TOKEN_BACKGROUND, THEME_TOKEN_BG, THEME_TOKEN_FG, THEME_TOKEN_MUTED, THEME_TOKEN_PANEL,
    THEME_TOKEN_PANEL_BORDER, THEME_TOKEN_SURFACE, THEME_TOKEN_SURFACE_BORDER, THEME_TOKEN_TEXT,
    THEME_VISUAL_TOKEN_MANIFEST_VERSION, THEME_VISUAL_TOKENS, ThemeAnimationMode,
    ThemeAnimationPreset, ThemeColorScheme, ThemeConfig, ThemeDefinition, ThemeReducedMotion,
    ThemeRegistry, ThemeValidationCode, ThemeValidationIssue, ThemeValidationReport,
    ThemeValidationSeverity, ThemeVisualTokenDefinition, ThemeVisualTokenManifest,
    ThemeVisualTokenRole, is_safe_css_token_value, is_valid_theme_attribute, is_valid_theme_target,
    normalize_animation_speed, theme_id, theme_tokens_css, theme_visual_token_manifest,
    theme_visual_token_manifest_json,
};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ThemeRuntimeMode {
    BrowserRuntime,
    StaticFallback,
}

pub fn theme_runtime_mode(config: &ThemeConfig) -> ThemeRuntimeMode {
    if cfg!(all(feature = "web", target_arch = "wasm32")) && config.animation.is_animated() {
        ThemeRuntimeMode::BrowserRuntime
    } else {
        ThemeRuntimeMode::StaticFallback
    }
}

pub fn theme_native_fallback_config() -> ThemeConfig {
    ThemeConfig::default().with_animation(ThemeAnimationMode::CssOnly)
}

pub fn theme_native_compatibility_manifest() -> dioxus_native_port::VisualCompatibilityManifest {
    dioxus_native_port::native_port_visual_compatibility_manifest("dioxus-theme")
        .expect("dioxus-theme visual compatibility manifest is registered")
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ThemeNativeAction {
    ToggleTheme,
    SetTheme,
    CycleTheme,
    SetAnimationPreset,
    SetAnimationSpeed,
}

impl ThemeNativeAction {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ToggleTheme => "toggle-theme",
            Self::SetTheme => "set-theme",
            Self::CycleTheme => "cycle-theme",
            Self::SetAnimationPreset => "set-animation-preset",
            Self::SetAnimationSpeed => "set-animation-speed",
        }
    }

    pub const fn label(self) -> &'static str {
        match self {
            Self::ToggleTheme => "Toggle theme",
            Self::SetTheme => "Set theme",
            Self::CycleTheme => "Cycle theme",
            Self::SetAnimationPreset => "Set animation preset",
            Self::SetAnimationSpeed => "Set animation speed",
        }
    }
}

pub fn theme_native_package_actions(
    route: Option<&str>,
) -> Vec<dioxus_native_port::NativePackageAction> {
    let route = route.map(str::to_string);
    [
        ThemeNativeAction::ToggleTheme,
        ThemeNativeAction::SetTheme,
        ThemeNativeAction::CycleTheme,
        ThemeNativeAction::SetAnimationPreset,
        ThemeNativeAction::SetAnimationSpeed,
    ]
    .into_iter()
    .map(|action| {
        let mut package_action = dioxus_native_port::NativePackageAction::new(
            "dioxus-theme",
            action.as_str(),
            action.label(),
            dioxus_native_port::NativeActionKind::NativeAction,
        )
        .description("Applies a configured theme without reloading the page.");
        if let Some(route) = route.clone() {
            package_action = package_action.route(route);
        }
        package_action
    })
    .collect()
}

pub fn theme_native_action(
    config: &ThemeConfig,
    action: ThemeNativeAction,
    current_theme: impl Into<String>,
) -> dioxus_native_port::NativeActionResult {
    let current_theme = theme_id(current_theme.into());
    let next_theme = match action {
        ThemeNativeAction::ToggleTheme | ThemeNativeAction::CycleTheme => {
            config.toggle_theme_id(&current_theme)
        }
        ThemeNativeAction::SetTheme => current_theme.clone(),
        ThemeNativeAction::SetAnimationPreset | ThemeNativeAction::SetAnimationSpeed => {
            current_theme.clone()
        }
    };
    let mode = theme_runtime_mode(config);
    let backend = match mode {
        ThemeRuntimeMode::BrowserRuntime => "browser-runtime",
        ThemeRuntimeMode::StaticFallback => "static-fallback",
    };

    dioxus_native_port::NativeActionResult::succeeded(
        "dioxus-theme",
        action.as_str(),
        dioxus_native_port::NativeActionKind::NativeAction,
        format!("{} prepared `{next_theme}`", action.label()),
    )
    .with_backend(backend)
    .with_output("currentTheme", current_theme)
    .with_output("nextTheme", next_theme)
    .with_output("storageKey", config.storage_key.clone())
    .with_output("animation", config.animation.as_attr())
    .with_output("animationPreset", config.animation_preset.as_attr())
    .with_output("animationStorageKey", config.animation_storage_key.clone())
    .with_output("animationSpeed", config.animation_speed.to_string())
    .with_output(
        "animationSpeedStorageKey",
        config.animation_speed_storage_key.clone(),
    )
    .with_output("themeCount", config.registry.themes.len().to_string())
}

pub fn use_theme(config: ThemeConfig) -> dioxus_native_port::PortableStorage {
    let key = config.storage_key.clone();
    let default_theme = config.default_theme.clone();
    dioxus_native_port::use_portable_storage(key, move || default_theme)
}

fn theme_control_id(prefix: &str, handler: &str, label: &str) -> String {
    format!("{prefix}-{}", theme_id(format!("{handler}-{label}")))
}

#[derive(Props, Clone, PartialEq)]
pub struct ThemeProviderProps {
    #[props(default)]
    pub config: ThemeConfig,
    #[props(default)]
    pub class: String,
    pub children: Element,
}

#[component]
pub fn ThemeProvider(props: ThemeProviderProps) -> Element {
    let default_theme = props.config.default_theme.clone();
    let storage_key = props.config.storage_key.clone();
    rsx! {
        div {
            class: "{props.class}",
            "data-dxt-provider": "true",
            "data-dxt-default-theme": "{default_theme}",
            "data-dxt-storage-key": "{storage_key}",
            {props.children}
        }
    }
}

#[derive(Props, Clone, PartialEq)]
pub struct ThemeToggleProps {
    #[props(default = "theme.toggle".to_string())]
    pub handler: String,
    #[props(default = "Toggle theme".to_string())]
    pub label: String,
    #[props(default)]
    pub class: String,
    #[props(default)]
    pub next_theme: String,
}

#[component]
pub fn ThemeToggle(props: ThemeToggleProps) -> Element {
    let next_theme = theme_id(&props.next_theme);
    rsx! {
        button {
            r#type: "button",
            class: "{props.class}",
            "aria-label": "{props.label}",
            "data-dxr-on-click": "{props.handler}",
            "data-dxt-theme-next": "{next_theme}",
            "data-dxt-theme-control": "toggle",
            span {
                "data-dxt-theme-toggle-label": "true",
                "aria-live": "polite",
                "{props.label}"
            }
        }
    }
}

#[derive(Props, Clone, PartialEq)]
pub struct ThemeSelectProps {
    #[props(default)]
    pub config: ThemeConfig,
    #[props(default = "theme.set".to_string())]
    pub handler: String,
    #[props(default)]
    pub class: String,
    #[props(default = "Theme".to_string())]
    pub label: String,
}

#[component]
pub fn ThemeSelect(props: ThemeSelectProps) -> Element {
    let select_id = theme_control_id("dxt-theme-select", &props.handler, &props.label);
    let label_id = format!("{select_id}-label");
    let current_id = format!("{select_id}-current");
    let current_label = props
        .config
        .resolve_theme(&props.config.default_theme)
        .map(|theme| theme.label.clone())
        .unwrap_or_else(|| props.config.default_theme.clone());
    rsx! {
        label {
            class: "{props.class}",
            "data-dxt-theme-control": "select",
            "for": "{select_id}",
            span {
                id: "{label_id}",
                "{props.label}"
            }
            select {
                id: "{select_id}",
                "aria-labelledby": "{label_id} {current_id}",
                "data-dxr-on-change": "{props.handler}",
                "data-dxt-theme-select": "true",
                for theme in props.config.registry.themes.iter() {
                    option {
                        value: "{theme.id}",
                        "{theme.label}"
                    }
                }
            }
            span {
                id: "{current_id}",
                "aria-live": "polite",
                "data-dxt-theme-current": "true",
                "{current_label}"
            }
        }
    }
}

#[derive(Props, Clone, PartialEq)]
pub struct ThemeAnimationSelectProps {
    #[props(default)]
    pub config: ThemeConfig,
    #[props(default = "theme.animation".to_string())]
    pub handler: String,
    #[props(default)]
    pub class: String,
    #[props(default = "Animation".to_string())]
    pub label: String,
}

#[component]
pub fn ThemeAnimationSelect(props: ThemeAnimationSelectProps) -> Element {
    let current = props.config.animation_preset.as_attr();
    let select_id = theme_control_id("dxt-theme-animation", &props.handler, &props.label);
    let label_id = format!("{select_id}-label");
    let current_id = format!("{select_id}-current");
    let current_label = props.config.animation_preset.label();
    rsx! {
        label {
            class: "{props.class}",
            "data-dxt-theme-control": "animation-select",
            "for": "{select_id}",
            span {
                id: "{label_id}",
                "{props.label}"
            }
            select {
                id: "{select_id}",
                value: "{current}",
                "aria-labelledby": "{label_id} {current_id}",
                "data-dxr-on-change": "{props.handler}",
                "data-dxt-theme-animation-select": "true",
                for preset in ThemeAnimationPreset::all().iter().copied() {
                    option {
                        value: "{preset.as_attr()}",
                        selected: preset == props.config.animation_preset,
                        "{preset.label()}"
                    }
                }
            }
            span {
                id: "{current_id}",
                "aria-live": "polite",
                "data-dxt-theme-animation-current": "true",
                "{current_label}"
            }
        }
    }
}

#[derive(Props, Clone, PartialEq)]
pub struct ThemeAnimationSpeedSliderProps {
    #[props(default)]
    pub config: ThemeConfig,
    #[props(default = "theme.animation-speed".to_string())]
    pub handler: String,
    #[props(default)]
    pub class: String,
    #[props(default = "Animation speed".to_string())]
    pub label: String,
    #[props(default = MIN_THEME_ANIMATION_SPEED)]
    pub min: u16,
    #[props(default = MAX_THEME_ANIMATION_SPEED)]
    pub max: u16,
    #[props(default = 25)]
    pub step: u16,
}

#[component]
pub fn ThemeAnimationSpeedSlider(props: ThemeAnimationSpeedSliderProps) -> Element {
    let value = normalize_animation_speed(props.config.animation_speed);
    let min = normalize_animation_speed(props.min);
    let max = normalize_animation_speed(props.max);
    let step = props.step.max(1);
    let input_id = theme_control_id("dxt-theme-animation-speed", &props.handler, &props.label);
    let output_id = format!("{input_id}-output");
    rsx! {
        label {
            class: "{props.class}",
            "data-dxt-theme-control": "animation-speed",
            "for": "{input_id}",
            span {
                "{props.label}: "
                output {
                    id: "{output_id}",
                    "for": "{input_id}",
                    "aria-live": "polite",
                    "data-dxt-theme-animation-speed-current": "true",
                    "{value}%"
                }
            }
            input {
                id: "{input_id}",
                r#type: "range",
                min: "{min}",
                max: "{max}",
                step: "{step}",
                value: "{value}",
                "aria-describedby": "{output_id}",
                "data-dxr-on-input": "{props.handler}",
                "data-dxt-theme-animation-speed": "true"
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn native_action_reports_next_theme() {
        let config = ThemeConfig::default().with_default_theme("dark");
        let result = theme_native_action(&config, ThemeNativeAction::ToggleTheme, "dark");
        assert_eq!(
            result.outputs.get("currentTheme"),
            Some(&"dark".to_string())
        );
        assert!(result.outputs.contains_key("nextTheme"));
        assert_eq!(
            result.outputs.get("animationPreset"),
            Some(&"cross-fade".to_string())
        );
        assert_eq!(
            result.outputs.get("animationSpeed"),
            Some(&"100".to_string())
        );

        let actions = theme_native_package_actions(Some("/browser"));
        assert!(
            actions
                .iter()
                .any(|action| action.action == "set-animation-preset")
        );
        assert!(
            actions
                .iter()
                .any(|action| action.action == "set-animation-speed")
        );
    }

    #[test]
    fn visual_token_contract_is_reexported() {
        let manifest = theme_visual_token_manifest();
        let native_manifest = theme_native_compatibility_manifest();
        assert_eq!(THEME_CHANGE_EVENT, "dioxus-theme:change");
        assert_eq!(manifest.tokens.len(), THEME_VISUAL_TOKENS.len());
        assert_eq!(native_manifest.package, "dioxus-theme");
        assert_eq!(ThemeVisualTokenRole::Accent.css_var(), THEME_TOKEN_ACCENT);
        assert_eq!(THEME_TOKEN_SURFACE_BORDER, THEME_TOKEN_PANEL_BORDER);
    }
}