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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! Media workspace parts: `MediaViewport`, `MediaThumbnail`, and `MediaFilmstrip`.
// cspell:words figcaption onmousedown onmouseleave onmousemove onmouseup onpointercancel

use std::rc::Rc;

use dioxus::html::input_data::MouseButton;
use dioxus::prelude::*;

use super::number_format::{
    FormattedNumberFormat, FormattedNumberValue, NumberFormatOptions, format_lumen_number,
};
use super::util::js_number;
use crate::class::compose;
use crate::hooks::{use_controllable, use_unique_id};
use crate::{Button, ButtonVariant};

/// Zoom and pan of a [`MediaViewport`]. `zoom` is relative to fit; `x` and `y` are fractions of
/// the available pan extent, from -1 to 1.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MediaViewportValue {
    /// Horizontal pan, from -1 (left edge) to 1 (right edge).
    pub x: f64,
    /// Vertical pan, from -1 (top edge) to 1 (bottom edge).
    pub y: f64,
    /// Zoom relative to fit, from 1 to the maximum zoom.
    pub zoom: f64,
}

impl Default for MediaViewportValue {
    fn default() -> Self {
        Self {
            x: 0.0,
            y: 0.0,
            zoom: 1.0,
        }
    }
}

/// A [`MediaViewport`] action.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum MediaViewportAction {
    /// Zoom in by a quarter.
    ZoomIn,
    /// Zoom out by a quarter.
    ZoomOut,
    /// Reset to fit.
    Fit,
    /// Pan left.
    Left,
    /// Pan right.
    Right,
    /// Pan up.
    Up,
    /// Pan down.
    Down,
}

impl MediaViewportAction {
    /// Every action, in toolbar order.
    pub const ALL: [Self; 7] = [
        Self::ZoomIn,
        Self::ZoomOut,
        Self::Fit,
        Self::Left,
        Self::Right,
        Self::Up,
        Self::Down,
    ];

    /// The `data-ui-media-viewport-action` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::ZoomIn => "zoom-in",
            Self::ZoomOut => "zoom-out",
            Self::Fit => "fit",
            Self::Left => "left",
            Self::Right => "right",
            Self::Up => "up",
            Self::Down => "down",
        }
    }
}

/// Toolbar labels of a [`MediaViewport`]. Unset fields keep the English default.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct MediaViewportLabels {
    /// Default: "Zoom in".
    pub zoom_in: Option<String>,
    /// Default: "Zoom out".
    pub zoom_out: Option<String>,
    /// Default: "Fit to view".
    pub fit: Option<String>,
    /// Default: "Pan left".
    pub left: Option<String>,
    /// Default: "Pan right".
    pub right: Option<String>,
    /// Default: "Pan up".
    pub up: Option<String>,
    /// Default: "Pan down".
    pub down: Option<String>,
}

impl MediaViewportLabels {
    fn label(&self, action: MediaViewportAction) -> String {
        let (custom, fallback) = match action {
            MediaViewportAction::ZoomIn => (&self.zoom_in, "Zoom in"),
            MediaViewportAction::ZoomOut => (&self.zoom_out, "Zoom out"),
            MediaViewportAction::Fit => (&self.fit, "Fit to view"),
            MediaViewportAction::Left => (&self.left, "Pan left"),
            MediaViewportAction::Right => (&self.right, "Pan right"),
            MediaViewportAction::Up => (&self.up, "Pan up"),
            MediaViewportAction::Down => (&self.down, "Pan down"),
        };

        custom.clone().unwrap_or_else(|| fallback.to_string())
    }
}

/// Clamps a maximum zoom to 1 through 16; non-finite values become 4.
pub fn resolve_media_max_zoom(max_zoom: f64) -> f64 {
    if max_zoom.is_finite() {
        max_zoom.clamp(1.0, 16.0)
    } else {
        4.0
    }
}

fn finite_or(value: f64, fallback: f64) -> f64 {
    if value.is_finite() { value } else { fallback }
}

