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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
// cspell:words onpointerleave onpointermove onpointerdown
//! [`LineChart`]: lines and areas over categories, numbers, or dates, with optional keyboard and
//! pointer inspection.

use std::collections::{HashMap, HashSet};
use std::rc::Rc;

use dioxus::prelude::*;

use super::activation::{ChartDatumActivation, DatumAction, motion_key};
use super::format::{js_number, json_string};
use super::frame::{
    ChartFrame, ChartPresentation, activate_on_click, chart_data_table, chart_legend,
    datum_actions, detail_label, plot_label, render_frame, serialized,
};
use super::geometry::{
    LineChartAnnotation, LineChartAnnotationAxis, LineChartModelOptions, LineChartScale,
    line_chart_model,
};
use super::interaction::{
    CHART_SYNC, CursorEmit, Inspection, InspectionKey, LineChartCursor, closest_point,
    panel_position, publish_sync, svg_x, use_chart_instance,
};
use super::model::{
    ChartBounds, ChartLabels, ChartSeries, ChartSeriesDash, ChartTone, ChartX, format_with,
    summarize,
};
use super::scale::{CategoryTick, has_chart_data};
use crate::class::{Glass, compose};
use crate::overlay::focus_element;
use crate::{Button, ButtonSize, ButtonVariant};

/// Which points of a [`LineChart`] get a marker dot.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum LineChartMarkers {
    /// Every point up to 24 categories, then every `n`th point.
    #[default]
    Auto,
    /// Every point.
    All,
    /// No markers.
    None,
    /// Every `n`th point (at least every point).
    Every(u32),
}

impl From<bool> for LineChartMarkers {
    fn from(value: bool) -> Self {
        if value { Self::All } else { Self::None }
    }
}

impl LineChartMarkers {
    /// The marker step for `category_count` categories; `None` hides markers.
    fn step(self, category_count: usize) -> Option<usize> {
        match self {
            Self::None => None,
            Self::All => Some(1),
            Self::Every(step) => Some(usize::try_from(step).unwrap_or(1).max(1)),
            Self::Auto => Some(category_count.div_ceil(24).max(1)),
        }
    }
}

