egui_charts/chart/selection/mod.rs
1//! Generic selection state for chart elements.
2//!
3//! Provides a shared selection pattern used by series, indicators, and other
4//! selectable chart elements.
5//!
6//! The whole chart tracks a single selection through one
7//! `SelectionState`. The [`ChartElementId`] enum distinguishes
8//! the kinds of selectable things (a price/volume series or a study, drawn on
9//! the main chart or in a pane below it), so one selection model can express
10//! "whatever the user last clicked" regardless of which layer it lives on.
11
12/// Identifier shared by bar series, the volume series and studies.
13///
14/// Well-known constants: [`MAIN`](Self::MAIN) (candlesticks/bars) and
15/// [`VOLUME`](Self::VOLUME).
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
17pub struct SeriesId(pub usize);
18
19impl SeriesId {
20 /// Main chart series (candlesticks/bars)
21 pub const MAIN: SeriesId = SeriesId(0);
22 /// Volume series
23 pub const VOLUME: SeriesId = SeriesId(1);
24
25 /// Get display name for this series
26 pub fn name(&self) -> &'static str {
27 match self.0 {
28 0 => "Main Series",
29 1 => "Volume",
30 _ => "Series",
31 }
32 }
33}
34
35/// Identifies any selectable element across the entire chart.
36///
37/// Read the chart's current selection with [`Chart::selected_element`](crate::Chart::selected_element).
38/// Series and studies can be selected in the main pane or an additional pane.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
40pub enum ChartElementId {
41 /// A bar or volume series.
42 Series(SeriesId),
43 /// A study, identified by the id [`Chart::add_indicator`](crate::Chart::add_indicator)
44 /// returned.
45 Indicator(SeriesId),
46}
47
48/// Selection and bar index shared by series and studies.
49#[derive(Clone, Debug, Default)]
50pub(crate) struct SelectionState {
51 /// Currently selected element
52 pub selected: Option<ChartElementId>,
53 /// Additional selection metadata (bar index, etc.)
54 pub bar_idx: Option<usize>,
55}
56
57impl SelectionState {
58 /// Create new empty selection state.
59 pub fn new() -> Self {
60 Self::default()
61 }
62
63 /// Select an element.
64 pub fn select(&mut self, id: ChartElementId, bar_idx: Option<usize>) {
65 self.selected = Some(id);
66 self.bar_idx = bar_idx;
67 }
68
69 /// Deselect all elements.
70 pub fn deselect(&mut self) {
71 self.selected = None;
72 self.bar_idx = None;
73 }
74
75 /// Get the currently selected element ID.
76 pub fn selected_id(&self) -> Option<ChartElementId> {
77 self.selected
78 }
79
80 /// Get the bar index where selection occurred.
81 pub fn selected_bar(&self) -> Option<usize> {
82 self.bar_idx
83 }
84}