/// Clamps zoom and pan like `normalizeLumenMediaViewport`; pan resets at zoom 1.
pub fn normalize_media_viewport(value: MediaViewportValue, max_zoom: f64) -> MediaViewportValue {
    let zoom = finite_or(value.zoom, 1.0).clamp(1.0, resolve_media_max_zoom(max_zoom));

    if zoom <= 1.0 {
        return MediaViewportValue::default();
    }

    MediaViewportValue {
        x: finite_or(value.x, 0.0).clamp(-1.0, 1.0),
        y: finite_or(value.y, 0.0).clamp(-1.0, 1.0),
        zoom,
    }
}

/// Applies a toolbar or keyboard action like `applyLumenMediaViewportAction`.
pub fn apply_media_viewport_action(
    value: MediaViewportValue,
    action: MediaViewportAction,
    max_zoom: f64,
) -> MediaViewportValue {
    let current = normalize_media_viewport(value, max_zoom);
    let next = match action {
        MediaViewportAction::Fit => return MediaViewportValue::default(),
        MediaViewportAction::ZoomIn => MediaViewportValue {
            zoom: current.zoom + 0.25,
            ..current
        },
        MediaViewportAction::ZoomOut => MediaViewportValue {
            zoom: current.zoom - 0.25,
            ..current
        },
        MediaViewportAction::Left => MediaViewportValue {
            x: current.x - 0.25,
            ..current
        },
        MediaViewportAction::Right => MediaViewportValue {
            x: current.x + 0.25,
            ..current
        },
        MediaViewportAction::Up => MediaViewportValue {
            y: current.y - 0.25,
            ..current
        },
        MediaViewportAction::Down => MediaViewportValue {
            y: current.y + 0.25,
            ..current
        },
    };

    normalize_media_viewport(next, max_zoom)
}

/// Maps a pointer drag of `delta_x` by `delta_y` pixels over a `width` by `height` stage to a new
/// pan, like `panLumenMediaViewport`.
pub fn pan_media_viewport(
    value: MediaViewportValue,
    delta_x: f64,
    delta_y: f64,
    width: f64,
    height: f64,
    max_zoom: f64,
) -> MediaViewportValue {
    let current = normalize_media_viewport(value, max_zoom);
    let extent = (current.zoom - 1.0) / 2.0;

    if extent == 0.0 || !width.is_finite() || !height.is_finite() || width <= 0.0 || height <= 0.0 {
        return current;
    }

    let step = |delta: f64, size: f64| {
        if delta.is_finite() {
            delta / size / extent
        } else {
            0.0
        }
    };

    normalize_media_viewport(
        MediaViewportValue {
            x: current.x + step(delta_x, width),
            y: current.y + step(delta_y, height),
            zoom: current.zoom,
        },
        max_zoom,
    )
}

fn keyboard_action(key: &Key) -> Option<MediaViewportAction> {
    match key {
        Key::ArrowDown => Some(MediaViewportAction::Down),
        Key::ArrowLeft => Some(MediaViewportAction::Left),
        Key::ArrowRight => Some(MediaViewportAction::Right),
        Key::ArrowUp => Some(MediaViewportAction::Up),
        Key::Home => Some(MediaViewportAction::Fit),
        Key::Character(text) if text == "+" || text == "=" => Some(MediaViewportAction::ZoomIn),
        Key::Character(text) if text == "-" => Some(MediaViewportAction::ZoomOut),
        _ => None,
    }
}

fn format_zoom(zoom: f64, locale: Option<&str>) -> String {
    let options = NumberFormatOptions {
        format: FormattedNumberFormat::Percent,
        locale: locale.map(str::to_string),
        maximum_fraction_digits: Some(0.0),
        ..NumberFormatOptions::default()
    };

    format_lumen_number(&FormattedNumberValue::Number(zoom), &options, "").text
}