/// Props for [`LineChart`].
#[derive(Props, Clone, PartialEq)]
pub struct LineChartProps {
    /// The series to plot. Missing values break their line.
    #[props(default)]
    pub series: Vec<ChartSeries>,
    /// Fills the area under each line.
    #[props(default)]
    pub area: bool,
    /// Which points show a marker dot.
    #[props(default, into)]
    pub markers: LineChartMarkers,
    /// How x values are placed: evenly spaced categories (default), numbers, or dates.
    #[props(default)]
    pub x_scale: LineChartScale,
    /// Requested y bounds. Finite bounds are kept exactly; a missing bound is calculated and
    /// rounded outward to the next tick.
    pub domain: Option<ChartBounds>,
    /// Requested x bounds for linear and time scales.
    pub x_domain: Option<ChartBounds>,
    /// The `viewBox` width (at least 240, default 640).
    pub width: Option<f64>,
    /// The `viewBox` height (at least 240, default 240).
    pub height: Option<f64>,
    /// A dashed horizontal reference line at this value.
    pub reference_value: Option<f64>,
    /// Labelled reference lines.
    #[props(default)]
    pub annotations: Vec<LineChartAnnotation>,
    /// Enables keyboard and pointer inspection with a tooltip panel and series toggles.
    #[props(default)]
    pub interactive: bool,
    /// Charts with the same group move their inspection cursor together.
    #[props(into)]
    pub sync_group: Option<String>,
    /// Controls the inspection cursor. Leave unset for an uncontrolled cursor.
    pub cursor: Option<LineChartCursor>,
    /// Called with the new x identity whenever inspection moves (or clears).
    pub on_cursor_change: Option<EventHandler<Option<ChartX>>>,
    /// Formats values on the axis, in tooltips, and in the table. Without it, tooltips and the table
    /// use `String(value)` and axis ticks use grouped `en-US` numbers (`1,000`), switching the whole
    /// axis to compact notation (`15K`) when a label would exceed five characters.
    pub format_value: Option<Callback<f64, String>>,
    /// Formats categories in tooltips and the table.
    pub format_category: Option<Callback<ChartX, String>>,
    /// Text shown instead of the plot when there is no data.
    #[props(into)]
    pub empty_label: Option<String>,
    /// Localized chart text.
    pub labels: Option<ChartLabels>,
    /// Shows the legend. Defaults to `true` with more than one series.
    pub show_legend: Option<bool>,
    /// Shows the collapsible data table.
    #[props(default = true)]
    pub show_table: bool,
    /// Makes every point clickable and adds a keyboard-reachable action menu.
    pub on_datum_activate: Option<EventHandler<ChartDatumActivation>>,
    /// The chart title.
    #[props(into)]
    pub heading: Option<String>,
    /// Supporting text under the heading.
    #[props(into)]
    pub description: Option<String>,
    /// A headline value beside the heading.
    #[props(into)]
    pub value: Option<String>,
    /// A screen reader summary; defaults to a generated description of the data.
    #[props(into)]
    pub summary: Option<String>,
    /// A visible caption, such as the data source.
    #[props(into)]
    pub caption: Option<String>,
    /// `Bare` removes the card chrome.
    #[props(default)]
    pub presentation: ChartPresentation,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<figure>` or global attribute.
    #[props(extends = GlobalAttributes, extends = figure)]
    pub attributes: Vec<Attribute>,
}

struct Marker {
    key: String,
    cx: String,
    cy: String,
    motion_key: String,
    datum: Option<String>,
    title: String,
    visible: bool,
    action: Option<DatumAction>,
}

struct SeriesLayer {
    dash: Option<ChartSeriesDash>,
    id: String,
    class: String,
    area: Option<String>,
    area_key: String,
    path: String,
    path_key: String,
    markers: Vec<Marker>,
    hidden: bool,
}

struct AnnotationText {
    id: String,
    class: String,
    vertical: bool,
    coordinate: String,
    label_x: String,
    label_y: String,
    label: String,
    value: String,
}

/// Builds the screen reader announcement for an inspected x identity.
type Announcer = Rc<dyn Fn(Option<&ChartX>) -> String>;

/// Values the effects need from the latest render (effect closures are created once).
#[derive(Clone)]
struct Latest {
    announce: Announcer,
    sync_group: Option<String>,
    interactive: bool,
    controlled: bool,
}

struct InspectionPoint {
    key: String,
    json: String,
    position: String,
    label: String,
    values: Vec<(String, &'static str, String, String)>,
}

/// The rendered layout of the inspection panel and its measurement handles.
#[derive(Clone, Copy)]
struct Measurements {
    frame: Signal<Option<Rc<MountedData>>>,
    svg: Signal<Option<Rc<MountedData>>>,
    panel: Signal<Option<Rc<MountedData>>>,
    plot: Signal<Option<Rc<MountedData>>>,
    svg_rect: Signal<Option<(f64, f64, f64, f64)>>,
}

/// Plots one or more series as lines or areas, with optional inspection (arrow keys, `Home`,
/// `End`, `Escape`, and pointer hover or press), synchronized cursors, annotations, a legend,
/// a screen reader summary, and a data table.
#[component]
#[allow(clippy::too_many_lines)]
pub fn LineChart(props: LineChartProps) -> Element {
    let labels = props.labels.clone().unwrap_or_default();
    let format_value = props.format_value.as_ref();
    let format_category = props.format_category.as_ref();
    let model = line_chart_model(
        &props.series,
        &LineChartModelOptions {
            annotations: &props.annotations,
            domain: props.domain,
            format_category,
            format_value,
            height: props.height,
            reference_value: props.reference_value,
            width: props.width,
            x_domain: props.x_domain,
            x_scale: props.x_scale,
        },
    );
    let interactive = props.interactive;
    let has_data = has_chart_data(&model.series);
    let show_legend = props.show_legend.unwrap_or(props.series.len() > 1);
    let marker_step = props.markers.step(model.categories.len());
    let (width, height, padding_left, padding_top) = (
        model.width,
        model.height,
        model.padding_left,
        model.padding_top,
    );
    let plot_right = width - model.padding_right;
    let plot_bottom = height - model.padding_bottom;
    let clip = model.clip;
    let on_activate = props.on_datum_activate;
    let instance = use_chart_instance();
    let mut state = use_signal(Inspection::default);
    let mut announcement = use_signal(String::new);
    let mut hidden_series = use_signal(HashSet::<String>::new);
    let mut pending = use_signal(|| None::<Option<ChartX>>);
    let mut enhanced = use_signal(|| false);
    let mut panel_style = use_signal(|| None::<String>);
    let mut last_sync = use_signal(|| None::<u64>);
    let measurements = Measurements {
        frame: use_signal(|| None),
        svg: use_signal(|| None),
        panel: use_signal(|| None),
        plot: use_signal(|| None),
        svg_rect: use_signal(|| None),
    };

    // The client enables the legend toggles once it can handle them, like lumen-react's
    // enhancement; server-rendered markup keeps them disabled.
    use_effect(use_reactive!(|interactive| {
        if interactive {
            enhanced.set(true);
        }
    }));

    // Inspection points: categories with an axis value inside the clipping viewport.
    let viewport = (clip.x, clip.x + clip.width);
    let points: Vec<(ChartX, f64)> = model
        .categories
        .iter()
        .zip(&model.positions)
        .filter(|(x, position)| {
            x.is_axis_value()
                && position.is_finite()
                && **position >= viewport.0
                && **position <= viewport.1
        })
        .map(|(x, position)| (x.clone(), *position))
        .collect();
    let point_xs: Vec<ChartX> = points.iter().map(|(x, _)| x.clone()).collect();
    let lookups: Vec<HashMap<String, Option<f64>>> = model
        .series
        .iter()
        .map(|item| {
            item.data
                .iter()
                .map(|datum| (datum.x.key(), datum.y))
                .collect()
        })
        .collect();
    let value_text = |series_index: usize, x: &ChartX| -> String {
        let value = lookups
            .get(series_index)
            .and_then(|lookup| lookup.get(&x.key()))
            .copied()
            .flatten()
            .filter(|value| value.is_finite());

        value.map_or_else(
            || labels.not_available.clone(),
            |value| format_with(format_value, value),
        )
    };
    let announce_text = {
        let series = model.series.clone();
        let format_category = props.format_category;
        let format_value = props.format_value;
        let not_available = labels.not_available.clone();
        let lookups = lookups.clone();

        move |x: &ChartX, hidden: &HashSet<String>| -> String {
            let mut parts = vec![detail_label(&series, x, format_category.as_ref())];

            for (index, item) in series.iter().enumerate() {
                if hidden.contains(&item.id) {
                    continue;
                }

                let value = lookups
                    .get(index)
                    .and_then(|lookup| lookup.get(&x.key()))
                    .copied()
                    .flatten()
                    .filter(|value| value.is_finite())
                    .map_or_else(
                        || not_available.clone(),
                        |value| format_with(format_value.as_ref(), value),
                    );
                parts.push(format!("{} {value}", item.label));
            }

            parts.join(". ")
        }
    };
    let controlled = props.cursor.clone();
    let on_cursor_change = props.on_cursor_change;
    let sync_group = props.sync_group.clone();
    let point_set = point_xs.clone();
    let announce_for = {
        let announce_text = announce_text.clone();
        let point_set = point_set.clone();

        move |x: Option<&ChartX>| -> String {
            match x.filter(|x| point_set.contains(x)) {
                Some(x) => announce_text(x, &hidden_series.peek()),
                None => String::new(),
            }
        }
    };
    let emit = {
        let controlled = controlled.clone();
        let sync_group = sync_group.clone();
        let announce_for = announce_for.clone();

        move |change: CursorEmit| {
            if controlled.is_none() {
                state.write().selected.clone_from(&change.x);

                if change.announce {
                    announcement.set(announce_for(change.x.as_ref()));
                }

                if let Some(group) = sync_group.as_deref().filter(|group| !group.is_empty()) {
                    publish_sync(group, instance, change.x.clone());
                }
            } else {
                pending.set(change.announce.then(|| change.x.clone()));
            }

            if let Some(handler) = on_cursor_change {
                handler.call(change.x);
            }
        }
    };

    let mut latest = use_hook(|| {
        CopyValue::new(Latest {
            announce: Rc::new(|_: Option<&ChartX>| String::new()),
            sync_group: None,
            interactive: false,
            controlled: false,
        })
    });
    latest.set(Latest {
        announce: Rc::new(announce_for.clone()),
        sync_group: sync_group.clone(),
        interactive,
        controlled: controlled.is_some(),
    });

    // A controlled cursor selects its point, announces a pending keyboard move, and syncs peers.
    use_effect(use_reactive!(|controlled| {
        let Some(cursor) = controlled else {
            return;
        };
        let value = cursor.x();
        let changed = state.peek().selected != value;
        let current = latest.read().clone();
        state.write().selected.clone_from(&value);

        if pending.peek().as_ref() == Some(&value) {
            announcement.set((current.announce)(value.as_ref()));
        }

        pending.set(None);

        if changed
            && let Some(group) = current
                .sync_group
                .as_deref()
                .filter(|group| !group.is_empty())
        {
            publish_sync(group, instance, value);
        }
    }));

    // Peers in the same sync group move this cursor unless it is controlled.
    use_effect(move || {
        let current = latest.read().clone();
        let Some(group) = current.sync_group.filter(|group| !group.is_empty()) else {
            return;
        };
        let Some(event) = CHART_SYNC.read().get(&group).cloned() else {
            return;
        };

        if event.origin == instance || *last_sync.peek() == Some(event.sequence) {
            return;
        }

        last_sync.set(Some(event.sequence));

        if !current.controlled && current.interactive {
            state.write().peer_select(event.x);
        }
    });

    let selected = state.read().selected.clone();
    let active_point = selected
        .as_ref()
        .and_then(|x| points.iter().find(|(candidate, _)| candidate == x))
        .cloned();
    let hidden = hidden_series.read().clone();

    // Place the panel beside the inspected point once it is visible and measurable.
    {
        let active_position = active_point.as_ref().map(|(_, position)| *position);
        use_effect(use_reactive!(|active_position| {
            let Some(position) = active_position else {
                return;
            };
            let (Some(frame), Some(svg), Some(panel)) = (
                measurements.frame.peek().clone(),
                measurements.svg.peek().clone(),
                measurements.panel.peek().clone(),
            ) else {
                return;
            };

            spawn(async move {
                let (Ok(frame), Ok(svg), Ok(panel)) = (
                    frame.get_client_rect().await,
                    svg.get_client_rect().await,
                    panel.get_client_rect().await,
                ) else {
                    return;
                };

                if let Some((left, top)) = panel_position(
                    (frame.origin.x, frame.origin.y, frame.size.width),
                    (svg.origin.x, svg.origin.y, svg.size.width),
                    width,
                    panel.size.width,
                    position,
                ) {
                    panel_style.set(Some(format!(
                        "--ui-chart-inspection-x:{}px;--ui-chart-inspection-y:{}px",
                        js_number(left),
                        js_number(top)
                    )));
                }
            });
        }));
    }

    let point_actions: Vec<Vec<Option<DatumAction>>> = model
        .geometries
        .iter()
        .zip(&model.series)
        .map(|(geometry, item)| {
            if on_activate.is_none() {
                return Vec::new();
            }

            geometry
                .points
                .iter()
                .map(|point| {
                    let context = format!(
                        "{} · {}: {}",
                        detail_label(&model.series, &point.datum.x, format_category),
                        item.label,
                        format_with(format_value, point.datum.y.unwrap_or(0.0))
                    );

                    DatumAction::new(
                        ChartDatumActivation::series(&item.id, &point.datum),
                        &context,
                        &labels,
                    )
                })
                .collect()
        })
        .collect();
    let actions: Vec<Option<DatumAction>> = point_actions.iter().flatten().cloned().collect();
    let layers: Vec<SeriesLayer> = model
        .geometries
        .iter()
        .zip(&props.series)
        .enumerate()
        .map(|(index, (geometry, item))| {
            let tone = ChartTone::resolve(item.tone, index);
            let markers = geometry
                .points
                .iter()
                .enumerate()
                .map(|(point_index, point)| {
                    let action = point_actions
                        .get(index)
                        .and_then(|actions| actions.get(point_index))
                        .cloned()
                        .flatten();

                    Marker {
                        key: point
                            .datum
                            .id
                            .clone()
                            .unwrap_or_else(|| point.datum.x.key()),
                        cx: js_number(point.x),
                        cy: js_number(point.y),
                        motion_key: motion_key(&item.id, point.datum.id.as_ref(), &point.datum.x),
                        datum: serialized(action.as_ref()),
                        title: format!(
                            "{} · {}: {}",
                            detail_label(&model.series, &point.datum.x, format_category),
                            item.label,
                            format_with(format_value, point.datum.y.unwrap_or(0.0))
                        ),
                        visible: marker_step.is_some_and(|step| point_index % step == 0),
                        action,
                    }
                })
                .collect();

            SeriesLayer {
                id: item.id.clone(),
                class: compose([Some("ui-line-chart__series"), Some(tone.class_name())]),
                area: (props.area && !geometry.area_paths.is_empty())
                    .then(|| geometry.area_paths.join(" ")),
                area_key: format!("[\"area\",{}]", json_string(&item.id)),
                dash: item.dash,
                path: geometry.path.clone(),
                path_key: format!("[\"path\",{}]", json_string(&item.id)),
                markers,
                hidden: hidden.contains(&item.id),
            }
        })
        .collect();
    let grid: Vec<(String, String, String)> = model
        .ticks
        .iter()
        .zip(&model.tick_labels)
        .map(|(tick, label)| {
            let y = super::scale::scale_value(*tick, model.domain, plot_bottom, padding_top);

            (js_number(*tick), js_number(y), label.clone())
        })
        .collect();
    let axis_y = js_number(height - 14.0);
    let category_ticks: Vec<(String, &'static str, String, String)> = model
        .category_ticks
        .iter()
        .map(|tick| {
            (
                tick.index.to_string(),
                CategoryTick::ANCHOR,
                js_number(tick.position),
                tick.label.clone(),
            )
        })
        .collect();
    let reference_y = props.reference_value.map(|value| {
        js_number(super::scale::scale_value(
            value,
            model.domain,
            plot_bottom,
            padding_top,
        ))
    });
    let annotations: Vec<AnnotationText> = model
        .annotation_marks
        .iter()
        .map(|mark| {
            let annotation = &mark.annotation;
            let class = compose([
                Some("ui-chart__annotation"),
                Some(ChartTone::resolve(annotation.tone, 0).class_name()),
            ]);
            let value = match annotation.axis {
                LineChartAnnotationAxis::X => {
                    detail_label(&model.series, &annotation.value, format_category)
                }
                LineChartAnnotationAxis::Y => match annotation.value {
                    ChartX::Number(number) => format_with(format_value, number),
                    ChartX::Text(_) => String::new(),
                },
            };

            AnnotationText {
                id: annotation.id.clone(),
                class,
                vertical: annotation.axis == LineChartAnnotationAxis::X,
                coordinate: js_number(mark.coordinate),
                label_x: js_number(mark.coordinate + 4.0),
                label_y: js_number(mark.coordinate - 8.0),
                label: annotation.label.clone(),
                value,
            }
        })
        .collect();
    let inspection_points: Vec<InspectionPoint> = if interactive && has_data {
        model
            .categories
            .iter()
            .zip(&model.positions)
            .map(|(category, position)| InspectionPoint {
                key: category.key(),
                json: category.json(),
                position: js_number(*position),
                label: detail_label(&model.series, category, format_category),
                values: model
                    .series
                    .iter()
                    .enumerate()
                    .map(|(index, item)| {
                        (
                            item.id.clone(),
                            ChartTone::resolve(item.tone, index).class_name(),
                            item.label.clone(),
                            value_text(index, category),
                        )
                    })
                    .collect(),
            })
            .collect()
    } else {
        Vec::new()
    };
    let active_key = active_point.as_ref().map(|(x, _)| x.key());
    let crosshair = active_point
        .as_ref()
        .map(|(_, position)| js_number(*position));
    let summary = props
        .summary
        .clone()
        .or_else(|| Some(labels.summary(summarize(&model.series, format_value))));
    let plot_name = plot_label(
        &props.attributes,
        props.heading.as_ref(),
        &labels.chart_data,
    );
    let frame = ChartFrame {
        chart_class: Some(compose([Some("ui-line-chart"), props.class.as_deref()])),
        heading: props.heading.clone(),
        description: props.description.clone(),
        value: props.value.clone(),
        summary,
        caption: props.caption.clone(),
        presentation: props.presentation,
        glass: props.glass,
        activation: on_activate.is_some(),
        attributes: props.attributes.clone(),
        on_mounted: None,
    };
    let view_box = format!("0 0 {} {}", js_number(width), js_number(height));
    let viewbox_width = js_number(width);
    let inner = (
        js_number(clip.x),
        js_number(clip.y),
        js_number(clip.width),
        js_number(clip.height),
    );
    let inner_view_box = format!("{} {} {} {}", inner.0, inner.1, inner.2, inner.3);
    let left = js_number(padding_left);
    let right = js_number(plot_right);
    let top = js_number(padding_top);
    let bottom = js_number(plot_bottom);
    let label_x = js_number(padding_left - 8.0);
    let annotation_top = js_number(padding_top - 8.0);
    let is_enhanced = *enhanced.read();
    let point_xs_for_keys = point_xs.clone();
    let mut emit_key = emit.clone();
    let mut emit_move = emit.clone();
    let emit_down = emit.clone();
    let mut emit_leave = emit;
    let points_for_move = points.clone();
    let points_for_down = points;
    let content = rsx! {
        div {
            class: "ui-chart__content",
            "data-ui-chart-sync": sync_group.clone(),
            "data-ui-chart-enhanced": (interactive && is_enhanced).then_some("true"),
            onpointerleave: move |_| {
                if !interactive {
                    return;
                }

                let change = state.write().pointer_leave();

                if let Some(change) = change {
                    emit_leave(change);
                }
            },
            if show_legend && has_data {
                if interactive {
                    ul { class: "ui-chart__legend", aria_label: "{labels.chart_legend}",
                        for (index, item) in props.series.iter().enumerate() {
                            li {
                                key: "{item.id}",
                                class: ChartTone::resolve(item.tone, index).class_name(),
                                Button {
                                    aria_pressed: if hidden.contains(&item.id) { "false" } else { "true" },
                                    "data-ui-chart-toggle": item.id.clone(),
                                    disabled: !is_enhanced,
                                    size: ButtonSize::Sm,
                                    variant: ButtonVariant::Ghost,
                                    onclick: {
                                        let id = item.id.clone();
                                        move |_| {
                                            let mut hidden = hidden_series.write();

                                            if !hidden.remove(&id) {
                                                hidden.insert(id.clone());
                                            }
                                        }
                                    },
                                    "{item.label}"
                                }
                            }
                        }
                    }
                } else {
                    {chart_legend(&labels.chart_legend, &props.series)}
                }
            }
            if !has_data {
                p { class: "ui-chart__empty", role: "status",
                    "{props.empty_label.clone().unwrap_or_else(|| labels.empty.clone())}"
                }
            }
            div {
                aria_label: "{plot_name}",
                class: "ui-chart__plot",
                "data-ui-chart-interaction-plot": interactive.then_some("true"),
                role: "region",
                tabindex: "0",
                hidden: !has_data,
                onmounted: move |event| {
                    let mut plot = measurements.plot;
                    plot.set(Some(event.data()));
                },
                onkeydown: move |event| {
                    if !interactive || event.is_composing() {
                        return;
                    }

                    let Some(key) = InspectionKey::from_key(&event.key()) else {
                        return;
                    };
                    let change = state.write().key(key, &point_xs_for_keys);

                    if let Some(change) = change {
                        event.prevent_default();
                        emit_key(change);
                    }
                },
                onpointermove: move |event| {
                    if !interactive {
                        return;
                    }

                    let client_x = event.client_coordinates().x;
                    let rect = *measurements.svg_rect.peek();

                    if let Some(svg) = measurements.svg.peek().clone() {
                        let mut svg_rect = measurements.svg_rect;
                        spawn(async move {
                            if let Ok(rect) = svg.get_client_rect().await {
                                svg_rect.set(Some((rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)));
                            }
                        });
                    }

                    let closest = rect
                        .and_then(|rect| svg_x(client_x, rect, (width, height)))
                        .and_then(|position| closest_point(position, &points_for_move));
                    let touch = event.pointer_type() == "touch";
                    let change = state.write().pointer_move(closest, touch);

                    if let Some(change) = change {
                        emit_move(change);
                    }
                },
                onpointerdown: move |event| {
                    if !interactive {
                        return;
                    }

                    let primary = event
                        .trigger_button()
                        .is_none_or(|button| button == dioxus::html::input_data::MouseButton::Primary);

                    if !primary {
                        return;
                    }

                    let client_x = event.client_coordinates().x;
                    let svg = measurements.svg.peek().clone();
                    let mut svg_rect = measurements.svg_rect;
                    let points = points_for_down.clone();
                    let mut emit_down = emit_down.clone();
                    focus_element(measurements.plot.peek().clone());
                    spawn(async move {
                        if let Some(svg) = svg
                            && let Ok(rect) = svg.get_client_rect().await
                        {
                            svg_rect.set(Some((rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)));
                        }

                        let closest = svg_rect
                            .peek()
                            .and_then(|rect| svg_x(client_x, rect, (width, height)))
                            .and_then(|position| closest_point(position, &points));
                        let change = state.write().pointer_down(closest);
                        emit_down(change);
                    });
                },
                svg {
                    "aria-hidden": "true",
                    "preserveAspectRatio": "xMidYMid meet",
                    "style": "--ui-chart-viewbox-width: {viewbox_width}",
                    "viewBox": "{view_box}",
                    onmounted: move |event| {
                        let mut svg = measurements.svg;
                        svg.set(Some(event.data()));
                    },
                    g { class: "ui-chart__grid",
                        for (key, y, text) in grid {
                            line { key: "{key}-line", x1: "{left}", x2: "{right}", y1: "{y}", y2: "{y}" }
                            text { x: "{label_x}", y: "{y}", "{text}" }
                        }
                    }
                    g { class: "ui-chart__axis-labels",
                        for (key, anchor, x, label) in category_ticks {
                            text { key: "{key}", "text-anchor": anchor, x: "{x}", y: "{axis_y}", "{label}" }
                        }
                    }
                    svg {
                        "aria-hidden": "true",
                        x: "{inner.0}",
                        y: "{inner.1}",
                        width: "{inner.2}",
                        height: "{inner.3}",
                        "viewBox": "{inner_view_box}",
                        overflow: "hidden",
                        if let Some(y) = reference_y {
                            line { class: "ui-chart__reference", x1: "{left}", x2: "{right}", y1: "{y}", y2: "{y}" }
                        }
                        for layer in layers.iter() {
                            g {
                                key: "{layer.id}",
                                class: "{layer.class}",
                                "data-ui-chart-series": "{layer.id}",
                                style: layer.hidden.then_some("display:none"),
                                if let Some(area) = layer.area.clone() {
                                    path {
                                        "data-ui-chart-motion-key": "{layer.area_key}",
                                        class: "ui-line-chart__area",
                                        d: "{area}",
                                    }
                                }
                                path {
                                    "data-ui-chart-motion-key": "{layer.path_key}",
                                    class: "ui-line-chart__line",
                                    "data-ui-chart-dash": layer.dash.map(ChartSeriesDash::as_str),
                                    d: "{layer.path}",
                                }
                                for marker in layer.markers.iter().filter(|marker| marker.visible) {
                                    circle {
                                        key: "{marker.key}",
                                        "data-ui-chart-datum": marker.datum.clone(),
                                        "data-ui-chart-motion-key": "{marker.motion_key}",
                                        class: "ui-line-chart__point",
                                        cx: "{marker.cx}",
                                        cy: "{marker.cy}",
                                        r: "3",
                                        onclick: activate_on_click(marker.action.as_ref(), on_activate),
                                        title { "{marker.title}" }
                                    }
                                }
                                if on_activate.is_some() {
                                    for marker in layer.markers.iter() {
                                        circle {
                                            key: "hit-{marker.key}",
                                            class: "ui-chart__datum-hit",
                                            cx: "{marker.cx}",
                                            cy: "{marker.cy}",
                                            r: "10",
                                            "data-ui-chart-datum": marker.datum.clone(),
                                            onclick: activate_on_click(marker.action.as_ref(), on_activate),
                                        }
                                    }
                                }
                            }
                        }
                    }
                    for mark in annotations.iter() {
                        g { key: "{mark.id}", class: "{mark.class}",
                            if mark.vertical {
                                line { x1: "{mark.coordinate}", x2: "{mark.coordinate}", y1: "{top}", y2: "{bottom}" }
                                text { x: "{mark.label_x}", y: "{annotation_top}", "{mark.label}" }
                            } else {
                                line { x1: "{left}", x2: "{right}", y1: "{mark.coordinate}", y2: "{mark.coordinate}" }
                                text { "text-anchor": "end", x: "{right}", y: "{mark.label_y}", "{mark.label}" }
                            }
                        }
                    }
                    if interactive {
                        line {
                            class: "ui-chart__crosshair",
                            "data-ui-chart-crosshair": "true",
                            style: if crosshair.is_some() { "" } else { "display:none" },
                            x1: crosshair.clone(),
                            x2: crosshair.clone(),
                            y1: "{top}",
                            y2: "{bottom}",
                        }
                    }
                }
            }
            if !annotations.is_empty() {
                ul { class: "ui-sr-only",
                    for mark in annotations.iter() {
                        li { key: "{mark.id}", "{mark.label}: {mark.value}" }
                    }
                }
            }
            if interactive && has_data {
                div {
                    class: "ui-chart__inspection",
                    "data-ui-chart-inspection": "true",
                    hidden: active_key.is_none(),
                    style: panel_style.read().clone(),
                    onmounted: move |event| {
                        let mut panel = measurements.panel;
                        panel.set(Some(event.data()));
                    },
                    for point in inspection_points {
                        div {
                            key: "{point.key}",
                            "data-ui-chart-point": "{point.json}",
                            "data-ui-chart-position": "{point.position}",
                            hidden: active_key.as_ref() != Some(&point.key),
                            strong { "{point.label}" }
                            for (id, class, label, value) in point.values {
                                span {
                                    key: "{id}",
                                    class,
                                    "data-ui-chart-series-value": "{id}",
                                    hidden: hidden.contains(&id),
                                    i { aria_hidden: "true" }
                                    "{label} "
                                    b { "{value}" }
                                }
                            }
                        }
                    }
                }
                p {
                    aria_live: "polite",
                    aria_atomic: "true",
                    class: "ui-sr-only",
                    "data-ui-chart-announcement": "true",
                    "{announcement}"
                }
            }
        }
        if props.show_table && has_data {
            {chart_data_table(&model.categories, format_category, format_value, &labels, &props.series)}
        }
        if on_activate.is_some() {
            {datum_actions(&actions, &labels.explore_data, on_activate)}
        }
    };

    render_frame_with_mount(frame, content, measurements.frame)
}

/// Renders the frame and records the `<figure>` element for panel placement.
fn render_frame_with_mount(
    mut frame: ChartFrame,
    content: Element,
    mut target: Signal<Option<Rc<MountedData>>>,
) -> Element {
    frame.on_mounted = Some(EventHandler::new(move |data: Rc<MountedData>| {
        target.set(Some(data));
    }));

    render_frame(frame, content)
}