lodviz_components 0.3.0

Components for data visualization using lodviz_core
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
/// LineChart component with LTTB downsampling and multi-series support
use crate::components::interaction::linked_context::DashboardContext;
use crate::components::interaction::zoom_pan::{ZoomPan, ZoomTransform};
use crate::components::layout::card_registry::get_card_transform_signal;
use crate::components::layout::draggable_card::CardId;
use crate::components::svg::axis::{Axis, AxisOrientation};
use crate::components::svg::grid::Grid;
use crate::components::svg::legend::{estimate_legend_width, Legend, LegendItem, LegendPosition};
use crate::components::svg::tooltip::Tooltip;
use crate::hooks::use_container_size;
use crate::rendering::RenderMode;
use leptos::prelude::*;
use lodviz_core::algorithms::lttb::lttb_downsample;
use lodviz_core::core::a11y;
use lodviz_core::core::data::{DataPoint, Dataset};
use lodviz_core::core::mark::Mark;
use lodviz_core::core::scale::{LinearScale, Scale};
use lodviz_core::core::theme::{ChartConfig, ChartTheme, GridStyle};

/// Generate SVG path `d` attribute from data points and scales
fn generate_path_data(
    points: &[DataPoint],
    x_scale: &LinearScale,
    y_scale: &LinearScale,
) -> String {
    if points.is_empty() {
        return String::from("M 0 0");
    }

    let mut path = String::with_capacity(points.len() * 16);
    for (i, point) in points.iter().enumerate() {
        let x = x_scale.map(point.x);
        let y = y_scale.map(point.y);
        if i == 0 {
            path.push_str(&format!("M {x:.2} {y:.2}"));
        } else {
            path.push_str(&format!(" L {x:.2} {y:.2}"));
        }
    }
    path
}