/// A drag in progress: where it started, the value at the start, and the input kind.
#[derive(Clone, Copy, PartialEq)]
struct MediaDrag {
    x: f64,
    y: f64,
    value: MediaViewportValue,
    touch: bool,
}

/// Props for [`MediaViewport`].
#[derive(Props, Clone, PartialEq)]
pub struct MediaViewportProps {
    /// Accessible name of the stage and the toolbar, also shown in the caption.
    #[props(into)]
    pub label: String,
    /// Toolbar labels.
    #[props(default)]
    pub labels: MediaViewportLabels,
    /// Controlled zoom and pan.
    pub value: Option<MediaViewportValue>,
    /// Initial zoom and pan when uncontrolled.
    #[props(default)]
    pub default_value: MediaViewportValue,
    /// Called with the requested zoom and pan.
    pub on_value_change: Option<EventHandler<MediaViewportValue>>,
    /// Maximum zoom, from 1 to 16. Defaults to 4.
    #[props(default = 4.0)]
    pub max_zoom: f64,
    /// Width to height ratio of the stage, from 0.1 to 10. Defaults to 16 / 9.
    #[props(default = 16.0 / 9.0)]
    pub ratio: f64,
    /// Disables zoom and pan.
    #[props(default)]
    pub disabled: bool,
    /// Stage width in pixels used to turn drag distance into pan when the renderer cannot measure
    /// the stage (Dioxus Native). The web and desktop measure it. Defaults to 640.
    #[props(default = 640.0)]
    pub drag_extent: f64,
    /// BCP 47 locale of the zoom status; defaults to English.
    #[props(into)]
    pub locale: Option<String>,
    /// 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>,
    /// The media, usually an image.
    pub children: Element,
}

