lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! `WorldMap`: an interactive dotted or solid world map with highlighted countries, location
//! markers, country selection, and zoom and pan that work without JavaScript.

// cspell:words figcaption onmousedown onmousemove onmouseup onresize onwheel

#[rustfmt::skip]
mod countries;
mod model;

pub use model::*;

use std::rc::Rc;

use dioxus::html::geometry::WheelDelta;
use dioxus::prelude::*;

use crate::class::compose;
use crate::hooks::{use_controllable, use_unique_id};
use crate::icons::lucide;
use crate::{Button, ButtonSize, ButtonVariant, Icon};

/// Copy for the [`WorldMap`] zoom controls.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorldMapZoomLabels {
    /// Fit button text.
    pub fit: String,
    /// Name of the zoom level output.
    pub level: String,
    /// Reset button text.
    pub reset: String,
    /// Prefix of the viewport region name.
    pub viewport: String,
    /// Name of the zoom-in button.
    pub zoom_in: String,
    /// Name of the zoom-out button.
    pub zoom_out: String,
}

impl Default for WorldMapZoomLabels {
    fn default() -> Self {
        Self {
            fit: "Fit highlighted countries".into(),
            level: "Zoom level".into(),
            reset: "Reset zoom".into(),
            viewport: "Map viewport".into(),
            zoom_in: "Zoom in".into(),
            zoom_out: "Zoom out".into(),
        }
    }
}

/// The view a [`WorldMap`] starts with.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum WorldMapInitialView {
    /// The whole map.
    World,
    /// Fitted to the highlighted countries.
    Highlighted,
}

impl WorldMapInitialView {
    /// The `data-initial-view` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::World => "world",
            Self::Highlighted => "highlighted",
        }
    }
}

