1use std::rc::Rc;
10
11use arc_motion::{is_reduced_motion, motion_now};
12use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
13use gpui_kit::{
14 App, Bounds, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent,
15 MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, RenderOnce, Role,
16 SharedString, Styled, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
17};
18
19use super::common::{
20 ChartSpring, build_circle_fill, build_polyline_stroke, format_grouped,
21 slice_polyline_by_progress,
22};
23
24const LABEL_GAP: f32 = 22.0;
25const PLOT_PAD: f32 = 16.0;
26const HEAD_H: f32 = 28.0;
27
28#[derive(Clone, Debug)]
30pub struct SlopeItem {
31 pub key: SharedString,
32 pub label: SharedString,
33 pub start: f64,
34 pub end: f64,
35}
36
37impl SlopeItem {
38 pub fn new(
39 key: impl Into<SharedString>,
40 label: impl Into<SharedString>,
41 start: f64,
42 end: f64,
43 ) -> Self {
44 Self {
45 key: key.into(),
46 label: label.into(),
47 start,
48 end,
49 }
50 }
51}
52
53pub fn slope_spread_labels(wanted: &[f32], gap: f32, low: f32, high: f32) -> Vec<f32> {
56 if wanted.is_empty() {
57 return Vec::new();
58 }
59 let mut order: Vec<(usize, f32)> = wanted.iter().copied().enumerate().collect();
60 order.sort_by(|a, b| a.1.total_cmp(&b.1));
61
62 struct Group {
63 members: Vec<(usize, f32)>,
64 top: f32,
65 }
66
67 let mut groups: Vec<Group> = order
68 .into_iter()
69 .map(|entry| Group {
70 top: entry.1,
71 members: vec![entry],
72 })
73 .collect();
74
75 loop {
76 let mut changed = false;
77 let mut next: Vec<Group> = Vec::with_capacity(groups.len());
78 for group in groups {
79 if let Some(prev) = next.last_mut()
80 && prev.top + prev.members.len() as f32 * gap > group.top
81 {
82 prev.members.extend(group.members);
83 let sum: f32 = prev
84 .members
85 .iter()
86 .enumerate()
87 .map(|(k, &(_, y))| y - k as f32 * gap)
88 .sum();
89 prev.top = sum / prev.members.len() as f32;
90 changed = true;
91 continue;
92 }
93 next.push(group);
94 }
95 for g in &mut next {
96 let max_top = (high - (g.members.len().saturating_sub(1) as f32) * gap).max(low);
97 g.top = g.top.clamp(low, max_top);
98 }
99 groups = next;
100 if !changed {
101 break;
102 }
103 }
104
105 let mut out = vec![0.0f32; wanted.len()];
106 for g in groups {
107 for (k, &(idx, _)) in g.members.iter().enumerate() {
108 out[idx] = g.top + k as f32 * gap;
109 }
110 }
111 out
112}
113
114pub fn slope_ranks(values: &[f64]) -> Vec<usize> {
116 let mut indexed: Vec<(usize, f64)> = values.iter().copied().enumerate().collect();
117 indexed.sort_by(|a, b| b.1.total_cmp(&a.1));
118 let mut ranks = vec![1usize; values.len()];
119 for (pos, (idx, _)) in indexed.into_iter().enumerate() {
120 ranks[idx] = pos + 1;
121 }
122 ranks
123}
124
125#[derive(Clone)]
126struct SlopeRow {
127 item: SlopeItem,
128 y0: f32,
129 y1: f32,
130 l0: f32,
131 l1: f32,
132 rank0: usize,
133 rank1: usize,
134 end_order: usize,
135}
136
137#[derive(Clone)]
138struct SlopeState {
139 focus_handle: FocusHandle,
140 own_active: Option<String>,
141 stage_bounds: Bounds<Pixels>,
142 reveal_spring: ChartSpring,
143 last_tick: f64,
144}
145
146type ChangeFormatter = Rc<dyn Fn(f64, &SlopeItem) -> String>;
147type ActiveChangeHandler = Rc<dyn Fn(Option<SharedString>, &mut Window, &mut App)>;
148
149#[derive(IntoElement)]
151pub struct SlopeChart {
152 id: ElementId,
153 data: Vec<SlopeItem>,
154 label: SharedString,
155 start_label: SharedString,
156 end_label: SharedString,
157 format_value: Option<Rc<dyn Fn(f64) -> String>>,
158 format_change: Option<ChangeFormatter>,
159 height: Option<f32>,
160 highlight_key: Option<SharedString>,
161 active_key: Option<Option<SharedString>>,
162 on_active_change: Option<ActiveChangeHandler>,
163 ranks: bool,
164 empty_label: SharedString,
165}
166
167impl SlopeChart {
168 pub fn new(
169 id: impl Into<ElementId>,
170 data: Vec<SlopeItem>,
171 label: impl Into<SharedString>,
172 start_label: impl Into<SharedString>,
173 end_label: impl Into<SharedString>,
174 ) -> Self {
175 Self {
176 id: id.into(),
177 data,
178 label: label.into(),
179 start_label: start_label.into(),
180 end_label: end_label.into(),
181 format_value: None,
182 format_change: None,
183 height: None,
184 highlight_key: None,
185 active_key: None,
186 on_active_change: None,
187 ranks: true,
188 empty_label: "No data".into(),
189 }
190 }
191
192 pub fn format_value(mut self, f: impl Fn(f64) -> String + 'static) -> Self {
193 self.format_value = Some(Rc::new(f));
194 self
195 }
196
197 pub fn format_change(mut self, f: impl Fn(f64, &SlopeItem) -> String + 'static) -> Self {
198 self.format_change = Some(Rc::new(f));
199 self
200 }
201
202 pub fn height(mut self, height: f32) -> Self {
203 self.height = Some(height.max(160.0));
204 self
205 }
206
207 pub fn highlight_key(mut self, key: impl Into<SharedString>) -> Self {
208 self.highlight_key = Some(key.into());
209 self
210 }
211
212 pub fn active_key(mut self, key: Option<impl Into<SharedString>>) -> Self {
213 self.active_key = Some(key.map(Into::into));
214 self
215 }
216
217 pub fn on_active_change(
218 mut self,
219 f: impl Fn(Option<SharedString>, &mut Window, &mut App) + 'static,
220 ) -> Self {
221 self.on_active_change = Some(Rc::new(f));
222 self
223 }
224
225 pub fn ranks(mut self, show: bool) -> Self {
226 self.ranks = show;
227 self
228 }
229
230 pub fn empty_label(mut self, label: impl Into<SharedString>) -> Self {
231 self.empty_label = label.into();
232 self
233 }
234
235 fn fmt_val(&self, v: f64) -> String {
236 if let Some(f) = &self.format_value {
237 f(v)
238 } else {
239 format_grouped(v, 1)
240 }
241 }
242
243 fn fmt_change(&self, item: &SlopeItem) -> String {
244 let delta = item.end - item.start;
245 if let Some(f) = &self.format_change {
246 f(delta, item)
247 } else {
248 let sign = if delta >= 0.0 { "+" } else { "−" };
249 format!("{sign}{}", self.fmt_val(delta.abs()))
250 }
251 }
252}
253
254impl RenderOnce for SlopeChart {
255 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
256 let theme = cx.arc_theme().clone();
257 let colors = theme.colors;
258 let reduced = is_reduced_motion(cx);
259 let now = motion_now(cx);
260
261 let empty = self.data.is_empty();
262 let plot_h = self
263 .height
264 .unwrap_or_else(|| (self.data.len() as f32 * 44.0).max(200.0));
265
266 let state = window.use_keyed_state(
267 ElementId::NamedChild(self.id.clone().into(), "__slope-state".into()),
268 cx,
269 |_w, cx| SlopeState {
270 focus_handle: cx.focus_handle(),
271 own_active: None,
272 stage_bounds: Bounds::default(),
273 reveal_spring: {
274 let mut sp = ChartSpring::new(if reduced { 1.0 } else { 0.0 });
275 sp.set_target(1.0);
276 sp
277 },
278 last_tick: now,
279 },
280 );
281
282 let mut running = false;
283 state.update(cx, |s, _cx| {
284 let dt = (now - s.last_tick).clamp(0.0, 0.05);
285 s.last_tick = now;
286 if reduced {
287 s.reveal_spring.snap(1.0);
288 } else if dt > 0.0 && !s.reveal_spring.is_settled() {
289 s.reveal_spring.step(0.76, 0.02, dt as f32);
290 }
291 running = !s.reveal_spring.is_settled();
292 });
293 if running {
294 window.request_animation_frame();
295 }
296
297 let snap = state.read(cx).clone();
298 let measured_w: f32 = snap.stage_bounds.size.width.into();
299 let stage_w = if measured_w > 120.0 {
300 measured_w
301 } else {
302 520.0
303 };
304 let narrow = stage_w < 440.0;
305 let left_room = if narrow { 132.0 } else { 172.0 };
306 let right_room = if self.ranks {
307 if narrow { 82.0 } else { 104.0 }
308 } else if narrow {
309 56.0
310 } else {
311 68.0
312 };
313 let x0 = left_room;
314 let x1 = (stage_w - right_room).max(x0 + 60.0);
315
316 let mut lo = f64::INFINITY;
318 let mut hi = f64::NEG_INFINITY;
319 for item in &self.data {
320 if item.start.is_finite() {
321 lo = lo.min(item.start);
322 hi = hi.max(item.start);
323 }
324 if item.end.is_finite() {
325 lo = lo.min(item.end);
326 hi = hi.max(item.end);
327 }
328 }
329 if !lo.is_finite() || !hi.is_finite() {
330 lo = 0.0;
331 hi = 1.0;
332 }
333 if (hi - lo).abs() < 1e-9 {
334 lo -= 1.0;
335 hi += 1.0;
336 }
337 let y_of = |v: f64| -> f32 {
338 let t = ((v - lo) / (hi - lo)).clamp(0.0, 1.0) as f32;
339 PLOT_PAD + (1.0 - t) * (plot_h - PLOT_PAD * 2.0)
340 };
341
342 let starts: Vec<f64> = self.data.iter().map(|d| d.start).collect();
343 let ends: Vec<f64> = self.data.iter().map(|d| d.end).collect();
344 let ranks0 = slope_ranks(&starts);
345 let ranks1 = slope_ranks(&ends);
346 let y0s: Vec<f32> = self.data.iter().map(|d| y_of(d.start)).collect();
347 let y1s: Vec<f32> = self.data.iter().map(|d| y_of(d.end)).collect();
348 let l0s = slope_spread_labels(&y0s, LABEL_GAP, 10.0, plot_h - 10.0);
349 let l1s = slope_spread_labels(&y1s, LABEL_GAP, 10.0, plot_h - 10.0);
350
351 let mut rows: Vec<SlopeRow> = self
352 .data
353 .iter()
354 .enumerate()
355 .map(|(i, item)| SlopeRow {
356 item: item.clone(),
357 y0: y0s[i],
358 y1: y1s[i],
359 l0: l0s[i],
360 l1: l1s[i],
361 rank0: ranks0[i],
362 rank1: ranks1[i],
363 end_order: 0,
364 })
365 .collect();
366
367 let mut by_end_indices: Vec<usize> = (0..rows.len()).collect();
368 by_end_indices.sort_by_key(|&i| rows[i].rank1);
369 for (ord, &idx) in by_end_indices.iter().enumerate() {
370 rows[idx].end_order = ord;
371 }
372 let by_end_keys: Vec<String> = by_end_indices
373 .iter()
374 .map(|&i| rows[i].item.key.to_string())
375 .collect();
376
377 let is_controlled = self.active_key.is_some();
378 let wanted_active = match &self.active_key {
379 Some(opt) => opt.as_ref().map(|s| s.to_string()),
380 None => snap.own_active.clone(),
381 };
382 let active_key = wanted_active.filter(|k| self.data.iter().any(|d| d.key.as_ref() == k));
383 let active_row = active_key
384 .as_deref()
385 .and_then(|k| rows.iter().find(|r| r.item.key.as_ref() == k))
386 .cloned();
387
388 let reveal_p = snap.reveal_spring.position().clamp(0.0, 1.0);
389 let highlight_key = self.highlight_key.as_ref().map(|s| s.to_string());
390
391 let canvas_state = state.clone();
393 let canvas_rows = rows.clone();
394 let canvas_active = active_key.clone();
395 let canvas_highlight = highlight_key.clone();
396 let axis_color = colors.border;
397 let muted_line = oklab_mix(colors.foreground, colors.surface, 0.38);
398 let accent_color = colors.series.series_1;
399 let fg_color = colors.foreground;
400 let surface_color = colors.surface;
401
402 let plot_canvas = canvas(
403 move |bounds, _w, cx| {
404 canvas_state.update(cx, |s, _cx| {
405 s.stage_bounds = bounds;
406 });
407 },
408 move |bounds, _, window, _cx| {
409 let ox: f32 = bounds.origin.x.into();
410 let oy: f32 = bounds.origin.y.into();
411
412 for ax in [x0, x1] {
414 if let Some(p) = build_polyline_stroke(
415 &[
416 point(px(ox + ax), px(oy)),
417 point(px(ox + ax), px(oy + plot_h)),
418 ],
419 1.0,
420 ) {
421 window.paint_path(p, axis_color.opacity(0.75));
422 }
423 }
424
425 let mut draw_indices: Vec<usize> = (0..canvas_rows.len()).collect();
427 draw_indices.sort_by_key(|&i| {
428 if canvas_active.as_deref() == Some(canvas_rows[i].item.key.as_ref()) {
429 2u8
430 } else if canvas_highlight.as_deref() == Some(canvas_rows[i].item.key.as_ref())
431 {
432 1u8
433 } else {
434 0u8
435 }
436 });
437
438 for idx in draw_indices {
439 let row = &canvas_rows[idx];
440 let is_on = canvas_active.as_deref() == Some(row.item.key.as_ref());
441 let is_accent = canvas_highlight.as_deref() == Some(row.item.key.as_ref());
442 let is_dim = canvas_active.is_some() && !is_on;
443
444 let delay = (idx as f32 * 0.04).min(0.24);
445 let line_p = ((reveal_p - delay) / (1.0 - delay).max(0.01)).clamp(0.0, 1.0);
446
447 let stroke_col = if is_accent {
448 accent_color
449 } else if is_on {
450 fg_color
451 } else {
452 muted_line
453 };
454 let alpha = if is_dim { 0.22 } else { 1.0 };
455 let stroke_w = if is_on || is_accent { 2.4 } else { 1.5 };
456
457 if (row.l0 - row.y0).abs() > 1.5
459 && let Some(p) = build_polyline_stroke(
460 &[
461 point(px(ox + x0 - 7.0), px(oy + row.l0)),
462 point(px(ox + x0 - 2.0), px(oy + row.y0)),
463 ],
464 1.0,
465 )
466 {
467 window.paint_path(p, stroke_col.opacity(alpha * 0.45));
468 }
469 if (row.l1 - row.y1).abs() > 1.5
470 && let Some(p) = build_polyline_stroke(
471 &[
472 point(px(ox + x1 + 7.0), px(oy + row.l1)),
473 point(px(ox + x1 + 2.0), px(oy + row.y1)),
474 ],
475 1.0,
476 )
477 {
478 window.paint_path(p, stroke_col.opacity(alpha * 0.45));
479 }
480
481 let full_seg = [
483 point(px(ox + x0), px(oy + row.y0)),
484 point(px(ox + x1), px(oy + row.y1)),
485 ];
486 let drawn_seg = slice_polyline_by_progress(&full_seg, line_p);
487 if let Some(p) = build_polyline_stroke(&drawn_seg, stroke_w) {
488 window.paint_path(p, stroke_col.opacity(alpha));
489 }
490
491 let dot_r = if is_on {
493 4.8
494 } else if is_accent {
495 4.2
496 } else {
497 3.6
498 };
499 if line_p > 0.02 {
500 if let Some(c) = build_circle_fill(ox + x0, oy + row.y0, dot_r + 1.2, 16) {
501 window.paint_path(c, surface_color);
502 }
503 if let Some(c) = build_circle_fill(ox + x0, oy + row.y0, dot_r, 16) {
504 window.paint_path(c, stroke_col.opacity(alpha));
505 }
506 }
507 if line_p > 0.85 {
508 let end_scale = ((line_p - 0.85) / 0.15).clamp(0.0, 1.0);
509 if let Some(c) =
510 build_circle_fill(ox + x1, oy + row.y1, (dot_r + 1.2) * end_scale, 16)
511 {
512 window.paint_path(c, surface_color);
513 }
514 if let Some(c) =
515 build_circle_fill(ox + x1, oy + row.y1, dot_r * end_scale, 16)
516 {
517 window.paint_path(c, stroke_col.opacity(alpha));
518 }
519 }
520 }
521 },
522 )
523 .w_full()
524 .h(px(plot_h));
525
526 let hit_rows = rows.clone();
528 let on_active = self.on_active_change.clone();
529 let move_state = state.clone();
530 let move_cb = on_active.clone();
531 let click_state = state.clone();
532 let key_state = state.clone();
533 let key_cb = on_active.clone();
534
535 let nearest_key = move |lx: f32, ly: f32| -> Option<String> {
536 let clamped_x = lx.clamp(x0, x1);
537 let t = (clamped_x - x0) / (x1 - x0).max(1.0);
538 let mut best: Option<&SlopeRow> = None;
539 let mut best_dist = f32::INFINITY;
540 for row in &hit_rows {
541 let y_line = row.y0 + (row.y1 - row.y0) * t;
542 let d_line = (y_line - ly).abs();
543 let d_label = if lx < x0 {
544 (row.l0 - ly).abs()
545 } else if lx > x1 {
546 (row.l1 - ly).abs()
547 } else {
548 f32::INFINITY
549 };
550 let d = d_line.min(d_label);
551 if d < best_dist {
552 best_dist = d;
553 best = Some(row);
554 }
555 }
556 if best_dist <= 22.0 {
557 best.map(|r| r.item.key.to_string())
558 } else {
559 None
560 }
561 };
562
563 let nearest_for_down = nearest_key.clone();
564
565 let header = div()
567 .relative()
568 .w_full()
569 .h(px(HEAD_H))
570 .child(
571 div()
572 .absolute()
573 .left(px((x0 - 44.0).max(0.0)))
574 .top(px(4.0))
575 .w(px(88.0))
576 .flex()
577 .justify_center()
578 .text_size(Typography::TEXT_XS)
579 .font_semibold()
580 .text_color(colors.text_muted)
581 .child(self.start_label.clone()),
582 )
583 .child(
584 div()
585 .absolute()
586 .left(px((x1 - 44.0).max(0.0)))
587 .top(px(4.0))
588 .w(px(88.0))
589 .flex()
590 .justify_center()
591 .text_size(Typography::TEXT_XS)
592 .font_semibold()
593 .text_color(colors.text_muted)
594 .child(self.end_label.clone()),
595 );
596
597 let mut plot = div().relative().w_full().h(px(plot_h)).child(plot_canvas);
599
600 for row in &rows {
601 let is_on = active_key.as_deref() == Some(row.item.key.as_ref());
602 let is_accent = highlight_key.as_deref() == Some(row.item.key.as_ref());
603 let is_dim = active_key.is_some() && !is_on;
604 let opacity = reveal_p * if is_dim { 0.30 } else { 1.0 };
605 let text_col = if is_accent {
606 accent_color
607 } else {
608 colors.foreground
609 };
610
611 plot = plot.child(
613 div()
614 .absolute()
615 .left(px(0.0))
616 .top(px(row.l0 - 9.0))
617 .w(px((x0 - 12.0).max(40.0)))
618 .h(px(18.0))
619 .flex()
620 .items_center()
621 .justify_end()
622 .gap(px(6.0))
623 .opacity(opacity)
624 .child(
625 div()
626 .text_size(Typography::TEXT_XS)
627 .when(is_on || is_accent, |this| this.font_semibold())
628 .text_color(text_col)
629 .truncate()
630 .child(row.item.label.clone()),
631 )
632 .child(
633 div()
634 .text_size(Typography::TEXT_XS)
635 .font_medium()
636 .text_color(colors.text_muted)
637 .flex_shrink_0()
638 .child(self.fmt_val(row.item.start)),
639 ),
640 );
641
642 let move_delta = row.rank0 as isize - row.rank1 as isize;
644 let mut end_row = div()
645 .absolute()
646 .left(px(x1 + 12.0))
647 .top(px(row.l1 - 9.0))
648 .h(px(18.0))
649 .flex()
650 .items_center()
651 .gap(px(6.0))
652 .opacity(opacity)
653 .child(
654 div()
655 .text_size(Typography::TEXT_XS)
656 .font_medium()
657 .when(is_on || is_accent, |this| this.font_semibold())
658 .text_color(text_col)
659 .child(self.fmt_val(row.item.end)),
660 );
661
662 if self.ranks {
663 let (badge_text, badge_color) = if move_delta > 0 {
664 (format!("↑{move_delta}"), colors.success)
665 } else if move_delta < 0 {
666 (format!("↓{}", move_delta.abs()), colors.danger)
667 } else {
668 ("=".to_string(), colors.text_muted)
669 };
670 end_row = end_row.child(
671 div()
672 .text_size(px(11.0))
673 .font_medium()
674 .text_color(badge_color)
675 .child(badge_text),
676 );
677 }
678
679 plot = plot.child(end_row);
680 }
681
682 if let Some(row) = &active_row {
684 let mid_y = (row.y0 + row.y1) * 0.5;
685 let mid_x = (x0 + x1) * 0.5;
686 let tip_w = 188.0f32;
687 let tip_h = 84.0f32;
688 let left = (mid_x - tip_w * 0.5).clamp(4.0, (stage_w - tip_w - 4.0).max(4.0));
689 let top = if mid_y - tip_h - 14.0 >= 0.0 {
690 mid_y - tip_h - 14.0
691 } else {
692 (mid_y + 14.0).min((plot_h - tip_h).max(0.0))
693 };
694 let rank_note = if row.rank0 == row.rank1 {
695 format!("Rank #{} (unchanged)", row.rank1)
696 } else if row.rank1 < row.rank0 {
697 format!("↑{} to rank #{}", row.rank0 - row.rank1, row.rank1)
698 } else {
699 format!("↓{} to rank #{}", row.rank1 - row.rank0, row.rank1)
700 };
701
702 plot = plot.child(
703 div()
704 .absolute()
705 .left(px(left))
706 .top(px(top))
707 .w(px(tip_w))
708 .px(Spacing::S3)
709 .py(Spacing::S2)
710 .rounded(Radii::CONTROL)
711 .bg(colors.surface_raised)
712 .border_1()
713 .border_color(colors.border)
714 .shadow_md()
715 .flex()
716 .flex_col()
717 .gap(px(2.0))
718 .child(
719 div()
720 .text_size(Typography::TEXT_XS)
721 .font_semibold()
722 .text_color(colors.foreground)
723 .child(row.item.label.clone()),
724 )
725 .child(
726 div()
727 .flex()
728 .items_center()
729 .justify_between()
730 .text_size(px(11.0))
731 .child(
732 div()
733 .text_color(colors.text_muted)
734 .child(self.start_label.clone()),
735 )
736 .child(
737 div()
738 .font_medium()
739 .text_color(colors.foreground)
740 .child(self.fmt_val(row.item.start)),
741 ),
742 )
743 .child(
744 div()
745 .flex()
746 .items_center()
747 .justify_between()
748 .text_size(px(11.0))
749 .child(
750 div()
751 .text_color(colors.text_muted)
752 .child(self.end_label.clone()),
753 )
754 .child(
755 div()
756 .font_medium()
757 .text_color(colors.foreground)
758 .child(self.fmt_val(row.item.end)),
759 ),
760 )
761 .child(
762 div()
763 .pt(px(2.0))
764 .text_size(px(11.0))
765 .text_color(colors.text_muted)
766 .child(format!("{}, {}", self.fmt_change(&row.item), rank_note)),
767 ),
768 );
769 }
770
771 if empty {
772 plot = plot.child(
773 div()
774 .absolute()
775 .inset_0()
776 .flex()
777 .items_center()
778 .justify_center()
779 .text_size(px(13.0))
780 .text_color(colors.text_muted)
781 .child(self.empty_label.clone()),
782 );
783 }
784
785 let active_order = active_row.as_ref().map(|r| r.end_order);
786
787 div()
788 .id(self.id)
789 .role(Role::Group)
790 .aria_label(self.label)
791 .track_focus(&snap.focus_handle)
792 .w_full()
793 .flex()
794 .flex_col()
795 .on_mouse_move(move |ev: &MouseMoveEvent, window, cx| {
796 let (in_bounds, next) = {
797 let s = move_state.read(cx);
798 let b = s.stage_bounds;
799 let lx: f32 = (ev.position.x - b.origin.x).into();
800 let ly: f32 = (ev.position.y - b.origin.y).into();
801 let bw: f32 = b.size.width.into();
802 let bh: f32 = b.size.height.into();
803 if lx < 0.0 || ly < 0.0 || lx > bw || ly > bh {
804 (false, None)
805 } else {
806 (true, nearest_key(lx, ly))
807 }
808 };
809 let prev = move_state.read(cx).own_active.clone();
810 if (!in_bounds && prev.is_some()) || (in_bounds && prev != next) {
811 if !is_controlled {
812 move_state.update(cx, |s, cx| {
813 s.own_active = next.clone();
814 cx.notify();
815 });
816 }
817 if let Some(cb) = &move_cb {
818 cb(next.map(SharedString::from), window, cx);
819 }
820 }
821 })
822 .on_mouse_down(MouseButton::Left, move |ev: &MouseDownEvent, window, cx| {
823 let fh = click_state.read(cx).focus_handle.clone();
824 window.focus(&fh, cx);
825 let next = {
826 let s = click_state.read(cx);
827 let b = s.stage_bounds;
828 let lx: f32 = (ev.position.x - b.origin.x).into();
829 let ly: f32 = (ev.position.y - b.origin.y).into();
830 nearest_for_down(lx, ly)
831 };
832 if !is_controlled {
833 click_state.update(cx, |s, cx| {
834 s.own_active = next;
835 cx.notify();
836 });
837 }
838 })
839 .on_key_down(move |ev: &KeyDownEvent, window, cx| {
840 if by_end_keys.is_empty() {
841 return;
842 }
843 let key = ev.keystroke.key.as_str();
844 if key == "escape" {
845 if !is_controlled {
846 key_state.update(cx, |s, cx| {
847 s.own_active = None;
848 cx.notify();
849 });
850 }
851 if let Some(cb) = &key_cb {
852 cb(None, window, cx);
853 }
854 return;
855 }
856 let last = by_end_keys.len() - 1;
857 let next_idx = match key {
858 "down" | "right" => Some(match active_order {
859 Some(o) => (o + 1).min(last),
860 None => 0,
861 }),
862 "up" | "left" => Some(match active_order {
863 Some(o) => o.saturating_sub(1),
864 None => 0,
865 }),
866 "home" => Some(0),
867 "end" => Some(last),
868 _ => None,
869 };
870 if let Some(i) = next_idx {
871 cx.stop_propagation();
872 let k = by_end_keys[i].clone();
873 if !is_controlled {
874 key_state.update(cx, |s, cx| {
875 s.own_active = Some(k.clone());
876 cx.notify();
877 });
878 }
879 if let Some(cb) = &key_cb {
880 cb(Some(SharedString::from(k)), window, cx);
881 }
882 }
883 })
884 .child(header)
885 .child(plot)
886 }
887}
888
889#[cfg(test)]
890mod tests {
891 use super::*;
892
893 #[test]
894 fn slope_label_spreading_and_rank_deltas() {
895 let spread = slope_spread_labels(&[50.0, 52.0, 150.0], 20.0, 8.0, 200.0);
897 assert!((spread[1] - spread[0]) >= 19.9);
898 assert!((spread[2] - 150.0).abs() < 1e-4);
899
900 let r0 = slope_ranks(&[10.0, 40.0, 25.0]);
901 assert_eq!(r0, vec![3, 1, 2]);
902 let r1 = slope_ranks(&[50.0, 30.0, 25.0]);
903 assert_eq!(r1, vec![1, 2, 3]);
904 }
905}