/// A media stage that zooms and pans, with a toolbar. The stage takes focus: arrow keys pan, `+`
/// and `-` zoom, and Home fits; dragging pans while zoomed in.
#[component]
pub fn MediaViewport(props: MediaViewportProps) -> Element {
    let max_zoom = props.max_zoom;
    let viewport = use_controllable(
        props.value,
        || normalize_media_viewport(props.default_value, max_zoom),
        props.on_value_change,
    );
    let status_id = use_unique_id();
    let mut stage = use_signal(|| None::<Rc<MountedData>>);
    let mut drag = use_signal(|| None::<MediaDrag>);
    let current = normalize_media_viewport(viewport.get(), max_zoom);
    let disabled = props.disabled;
    let ratio = if props.ratio.is_finite() && (0.1..=10.0).contains(&props.ratio) {
        props.ratio
    } else {
        16.0 / 9.0
    };
    let touch_action = if current.zoom > 1.0 && !disabled {
        "none"
    } else {
        "pan-y"
    };
    let stage_style = format!(
        "aspect-ratio: {}; touch-action: {touch_action}",
        js_number(ratio)
    );
    let transform = format!(
        "transform: translate({}%, {}%) scale({})",
        js_number(current.x * (current.zoom - 1.0) * 50.0),
        js_number(current.y * (current.zoom - 1.0) * 50.0),
        js_number(current.zoom)
    );
    let act = move |action: MediaViewportAction| {
        if !disabled {
            let current = normalize_media_viewport(viewport.peek(), max_zoom);
            viewport.set(apply_media_viewport_action(current, action, max_zoom));
        }
    };
    let fallback_size = if props.drag_extent.is_finite() && props.drag_extent >= 1.0 {
        (props.drag_extent, props.drag_extent / ratio)
    } else {
        (640.0, 640.0 / ratio)
    };
    let mut measured = use_signal(|| None::<(f64, f64)>);
    let mut start = move |x: f64, y: f64, touch: bool| -> bool {
        let value = normalize_media_viewport(viewport.peek(), max_zoom);

        if disabled || drag.peek().is_some() || value.zoom <= 1.0 {
            return false;
        }

        drag.set(Some(MediaDrag { x, y, value, touch }));

        // Measure the stage where the renderer supports it (web and desktop).
        if let Some(mounted) = stage.peek().clone() {
            spawn(async move {
                if let Ok(rect) = mounted.get_client_rect().await {
                    measured.set(Some((rect.size.width, rect.size.height)));
                }
            });
        }

        true
    };
    let follow = move |x: f64, y: f64, touch: bool| {
        let Some(active) = *drag.peek() else { return };

        if active.touch != touch || disabled {
            return;
        }

        let (width, height) = measured.peek().unwrap_or(fallback_size);
        viewport.set(pan_media_viewport(
            active.value,
            x - active.x,
            y - active.y,
            width,
            height,
            max_zoom,
        ));
    };
    let mut stop = move |touch: bool| {
        if drag.peek().is_some_and(|active| active.touch == touch) {
            drag.set(None);
        }
    };
    let class = compose([Some("ui-media-viewport"), props.class.as_deref()]);
    let label = props.label.clone();

    rsx! {
        figure { class, ..props.attributes,
            div {
                aria_describedby: status_id.clone(),
                aria_disabled: if disabled { "true" } else { "false" },
                aria_label: label.clone(),
                class: "ui-media-viewport__stage",
                "data-ui-media-viewport-stage": "true",
                role: "group",
                style: stage_style,
                tabindex: "0",
                onmounted: move |event| stage.set(Some(event.data())),
                onkeydown: move |event: KeyboardEvent| {
                    let modifiers = event.modifiers();

                    if modifiers.alt() || modifiers.ctrl() || modifiers.meta() || disabled {
                        return;
                    }

                    if let Some(action) = keyboard_action(&event.key()) {
                        event.prevent_default();
                        act(action);
                    }
                },
                // Mouse events reach every renderer, Dioxus Native included.
                onmousedown: move |event: MouseEvent| {
                    if event.trigger_button() == Some(MouseButton::Primary) {
                        let point = event.client_coordinates();

                        if start(point.x, point.y, false) {
                            event.prevent_default();
                        }
                    }
                },
                onmousemove: move |event: MouseEvent| {
                    let point = event.client_coordinates();
                    follow(point.x, point.y, false);
                },
                onmouseup: move |_| stop(false),
                onmouseleave: move |_| stop(false),
                // Touch and pen input arrives as pointer events on the web and desktop.
                onpointerdown: move |event: PointerEvent| {
                    if event.pointer_type() != "mouse" {
                        let point = event.client_coordinates();
                        start(point.x, point.y, true);
                    }
                },
                onpointermove: move |event: PointerEvent| {
                    if event.pointer_type() != "mouse" {
                        let point = event.client_coordinates();
                        follow(point.x, point.y, true);
                    }
                },
                onpointerup: move |event: PointerEvent| {
                    if event.pointer_type() != "mouse" {
                        stop(true);
                    }
                },
                onpointercancel: move |event: PointerEvent| {
                    if event.pointer_type() != "mouse" {
                        stop(true);
                    }
                },
                div {
                    class: "ui-media-viewport__content",
                    "data-ui-media-viewport-content": "true",
                    style: transform,
                    {props.children}
                }
            }
            figcaption {
                span { {label.clone()} }
                span {
                    id: status_id,
                    role: "status",
                    aria_live: "polite",
                    "data-ui-media-viewport-status": "true",
                    {format_zoom(current.zoom, props.locale.as_deref())}
                }
                div { class: "ui-media-viewport__actions", role: "group", aria_label: label,
                    for action in MediaViewportAction::ALL {
                        Button {
                            key: "{action.as_str()}",
                            variant: ButtonVariant::Outline,
                            disabled: disabled
                                || apply_media_viewport_action(current, action, max_zoom) == current,
                            onclick: move |_| act(action),
                            attributes: vec![Attribute::new("data-ui-media-viewport-action", action.as_str(), None, false)],
                            {props.labels.label(action)}
                        }
                    }
                }
            }
        }
    }
}