/// Props for [`WorldMap`].
#[derive(Props, Clone, PartialEq)]
pub struct WorldMapProps {
    /// Accessible name of the map image.
    #[props(into)]
    pub label: String,
    /// Country geometry, usually `world_map_countries().to_vec()`. Invalid and duplicate
    /// entries are dropped.
    pub countries: Vec<WorldMapCountry>,
    /// Highlighted country ids (case-insensitive). Unknown ids are ignored.
    #[props(default)]
    pub highlighted_countries: Vec<String>,
    /// Location markers. Invalid markers are dropped.
    #[props(default)]
    pub markers: Vec<WorldMapMarker>,
    /// Country label overrides as `(id, label)` pairs.
    #[props(default)]
    pub labels: Vec<(String, String)>,
    /// Dotted (default) or solid land.
    #[props(default)]
    pub variant: WorldMapVariant,
    /// Lets users select countries by clicking or with the country list.
    #[props(default = true)]
    pub interactive: bool,
    /// Shows the zoom controls and lets users zoom and pan.
    #[props(default = true)]
    pub zoomable: bool,
    /// The first view once the map is mounted.
    pub initial_view: Option<WorldMapInitialView>,
    /// Plays the entrance and marker animations (reduced motion turns them off).
    #[props(default = true)]
    pub animated: bool,
    /// Controlled selected country id.
    #[props(into)]
    pub selected_country: Option<String>,
    /// Initially selected country id when uncontrolled.
    #[props(into)]
    pub default_selected_country: Option<String>,
    /// Called with the selected country id, or an empty string when the selection clears.
    pub on_selected_country_change: Option<EventHandler<String>>,
    /// Called with details of a newly selected country.
    pub on_country_select: Option<EventHandler<WorldMapSelectDetail>>,
    /// Heading above the map.
    #[props(into)]
    pub heading: Option<String>,
    /// Description under the heading.
    #[props(into)]
    pub description: Option<String>,
    /// Caption under the map.
    #[props(into)]
    pub caption: Option<String>,
    /// Label and placeholder of the country list. Defaults to `Choose a country`.
    #[props(default = "Choose a country".to_string(), into)]
    pub list_label: String,
    /// Copy for the zoom controls.
    #[props(default)]
    pub zoom_labels: WorldMapZoomLabels,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<figure>` or global attribute.
    #[props(extends = GlobalAttributes, extends = figure)]
    pub attributes: Vec<Attribute>,
}

#[derive(Clone, Copy, Debug, PartialEq)]
struct Drag {
    x: f64,
    y: f64,
    start: WorldMapView,
    moved: bool,
}

/// An interactive world map.
///
/// Zoom and pan change the SVG `viewBox` instead of scrolling a scaled plot, so they work on
/// every renderer: the zoom buttons, `+`, `-`, and `0` on the focused viewport, arrow keys to
/// pan, Ctrl or Cmd with the wheel, and dragging when zoomed in (where the renderer reports
/// pointer events). Like lumen-react, the first render keeps the zoom controls disabled until the
/// component is mounted.
#[component]
#[allow(clippy::too_many_lines)]
pub fn WorldMap(props: WorldMapProps) -> Element {
    let unique = use_unique_id();
    let neutral_pattern = format!("{unique}-dot-neutral");
    let highlight_pattern = format!("{unique}-dot-highlight");
    let countries: Rc<[WorldMapCountry]> =
        Rc::from(normalize_world_map_countries(&props.countries));
    let highlighted: Rc<[String]> = Rc::from(normalize_world_map_highlighted(
        &props.highlighted_countries,
        &countries,
    ));
    let markers = normalize_world_map_markers(&props.markers);
    let labels: Rc<[(String, String)]> = Rc::from(props.labels.clone());
    let selection = use_controllable(
        props.selected_country.clone(),
        || props.default_selected_country.clone().unwrap_or_default(),
        props.on_selected_country_change,
    );
    let mut hovered = use_signal(|| None::<String>);
    let mut view = use_signal(WorldMapView::default);
    let mut enhanced = use_signal(|| false);
    let mut drag = use_signal(|| None::<Drag>);
    let mut suppress_click = use_signal(|| false);
    let mut viewport_size = use_signal(|| None::<(f64, f64)>);
    let initial_view = props.initial_view;
    let fit_countries = countries.clone();
    let fit_highlighted = highlighted.clone();

    use_effect(move || {
        if initial_view == Some(WorldMapInitialView::Highlighted)
            && let Some(fitted) = WorldMapView::fit_highlighted(&fit_countries, &fit_highlighted)
        {
            view.set(fitted);
        }

        enhanced.set(true);
    });

    let selected_id =
        find_world_map_country(&countries, &selection.get()).map(|country| country.id.to_string());
    let active_id = hovered().or_else(|| selected_id.clone());
    let active_label = active_id
        .as_deref()
        .and_then(|id| find_world_map_country(&countries, id))
        .map(|country| resolve_world_map_country_label(country, &labels).to_string());
    let selected_path = selected_id
        .as_deref()
        .and_then(|id| find_world_map_country(&countries, id))
        .map_or(String::new(), |country| country.path.to_string());
    let interactive = props.interactive;
    let zoomable = props.zoomable;
    let on_country_select = props.on_country_select;
    let select_countries = countries.clone();
    let select_highlighted = highlighted.clone();
    let select_labels = labels.clone();
    let select_country = move |id: String| {
        let country = find_world_map_country(&select_countries, &id);
        let current = selection.peek();

        if country.map(|country| country.id.as_ref())
            == find_world_map_country(&select_countries, &current)
                .map(|country| country.id.as_ref())
        {
            return;
        }

        selection.set(country.map_or_else(String::new, |country| country.id.to_string()));

        if let (Some(country), Some(handler)) = (country, on_country_select) {
            handler.call(world_map_select_detail(
                country,
                &select_highlighted,
                &select_labels,
            ));
        }
    };
    let current_view = view();
    let show = enhanced();
    let can_fit = !highlighted.is_empty();
    let class = compose([Some("ui-world-map"), props.class.as_deref()]);
    let variant = props.variant;
    let dotted = variant == WorldMapVariant::Dotted;
    let zoom_labels = props.zoom_labels.clone();
    let fit_target = WorldMapView::fit_highlighted(&countries, &highlighted);
    let pan_step = |view: &WorldMapView| view.view_box().width * 0.1;

    rsx! {
        figure {
            class,
            "data-animated": "{props.animated}",
            "data-initial-view": initial_view.map(WorldMapInitialView::as_str),
            "data-interactive": "{interactive}",
            "data-slot": "world-map",
            "data-variant": variant.as_str(),
            ..props.attributes,
            if props.heading.is_some() || props.description.is_some() {
                header { class: "ui-world-map__heading",
                    if let Some(heading) = props.heading.clone() {
                        h3 { "{heading}" }
                    }
                    if let Some(description) = props.description.clone() {
                        p { "{description}" }
                    }
                }
            }
            if zoomable {
                div { class: "ui-world-map__zoom-controls", "data-slot": "world-map-zoom-controls",
                    Button {
                        aria_label: "{zoom_labels.zoom_out}",
                        "data-ui-world-map-zoom": "out",
                        disabled: !show || !current_view.can_zoom_out(),
                        size: ButtonSize::Icon,
                        variant: ButtonVariant::Outline,
                        onclick: move |_| {
                            let next = view.peek().zoom_out();
                            view.set(next);
                        },
                        Icon { icon: &lucide::MINUS }
                    }
                    output {
                        aria_label: "{zoom_labels.level}",
                        aria_live: "polite",
                        "data-ui-world-map-zoom-status": "true",
                        "{current_view.zoom_percent()}"
                    }
                    Button {
                        aria_label: "{zoom_labels.zoom_in}",
                        "data-ui-world-map-zoom": "in",
                        disabled: !show || !current_view.can_zoom_in(),
                        size: ButtonSize::Icon,
                        variant: ButtonVariant::Outline,
                        onclick: move |_| {
                            let next = view.peek().zoom_in();
                            view.set(next);
                        },
                        Icon { icon: &lucide::PLUS }
                    }
                    Button {
                        "data-ui-world-map-zoom": "fit",
                        disabled: !show || !can_fit,
                        size: ButtonSize::Sm,
                        variant: ButtonVariant::Outline,
                        onclick: move |_| {
                            if let Some(fitted) = fit_target {
                                view.set(fitted);
                            }
                        },
                        "{zoom_labels.fit}"
                    }
                    Button {
                        "data-ui-world-map-zoom": "reset",
                        disabled: !show || !current_view.can_zoom_out(),
                        size: ButtonSize::Sm,
                        variant: ButtonVariant::Outline,
                        onclick: move |_| view.set(WorldMapView::default()),
                        "{zoom_labels.reset}"
                    }
                }
            }
            div { class: "ui-world-map__frame", "data-slot": "world-map-frame",
                div {
                    aria_label: "{zoom_labels.viewport}: {props.label}",
                    class: "ui-world-map__viewport",
                    "data-pan-enabled": (show && zoomable).then(|| (current_view.zoom > 1.0).to_string()),
                    "data-panning": drag().is_some_and(|drag| drag.moved).then_some(""),
                    "data-ui-world-map-viewport": "true",
                    role: "region",
                    tabindex: zoomable.then_some("0"),
                    onmounted: move |event| async move {
                        if let Ok(rect) = event.get_client_rect().await {
                            viewport_size.set(Some((rect.width(), rect.height())));
                        }
                    },
                    onresize: move |event| {
                        if let Ok(size) = event.get_border_box_size() {
                            viewport_size.set(Some((size.width, size.height)));
                        }
                    },
                    onkeydown: move |event| {
                        if !zoomable {
                            return;
                        }

                        let current = *view.peek();
                        let step = pan_step(&current);
                        let next = match event.key() {
                            Key::ArrowLeft => current.pan_by(-step, 0.0),
                            Key::ArrowRight => current.pan_by(step, 0.0),
                            Key::ArrowUp => current.pan_by(0.0, -step),
                            Key::ArrowDown => current.pan_by(0.0, step),
                            Key::Character(text) if text == "+" || text == "=" => current.zoom_in(),
                            Key::Character(text) if text == "-" => current.zoom_out(),
                            Key::Character(text) if text == "0" => WorldMapView::default(),
                            _ => return,
                        };

                        event.prevent_default();
                        view.set(next);
                    },
                    onwheel: move |event| {
                        let modifiers = event.modifiers();

                        if !zoomable || !(modifiers.ctrl() || modifiers.meta()) {
                            return;
                        }

                        event.prevent_default();
                        let height = viewport_size.peek().map_or(400.0, |(_, height)| height);
                        let delta = match event.delta() {
                            WheelDelta::Pixels(pixels) => pixels.y,
                            WheelDelta::Lines(lines) => lines.y * 16.0,
                            WheelDelta::Pages(pages) => pages.y * height,
                        };

                        let next = view.peek().zoom_by_wheel(delta, None);
                        view.set(next);
                    },
                    onmousedown: move |event| {
                        let primary = event.trigger_button().is_none_or(|button| button == dioxus::html::input_data::MouseButton::Primary);

                        if !zoomable || !primary || view.peek().zoom <= 1.0 {
                            return;
                        }

                        let point = event.client_coordinates();
                        drag.set(Some(Drag { x: point.x, y: point.y, start: *view.peek(), moved: false }));
                    },
                    onmousemove: move |event| {
                        let Some(mut current) = *drag.peek() else {
                            return;
                        };

                        let point = event.client_coordinates();
                        let (dx, dy) = (point.x - current.x, point.y - current.y);

                        if !current.moved && !world_map_pan_threshold_reached(dx, dy) {
                            return;
                        }

                        current.moved = true;
                        drag.set(Some(current));
                        let (width, height) = viewport_size.peek().unwrap_or((WORLD_MAP_VIEW_BOX_WIDTH, WORLD_MAP_VIEW_BOX_HEIGHT));
                        view.set(current.start.drag_by(dx, dy, width, height));
                        event.prevent_default();
                    },
                    onmouseup: move |_| {
                        suppress_click.set(drag.peek().is_some_and(|drag| drag.moved));
                        drag.set(None);
                    },
                    onmouseleave: move |_| drag.set(None),
                    svg {
                        "aria-label": "{props.label}",
                        class: "ui-world-map__plot",
                        role: "img",
                        view_box: "{current_view.view_box_attribute()}",
                        if dotted {
                            defs {
                                pattern { height: "4", id: "{neutral_pattern}", "patternUnits": "userSpaceOnUse", width: "4",
                                    circle { class: "ui-world-map__dot ui-world-map__dot--neutral", cx: "2", cy: "2", r: "1.1" }
                                }
                                pattern { height: "4", id: "{highlight_pattern}", "patternUnits": "userSpaceOnUse", width: "4",
                                    circle { class: "ui-world-map__dot ui-world-map__dot--highlight", cx: "2", cy: "2", r: "1.1" }
                                }
                            }
                        }
                        g { "aria-hidden": "true", class: "ui-world-map__countries",
                            for country in countries.iter() {
                                {
                                    let is_highlighted = highlighted.iter().any(|id| *id == country.id);
                                    let is_selected = selected_id.as_deref() == Some(country.id.as_ref());
                                    let country_class = compose([
                                        Some("ui-world-map__country"),
                                        is_highlighted.then_some("ui-world-map__country--highlighted"),
                                        is_selected.then_some("ui-world-map__country--selected"),
                                    ]);
                                    let fill = dotted.then(|| format!("url(#{})", if is_highlighted { &highlight_pattern } else { &neutral_pattern }));
                                    let (click_id, hover_id) = (country.id.to_string(), country.id.to_string());
                                    let select_country = select_country.clone();

                                    rsx! {
                                        path {
                                            key: "{country.id}",
                                            class: country_class,
                                            d: "{country.path}",
                                            fill,
                                            fill_rule: "evenodd",
                                            onclick: move |_| {
                                                if suppress_click() {
                                                    suppress_click.set(false);
                                                    return;
                                                }

                                                if interactive {
                                                    select_country(click_id.clone());
                                                }
                                            },
                                            onmouseenter: move |_| hovered.set(Some(hover_id.clone())),
                                            onmouseleave: move |_| hovered.set(None),
                                            title { "{resolve_world_map_country_label(country, &labels)}" }
                                        }
                                    }
                                }
                            }
                        }
                        if !markers.is_empty() {
                            g { "aria-hidden": "true", class: "ui-world-map__markers",
                                for marker in markers.iter() {
                                    if let Some(point) = marker.point() {
                                        circle { key: "{marker.id}", class: "ui-world-map__marker", cx: "{point.x}", cy: "{point.y}", r: "4",
                                            title { "{marker.label}" }
                                        }
                                    }
                                }
                            }
                        }
                        path { "aria-hidden": "true", class: "ui-world-map__selection", d: "{selected_path}" }
                    }
                }
                if let Some(label) = active_label {
                    span { class: "ui-world-map__inspection", "{label}" }
                }
            }
            if interactive {
                label { class: "ui-world-map__select-label",
                    span { "{props.list_label}" }
                    select {
                        class: "ui-select ui-world-map__select",
                        oninput: move |event| select_country(event.value()),
                        option { selected: selected_id.is_none(), value: "", "{props.list_label}" }
                        for country in countries.iter() {
                            option {
                                key: "{country.id}",
                                selected: selected_id.as_deref() == Some(country.id.as_ref()),
                                value: "{country.id}",
                                "{resolve_world_map_country_label(country, &labels)}"
                            }
                        }
                    }
                }
            }
            if !highlighted.is_empty() {
                ul { aria_label: "Highlighted countries", class: "ui-world-map__highlights",
                    for id in highlighted.iter() {
                        if let Some(country) = find_world_map_country(&countries, id) {
                            li { key: "{id}", "{resolve_world_map_country_label(country, &labels)}" }
                        }
                    }
                }
            }
            if !markers.is_empty() {
                ul { aria_label: "Map markers", class: "ui-sr-only",
                    for marker in markers.iter() {
                        li { key: "{marker.id}", "{marker.label}" }
                    }
                }
            }
            if let Some(caption) = props.caption.clone() {
                figcaption { "{caption}" }
            }
        }
    }
}