/// LineChart component for rendering line charts with automatic downsampling
///
/// Features:
/// - Multi-series support via `Dataset`
/// - Automatic LTTB downsampling for series > 1000 points
/// - Interactive legend with click-to-toggle
/// - Optional axis labels
/// - Responsive SVG rendering
#[component]
pub fn LineChart(
    /// Dataset containing one or more series
    data: Signal<Dataset>,
    /// Width of the chart (optional, uses card dimensions if in a DraggableCard)
    #[prop(optional)]
    width: Option<u32>,
    /// Height of the chart (optional, uses card dimensions if in a DraggableCard)
    #[prop(optional)]
    height: Option<u32>,
    /// Chart title (optional)
    #[prop(optional)]
    title: Option<String>,
    /// Show grid background
    #[prop(default = true)]
    show_grid: bool,
    /// X axis label (optional)
    #[prop(optional, into)]
    x_label: Option<String>,
    /// Y axis label (optional)
    #[prop(optional, into)]
    y_label: Option<String>,
    /// Chart configuration (overrides specific props if present)
    #[prop(default = Signal::derive(|| ChartConfig::default()), into)]
    config: Signal<ChartConfig>,
    /// Rendering mode (SVG, Canvas, or Auto based on data size)
    #[prop(default = RenderMode::Auto)]
    _render_mode: RenderMode,
) -> impl IntoView {
    // Reactive theme derived from config
    let ctx_theme = use_context::<Signal<ChartTheme>>();
    let theme = Memo::new(move |_| {
        config
            .get()
            .theme
            .unwrap_or_else(|| ctx_theme.map(|s| s.get()).unwrap_or_default())
    });

    // Get real-time container dimensions using ResizeObserver
    let (container_width, container_height, container_ref) = use_container_size();

    // Fallback to card dimensions or fixed size if container not yet measured
    let card_transform = use_context::<CardId>().map(|id| get_card_transform_signal(id.0.clone()));

    let chart_width = Memo::new(move |_| {
        let measured = container_width.get();
        if measured > 0.0 {
            return measured as u32;
        }
        config
            .get()
            .width
            .or(width)
            .or_else(|| {
                card_transform.and_then(|sig| sig.get().map(|ct| (ct.width - 32.0).max(0.0) as u32))
            })
            .unwrap_or(800)
    });

    let chart_height = Memo::new(move |_| {
        let measured = container_height.get();
        if measured > 0.0 {
            return measured as u32;
        }
        config
            .get()
            .height
            .or(height)
            .or_else(|| {
                card_transform
                    .and_then(|sig| sig.get().map(|ct| (ct.height - 40.0).max(100.0) as u32))
            })
            .unwrap_or(400)
    });

    // Series visibility (defined early — needed by legend_items before margin)
    let (series_visibility, set_series_visibility) = signal(Vec::<bool>::new());

    // Keep visibility in sync with number of series
    Effect::new(move |_| {
        let n = data.get().series.len();
        let current = series_visibility.get_untracked();
        if current.len() != n {
            set_series_visibility.set(vec![true; n]);
        }
    });

    // Processed data: LTTB downsample per series (defined early — needed by legend_items before margin)
    let processed_data = Memo::new(move |_| {
        let dataset = data.get();
        dataset
            .series
            .iter()
            .map(|s| {
                let points = if s.data.len() > 1000 {
                    lttb_downsample(&s.data, 1000)
                } else {
                    s.data.clone()
                };
                (s.name.clone(), points)
            })
            .collect::<Vec<_>>()
    });

    // Legend items — defined early so margin can adapt when legend_outside is enabled
    let legend_items = Signal::derive(move || {
        let series = processed_data.get();
        let vis = series_visibility.get();
        let th = theme.get();
        series
            .iter()
            .enumerate()
            .map(|(i, (name, _))| LegendItem {
                name: name.clone(),
                color: th.palette[i % th.palette.len()].clone(),
                visible: vis.get(i).copied().unwrap_or(true),
            })
            .collect::<Vec<_>>()
    });

    let legend_outside = Memo::new(move |_| config.get().legend_outside.unwrap_or(false));

    let margin = Memo::new(move |_| {
        let mut m = config.get().margin.unwrap_or_default();
        if legend_outside.get() {
            m.right += estimate_legend_width(&legend_items.get()) + 16.0;
        }
        m
    });

    let inner_width =
        Memo::new(move |_| chart_width.get() as f64 - margin.get().left - margin.get().right);
    let inner_height =
        Memo::new(move |_| chart_height.get() as f64 - margin.get().top - margin.get().bottom);

    let final_title = Memo::new(move |_| config.get().title.or(title.clone()));
    let grid_style = Memo::new(move |_| {
        config.get().grid.unwrap_or_else(|| {
            let th = theme.get();
            if show_grid {
                th.grid.clone()
            } else {
                GridStyle {
                    show_x: false,
                    show_y: false,
                    ..th.grid.clone()
                }
            }
        })
    });

    // Initial domain calculation (full extent)
    let initial_transform = Memo::new(move |_| {
        let series = processed_data.get();
        // Default 0..1 if empty
        let mut x_min = f64::INFINITY;
        let mut x_max = f64::NEG_INFINITY;
        let mut y_min = f64::INFINITY;
        let mut y_max = f64::NEG_INFINITY;

        let all_points = series.iter().flat_map(|(_, pts)| pts.iter());
        for p in all_points {
            if p.x < x_min {
                x_min = p.x;
            }
            if p.x > x_max {
                x_max = p.x;
            }
            if p.y < y_min {
                y_min = p.y;
            }
            if p.y > y_max {
                y_max = p.y;
            }
        }

        if x_min >= x_max {
            x_min = 0.0;
            x_max = 1.0;
        }
        if y_min >= y_max {
            y_min = 0.0;
            y_max = 1.0;
        }

        // Add minimal padding to Y to avoid cutting off peaks
        let y_pad = (y_max - y_min) * 0.05;

        ZoomTransform::from_domain(x_min, x_max, y_min - y_pad, y_max + y_pad)
    });

    // Zoom state
    let zoom_transform = RwSignal::new(ZoomTransform::from_domain(0.0, 1.0, 0.0, 1.0));

    // Reset zoom when data changes drastically (simple heuristic: if bounds change)
    Effect::new(move |_| {
        let new_initial = initial_transform.get();
        // Use a tracker to avoid resetting on every small update?
        // For now, always sync to data updates unless we want to persist zoom across data updates.
        // Let's reset for simplicity when data structure changes.
        zoom_transform.set(new_initial);
    });

    // Scales computed from ZoomTransform
    let x_scale = Memo::new(move |_| {
        let t = zoom_transform.get();
        let w = inner_width.get();
        LinearScale::new((t.x_min, t.x_max), (0.0, w))
    });

    let y_scale = Memo::new(move |_| {
        let t = zoom_transform.get();
        let h = inner_height.get();
        LinearScale::new((t.y_min, t.y_max), (h, 0.0))
    });

    // Dynamic tick counts
    let x_tick_count = Memo::new(move |_| (inner_width.get() / 100.0).max(2.0) as usize);
    let y_tick_count = Memo::new(move |_| (inner_height.get() / 50.0).max(2.0) as usize);

    // Accessibility
    let chart_description = Memo::new(move |_| {
        let series = processed_data.get();
        let total_points: usize = series.iter().map(|(_, pts)| pts.len()).sum();
        let mut desc = a11y::generate_chart_description(Mark::Line, total_points, None, None);
        if series.len() > 1 {
            desc.push_str(&format!(" {} series: ", series.len()));
            let names: Vec<_> = series.iter().map(|(n, _)| n.as_str()).collect();
            desc.push_str(&names.join(", "));
            desc.push('.');
        }
        desc
    });

    let aria_label = Memo::new(move |_| {
        final_title
            .get()
            .unwrap_or_else(|| "Line chart".to_string())
    });

    // Toggle handler
    let on_legend_toggle = Callback::new(move |idx: usize| {
        let mut vis = series_visibility.get();
        if let Some(v) = vis.get_mut(idx) {
            *v = !*v;
        }
        set_series_visibility.set(vis);
    });

    // Legend visibility: auto (show if > 1 series) unless overridden by config
    let show_legend = Memo::new(move |_| {
        config
            .get()
            .show_legend
            .unwrap_or_else(|| legend_items.get().len() > 1)
    });

    // Keyboard navigation state
    let (focused_index, set_focused_index) = signal(None::<usize>);

    // Tooltip data: flatten all visible series for tooltip lookup
    let tooltip_series = Memo::new(move |_| {
        let series = processed_data.get();
        let vis = series_visibility.get();
        series
            .iter()
            .enumerate()
            .filter(|(i, _)| vis.get(*i).copied().unwrap_or(true))
            .map(|(_, (name, pts))| (name.clone(), pts.clone()))
            .collect::<Vec<_>>()
    });

    let tooltip_colors = Memo::new(move |_| {
        let series = processed_data.get();
        let vis = series_visibility.get();
        let th = theme.get();
        series
            .iter()
            .enumerate()
            .filter(|(i, _)| vis.get(*i).copied().unwrap_or(true))
            .map(|(i, _)| th.palette[i % th.palette.len()].clone())
            .collect::<Vec<_>>()
    });

    let x_label_computed = Memo::new(move |_| config.get().x_label.or(x_label.clone()));
    let y_label_computed = Memo::new(move |_| config.get().y_label.or(y_label.clone()));

    // Unique IDs for clip path and a11y
    let clip_id = StoredValue::new_local(format!("clip-{}", uuid::Uuid::new_v4()));
    let a11y_title_id =
        StoredValue::new_local(format!("chart-title-{}", uuid::Uuid::new_v4().as_simple()));
    let a11y_desc_id =
        StoredValue::new_local(format!("chart-desc-{}", uuid::Uuid::new_v4().as_simple()));
    let a11y_labelledby = StoredValue::new_local(format!(
        "{} {}",
        a11y_title_id.get_value(),
        a11y_desc_id.get_value()
    ));

    // Cursor tracking for tooltips
    let (cursor_norm, set_cursor_norm) = signal(None::<(f64, f64)>);

    // Derived cursor X for tooltips (normalized X)
    let cursor_x = Memo::new(move |_| cursor_norm.get().map(|(x, _)| x));

    // --- Linked dashboard crosshair ---
    // Extract the shared hover_x signal from DashboardContext (if wrapped in LinkedDashboard)
    let dash_hover_x = use_context::<DashboardContext>().map(|ctx| ctx.hover_x);

    // Emit our cursor position as domain-X to the shared context
    Effect::new(move |_| {
        let Some(hover_signal) = dash_hover_x else {
            return;
        };
        let domain_x = cursor_norm.get().map(|(norm_x, _)| {
            let t = zoom_transform.get();
            t.x_min + norm_x * (t.x_max - t.x_min)
        });
        hover_signal.set(domain_x);
    });

    // Crosshair from other linked charts (only when THIS chart is not being hovered)
    let crosshair_svg_x = Signal::derive(move || -> Option<f64> {
        let hover_signal = dash_hover_x?;
        if cursor_norm.get().is_some() {
            return None; // We are the source — tooltip covers it
        }
        let domain_x = hover_signal.get()?;
        let svg_x = x_scale.get().map(domain_x);
        let w = inner_width.get();
        (svg_x >= 0.0 && svg_x <= w).then_some(svg_x)
    });

    // Check if dataset is empty
    let is_empty = Memo::new(move |_| {
        let series = processed_data.get();
        series.is_empty() || series.iter().all(|(_, pts)| pts.is_empty())
    });

    view! {
        <div
            class="line-chart"
            style=move || {
                format!(
                    "width: 100%; height: 100%; display: flex; flex-direction: column; background-color: {};",
                    theme.get().background_color,
                )
            }
        >
            {move || {
                use crate::components::svg::empty_state::{EmptyStateMessage, EmptyStateProps};
                if is_empty.get() {
                    view! { <EmptyStateMessage props=EmptyStateProps::no_data() theme=theme /> }
                        .into_any()
                } else {
                    view! {
                        {move || {
                            final_title
                                .get()
                                .map(|t| {
                                    let th = theme.get();
                                    view! {
                                        <h3 style=format!(
                                            "text-align: center; margin: 0; padding-top: {}px; padding-bottom: {}px; font-size: {}px; font-family: {}; color: {}; font-weight: {};",
                                            th.title_padding_top,
                                            th.title_padding_bottom,
                                            th.title_font_size,
                                            th.font_family,
                                            th.text_color,
                                            th.title_font_weight,
                                        )>{t}</h3>
                                    }
                                })
                        }}
                        <div
                            node_ref=container_ref
                            style="flex: 1; min-height: 0; position: relative;"
                        >
                            <svg
                                role="img"
                                aria-labelledby=a11y_labelledby.get_value()
                                tabindex="0"
                                viewBox=move || {
                                    format!("0 0 {} {}", chart_width.get(), chart_height.get())
                                }
                                style="width: 100%; height: 100%; display: block; outline: none; will-change: transform;"
                                style:outline=move || {
                                    focused_index
                                        .get()
                                        .map(|_| format!("2px solid {}", theme.get().focus_outline))
                                }
                                on:keydown=move |ev| {
                                    let series = processed_data.get();
                                    let vis = series_visibility.get();
                                    let first_visible = series
                                        .iter()
                                        .enumerate()
                                        .find(|(i, _)| vis.get(*i).copied().unwrap_or(true))
                                        .map(|(_, (_, pts))| pts.clone());
                                    let Some(data_points) = first_visible else { return };
                                    if data_points.is_empty() {
                                        return;
                                    }
                                    let key = ev.key();
                                    match key.as_str() {
                                        "ArrowRight" => {
                                            ev.prevent_default();
                                            let next = match focused_index.get() {
                                                Some(i) => (i + 1).min(data_points.len() - 1),
                                                None => 0,
                                            };
                                            set_focused_index.set(Some(next));
                                        }
                                        "ArrowLeft" => {
                                            ev.prevent_default();
                                            let prev = match focused_index.get() {
                                                Some(i) => i.saturating_sub(1),
                                                None => 0,
                                            };
                                            set_focused_index.set(Some(prev));
                                        }
                                        "Escape" => {
                                            set_focused_index.set(None);
                                        }
                                        _ => {}
                                    }
                                }
                            >
                                <title id=a11y_title_id
                                    .get_value()>{move || aria_label.get()}</title>
                                <desc id=a11y_desc_id
                                    .get_value()>{move || chart_description.get()}</desc>
                                <g transform=move || {
                                    format!(
                                        "translate({}, {})",
                                        margin.get().left,
                                        margin.get().top,
                                    )
                                }>
                                    <defs>
                                        <clipPath id=clip_id.get_value()>
                                            <rect
                                                x="0"
                                                y="0"
                                                width=move || inner_width.get()
                                                height=move || inner_height.get()
                                            ></rect>
                                        </clipPath>
                                    </defs>

                                    // Grid (optional)
                                    {move || {
                                        let gs = grid_style.get();
                                        (gs.show_x || gs.show_y)
                                            .then(|| {
                                                view! {
                                                    <Grid
                                                        x_scale=x_scale.get()
                                                        y_scale=y_scale.get()
                                                        tick_count=x_tick_count.get()
                                                        width=inner_width.get()
                                                        height=inner_height.get()
                                                        style=gs
                                                    />
                                                }
                                            })
                                    }}
                                    // Line paths (one per series)
                                    {move || {
                                        let series = processed_data.get();
                                        let vis = series_visibility.get();
                                        let xs = x_scale.get();
                                        let ys = y_scale.get();
                                        let th = theme.get();
                                        series
                                            .iter()
                                            .enumerate()
                                            .map(|(i, (_, points))| {
                                                let visible = vis.get(i).copied().unwrap_or(true);
                                                let color = th.palette[i % th.palette.len()].clone();
                                                let d = generate_path_data(points, &xs, &ys);
                                                let display_style = if visible { "inline" } else { "none" };
                                                // Default to true if index not found
                                                // Generate path data regardless (could optimize to skip if invisible)

                                                // Use CSS display or opacity to hide.
                                                // Since we want to keep the element for potential transitions,
                                                // opacity or display is fine. display="none" removes it from layout/hit-testing.

                                                view! {
                                                    <g clip-path=format!("url(#{})", clip_id.get_value())>
                                                        <path
                                                            d=d
                                                            fill="none"
                                                            stroke=color
                                                            stroke-width=th.stroke_width
                                                            stroke-linejoin="round"
                                                            stroke-linecap="round"
                                                            opacity=th.line_opacity
                                                            style=format!("display: {}", display_style)
                                                        />
                                                    </g>
                                                }
                                            })
                                            .collect_view()
                                    }}
                                    // Keyboard focus indicator
                                    {move || {
                                        let series = processed_data.get();
                                        let vis = series_visibility.get();
                                        let th = theme.get();
                                        focused_index
                                            .get()
                                            .and_then(|idx| {
                                                let (si, (_, points)) = series
                                                    .iter()
                                                    .enumerate()
                                                    .find(|(i, _)| vis.get(*i).copied().unwrap_or(true))?;
                                                let point = points.get(idx)?;
                                                let cx = x_scale.get().map(point.x);
                                                let cy = y_scale.get().map(point.y);
                                                let desc = a11y::describe_point(point, idx, points.len());
                                                let color = th.palette[si % th.palette.len()].clone();
                                                Some(
                                                    // Use first visible series
                                                    view! {
                                                        <g>
                                                            <circle
                                                                cx=format!("{cx:.2}")
                                                                cy=format!("{cy:.2}")
                                                                r=6
                                                                fill="white"
                                                                stroke=color
                                                                stroke-width=2
                                                            />
                                                            <text
                                                                x=format!("{cx:.2}")
                                                                y=format!("{:.2}", cy - 12.0)
                                                                text-anchor="middle"
                                                                font-size="11"
                                                                fill=th.text_color.clone()
                                                                role="status"
                                                                aria-live="polite"
                                                            >
                                                                {desc}
                                                            </text>
                                                        </g>
                                                    },
                                                )
                                            })
                                    }}
                                    // X axis (bottom)
                                    <g transform=move || {
                                        format!("translate(0, {})", inner_height.get())
                                    }>
                                        {move || {
                                            view! {
                                                <Axis
                                                    orientation=AxisOrientation::Bottom
                                                    scale=x_scale.get()
                                                    tick_count=x_tick_count.get()
                                                    _dimension=inner_width.get()
                                                    stroke=theme.get().axis_color
                                                    font_size=theme.get().axis_font_size
                                                    label=x_label_computed.get()
                                                />
                                            }
                                        }}
                                    // Y axis (left)
                                    </g>
                                    {move || {
                                        view! {
                                            <Axis
                                                orientation=AxisOrientation::Left
                                                scale=y_scale.get()
                                                tick_count=y_tick_count.get()
                                                _dimension=inner_height.get()
                                                stroke=theme.get().axis_color
                                                font_size=theme.get().axis_font_size
                                                label=y_label_computed.get()
                                            />
                                        }
                                    }}

                                    // Crosshair from linked DashboardContext
                                    {move || {
                                        crosshair_svg_x
                                            .get()
                                            .map(|x| {
                                                let h = inner_height.get();
                                                let crosshair_stroke = theme.get().crosshair_color.clone();
                                                view! {
                                                    <line
                                                        x1=x
                                                        y1="0"
                                                        x2=x
                                                        y2=h
                                                        stroke=crosshair_stroke
                                                        stroke-width="1"
                                                        stroke-dasharray="4,3"
                                                        style="pointer-events: none;"
                                                    />
                                                }
                                            })
                                    }}

                                    // Tooltip overlay (must be last to receive mouse events)
                                    <Tooltip
                                        series_data=tooltip_series
                                        series_colors=tooltip_colors
                                        x_scale=x_scale
                                        y_scale=y_scale
                                        inner_width=inner_width
                                        inner_height=inner_height
                                        cursor_normalized_x=cursor_x
                                        crosshair_color=Signal::derive(move || {
                                            theme.get().crosshair_color.clone()
                                        })
                                        tooltip_bg=Signal::derive(move || {
                                            theme.get().tooltip_bg.clone()
                                        })
                                        tooltip_text=Signal::derive(move || {
                                            theme.get().tooltip_text.clone()
                                        })
                                    />

                                    // ZoomPan overlay
                                    <ZoomPan
                                        transform=zoom_transform
                                        original=initial_transform
                                        inner_width=inner_width
                                        inner_height=inner_height
                                        set_cursor=set_cursor_norm
                                        zoom_fill=Signal::derive(move || {
                                            theme.get().zoom_fill.clone()
                                        })
                                        zoom_stroke=Signal::derive(move || {
                                            theme.get().zoom_stroke.clone()
                                        })
                                    />

                                    // SVG Legend overlay (must be last to render on top)
                                    {move || {
                                        show_legend
                                            .get()
                                            .then(|| {
                                                let text_color = theme.get().text_color;
                                                let position = if legend_outside.get() {
                                                    LegendPosition::ExternalRight
                                                } else {
                                                    LegendPosition::TopRight
                                                };
                                                view! {
                                                    <Legend
                                                        items=legend_items
                                                        position=position
                                                        inner_width=inner_width
                                                        inner_height=inner_height
                                                        on_toggle=on_legend_toggle
                                                        text_color=text_color
                                                    />
                                                }
                                            })
                                    }}

                                </g>
                            </svg>
                        </div>
                    }
                        .into_any()
                }
            }}
        </div>
    }
}