Skip to main content

lumen_dioxus/charts/
line.rs

1// cspell:words onpointerleave onpointermove onpointerdown
2//! [`LineChart`]: lines and areas over categories, numbers, or dates, with optional keyboard and
3//! pointer inspection.
4
5use std::collections::{HashMap, HashSet};
6use std::rc::Rc;
7
8use dioxus::prelude::*;
9
10use super::activation::{ChartDatumActivation, DatumAction, motion_key};
11use super::format::{js_number, json_string};
12use super::frame::{
13    ChartFrame, ChartPresentation, activate_on_click, chart_data_table, chart_legend,
14    datum_actions, detail_label, plot_label, render_frame, serialized,
15};
16use super::geometry::{
17    LineChartAnnotation, LineChartAnnotationAxis, LineChartModelOptions, LineChartScale,
18    line_chart_model,
19};
20use super::interaction::{
21    CHART_SYNC, CursorEmit, Inspection, InspectionKey, LineChartCursor, closest_point,
22    panel_position, publish_sync, svg_x, use_chart_instance,
23};
24use super::model::{
25    ChartBounds, ChartLabels, ChartSeries, ChartSeriesDash, ChartTone, ChartX, format_with,
26    summarize,
27};
28use super::scale::{CategoryTick, has_chart_data};
29use crate::class::{Glass, compose};
30use crate::overlay::focus_element;
31use crate::{Button, ButtonSize, ButtonVariant};
32
33/// Which points of a [`LineChart`] get a marker dot.
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum LineChartMarkers {
37    /// Every point up to 24 categories, then every `n`th point.
38    #[default]
39    Auto,
40    /// Every point.
41    All,
42    /// No markers.
43    None,
44    /// Every `n`th point (at least every point).
45    Every(u32),
46}
47
48impl From<bool> for LineChartMarkers {
49    fn from(value: bool) -> Self {
50        if value { Self::All } else { Self::None }
51    }
52}
53
54impl LineChartMarkers {
55    /// The marker step for `category_count` categories; `None` hides markers.
56    fn step(self, category_count: usize) -> Option<usize> {
57        match self {
58            Self::None => None,
59            Self::All => Some(1),
60            Self::Every(step) => Some(usize::try_from(step).unwrap_or(1).max(1)),
61            Self::Auto => Some(category_count.div_ceil(24).max(1)),
62        }
63    }
64}
65
66/// Props for [`LineChart`].
67#[derive(Props, Clone, PartialEq)]
68pub struct LineChartProps {
69    /// The series to plot. Missing values break their line.
70    #[props(default)]
71    pub series: Vec<ChartSeries>,
72    /// Fills the area under each line.
73    #[props(default)]
74    pub area: bool,
75    /// Which points show a marker dot.
76    #[props(default, into)]
77    pub markers: LineChartMarkers,
78    /// How x values are placed: evenly spaced categories (default), numbers, or dates.
79    #[props(default)]
80    pub x_scale: LineChartScale,
81    /// Requested y bounds. Finite bounds are kept exactly; a missing bound is calculated and
82    /// rounded outward to the next tick.
83    pub domain: Option<ChartBounds>,
84    /// Requested x bounds for linear and time scales.
85    pub x_domain: Option<ChartBounds>,
86    /// The `viewBox` width (at least 240, default 640).
87    pub width: Option<f64>,
88    /// The `viewBox` height (at least 240, default 240).
89    pub height: Option<f64>,
90    /// A dashed horizontal reference line at this value.
91    pub reference_value: Option<f64>,
92    /// Labelled reference lines.
93    #[props(default)]
94    pub annotations: Vec<LineChartAnnotation>,
95    /// Enables keyboard and pointer inspection with a tooltip panel and series toggles.
96    #[props(default)]
97    pub interactive: bool,
98    /// Charts with the same group move their inspection cursor together.
99    #[props(into)]
100    pub sync_group: Option<String>,
101    /// Controls the inspection cursor. Leave unset for an uncontrolled cursor.
102    pub cursor: Option<LineChartCursor>,
103    /// Called with the new x identity whenever inspection moves (or clears).
104    pub on_cursor_change: Option<EventHandler<Option<ChartX>>>,
105    /// Formats values on the axis, in tooltips, and in the table. Without it, tooltips and the table
106    /// use `String(value)` and axis ticks use grouped `en-US` numbers (`1,000`), switching the whole
107    /// axis to compact notation (`15K`) when a label would exceed five characters.
108    pub format_value: Option<Callback<f64, String>>,
109    /// Formats categories in tooltips and the table.
110    pub format_category: Option<Callback<ChartX, String>>,
111    /// Text shown instead of the plot when there is no data.
112    #[props(into)]
113    pub empty_label: Option<String>,
114    /// Localized chart text.
115    pub labels: Option<ChartLabels>,
116    /// Shows the legend. Defaults to `true` with more than one series.
117    pub show_legend: Option<bool>,
118    /// Shows the collapsible data table.
119    #[props(default = true)]
120    pub show_table: bool,
121    /// Makes every point clickable and adds a keyboard-reachable action menu.
122    pub on_datum_activate: Option<EventHandler<ChartDatumActivation>>,
123    /// The chart title.
124    #[props(into)]
125    pub heading: Option<String>,
126    /// Supporting text under the heading.
127    #[props(into)]
128    pub description: Option<String>,
129    /// A headline value beside the heading.
130    #[props(into)]
131    pub value: Option<String>,
132    /// A screen reader summary; defaults to a generated description of the data.
133    #[props(into)]
134    pub summary: Option<String>,
135    /// A visible caption, such as the data source.
136    #[props(into)]
137    pub caption: Option<String>,
138    /// `Bare` removes the card chrome.
139    #[props(default)]
140    pub presentation: ChartPresentation,
141    /// Glass intensity.
142    #[props(default, into)]
143    pub glass: Glass,
144    /// Extra classes appended after the Lumen classes.
145    #[props(into)]
146    pub class: Option<String>,
147    /// Any other `<figure>` or global attribute.
148    #[props(extends = GlobalAttributes, extends = figure)]
149    pub attributes: Vec<Attribute>,
150}
151
152struct Marker {
153    key: String,
154    cx: String,
155    cy: String,
156    motion_key: String,
157    datum: Option<String>,
158    title: String,
159    visible: bool,
160    action: Option<DatumAction>,
161}
162
163struct SeriesLayer {
164    dash: Option<ChartSeriesDash>,
165    id: String,
166    class: String,
167    area: Option<String>,
168    area_key: String,
169    path: String,
170    path_key: String,
171    markers: Vec<Marker>,
172    hidden: bool,
173}
174
175struct AnnotationText {
176    id: String,
177    class: String,
178    vertical: bool,
179    coordinate: String,
180    label_x: String,
181    label_y: String,
182    label: String,
183    value: String,
184}
185
186/// Builds the screen reader announcement for an inspected x identity.
187type Announcer = Rc<dyn Fn(Option<&ChartX>) -> String>;
188
189/// Values the effects need from the latest render (effect closures are created once).
190#[derive(Clone)]
191struct Latest {
192    announce: Announcer,
193    sync_group: Option<String>,
194    interactive: bool,
195    controlled: bool,
196}
197
198struct InspectionPoint {
199    key: String,
200    json: String,
201    position: String,
202    label: String,
203    values: Vec<(String, &'static str, String, String)>,
204}
205
206/// The rendered layout of the inspection panel and its measurement handles.
207#[derive(Clone, Copy)]
208struct Measurements {
209    frame: Signal<Option<Rc<MountedData>>>,
210    svg: Signal<Option<Rc<MountedData>>>,
211    panel: Signal<Option<Rc<MountedData>>>,
212    plot: Signal<Option<Rc<MountedData>>>,
213    svg_rect: Signal<Option<(f64, f64, f64, f64)>>,
214}
215
216/// Plots one or more series as lines or areas, with optional inspection (arrow keys, `Home`,
217/// `End`, `Escape`, and pointer hover or press), synchronized cursors, annotations, a legend,
218/// a screen reader summary, and a data table.
219#[component]
220#[allow(clippy::too_many_lines)]
221pub fn LineChart(props: LineChartProps) -> Element {
222    let labels = props.labels.clone().unwrap_or_default();
223    let format_value = props.format_value.as_ref();
224    let format_category = props.format_category.as_ref();
225    let model = line_chart_model(
226        &props.series,
227        &LineChartModelOptions {
228            annotations: &props.annotations,
229            domain: props.domain,
230            format_category,
231            format_value,
232            height: props.height,
233            reference_value: props.reference_value,
234            width: props.width,
235            x_domain: props.x_domain,
236            x_scale: props.x_scale,
237        },
238    );
239    let interactive = props.interactive;
240    let has_data = has_chart_data(&model.series);
241    let show_legend = props.show_legend.unwrap_or(props.series.len() > 1);
242    let marker_step = props.markers.step(model.categories.len());
243    let (width, height, padding_left, padding_top) = (
244        model.width,
245        model.height,
246        model.padding_left,
247        model.padding_top,
248    );
249    let plot_right = width - model.padding_right;
250    let plot_bottom = height - model.padding_bottom;
251    let clip = model.clip;
252    let on_activate = props.on_datum_activate;
253    let instance = use_chart_instance();
254    let mut state = use_signal(Inspection::default);
255    let mut announcement = use_signal(String::new);
256    let mut hidden_series = use_signal(HashSet::<String>::new);
257    let mut pending = use_signal(|| None::<Option<ChartX>>);
258    let mut enhanced = use_signal(|| false);
259    let mut panel_style = use_signal(|| None::<String>);
260    let mut last_sync = use_signal(|| None::<u64>);
261    let measurements = Measurements {
262        frame: use_signal(|| None),
263        svg: use_signal(|| None),
264        panel: use_signal(|| None),
265        plot: use_signal(|| None),
266        svg_rect: use_signal(|| None),
267    };
268
269    // The client enables the legend toggles once it can handle them, like lumen-react's
270    // enhancement; server-rendered markup keeps them disabled.
271    use_effect(use_reactive!(|interactive| {
272        if interactive {
273            enhanced.set(true);
274        }
275    }));
276
277    // Inspection points: categories with an axis value inside the clipping viewport.
278    let viewport = (clip.x, clip.x + clip.width);
279    let points: Vec<(ChartX, f64)> = model
280        .categories
281        .iter()
282        .zip(&model.positions)
283        .filter(|(x, position)| {
284            x.is_axis_value()
285                && position.is_finite()
286                && **position >= viewport.0
287                && **position <= viewport.1
288        })
289        .map(|(x, position)| (x.clone(), *position))
290        .collect();
291    let point_xs: Vec<ChartX> = points.iter().map(|(x, _)| x.clone()).collect();
292    let lookups: Vec<HashMap<String, Option<f64>>> = model
293        .series
294        .iter()
295        .map(|item| {
296            item.data
297                .iter()
298                .map(|datum| (datum.x.key(), datum.y))
299                .collect()
300        })
301        .collect();
302    let value_text = |series_index: usize, x: &ChartX| -> String {
303        let value = lookups
304            .get(series_index)
305            .and_then(|lookup| lookup.get(&x.key()))
306            .copied()
307            .flatten()
308            .filter(|value| value.is_finite());
309
310        value.map_or_else(
311            || labels.not_available.clone(),
312            |value| format_with(format_value, value),
313        )
314    };
315    let announce_text = {
316        let series = model.series.clone();
317        let format_category = props.format_category;
318        let format_value = props.format_value;
319        let not_available = labels.not_available.clone();
320        let lookups = lookups.clone();
321
322        move |x: &ChartX, hidden: &HashSet<String>| -> String {
323            let mut parts = vec![detail_label(&series, x, format_category.as_ref())];
324
325            for (index, item) in series.iter().enumerate() {
326                if hidden.contains(&item.id) {
327                    continue;
328                }
329
330                let value = lookups
331                    .get(index)
332                    .and_then(|lookup| lookup.get(&x.key()))
333                    .copied()
334                    .flatten()
335                    .filter(|value| value.is_finite())
336                    .map_or_else(
337                        || not_available.clone(),
338                        |value| format_with(format_value.as_ref(), value),
339                    );
340                parts.push(format!("{} {value}", item.label));
341            }
342
343            parts.join(". ")
344        }
345    };
346    let controlled = props.cursor.clone();
347    let on_cursor_change = props.on_cursor_change;
348    let sync_group = props.sync_group.clone();
349    let point_set = point_xs.clone();
350    let announce_for = {
351        let announce_text = announce_text.clone();
352        let point_set = point_set.clone();
353
354        move |x: Option<&ChartX>| -> String {
355            match x.filter(|x| point_set.contains(x)) {
356                Some(x) => announce_text(x, &hidden_series.peek()),
357                None => String::new(),
358            }
359        }
360    };
361    let emit = {
362        let controlled = controlled.clone();
363        let sync_group = sync_group.clone();
364        let announce_for = announce_for.clone();
365
366        move |change: CursorEmit| {
367            if controlled.is_none() {
368                state.write().selected.clone_from(&change.x);
369
370                if change.announce {
371                    announcement.set(announce_for(change.x.as_ref()));
372                }
373
374                if let Some(group) = sync_group.as_deref().filter(|group| !group.is_empty()) {
375                    publish_sync(group, instance, change.x.clone());
376                }
377            } else {
378                pending.set(change.announce.then(|| change.x.clone()));
379            }
380
381            if let Some(handler) = on_cursor_change {
382                handler.call(change.x);
383            }
384        }
385    };
386
387    let mut latest = use_hook(|| {
388        CopyValue::new(Latest {
389            announce: Rc::new(|_: Option<&ChartX>| String::new()),
390            sync_group: None,
391            interactive: false,
392            controlled: false,
393        })
394    });
395    latest.set(Latest {
396        announce: Rc::new(announce_for.clone()),
397        sync_group: sync_group.clone(),
398        interactive,
399        controlled: controlled.is_some(),
400    });
401
402    // A controlled cursor selects its point, announces a pending keyboard move, and syncs peers.
403    use_effect(use_reactive!(|controlled| {
404        let Some(cursor) = controlled else {
405            return;
406        };
407        let value = cursor.x();
408        let changed = state.peek().selected != value;
409        let current = latest.read().clone();
410        state.write().selected.clone_from(&value);
411
412        if pending.peek().as_ref() == Some(&value) {
413            announcement.set((current.announce)(value.as_ref()));
414        }
415
416        pending.set(None);
417
418        if changed
419            && let Some(group) = current
420                .sync_group
421                .as_deref()
422                .filter(|group| !group.is_empty())
423        {
424            publish_sync(group, instance, value);
425        }
426    }));
427
428    // Peers in the same sync group move this cursor unless it is controlled.
429    use_effect(move || {
430        let current = latest.read().clone();
431        let Some(group) = current.sync_group.filter(|group| !group.is_empty()) else {
432            return;
433        };
434        let Some(event) = CHART_SYNC.read().get(&group).cloned() else {
435            return;
436        };
437
438        if event.origin == instance || *last_sync.peek() == Some(event.sequence) {
439            return;
440        }
441
442        last_sync.set(Some(event.sequence));
443
444        if !current.controlled && current.interactive {
445            state.write().peer_select(event.x);
446        }
447    });
448
449    let selected = state.read().selected.clone();
450    let active_point = selected
451        .as_ref()
452        .and_then(|x| points.iter().find(|(candidate, _)| candidate == x))
453        .cloned();
454    let hidden = hidden_series.read().clone();
455
456    // Place the panel beside the inspected point once it is visible and measurable.
457    {
458        let active_position = active_point.as_ref().map(|(_, position)| *position);
459        use_effect(use_reactive!(|active_position| {
460            let Some(position) = active_position else {
461                return;
462            };
463            let (Some(frame), Some(svg), Some(panel)) = (
464                measurements.frame.peek().clone(),
465                measurements.svg.peek().clone(),
466                measurements.panel.peek().clone(),
467            ) else {
468                return;
469            };
470
471            spawn(async move {
472                let (Ok(frame), Ok(svg), Ok(panel)) = (
473                    frame.get_client_rect().await,
474                    svg.get_client_rect().await,
475                    panel.get_client_rect().await,
476                ) else {
477                    return;
478                };
479
480                if let Some((left, top)) = panel_position(
481                    (frame.origin.x, frame.origin.y, frame.size.width),
482                    (svg.origin.x, svg.origin.y, svg.size.width),
483                    width,
484                    panel.size.width,
485                    position,
486                ) {
487                    panel_style.set(Some(format!(
488                        "--ui-chart-inspection-x:{}px;--ui-chart-inspection-y:{}px",
489                        js_number(left),
490                        js_number(top)
491                    )));
492                }
493            });
494        }));
495    }
496
497    let point_actions: Vec<Vec<Option<DatumAction>>> = model
498        .geometries
499        .iter()
500        .zip(&model.series)
501        .map(|(geometry, item)| {
502            if on_activate.is_none() {
503                return Vec::new();
504            }
505
506            geometry
507                .points
508                .iter()
509                .map(|point| {
510                    let context = format!(
511                        "{} · {}: {}",
512                        detail_label(&model.series, &point.datum.x, format_category),
513                        item.label,
514                        format_with(format_value, point.datum.y.unwrap_or(0.0))
515                    );
516
517                    DatumAction::new(
518                        ChartDatumActivation::series(&item.id, &point.datum),
519                        &context,
520                        &labels,
521                    )
522                })
523                .collect()
524        })
525        .collect();
526    let actions: Vec<Option<DatumAction>> = point_actions.iter().flatten().cloned().collect();
527    let layers: Vec<SeriesLayer> = model
528        .geometries
529        .iter()
530        .zip(&props.series)
531        .enumerate()
532        .map(|(index, (geometry, item))| {
533            let tone = ChartTone::resolve(item.tone, index);
534            let markers = geometry
535                .points
536                .iter()
537                .enumerate()
538                .map(|(point_index, point)| {
539                    let action = point_actions
540                        .get(index)
541                        .and_then(|actions| actions.get(point_index))
542                        .cloned()
543                        .flatten();
544
545                    Marker {
546                        key: point
547                            .datum
548                            .id
549                            .clone()
550                            .unwrap_or_else(|| point.datum.x.key()),
551                        cx: js_number(point.x),
552                        cy: js_number(point.y),
553                        motion_key: motion_key(&item.id, point.datum.id.as_ref(), &point.datum.x),
554                        datum: serialized(action.as_ref()),
555                        title: format!(
556                            "{} · {}: {}",
557                            detail_label(&model.series, &point.datum.x, format_category),
558                            item.label,
559                            format_with(format_value, point.datum.y.unwrap_or(0.0))
560                        ),
561                        visible: marker_step.is_some_and(|step| point_index % step == 0),
562                        action,
563                    }
564                })
565                .collect();
566
567            SeriesLayer {
568                id: item.id.clone(),
569                class: compose([Some("ui-line-chart__series"), Some(tone.class_name())]),
570                area: (props.area && !geometry.area_paths.is_empty())
571                    .then(|| geometry.area_paths.join(" ")),
572                area_key: format!("[\"area\",{}]", json_string(&item.id)),
573                dash: item.dash,
574                path: geometry.path.clone(),
575                path_key: format!("[\"path\",{}]", json_string(&item.id)),
576                markers,
577                hidden: hidden.contains(&item.id),
578            }
579        })
580        .collect();
581    let grid: Vec<(String, String, String)> = model
582        .ticks
583        .iter()
584        .zip(&model.tick_labels)
585        .map(|(tick, label)| {
586            let y = super::scale::scale_value(*tick, model.domain, plot_bottom, padding_top);
587
588            (js_number(*tick), js_number(y), label.clone())
589        })
590        .collect();
591    let axis_y = js_number(height - 14.0);
592    let category_ticks: Vec<(String, &'static str, String, String)> = model
593        .category_ticks
594        .iter()
595        .map(|tick| {
596            (
597                tick.index.to_string(),
598                CategoryTick::ANCHOR,
599                js_number(tick.position),
600                tick.label.clone(),
601            )
602        })
603        .collect();
604    let reference_y = props.reference_value.map(|value| {
605        js_number(super::scale::scale_value(
606            value,
607            model.domain,
608            plot_bottom,
609            padding_top,
610        ))
611    });
612    let annotations: Vec<AnnotationText> = model
613        .annotation_marks
614        .iter()
615        .map(|mark| {
616            let annotation = &mark.annotation;
617            let class = compose([
618                Some("ui-chart__annotation"),
619                Some(ChartTone::resolve(annotation.tone, 0).class_name()),
620            ]);
621            let value = match annotation.axis {
622                LineChartAnnotationAxis::X => {
623                    detail_label(&model.series, &annotation.value, format_category)
624                }
625                LineChartAnnotationAxis::Y => match annotation.value {
626                    ChartX::Number(number) => format_with(format_value, number),
627                    ChartX::Text(_) => String::new(),
628                },
629            };
630
631            AnnotationText {
632                id: annotation.id.clone(),
633                class,
634                vertical: annotation.axis == LineChartAnnotationAxis::X,
635                coordinate: js_number(mark.coordinate),
636                label_x: js_number(mark.coordinate + 4.0),
637                label_y: js_number(mark.coordinate - 8.0),
638                label: annotation.label.clone(),
639                value,
640            }
641        })
642        .collect();
643    let inspection_points: Vec<InspectionPoint> = if interactive && has_data {
644        model
645            .categories
646            .iter()
647            .zip(&model.positions)
648            .map(|(category, position)| InspectionPoint {
649                key: category.key(),
650                json: category.json(),
651                position: js_number(*position),
652                label: detail_label(&model.series, category, format_category),
653                values: model
654                    .series
655                    .iter()
656                    .enumerate()
657                    .map(|(index, item)| {
658                        (
659                            item.id.clone(),
660                            ChartTone::resolve(item.tone, index).class_name(),
661                            item.label.clone(),
662                            value_text(index, category),
663                        )
664                    })
665                    .collect(),
666            })
667            .collect()
668    } else {
669        Vec::new()
670    };
671    let active_key = active_point.as_ref().map(|(x, _)| x.key());
672    let crosshair = active_point
673        .as_ref()
674        .map(|(_, position)| js_number(*position));
675    let summary = props
676        .summary
677        .clone()
678        .or_else(|| Some(labels.summary(summarize(&model.series, format_value))));
679    let plot_name = plot_label(
680        &props.attributes,
681        props.heading.as_ref(),
682        &labels.chart_data,
683    );
684    let frame = ChartFrame {
685        chart_class: Some(compose([Some("ui-line-chart"), props.class.as_deref()])),
686        heading: props.heading.clone(),
687        description: props.description.clone(),
688        value: props.value.clone(),
689        summary,
690        caption: props.caption.clone(),
691        presentation: props.presentation,
692        glass: props.glass,
693        activation: on_activate.is_some(),
694        attributes: props.attributes.clone(),
695        on_mounted: None,
696    };
697    let view_box = format!("0 0 {} {}", js_number(width), js_number(height));
698    let viewbox_width = js_number(width);
699    let inner = (
700        js_number(clip.x),
701        js_number(clip.y),
702        js_number(clip.width),
703        js_number(clip.height),
704    );
705    let inner_view_box = format!("{} {} {} {}", inner.0, inner.1, inner.2, inner.3);
706    let left = js_number(padding_left);
707    let right = js_number(plot_right);
708    let top = js_number(padding_top);
709    let bottom = js_number(plot_bottom);
710    let label_x = js_number(padding_left - 8.0);
711    let annotation_top = js_number(padding_top - 8.0);
712    let is_enhanced = *enhanced.read();
713    let point_xs_for_keys = point_xs.clone();
714    let mut emit_key = emit.clone();
715    let mut emit_move = emit.clone();
716    let emit_down = emit.clone();
717    let mut emit_leave = emit;
718    let points_for_move = points.clone();
719    let points_for_down = points;
720    let content = rsx! {
721        div {
722            class: "ui-chart__content",
723            "data-ui-chart-sync": sync_group.clone(),
724            "data-ui-chart-enhanced": (interactive && is_enhanced).then_some("true"),
725            onpointerleave: move |_| {
726                if !interactive {
727                    return;
728                }
729
730                let change = state.write().pointer_leave();
731
732                if let Some(change) = change {
733                    emit_leave(change);
734                }
735            },
736            if show_legend && has_data {
737                if interactive {
738                    ul { class: "ui-chart__legend", aria_label: "{labels.chart_legend}",
739                        for (index, item) in props.series.iter().enumerate() {
740                            li {
741                                key: "{item.id}",
742                                class: ChartTone::resolve(item.tone, index).class_name(),
743                                Button {
744                                    aria_pressed: if hidden.contains(&item.id) { "false" } else { "true" },
745                                    "data-ui-chart-toggle": item.id.clone(),
746                                    disabled: !is_enhanced,
747                                    size: ButtonSize::Sm,
748                                    variant: ButtonVariant::Ghost,
749                                    onclick: {
750                                        let id = item.id.clone();
751                                        move |_| {
752                                            let mut hidden = hidden_series.write();
753
754                                            if !hidden.remove(&id) {
755                                                hidden.insert(id.clone());
756                                            }
757                                        }
758                                    },
759                                    "{item.label}"
760                                }
761                            }
762                        }
763                    }
764                } else {
765                    {chart_legend(&labels.chart_legend, &props.series)}
766                }
767            }
768            if !has_data {
769                p { class: "ui-chart__empty", role: "status",
770                    "{props.empty_label.clone().unwrap_or_else(|| labels.empty.clone())}"
771                }
772            }
773            div {
774                aria_label: "{plot_name}",
775                class: "ui-chart__plot",
776                "data-ui-chart-interaction-plot": interactive.then_some("true"),
777                role: "region",
778                tabindex: "0",
779                hidden: !has_data,
780                onmounted: move |event| {
781                    let mut plot = measurements.plot;
782                    plot.set(Some(event.data()));
783                },
784                onkeydown: move |event| {
785                    if !interactive || event.is_composing() {
786                        return;
787                    }
788
789                    let Some(key) = InspectionKey::from_key(&event.key()) else {
790                        return;
791                    };
792                    let change = state.write().key(key, &point_xs_for_keys);
793
794                    if let Some(change) = change {
795                        event.prevent_default();
796                        emit_key(change);
797                    }
798                },
799                onpointermove: move |event| {
800                    if !interactive {
801                        return;
802                    }
803
804                    let client_x = event.client_coordinates().x;
805                    let rect = *measurements.svg_rect.peek();
806
807                    if let Some(svg) = measurements.svg.peek().clone() {
808                        let mut svg_rect = measurements.svg_rect;
809                        spawn(async move {
810                            if let Ok(rect) = svg.get_client_rect().await {
811                                svg_rect.set(Some((rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)));
812                            }
813                        });
814                    }
815
816                    let closest = rect
817                        .and_then(|rect| svg_x(client_x, rect, (width, height)))
818                        .and_then(|position| closest_point(position, &points_for_move));
819                    let touch = event.pointer_type() == "touch";
820                    let change = state.write().pointer_move(closest, touch);
821
822                    if let Some(change) = change {
823                        emit_move(change);
824                    }
825                },
826                onpointerdown: move |event| {
827                    if !interactive {
828                        return;
829                    }
830
831                    let primary = event
832                        .trigger_button()
833                        .is_none_or(|button| button == dioxus::html::input_data::MouseButton::Primary);
834
835                    if !primary {
836                        return;
837                    }
838
839                    let client_x = event.client_coordinates().x;
840                    let svg = measurements.svg.peek().clone();
841                    let mut svg_rect = measurements.svg_rect;
842                    let points = points_for_down.clone();
843                    let mut emit_down = emit_down.clone();
844                    focus_element(measurements.plot.peek().clone());
845                    spawn(async move {
846                        if let Some(svg) = svg
847                            && let Ok(rect) = svg.get_client_rect().await
848                        {
849                            svg_rect.set(Some((rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)));
850                        }
851
852                        let closest = svg_rect
853                            .peek()
854                            .and_then(|rect| svg_x(client_x, rect, (width, height)))
855                            .and_then(|position| closest_point(position, &points));
856                        let change = state.write().pointer_down(closest);
857                        emit_down(change);
858                    });
859                },
860                svg {
861                    "aria-hidden": "true",
862                    "preserveAspectRatio": "xMidYMid meet",
863                    "style": "--ui-chart-viewbox-width: {viewbox_width}",
864                    "viewBox": "{view_box}",
865                    onmounted: move |event| {
866                        let mut svg = measurements.svg;
867                        svg.set(Some(event.data()));
868                    },
869                    g { class: "ui-chart__grid",
870                        for (key, y, text) in grid {
871                            line { key: "{key}-line", x1: "{left}", x2: "{right}", y1: "{y}", y2: "{y}" }
872                            text { x: "{label_x}", y: "{y}", "{text}" }
873                        }
874                    }
875                    g { class: "ui-chart__axis-labels",
876                        for (key, anchor, x, label) in category_ticks {
877                            text { key: "{key}", "text-anchor": anchor, x: "{x}", y: "{axis_y}", "{label}" }
878                        }
879                    }
880                    svg {
881                        "aria-hidden": "true",
882                        x: "{inner.0}",
883                        y: "{inner.1}",
884                        width: "{inner.2}",
885                        height: "{inner.3}",
886                        "viewBox": "{inner_view_box}",
887                        overflow: "hidden",
888                        if let Some(y) = reference_y {
889                            line { class: "ui-chart__reference", x1: "{left}", x2: "{right}", y1: "{y}", y2: "{y}" }
890                        }
891                        for layer in layers.iter() {
892                            g {
893                                key: "{layer.id}",
894                                class: "{layer.class}",
895                                "data-ui-chart-series": "{layer.id}",
896                                style: layer.hidden.then_some("display:none"),
897                                if let Some(area) = layer.area.clone() {
898                                    path {
899                                        "data-ui-chart-motion-key": "{layer.area_key}",
900                                        class: "ui-line-chart__area",
901                                        d: "{area}",
902                                    }
903                                }
904                                path {
905                                    "data-ui-chart-motion-key": "{layer.path_key}",
906                                    class: "ui-line-chart__line",
907                                    "data-ui-chart-dash": layer.dash.map(ChartSeriesDash::as_str),
908                                    d: "{layer.path}",
909                                }
910                                for marker in layer.markers.iter().filter(|marker| marker.visible) {
911                                    circle {
912                                        key: "{marker.key}",
913                                        "data-ui-chart-datum": marker.datum.clone(),
914                                        "data-ui-chart-motion-key": "{marker.motion_key}",
915                                        class: "ui-line-chart__point",
916                                        cx: "{marker.cx}",
917                                        cy: "{marker.cy}",
918                                        r: "3",
919                                        onclick: activate_on_click(marker.action.as_ref(), on_activate),
920                                        title { "{marker.title}" }
921                                    }
922                                }
923                                if on_activate.is_some() {
924                                    for marker in layer.markers.iter() {
925                                        circle {
926                                            key: "hit-{marker.key}",
927                                            class: "ui-chart__datum-hit",
928                                            cx: "{marker.cx}",
929                                            cy: "{marker.cy}",
930                                            r: "10",
931                                            "data-ui-chart-datum": marker.datum.clone(),
932                                            onclick: activate_on_click(marker.action.as_ref(), on_activate),
933                                        }
934                                    }
935                                }
936                            }
937                        }
938                    }
939                    for mark in annotations.iter() {
940                        g { key: "{mark.id}", class: "{mark.class}",
941                            if mark.vertical {
942                                line { x1: "{mark.coordinate}", x2: "{mark.coordinate}", y1: "{top}", y2: "{bottom}" }
943                                text { x: "{mark.label_x}", y: "{annotation_top}", "{mark.label}" }
944                            } else {
945                                line { x1: "{left}", x2: "{right}", y1: "{mark.coordinate}", y2: "{mark.coordinate}" }
946                                text { "text-anchor": "end", x: "{right}", y: "{mark.label_y}", "{mark.label}" }
947                            }
948                        }
949                    }
950                    if interactive {
951                        line {
952                            class: "ui-chart__crosshair",
953                            "data-ui-chart-crosshair": "true",
954                            style: if crosshair.is_some() { "" } else { "display:none" },
955                            x1: crosshair.clone(),
956                            x2: crosshair.clone(),
957                            y1: "{top}",
958                            y2: "{bottom}",
959                        }
960                    }
961                }
962            }
963            if !annotations.is_empty() {
964                ul { class: "ui-sr-only",
965                    for mark in annotations.iter() {
966                        li { key: "{mark.id}", "{mark.label}: {mark.value}" }
967                    }
968                }
969            }
970            if interactive && has_data {
971                div {
972                    class: "ui-chart__inspection",
973                    "data-ui-chart-inspection": "true",
974                    hidden: active_key.is_none(),
975                    style: panel_style.read().clone(),
976                    onmounted: move |event| {
977                        let mut panel = measurements.panel;
978                        panel.set(Some(event.data()));
979                    },
980                    for point in inspection_points {
981                        div {
982                            key: "{point.key}",
983                            "data-ui-chart-point": "{point.json}",
984                            "data-ui-chart-position": "{point.position}",
985                            hidden: active_key.as_ref() != Some(&point.key),
986                            strong { "{point.label}" }
987                            for (id, class, label, value) in point.values {
988                                span {
989                                    key: "{id}",
990                                    class,
991                                    "data-ui-chart-series-value": "{id}",
992                                    hidden: hidden.contains(&id),
993                                    i { aria_hidden: "true" }
994                                    "{label} "
995                                    b { "{value}" }
996                                }
997                            }
998                        }
999                    }
1000                }
1001                p {
1002                    aria_live: "polite",
1003                    aria_atomic: "true",
1004                    class: "ui-sr-only",
1005                    "data-ui-chart-announcement": "true",
1006                    "{announcement}"
1007                }
1008            }
1009        }
1010        if props.show_table && has_data {
1011            {chart_data_table(&model.categories, format_category, format_value, &labels, &props.series)}
1012        }
1013        if on_activate.is_some() {
1014            {datum_actions(&actions, &labels.explore_data, on_activate)}
1015        }
1016    };
1017
1018    render_frame_with_mount(frame, content, measurements.frame)
1019}
1020
1021/// Renders the frame and records the `<figure>` element for panel placement.
1022fn render_frame_with_mount(
1023    mut frame: ChartFrame,
1024    content: Element,
1025    mut target: Signal<Option<Rc<MountedData>>>,
1026) -> Element {
1027    frame.on_mounted = Some(EventHandler::new(move |data: Rc<MountedData>| {
1028        target.set(Some(data));
1029    }));
1030
1031    render_frame(frame, content)
1032}