/// Loading state of a [`MediaThumbnail`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum MediaThumbnailState {
    /// The media is ready to select.
    #[default]
    Ready,
    /// The media is loading.
    Loading,
    /// The media failed to load.
    Error,
}

impl MediaThumbnailState {
    /// The `data-state` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ready => "ready",
            Self::Loading => "loading",
            Self::Error => "error",
        }
    }
}

/// Props for [`MediaThumbnail`].
#[derive(Props, Clone, PartialEq)]
pub struct MediaThumbnailProps {
    /// Visible name of the media.
    #[props(into)]
    pub label: String,
    /// Id written to `data-media-id`.
    #[props(into)]
    pub media_id: Option<String>,
    /// Position shown as a badge, from 1. Zero hides it.
    pub order: Option<u32>,
    /// Marks the thumbnail as selected with `aria-pressed`.
    #[props(default)]
    pub selected: bool,
    /// Loading state. Loading and error thumbnails are disabled.
    #[props(default)]
    pub state: MediaThumbnailState,
    /// Text for the loading or error state. Defaults to "Loading" or "Unavailable".
    #[props(into)]
    pub state_label: Option<String>,
    /// Disables the thumbnail.
    #[props(default)]
    pub disabled: bool,
    /// Click handler, usually toggling the selection.
    pub onclick: Option<EventHandler<MouseEvent>>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<button>` or global attribute.
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
    /// The preview image.
    pub children: Element,
}

/// A selectable media thumbnail: a toggle button with a preview, label, order badge, and state.
#[component]
pub fn MediaThumbnail(props: MediaThumbnailProps) -> Element {
    let ready = props.state == MediaThumbnailState::Ready;
    let status = props.state_label.clone().unwrap_or_else(|| {
        if props.state == MediaThumbnailState::Loading {
            "Loading".to_string()
        } else {
            "Unavailable".to_string()
        }
    });
    let order = props.order.filter(|order| *order > 0);
    let class = compose([Some("ui-media-thumbnail"), props.class.as_deref()]);
    let onclick = props.onclick;

    let mut attributes = vec![
        Attribute::new(
            "aria-pressed",
            if props.selected { "true" } else { "false" },
            None,
            false,
        ),
        Attribute::new("data-state", props.state.as_str(), None, false),
    ];

    if props.state == MediaThumbnailState::Loading {
        attributes.push(Attribute::new("aria-busy", "true", None, false));
    }

    if let Some(media_id) = props.media_id.clone() {
        attributes.push(Attribute::new("data-media-id", media_id, None, false));
    }

    attributes.extend(props.attributes.iter().cloned());

    rsx! {
        Button {
            class,
            variant: ButtonVariant::Outline,
            disabled: props.disabled || !ready,
            onclick: move |event| {
                if let Some(handler) = onclick {
                    handler.call(event);
                }
            },
            attributes,
            span { class: "ui-media-thumbnail__media", aria_hidden: "true", {props.children} }
            span { class: "ui-media-thumbnail__label", {props.label.clone()} }
            if let Some(order) = order {
                span { class: "ui-media-thumbnail__order", "{order}" }
            }
            if !ready {
                span { class: "ui-media-thumbnail__state", {status} }
            }
        }
    }
}

/// Props for [`MediaFilmstrip`].
#[derive(Props, Clone, PartialEq)]
pub struct MediaFilmstripProps {
    /// Accessible name of the region, also shown as its heading.
    #[props(into)]
    pub label: String,
    /// Selection summary announced as a status, such as "2 selected".
    #[props(into)]
    pub selection_label: String,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<section>` or global attribute.
    #[props(extends = GlobalAttributes, extends = section)]
    pub attributes: Vec<Attribute>,
    /// `li` elements, each with a [`MediaThumbnail`] and optional move actions.
    pub children: Element,
}

/// An ordered strip of media thumbnails with a heading and a selection status.
#[component]
pub fn MediaFilmstrip(props: MediaFilmstripProps) -> Element {
    let class = compose([Some("ui-media-filmstrip"), props.class.as_deref()]);

    rsx! {
        section { class, aria_label: props.label.clone(), ..props.attributes,
            div { class: "ui-media-filmstrip__heading",
                span { {props.label.clone()} }
                span { role: "status", {props.selection_label.clone()} }
            }
            ol { class: "ui-media-filmstrip__items", {props.children} }
        }
    }
}

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

    fn value(x: f64, y: f64, zoom: f64) -> MediaViewportValue {
        MediaViewportValue { x, y, zoom }
    }

    #[test]
    fn normalizes_like_lumen_core() {
        assert_eq!(
            normalize_media_viewport(value(0.5, 0.5, 1.0), 4.0),
            MediaViewportValue::default()
        );
        assert_eq!(
            normalize_media_viewport(value(3.0, -3.0, 9.0), 4.0),
            value(1.0, -1.0, 4.0)
        );
        assert_eq!(
            normalize_media_viewport(value(f64::NAN, 0.0, f64::INFINITY), 4.0),
            MediaViewportValue::default()
        );
        assert!((resolve_media_max_zoom(40.0) - 16.0).abs() < f64::EPSILON);
        assert!((resolve_media_max_zoom(f64::NAN) - 4.0).abs() < f64::EPSILON);
        assert!((resolve_media_max_zoom(0.5) - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn actions_step_by_a_quarter() {
        let zoomed = apply_media_viewport_action(
            MediaViewportValue::default(),
            MediaViewportAction::ZoomIn,
            4.0,
        );
        assert_eq!(zoomed, value(0.0, 0.0, 1.25));
        assert_eq!(
            apply_media_viewport_action(zoomed, MediaViewportAction::Right, 4.0),
            value(0.25, 0.0, 1.25)
        );
        assert_eq!(
            apply_media_viewport_action(value(1.0, 0.0, 2.0), MediaViewportAction::Right, 4.0),
            value(1.0, 0.0, 2.0)
        );
        assert_eq!(
            apply_media_viewport_action(value(0.5, 0.5, 2.0), MediaViewportAction::Fit, 4.0),
            MediaViewportValue::default()
        );
        assert_eq!(
            apply_media_viewport_action(value(0.0, 0.0, 1.25), MediaViewportAction::ZoomOut, 4.0),
            MediaViewportValue::default()
        );
    }

    #[test]
    fn drags_pan_within_the_extent() {
        let start = value(0.0, 0.0, 3.0);
        assert_eq!(
            pan_media_viewport(start, 100.0, -50.0, 400.0, 200.0, 4.0),
            value(0.25, -0.25, 3.0)
        );
        assert_eq!(
            pan_media_viewport(start, 10_000.0, 0.0, 400.0, 200.0, 4.0),
            value(1.0, 0.0, 3.0)
        );
        assert_eq!(
            pan_media_viewport(start, 10.0, 10.0, 0.0, 200.0, 4.0),
            start
        );
        assert_eq!(
            pan_media_viewport(MediaViewportValue::default(), 10.0, 10.0, 400.0, 200.0, 4.0),
            MediaViewportValue::default()
        );
    }

    #[test]
    fn keys_map_to_actions() {
        assert_eq!(
            keyboard_action(&Key::ArrowUp),
            Some(MediaViewportAction::Up)
        );
        assert_eq!(
            keyboard_action(&Key::Character("=".into())),
            Some(MediaViewportAction::ZoomIn)
        );
        assert_eq!(
            keyboard_action(&Key::Character("-".into())),
            Some(MediaViewportAction::ZoomOut)
        );
        assert_eq!(keyboard_action(&Key::Home), Some(MediaViewportAction::Fit));
        assert_eq!(keyboard_action(&Key::Character("a".into())), None);
    }

    #[test]
    fn zoom_reads_as_a_percentage() {
        assert_eq!(format_zoom(1.0, None), "100%");
        assert_eq!(format_zoom(2.25, Some("en")), "225%");
    }
}