1use std::cell::{Cell, RefCell};
9use std::fmt;
10use std::hash::Hash;
11use std::rc::Rc;
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use crate::layout::layout_ext::{apply_layout_size, finish_view_sized, LayoutExt};
16use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
17use ailloli_ui_core::event::{Event, Key, KeyEvent, KeyState, NamedKey};
18use ailloli_ui_core::geometry::{Constraints, Rect, Size};
19use ailloli_ui_core::style::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
20use ailloli_ui_core::{Color, FontId, IconId, Point, TextStyle, Theme};
21use ailloli_ui_runtime::component::{
22 Binding, ComponentNode, Context, IntoView, Signal, View, Widget,
23};
24use ailloli_ui_runtime::input::{EventCtx, FocusPolicy, InputRole};
25use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
26use ailloli_ui_runtime::scene::PaintCtx;
27use ailloli_ui_runtime::{
28 DrawBorder, DrawCmd, DrawImage, DrawRRect, DrawRect, DrawText, Invalidation,
29};
30use ailloli_ui_text::{
31 PreparedTextLayout, TextBuffer, TextEditState, TextLayoutParams, TextSelection, WrapMode,
32};
33use lucide_icons::Icon as LucideIcon;
34
35use super::text_field_core::{
36 handle_single_line_text_event, ime_cursor_rect, paint_single_line_text, TextFieldEventOptions,
37};
38use super::text_input::TextInputStyle;
39use super::tree_model::{TreeModelHandle, TreeModelSubscription, TreeMutation};
40use crate::transactional_layout::TransactionalLayoutPending;
41
42const TREE_ACTIVATE_MAX_DELAY: Duration = Duration::from_millis(500);
44const TREE_ACTIVATE_MAX_DISTANCE: f32 = 4.0;
46const TREE_VIRTUAL_OVERSCAN_ROWS: usize = 8;
48
49#[derive(Clone, Default)]
62pub struct TreeViewDiagnostics {
63 inner: Rc<RefCell<TreeViewDiagnosticsSnapshot>>,
65}
66
67#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
68pub struct TreeViewDiagnosticsSnapshot {
81 pub layout_calls: u64,
83 pub paint_calls: u64,
85 pub hit_tests: u64,
87 pub loaded_rows: usize,
89 pub visible_rows: usize,
91 pub layout_rows_visited: u64,
93 pub paint_rows_visited: u64,
95 pub hit_test_rows_visited: u64,
97 pub flatten_rebuilds: u64,
99 pub snapshot_rows_cloned: u64,
101 pub text_measurements: u64,
103 pub virtualization_fallbacks: u64,
105}
106
107impl TreeViewDiagnostics {
108 pub fn new() -> Self {
117 Self::default()
118 }
119
120 pub fn snapshot(&self) -> TreeViewDiagnosticsSnapshot {
134 *self.inner.borrow()
135 }
136
137 fn update(&self, update: impl FnOnce(&mut TreeViewDiagnosticsSnapshot)) {
139 update(&mut self.inner.borrow_mut());
140 }
141}
142
143#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
144pub enum TreeViewSize {
154 Compact,
156 #[default]
157 Default,
159}
160
161#[derive(Clone, Debug, PartialEq)]
162pub struct TreeViewStyle {
175 pub background: Color,
177 pub selected_background: Color,
179 pub active_background: Color,
181 pub hover_background: Color,
183 pub pressed_background: Color,
185 pub drop_indicator: Color,
187 pub drop_inside_background: Color,
189 pub editing_background: Color,
191 pub editing_border: Color,
193 pub text: TextStyle,
195 pub selected_text: TextStyle,
197 pub disabled_text: TextStyle,
199 pub icon_tint: Color,
201 pub selected_icon_tint: Color,
203 pub chevron_tint: Color,
205 pub focus_ring: Border,
207 pub radius: Radius,
209 pub row_height: f32,
211 pub padding_x: f32,
213 pub padding_y: f32,
215 pub indent: f32,
217 pub gap: f32,
219 pub icon_size: f32,
221 pub chevron_size: f32,
223 pub disabled_opacity: f32,
225}
226
227impl Default for TreeViewStyle {
228 fn default() -> Self {
229 Self::from_theme(Theme::default(), TreeViewSize::Default)
230 }
231}
232
233impl TreeViewStyle {
234 pub fn from_theme(theme: Theme, size: TreeViewSize) -> Self {
248 let palette = theme.palette();
249 let (row_height, padding_x, padding_y, indent, text_size) = match size {
250 TreeViewSize::Compact => (24.0, 8.0, 4.0, 16.0, 12),
251 TreeViewSize::Default => (28.0, 10.0, 6.0, 18.0, 13),
252 };
253 Self {
254 background: Color::TRANSPARENT,
255 selected_background: palette.accent.with_alpha(0.18),
256 active_background: palette.accent.with_alpha(0.10),
257 hover_background: palette.surface_elevated,
258 pressed_background: Color::hex_rgb(0x20252A),
259 drop_indicator: palette.accent,
260 drop_inside_background: palette.accent.with_alpha(0.12),
261 editing_background: palette.surface,
262 editing_border: palette.focus,
263 text: TextStyle::new(FontId::Ui, text_size, palette.text),
264 selected_text: TextStyle::new(FontId::Ui, text_size, palette.text),
265 disabled_text: TextStyle::new(
266 FontId::Ui,
267 text_size,
268 palette.text_muted.with_alpha(0.70),
269 ),
270 icon_tint: palette.text_muted,
271 selected_icon_tint: palette.accent,
272 chevron_tint: palette.text_muted,
273 focus_ring: Border::new(1.0, palette.focus),
274 radius: Radius::uniform(theme.radius().md),
275 row_height,
276 padding_x,
277 padding_y,
278 indent,
279 gap: 6.0,
280 icon_size: 16.0,
281 chevron_size: 14.0,
282 disabled_opacity: 0.42,
283 }
284 }
285}
286
287#[derive(Debug, Clone, Copy, PartialEq, Eq)]
288pub enum TreeDropPosition {
297 Before,
299 After,
301 Inside,
303}
304
305#[derive(Debug, Clone, PartialEq, Eq)]
306pub struct TreeMove<T> {
316 pub source: T,
318 pub target: T,
320 pub position: TreeDropPosition,
322}
323
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325pub enum TreeMutationMode {
334 ApplyLocal,
336 IntentOnly,
338}
339
340#[derive(Debug, Clone, PartialEq, Eq)]
341pub enum TreeShortcut<T> {
353 Delete {
355 id: T,
357 },
358 Copy {
360 id: T,
362 },
363 Cut {
365 id: T,
367 },
368 Paste {
370 id: Option<T>,
372 },
373}
374
375#[derive(Debug, Clone, PartialEq, Eq)]
376pub struct TreeRename<T> {
386 pub id: T,
388 pub old_label: String,
390 pub new_label: String,
392}
393
394#[derive(Debug, Clone, Copy, PartialEq, Eq)]
395pub enum TreeCreateKind {
404 SiblingAfter,
406 Child,
408}
409
410#[derive(Debug, Clone, PartialEq, Eq)]
411pub struct TreeCreateRequest<T> {
421 pub parent: Option<T>,
423 pub after: Option<T>,
425 pub kind: TreeCreateKind,
427 pub default_label: String,
429}
430
431#[derive(Debug, Clone, PartialEq, Eq)]
432pub struct TreeCreate<T> {
442 pub id: T,
444 pub parent: Option<T>,
446 pub after: Option<T>,
448 pub kind: TreeCreateKind,
450 pub label: String,
452}
453
454#[derive(Debug, Clone, PartialEq, Eq)]
455pub struct TreeCreateCancel<T> {
466 pub id: T,
468 pub request: TreeCreateRequest<T>,
470}
471
472#[derive(Debug, Clone, PartialEq, Eq)]
473pub struct TreeDelete<T> {
483 pub id: T,
485 pub parent: Option<T>,
487}
488
489#[derive(Debug, Clone, PartialEq)]
490pub enum TreeContextMenu<T> {
501 Row {
503 row_id: T,
505 pointer_position: Point,
507 row_rect: Rect,
509 },
510 Blank {
512 pointer_position: Point,
514 },
515}
516
517#[derive(Debug, Clone, PartialEq, Eq)]
518pub enum TreeViewCommand<T> {
531 BeginRename(T),
533 BeginCreate(TreeCreateRequest<T>),
535}
536
537#[derive(Debug, Clone, PartialEq, Eq)]
538pub struct TreeNodeTrailingAction {
549 pub icon: IconId,
551 pub tooltip: Option<String>,
553}
554
555impl TreeNodeTrailingAction {
556 pub fn new(icon: IconId) -> Self {
566 Self {
567 icon,
568 tooltip: None,
569 }
570 }
571
572 pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self {
583 self.tooltip = Some(tooltip.into());
584 self
585 }
586}
587
588#[derive(Clone)]
589pub struct TreeNode<T> {
602 id: T,
604 label: String,
606 branch: bool,
608 children: Vec<TreeNode<T>>,
610 disabled: Binding<bool>,
612 leading_icon: Option<IconId>,
614 leading_icon_tint: Option<Color>,
616 trailing_action: Option<TreeNodeTrailingAction>,
618 transient: bool,
620}
621
622impl<T> TreeNode<T> {
623 pub fn branch(id: T, label: impl Into<String>) -> Self {
633 Self {
634 id,
635 label: label.into(),
636 branch: true,
637 children: Vec::new(),
638 disabled: Binding::Static(false),
639 leading_icon: None,
640 leading_icon_tint: None,
641 trailing_action: None,
642 transient: false,
643 }
644 }
645
646 pub fn leaf(id: T, label: impl Into<String>) -> Self {
656 Self {
657 id,
658 label: label.into(),
659 branch: false,
660 children: Vec::new(),
661 disabled: Binding::Static(false),
662 leading_icon: None,
663 leading_icon_tint: None,
664 trailing_action: None,
665 transient: false,
666 }
667 }
668
669 pub fn child(mut self, child: TreeNode<T>) -> Self {
679 self.branch = true;
680 self.children.push(child);
681 self
682 }
683
684 pub fn children(mut self, children: impl IntoIterator<Item = TreeNode<T>>) -> Self {
697 let children = children.into_iter().collect::<Vec<_>>();
698 if !children.is_empty() {
699 self.branch = true;
700 }
701 self.children.extend(children);
702 self
703 }
704
705 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
717 self.disabled = disabled.into();
718 self
719 }
720
721 pub fn leading_icon(mut self, icon: IconId) -> Self {
732 self.leading_icon = Some(icon);
733 self
734 }
735
736 pub fn leading_icon_tint(mut self, color: Color) -> Self {
747 self.leading_icon_tint = Some(color);
748 self
749 }
750
751 pub fn transient(mut self, transient: bool) -> Self {
762 self.transient = transient;
763 self
764 }
765
766 pub fn trailing_action(mut self, icon: IconId) -> Self {
779 self.trailing_action = Some(TreeNodeTrailingAction::new(icon));
780 self
781 }
782
783 pub fn trailing_action_with_tooltip(
796 mut self,
797 icon: IconId,
798 tooltip: impl Into<String>,
799 ) -> Self {
800 self.trailing_action = Some(TreeNodeTrailingAction::new(icon).tooltip(tooltip));
801 self
802 }
803
804 pub fn id(&self) -> &T {
813 &self.id
814 }
815
816 pub fn label(&self) -> &str {
825 &self.label
826 }
827
828 pub fn child_nodes(&self) -> &[TreeNode<T>] {
837 &self.children
838 }
839
840 pub fn is_transient(&self) -> bool {
849 self.transient
850 }
851
852 pub fn trailing_action_ref(&self) -> Option<&TreeNodeTrailingAction> {
861 self.trailing_action.as_ref()
862 }
863}
864
865type TreeSelectHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T)>;
867type TreeActivateHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T)>;
869type TreeToggleHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T, bool)>;
871type TreeTrailingActionHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T)>;
873type TreeMoveHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, TreeMove<T>)>;
875type TreeRenameHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, TreeRename<T>)>;
877type TreeCreateHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, TreeCreate<T>)>;
879type TreeCreateCancelHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, TreeCreateCancel<T>)>;
881type TreeDeleteHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, TreeDelete<T>)>;
883type TreeContextMenuHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, TreeContextMenu<T>)>;
885type TreeShortcutHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, TreeShortcut<T>)>;
887type TreeCreateFactory<T> = Rc<dyn Fn(TreeCreateRequest<T>) -> Option<TreeNode<T>>>;
889
890trait RetainedTreeSource<T> {
892 fn visible_len(&self) -> usize;
894 fn flat_node_at(&self, index: usize) -> Option<FlatNode<T>>;
896 fn row_of(&self, id: &T) -> Option<usize>;
898 fn first_enabled_row(&self) -> Option<usize>;
900 fn is_expanded(&self, id: &T) -> bool;
902 fn set_expanded(&self, id: T, expanded: bool) -> bool;
904 fn subscribe(&self, callback: &Rc<dyn Fn(u64)>) -> TreeModelSubscription;
906 fn flatten_rebuilds(&self) -> u64;
908}
909
910impl<T> RetainedTreeSource<T> for TreeModelHandle<T>
911where
912 T: Clone + Eq + Hash + fmt::Debug + 'static,
913{
914 fn visible_len(&self) -> usize {
916 self.read(|model| model.visible_len())
917 }
918
919 fn flat_node_at(&self, index: usize) -> Option<FlatNode<T>> {
921 self.read(|model| {
922 let row = model.flat_index().rows().get(index)?;
923 let item = model.item(row.node_id())?;
924 Some(FlatNode {
925 id: item.id().clone(),
926 label: item.label().to_string(),
927 depth: usize::from(row.depth()),
928 branch: item.is_branch(),
929 disabled: item.is_disabled(),
930 leading_icon: item.leading_icon_ref().cloned(),
931 leading_icon_tint: item.leading_icon_tint_ref(),
932 trailing_action: item.trailing_action_ref().cloned(),
933 parent: model.parent(item.id()).cloned(),
934 })
935 })
936 }
937
938 fn row_of(&self, id: &T) -> Option<usize> {
940 self.read(|model| model.flat_index().row_of(id))
941 }
942
943 fn first_enabled_row(&self) -> Option<usize> {
945 self.read(|model| model.flat_index().first_enabled_row())
946 }
947
948 fn is_expanded(&self, id: &T) -> bool {
950 self.read(|model| model.is_expanded(id))
951 }
952
953 fn set_expanded(&self, id: T, expanded: bool) -> bool {
955 self.apply(TreeMutation::SetExpanded { id, expanded })
956 .is_ok()
957 }
958
959 fn subscribe(&self, callback: &Rc<dyn Fn(u64)>) -> TreeModelSubscription {
961 TreeModelHandle::subscribe(self, callback)
962 }
963
964 fn flatten_rebuilds(&self) -> u64 {
966 self.read(|model| model.flat_index().rebuilds())
967 }
968}
969
970pub struct TreeView<T, A = ()> {
985 pub(crate) layout: LayoutStyle,
987 pub(crate) flex_item: FlexItemStyle,
989 nodes: Vec<TreeNode<T>>,
991 bound_nodes: Option<Signal<Vec<TreeNode<T>>>>,
993 model: Option<Rc<dyn RetainedTreeSource<T>>>,
995 selected: Option<Binding<T>>,
997 bound_selected: Option<Signal<T>>,
999 expanded: Option<Binding<Vec<T>>>,
1001 bound_expanded: Option<Signal<Vec<T>>>,
1003 command: Option<Signal<Option<TreeViewCommand<T>>>>,
1005 default_expanded: Vec<T>,
1007 disabled: Binding<bool>,
1009 draggable: Binding<bool>,
1011 mutation_mode: Binding<TreeMutationMode>,
1013 editable: Binding<bool>,
1015 deletable: Binding<bool>,
1017 creatable: Binding<bool>,
1019 create_node: Option<TreeCreateFactory<T>>,
1021 on_select: Option<TreeSelectHandler<T, A>>,
1023 on_activate: Option<TreeActivateHandler<T, A>>,
1025 on_toggle: Option<TreeToggleHandler<T, A>>,
1027 on_trailing_action: Option<TreeTrailingActionHandler<T, A>>,
1029 on_move: Option<TreeMoveHandler<T, A>>,
1031 on_rename: Option<TreeRenameHandler<T, A>>,
1033 on_create: Option<TreeCreateHandler<T, A>>,
1035 on_create_cancel: Option<TreeCreateCancelHandler<T, A>>,
1037 on_delete: Option<TreeDeleteHandler<T, A>>,
1039 on_context_menu: Option<TreeContextMenuHandler<T, A>>,
1041 on_shortcut: Option<TreeShortcutHandler<T, A>>,
1043 style: TreeViewStyle,
1045 virtualized: bool,
1047 diagnostics: Option<TreeViewDiagnostics>,
1049}
1050
1051impl<T: Clone + PartialEq + 'static, A: 'static> Default for TreeView<T, A> {
1052 fn default() -> Self {
1053 Self::new()
1054 }
1055}
1056
1057impl<T: Clone + PartialEq + 'static, A: 'static> LayoutExt for TreeView<T, A> {
1058 fn layout_mut(&mut self) -> &mut LayoutStyle {
1060 &mut self.layout
1061 }
1062}
1063
1064impl<T: Clone + PartialEq + 'static, A: 'static> TreeView<T, A> {
1065 pub fn new() -> Self {
1078 Self {
1079 layout: LayoutStyle::default(),
1080 flex_item: FlexItemStyle::default(),
1081 nodes: Vec::new(),
1082 bound_nodes: None,
1083 model: None,
1084 selected: None,
1085 bound_selected: None,
1086 expanded: None,
1087 bound_expanded: None,
1088 command: None,
1089 default_expanded: Vec::new(),
1090 disabled: Binding::Static(false),
1091 draggable: Binding::Static(false),
1092 mutation_mode: Binding::Static(TreeMutationMode::ApplyLocal),
1093 editable: Binding::Static(false),
1094 deletable: Binding::Static(false),
1095 creatable: Binding::Static(false),
1096 create_node: None,
1097 on_select: None,
1098 on_activate: None,
1099 on_toggle: None,
1100 on_trailing_action: None,
1101 on_move: None,
1102 on_rename: None,
1103 on_create: None,
1104 on_create_cancel: None,
1105 on_delete: None,
1106 on_context_menu: None,
1107 on_shortcut: None,
1108 style: TreeViewStyle::default(),
1109 virtualized: false,
1110 diagnostics: None,
1111 }
1112 }
1113
1114 pub fn node(mut self, node: TreeNode<T>) -> Self {
1126 self.nodes.push(node);
1127 self
1128 }
1129
1130 pub fn nodes(mut self, nodes: impl IntoIterator<Item = TreeNode<T>>) -> Self {
1140 self.nodes.extend(nodes);
1141 self
1142 }
1143
1144 pub fn bind_nodes(mut self, nodes: impl Into<Signal<Vec<TreeNode<T>>>>) -> Self {
1159 self.bound_nodes = Some(nodes.into());
1160 self
1161 }
1162
1163 pub fn model(mut self, model: TreeModelHandle<T>) -> Self
1178 where
1179 T: Eq + Hash + fmt::Debug,
1180 {
1181 self.model = Some(Rc::new(model));
1182 self
1183 }
1184
1185 pub fn selected(mut self, selected: impl Into<Binding<T>>) -> Self {
1199 self.selected = Some(selected.into());
1200 self
1201 }
1202
1203 pub fn bind_selected(mut self, selected: impl Into<Signal<T>>) -> Self {
1216 let signal = selected.into();
1217 self.selected = Some(Binding::Signal(signal.clone()));
1218 self.bound_selected = Some(signal);
1219 self
1220 }
1221
1222 pub fn expanded(mut self, expanded: impl Into<Binding<Vec<T>>>) -> Self {
1235 self.expanded = Some(expanded.into());
1236 self
1237 }
1238
1239 pub fn bind_expanded(mut self, expanded: impl Into<Signal<Vec<T>>>) -> Self {
1252 let signal = expanded.into();
1253 self.expanded = Some(Binding::Signal(signal.clone()));
1254 self.bound_expanded = Some(signal);
1255 self
1256 }
1257
1258 pub fn bind_command(mut self, command: impl Into<Signal<Option<TreeViewCommand<T>>>>) -> Self {
1273 self.command = Some(command.into());
1274 self
1275 }
1276
1277 pub fn default_expanded(mut self, id: T) -> Self {
1289 if !self.default_expanded.iter().any(|open| open == &id) {
1290 self.default_expanded.push(id);
1291 }
1292 self
1293 }
1294
1295 pub fn default_expanded_many(mut self, ids: impl IntoIterator<Item = T>) -> Self {
1305 self.default_expanded.clear();
1306 for id in ids {
1307 if !self.default_expanded.iter().any(|open| open == &id) {
1308 self.default_expanded.push(id);
1309 }
1310 }
1311 self
1312 }
1313
1314 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
1326 self.disabled = disabled.into();
1327 self
1328 }
1329
1330 pub fn draggable(mut self, draggable: impl Into<Binding<bool>>) -> Self {
1342 self.draggable = draggable.into();
1343 self
1344 }
1345
1346 pub fn mutation_mode(mut self, mode: impl Into<Binding<TreeMutationMode>>) -> Self {
1360 self.mutation_mode = mode.into();
1361 self
1362 }
1363
1364 pub fn editable(mut self, editable: impl Into<Binding<bool>>) -> Self {
1376 self.editable = editable.into();
1377 self
1378 }
1379
1380 pub fn deletable(mut self, deletable: impl Into<Binding<bool>>) -> Self {
1393 self.deletable = deletable.into();
1394 self
1395 }
1396
1397 pub fn creatable(mut self, creatable: impl Into<Binding<bool>>) -> Self {
1407 self.creatable = creatable.into();
1408 self
1409 }
1410
1411 pub fn create_node_with(
1423 mut self,
1424 factory: impl Fn(TreeCreateRequest<T>) -> Option<TreeNode<T>> + 'static,
1425 ) -> Self {
1426 self.create_node = Some(Rc::new(factory));
1427 self
1428 }
1429
1430 pub fn tree_style(mut self, style: TreeViewStyle) -> Self {
1440 self.style = style;
1441 self
1442 }
1443
1444 pub fn tree_size(mut self, size: TreeViewSize) -> Self {
1456 self.style = TreeViewStyle::from_theme(Theme::default(), size);
1457 self
1458 }
1459
1460 pub fn virtualized(mut self, virtualized: bool) -> Self {
1473 self.virtualized = virtualized;
1474 self
1475 }
1476
1477 pub fn diagnostics(mut self, diagnostics: TreeViewDiagnostics) -> Self {
1489 self.diagnostics = Some(diagnostics);
1490 self
1491 }
1492
1493 pub fn width(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
1503 self.layout.width = value.into();
1504 self
1505 }
1506
1507 pub fn height(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
1517 self.layout.height = value.into();
1518 self
1519 }
1520
1521 pub fn min_width(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
1531 self.layout.min_width = value.into();
1532 self
1533 }
1534
1535 pub fn max_width(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
1545 self.layout.max_width = value.into();
1546 self
1547 }
1548
1549 pub fn min_height(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
1559 self.layout.min_height = value.into();
1560 self
1561 }
1562
1563 pub fn max_height(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
1573 self.layout.max_height = value.into();
1574 self
1575 }
1576
1577 pub fn fill(mut self) -> Self {
1587 self.layout.width = ailloli_ui_core::style::Length::Fill;
1588 self.layout.height = ailloli_ui_core::style::Length::Fill;
1589 self
1590 }
1591
1592 pub fn fill_width(mut self) -> Self {
1602 self.layout.width = ailloli_ui_core::style::Length::Fill;
1603 self
1604 }
1605
1606 pub fn fill_height(mut self) -> Self {
1616 self.layout.height = ailloli_ui_core::style::Length::Fill;
1617 self
1618 }
1619
1620 pub fn flex_grow(mut self) -> Self {
1630 self.flex_item = self.flex_item.flex_grow(1.0);
1631 self
1632 }
1633
1634 pub fn on_select(mut self, f: impl Fn(T) -> A + 'static) -> Self {
1647 self.on_select = Some(Rc::new(move |ctx, id| ctx.dispatch(f(id))));
1648 self
1649 }
1650
1651 pub fn on_select_ctx(mut self, f: impl Fn(&mut EventCtx<A>, T) + 'static) -> Self {
1661 self.on_select = Some(Rc::new(f));
1662 self
1663 }
1664
1665 pub fn on_activate(mut self, f: impl Fn(T) -> A + 'static) -> Self {
1678 self.on_activate = Some(Rc::new(move |ctx, id| ctx.dispatch(f(id))));
1679 self
1680 }
1681
1682 pub fn on_activate_ctx(mut self, f: impl Fn(&mut EventCtx<A>, T) + 'static) -> Self {
1692 self.on_activate = Some(Rc::new(f));
1693 self
1694 }
1695
1696 pub fn on_toggle(mut self, f: impl Fn(T, bool) -> A + 'static) -> Self {
1709 self.on_toggle = Some(Rc::new(move |ctx, id, open| ctx.dispatch(f(id, open))));
1710 self
1711 }
1712
1713 pub fn on_toggle_ctx(mut self, f: impl Fn(&mut EventCtx<A>, T, bool) + 'static) -> Self {
1723 self.on_toggle = Some(Rc::new(f));
1724 self
1725 }
1726
1727 pub fn on_trailing_action(mut self, f: impl Fn(T) -> A + 'static) -> Self {
1737 self.on_trailing_action = Some(Rc::new(move |ctx, id| ctx.dispatch(f(id))));
1738 self
1739 }
1740
1741 pub fn on_trailing_action_ctx(mut self, f: impl Fn(&mut EventCtx<A>, T) + 'static) -> Self {
1751 self.on_trailing_action = Some(Rc::new(f));
1752 self
1753 }
1754
1755 pub fn on_move(mut self, f: impl Fn(TreeMove<T>) -> A + 'static) -> Self {
1768 self.on_move = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
1769 self
1770 }
1771
1772 pub fn on_move_ctx(mut self, f: impl Fn(&mut EventCtx<A>, TreeMove<T>) + 'static) -> Self {
1782 self.on_move = Some(Rc::new(f));
1783 self
1784 }
1785
1786 pub fn on_rename(mut self, f: impl Fn(TreeRename<T>) -> A + 'static) -> Self {
1800 self.on_rename = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
1801 self
1802 }
1803
1804 pub fn on_rename_ctx(mut self, f: impl Fn(&mut EventCtx<A>, TreeRename<T>) + 'static) -> Self {
1814 self.on_rename = Some(Rc::new(f));
1815 self
1816 }
1817
1818 pub fn on_create(mut self, f: impl Fn(TreeCreate<T>) -> A + 'static) -> Self {
1831 self.on_create = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
1832 self
1833 }
1834
1835 pub fn on_create_ctx(mut self, f: impl Fn(&mut EventCtx<A>, TreeCreate<T>) + 'static) -> Self {
1845 self.on_create = Some(Rc::new(f));
1846 self
1847 }
1848
1849 pub fn on_create_cancel_ctx(
1862 mut self,
1863 f: impl Fn(&mut EventCtx<A>, TreeCreateCancel<T>) + 'static,
1864 ) -> Self {
1865 self.on_create_cancel = Some(Rc::new(f));
1866 self
1867 }
1868
1869 pub fn on_delete(mut self, f: impl Fn(TreeDelete<T>) -> A + 'static) -> Self {
1882 self.on_delete = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
1883 self
1884 }
1885
1886 pub fn on_delete_ctx(mut self, f: impl Fn(&mut EventCtx<A>, TreeDelete<T>) + 'static) -> Self {
1896 self.on_delete = Some(Rc::new(f));
1897 self
1898 }
1899
1900 pub fn on_context_menu(mut self, f: impl Fn(TreeContextMenu<T>) -> A + 'static) -> Self {
1912 self.on_context_menu = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
1913 self
1914 }
1915
1916 pub fn on_context_menu_ctx(
1926 mut self,
1927 f: impl Fn(&mut EventCtx<A>, TreeContextMenu<T>) + 'static,
1928 ) -> Self {
1929 self.on_context_menu = Some(Rc::new(f));
1930 self
1931 }
1932
1933 pub fn on_shortcut(mut self, f: impl Fn(TreeShortcut<T>) -> A + 'static) -> Self {
1946 self.on_shortcut = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
1947 self
1948 }
1949
1950 pub fn on_shortcut_ctx(
1960 mut self,
1961 f: impl Fn(&mut EventCtx<A>, TreeShortcut<T>) + 'static,
1962 ) -> Self {
1963 self.on_shortcut = Some(Rc::new(f));
1964 self
1965 }
1966}
1967
1968struct TreeViewComponent<T, A> {
1970 layout: LayoutStyle,
1972 nodes: Vec<TreeNode<T>>,
1974 bound_nodes: Option<Signal<Vec<TreeNode<T>>>>,
1976 model: Option<Rc<dyn RetainedTreeSource<T>>>,
1978 selected: Option<Binding<T>>,
1980 bound_selected: Option<Signal<T>>,
1982 expanded: Option<Binding<Vec<T>>>,
1984 bound_expanded: Option<Signal<Vec<T>>>,
1986 command: Option<Signal<Option<TreeViewCommand<T>>>>,
1988 default_expanded: Vec<T>,
1990 disabled: Binding<bool>,
1992 draggable: Binding<bool>,
1994 mutation_mode: Binding<TreeMutationMode>,
1996 editable: Binding<bool>,
1998 deletable: Binding<bool>,
2000 creatable: Binding<bool>,
2002 create_node: Option<TreeCreateFactory<T>>,
2004 on_select: Option<TreeSelectHandler<T, A>>,
2006 on_activate: Option<TreeActivateHandler<T, A>>,
2008 on_toggle: Option<TreeToggleHandler<T, A>>,
2010 on_trailing_action: Option<TreeTrailingActionHandler<T, A>>,
2012 on_move: Option<TreeMoveHandler<T, A>>,
2014 on_rename: Option<TreeRenameHandler<T, A>>,
2016 on_create: Option<TreeCreateHandler<T, A>>,
2018 on_create_cancel: Option<TreeCreateCancelHandler<T, A>>,
2020 on_delete: Option<TreeDeleteHandler<T, A>>,
2022 on_context_menu: Option<TreeContextMenuHandler<T, A>>,
2024 on_shortcut: Option<TreeShortcutHandler<T, A>>,
2026 style: TreeViewStyle,
2028 virtualized: bool,
2030 diagnostics: Option<TreeViewDiagnostics>,
2032}
2033
2034impl<T: Clone + PartialEq + 'static, A: 'static> ComponentNode<A> for TreeViewComponent<T, A> {
2035 fn build(&self, context: &mut Context<A>) -> View<A> {
2037 let internal_expanded = context.signal_with_invalidation(
2038 unique_vec(self.default_expanded.clone()),
2039 Invalidation::Layout,
2040 );
2041 let expanded = self
2042 .expanded
2043 .clone()
2044 .unwrap_or_else(|| Binding::Signal(internal_expanded.clone()));
2045 let mutable_expanded = self
2046 .bound_expanded
2047 .clone()
2048 .or_else(|| self.expanded.is_none().then_some(internal_expanded));
2049 let model_callback = self.model.as_ref().map(|_| {
2050 let invalidate = context.invalidation_target(Invalidation::Layout);
2051 Rc::new(move |_revision: u64| invalidate()) as Rc<dyn Fn(u64)>
2052 });
2053 let model_subscription = self
2054 .model
2055 .as_ref()
2056 .zip(model_callback.as_ref())
2057 .map(|(model, callback)| model.subscribe(callback));
2058 View::leaf(TreeViewWidget {
2059 layout: self.layout,
2060 nodes: self.nodes.clone(),
2061 bound_nodes: self.bound_nodes.clone(),
2062 model: self.model.clone(),
2063 _model_callback: model_callback,
2064 _model_subscription: model_subscription,
2065 selected: self.selected.clone(),
2066 bound_selected: self.bound_selected.clone(),
2067 expanded,
2068 mutable_expanded,
2069 command: self.command.clone(),
2070 pending_command: RefCell::new(None),
2071 disabled: self.disabled.clone(),
2072 draggable: self.draggable.clone(),
2073 mutation_mode: self.mutation_mode.clone(),
2074 editable: self.editable.clone(),
2075 deletable: self.deletable.clone(),
2076 creatable: self.creatable.clone(),
2077 create_node: self.create_node.clone(),
2078 on_select: self.on_select.clone(),
2079 on_activate: self.on_activate.clone(),
2080 on_toggle: self.on_toggle.clone(),
2081 on_trailing_action: self.on_trailing_action.clone(),
2082 on_move: self.on_move.clone(),
2083 on_rename: self.on_rename.clone(),
2084 on_create: self.on_create.clone(),
2085 on_create_cancel: self.on_create_cancel.clone(),
2086 on_delete: self.on_delete.clone(),
2087 on_context_menu: self.on_context_menu.clone(),
2088 on_shortcut: self.on_shortcut.clone(),
2089 style: self.style.clone(),
2090 virtualized: self.virtualized,
2091 diagnostics: self.diagnostics.clone(),
2092 active_index: context.signal_with_invalidation(None, Invalidation::Paint),
2093 drag: context.signal_with_invalidation(None, Invalidation::Paint),
2094 editing: context.signal_with_invalidation(None, Invalidation::Paint),
2095 draft: context.signal_with_invalidation(None, Invalidation::Layout),
2096 edit_value: context.signal_with_invalidation(String::new(), Invalidation::Paint),
2097 edit_buffer: context.signal_with_invalidation(
2098 TextBuffer::from_string(String::new()),
2099 Invalidation::Paint,
2100 ),
2101 edit_state: context.signal_with_invalidation(TextEditState::new(), Invalidation::Paint),
2102 last_click: context.signal_with_invalidation(None, Invalidation::Paint),
2103 observed_max_width: Rc::new(Cell::new(160.0)),
2104 snapshot_flat_cache: Rc::new(RefCell::new(SnapshotFlatCache::default())),
2105 })
2106 }
2107}
2108
2109impl<T: Clone + PartialEq + 'static, A: 'static> IntoView<A> for TreeView<T, A> {
2110 fn into_view(self) -> View<A> {
2112 finish_view_sized(
2113 View::component(TreeViewComponent {
2114 layout: self.layout,
2115 nodes: self.nodes,
2116 bound_nodes: self.bound_nodes,
2117 model: self.model,
2118 selected: self.selected,
2119 bound_selected: self.bound_selected,
2120 expanded: self.expanded,
2121 bound_expanded: self.bound_expanded,
2122 command: self.command,
2123 default_expanded: self.default_expanded,
2124 disabled: self.disabled,
2125 draggable: self.draggable,
2126 mutation_mode: self.mutation_mode,
2127 editable: self.editable,
2128 deletable: self.deletable,
2129 creatable: self.creatable,
2130 create_node: self.create_node,
2131 on_select: self.on_select,
2132 on_activate: self.on_activate,
2133 on_toggle: self.on_toggle,
2134 on_trailing_action: self.on_trailing_action,
2135 on_move: self.on_move,
2136 on_rename: self.on_rename,
2137 on_create: self.on_create,
2138 on_create_cancel: self.on_create_cancel,
2139 on_delete: self.on_delete,
2140 on_context_menu: self.on_context_menu,
2141 on_shortcut: self.on_shortcut,
2142 style: self.style,
2143 virtualized: self.virtualized,
2144 diagnostics: self.diagnostics,
2145 }),
2146 self.flex_item,
2147 LayoutSizeHint::from_layout(self.layout),
2148 )
2149 }
2150}
2151
2152#[derive(Clone)]
2153struct FlatNode<T> {
2155 id: T,
2157 label: String,
2159 depth: usize,
2161 branch: bool,
2163 disabled: bool,
2165 leading_icon: Option<IconId>,
2167 leading_icon_tint: Option<Color>,
2169 trailing_action: Option<TreeNodeTrailingAction>,
2171 parent: Option<T>,
2173}
2174
2175#[derive(Clone)]
2176struct TreeDropTarget<T> {
2178 target: T,
2180 position: TreeDropPosition,
2182}
2183
2184#[derive(Clone)]
2185struct TreeDragState<T> {
2187 source: T,
2189 start: Point,
2191 active: bool,
2193 target: Option<TreeDropTarget<T>>,
2195}
2196
2197#[derive(Clone)]
2198struct TreeClickState<T> {
2200 at: TreeClickTimestamp,
2202 pos: Point,
2204 id: T,
2206 count: u8,
2208}
2209
2210#[derive(Clone, Copy)]
2211enum TreeClickTimestamp {
2213 Event(Duration),
2215 Legacy(Instant),
2217}
2218
2219impl TreeClickTimestamp {
2220 fn elapsed_since(self, earlier: Self) -> Option<Duration> {
2222 match (self, earlier) {
2223 (Self::Event(now), Self::Event(earlier)) => now.checked_sub(earlier),
2224 (Self::Legacy(now), Self::Legacy(earlier)) => now.checked_duration_since(earlier),
2225 _ => None,
2226 }
2227 }
2228}
2229
2230#[derive(Clone)]
2231struct TreeEditing<T> {
2233 id: T,
2235 original: String,
2237 create: Option<TreeCreateRequest<T>>,
2239}
2240
2241#[derive(Clone)]
2242struct TreeDraft<T> {
2244 node: FlatNode<T>,
2246 insert_index: usize,
2248}
2249
2250struct SnapshotFlatCache<T> {
2252 nodes_revision: u64,
2254 initialized: bool,
2256 expanded: Vec<T>,
2258 rows: Vec<FlatNode<T>>,
2260 rebuilds: u64,
2262}
2263
2264impl<T> Default for SnapshotFlatCache<T> {
2265 fn default() -> Self {
2266 Self {
2267 nodes_revision: 0,
2268 initialized: false,
2269 expanded: Vec::new(),
2270 rows: Vec::new(),
2271 rebuilds: 0,
2272 }
2273 }
2274}
2275
2276struct TreeNodePaint<'a, T> {
2278 row: Rect,
2280 node: &'a FlatNode<T>,
2282 selected: bool,
2284 opacity: f32,
2286 layout: &'a LayoutResult,
2288 focused: bool,
2290 editing: Option<&'a TreeEditing<T>>,
2292}
2293
2294struct TreeViewWidget<T, A> {
2296 layout: LayoutStyle,
2298 nodes: Vec<TreeNode<T>>,
2300 bound_nodes: Option<Signal<Vec<TreeNode<T>>>>,
2302 model: Option<Rc<dyn RetainedTreeSource<T>>>,
2304 _model_callback: Option<Rc<dyn Fn(u64)>>,
2306 _model_subscription: Option<TreeModelSubscription>,
2308 selected: Option<Binding<T>>,
2310 bound_selected: Option<Signal<T>>,
2312 expanded: Binding<Vec<T>>,
2314 mutable_expanded: Option<Signal<Vec<T>>>,
2316 command: Option<Signal<Option<TreeViewCommand<T>>>>,
2318 pending_command: RefCell<Option<TransactionalLayoutPending<TreeViewCommand<T>>>>,
2320 disabled: Binding<bool>,
2322 draggable: Binding<bool>,
2324 mutation_mode: Binding<TreeMutationMode>,
2326 editable: Binding<bool>,
2328 deletable: Binding<bool>,
2330 creatable: Binding<bool>,
2332 create_node: Option<TreeCreateFactory<T>>,
2334 on_select: Option<TreeSelectHandler<T, A>>,
2336 on_activate: Option<TreeActivateHandler<T, A>>,
2338 on_toggle: Option<TreeToggleHandler<T, A>>,
2340 on_trailing_action: Option<TreeTrailingActionHandler<T, A>>,
2342 on_move: Option<TreeMoveHandler<T, A>>,
2344 on_rename: Option<TreeRenameHandler<T, A>>,
2346 on_create: Option<TreeCreateHandler<T, A>>,
2348 on_create_cancel: Option<TreeCreateCancelHandler<T, A>>,
2350 on_delete: Option<TreeDeleteHandler<T, A>>,
2352 on_context_menu: Option<TreeContextMenuHandler<T, A>>,
2354 on_shortcut: Option<TreeShortcutHandler<T, A>>,
2356 style: TreeViewStyle,
2358 virtualized: bool,
2360 active_index: Signal<Option<usize>>,
2362 drag: Signal<Option<TreeDragState<T>>>,
2364 editing: Signal<Option<TreeEditing<T>>>,
2366 draft: Signal<Option<TreeDraft<T>>>,
2368 edit_value: Signal<String>,
2370 edit_buffer: Signal<TextBuffer>,
2372 edit_state: Signal<TextEditState>,
2374 last_click: Signal<Option<TreeClickState<T>>>,
2376 observed_max_width: Rc<Cell<f32>>,
2378 snapshot_flat_cache: Rc<RefCell<SnapshotFlatCache<T>>>,
2380 diagnostics: Option<TreeViewDiagnostics>,
2382}
2383
2384impl<T: Clone + PartialEq + 'static, A: 'static> Widget<A> for TreeViewWidget<T, A> {
2385 fn debug_name(&self) -> &'static str {
2387 "TreeView"
2388 }
2389
2390 fn layout(
2395 &self,
2396 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
2397 ctx: &mut LayoutCtx<'_>,
2398 _children: &mut [LayoutChild],
2399 constraints: Constraints,
2400 ) -> LayoutResult {
2401 if ctx.layout_pass().is_committed() {
2402 let command = self.command.as_ref().and_then(Signal::read);
2403 self.pending_command
2404 .replace(command.and_then(|command| TransactionalLayoutPending::new(ctx, command)));
2405 }
2406 let total_rows = self.visible_len();
2407 let layout_range = self.layout_row_range(ctx, constraints, total_rows);
2408 let layout_rows = layout_range.len();
2409 let nodes = self.visible_nodes_range(layout_range);
2410 if let Some(diagnostics) = &self.diagnostics {
2411 let flatten_rebuilds = self
2412 .model
2413 .as_ref()
2414 .map_or(0, |model| model.flatten_rebuilds());
2415 let fallback = self.virtualized
2416 && ctx.virtual_viewport().is_none()
2417 && !constraints.max_h.is_finite();
2418 diagnostics.update(|snapshot| {
2419 snapshot.layout_calls = snapshot.layout_calls.saturating_add(1);
2420 snapshot.loaded_rows = total_rows;
2421 snapshot.visible_rows = layout_rows;
2422 snapshot.layout_rows_visited = snapshot
2423 .layout_rows_visited
2424 .saturating_add(layout_rows as u64);
2425 snapshot.text_measurements = snapshot
2426 .text_measurements
2427 .saturating_add(layout_rows as u64);
2428 snapshot.flatten_rebuilds = flatten_rebuilds.max(snapshot.flatten_rebuilds);
2429 snapshot.virtualization_fallbacks = snapshot
2430 .virtualization_fallbacks
2431 .saturating_add(u64::from(fallback));
2432 });
2433 }
2434 let mut max_w = self.observed_max_width.get().max(160.0);
2435 for node in &nodes {
2436 let text_w = measure_text(ctx, &node.label, self.text_style(node)).unwrap_or(80.0);
2437 let icon_w = node
2438 .leading_icon
2439 .as_ref()
2440 .map(|_| self.style.icon_size + self.style.gap)
2441 .unwrap_or(0.0);
2442 let action_w = node
2443 .trailing_action
2444 .as_ref()
2445 .map(|_| self.trailing_action_size() + self.style.gap)
2446 .unwrap_or(0.0);
2447 max_w = max_w.max(
2448 self.style.padding_x * 2.0
2449 + node.depth as f32 * self.style.indent
2450 + self.style.chevron_size
2451 + self.style.gap
2452 + icon_w
2453 + text_w
2454 + action_w,
2455 );
2456 }
2457 self.observed_max_width.set(max_w);
2458 let intrinsic = Size::new(
2459 max_w,
2460 self.style.padding_y * 2.0 + total_rows as f32 * self.style.row_height,
2461 );
2462 let size = apply_layout_size(intrinsic, self.layout, constraints);
2463 LayoutResult {
2464 size,
2465 children: Vec::new(),
2466 paint_bounds: Rect::new(0.0, 0.0, size.w, size.h),
2467 visual_bounds: Rect::new(0.0, 0.0, size.w, size.h),
2468 overlay_hit_bounds: Vec::new(),
2469 clip: None,
2470 is_window_root_clip: false,
2471 artifact: None,
2472 }
2473 }
2474
2475 fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
2481 let Some(command) = self
2482 .pending_command
2483 .borrow_mut()
2484 .take()
2485 .and_then(|pending| pending.into_committed(ctx))
2486 else {
2487 return;
2488 };
2489 if let Some(command_signal) = &self.command {
2490 command_signal.set(None);
2491 }
2492 self.apply_pending_command(command);
2493 }
2494
2495 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, layout: &LayoutResult) {
2497 let disabled = self.disabled.read();
2498 if self.style.background.a > 0.0 {
2499 ctx.push(DrawCmd::RRect(DrawRRect {
2500 rect: bounds,
2501 radius: self.style.radius.tl,
2502 color: self.style.background,
2503 }));
2504 }
2505
2506 let total_rows = self.visible_len();
2507 let paint_range = self.paint_row_range(ctx, bounds, total_rows);
2508 let paint_rows = paint_range.len();
2509 let nodes = self.visible_nodes_range(paint_range.clone());
2510 if let Some(diagnostics) = &self.diagnostics {
2511 diagnostics.update(|snapshot| {
2512 snapshot.paint_calls = snapshot.paint_calls.saturating_add(1);
2513 snapshot.loaded_rows = total_rows;
2514 snapshot.visible_rows = paint_rows;
2515 snapshot.paint_rows_visited = snapshot
2516 .paint_rows_visited
2517 .saturating_add(paint_rows as u64);
2518 });
2519 }
2520 let selected = self.selected_value();
2521 let active = self.normalized_active_index_for_source();
2522 let drag = self.drag.read();
2523 let editing = self.editing.read();
2524 for (local_index, node) in nodes.iter().enumerate() {
2525 let idx = paint_range.start + local_index;
2526 let row = self.row_rect(bounds, idx);
2527 let is_selected = selected.as_ref().is_some_and(|value| value == &node.id);
2528 let is_active = ctx.is_focused() && active == Some(idx);
2529 let is_drag_source = drag
2530 .as_ref()
2531 .is_some_and(|drag| drag.active && drag.source == node.id);
2532 let opacity = if disabled || node.disabled {
2533 self.style.disabled_opacity
2534 } else if is_drag_source {
2535 0.42
2536 } else {
2537 1.0
2538 };
2539 let bg = if is_selected {
2540 self.style.selected_background
2541 } else if is_active {
2542 self.style.active_background
2543 } else {
2544 Color::TRANSPARENT
2545 };
2546 if bg.a > 0.0 {
2547 ctx.push(DrawCmd::RRect(DrawRRect {
2548 rect: row,
2549 radius: self.style.radius.tl,
2550 color: bg.with_alpha(bg.a * opacity),
2551 }));
2552 }
2553
2554 if let Some(drop) = drag
2555 .as_ref()
2556 .and_then(|drag| drag.active.then_some(drag))
2557 .and_then(|drag| drag.target.as_ref())
2558 .filter(|drop| drop.target == node.id)
2559 {
2560 self.paint_drop_target(ctx, row, drop);
2561 }
2562
2563 self.paint_node(
2564 ctx,
2565 TreeNodePaint {
2566 row,
2567 node,
2568 selected: is_selected,
2569 opacity,
2570 layout,
2571 focused: ctx.is_focused(),
2572 editing: editing.as_ref().filter(|edit| edit.id == node.id),
2573 },
2574 );
2575 if is_active && !disabled && !node.disabled {
2576 ctx.push(DrawCmd::Border(DrawBorder {
2577 rect: row,
2578 radius: self.style.radius,
2579 border: self.style.focus_ring,
2580 }));
2581 }
2582 }
2583 }
2584
2585 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, layout: &LayoutResult) {
2587 self.consume_pending_command_for_event();
2591 if self.disabled.read() {
2592 return;
2593 }
2594 if self.handle_editing_event(ctx, event, bounds, layout) {
2595 return;
2596 }
2597 match event {
2598 Event::Pointer(PointerEvent::Button {
2599 pos,
2600 button: MouseButton::Left,
2601 pressed: true,
2602 ..
2603 }) if bounds.contains(pos.x, pos.y) => {
2604 self.handle_pointer_press(ctx, bounds, *pos);
2605 }
2606 Event::Pointer(PointerEvent::Button {
2607 pos,
2608 button: MouseButton::Right,
2609 pressed: true,
2610 ..
2611 }) if bounds.contains(pos.x, pos.y) => {
2612 self.handle_context_menu(ctx, bounds, *pos);
2613 }
2614 Event::Pointer(PointerEvent::Button {
2615 pos,
2616 button: MouseButton::Left,
2617 pressed: false,
2618 ..
2619 }) => {
2620 self.handle_pointer_release(ctx, bounds, *pos);
2621 }
2622 Event::Pointer(PointerEvent::Moved { pos, .. }) => {
2623 self.handle_pointer_move(ctx, bounds, *pos);
2624 }
2625 Event::Keyboard(key) if key.state == KeyState::Pressed => {
2626 self.handle_keyboard(ctx, key);
2627 }
2628 _ => {}
2629 }
2630 }
2631
2632 fn focus_policy(&self) -> FocusPolicy {
2634 let has_enabled = self.draft.read().is_some_and(|draft| !draft.node.disabled)
2635 || self.model.as_ref().map_or_else(
2636 || self.visible_nodes().iter().any(|node| !node.disabled),
2637 |model| model.first_enabled_row().is_some(),
2638 );
2639 if self.disabled.read() || !has_enabled {
2640 FocusPolicy::NotFocusable
2641 } else {
2642 FocusPolicy::Focusable
2643 }
2644 }
2645
2646 fn input_role(&self) -> InputRole {
2648 if self.editing.read().is_some() {
2649 InputRole::TextSingleLine
2650 } else {
2651 InputRole::None
2652 }
2653 }
2654
2655 fn ime_cursor_rect(&self, bounds: Rect, layout: &LayoutResult) -> Option<Rect> {
2657 let editing = self.editing.read()?;
2658 let nodes = self.visible_nodes();
2659 let idx = nodes.iter().position(|node| node.id == editing.id)?;
2660 let row = self.row_rect(bounds, idx);
2661 let edit_rect = self.edit_rect(row, &nodes[idx]);
2662 ime_cursor_rect(
2663 edit_rect,
2664 layout,
2665 &self.edit_value,
2666 &self.edit_buffer,
2667 &self.edit_state,
2668 self.edit_text_style(),
2669 )
2670 }
2671}
2672
2673impl<T: Clone + PartialEq + 'static, A: 'static> TreeViewWidget<T, A> {
2674 fn consume_pending_command_for_event(&self) {
2676 let Some(command_signal) = &self.command else {
2677 return;
2678 };
2679 let Some(command) = command_signal.read() else {
2680 return;
2681 };
2682 command_signal.set(None);
2683 self.apply_pending_command(command);
2684 }
2685
2686 fn apply_pending_command(&self, command: TreeViewCommand<T>) {
2688 match command {
2689 TreeViewCommand::BeginRename(id) => {
2690 let nodes = self.visible_nodes();
2691 if let Some((idx, node)) = nodes.iter().enumerate().find(|(_, node)| node.id == id)
2692 {
2693 if let Some(bound) = &self.bound_selected {
2694 bound.set(node.id.clone());
2695 }
2696 self.active_index.set(Some(idx));
2697 self.begin_rename(node);
2698 }
2699 }
2700 TreeViewCommand::BeginCreate(request) => {
2701 self.begin_create_from_request(request);
2702 }
2703 }
2704 }
2705
2706 fn current_nodes(&self) -> Vec<TreeNode<T>> {
2708 self.bound_nodes
2709 .as_ref()
2710 .map(Signal::read)
2711 .unwrap_or_else(|| self.nodes.clone())
2712 }
2713
2714 fn source_visible_len(&self) -> usize {
2716 self.model.as_ref().map_or_else(
2717 || {
2718 self.sync_snapshot_flat_cache();
2719 self.snapshot_flat_cache.borrow().rows.len()
2720 },
2721 |model| model.visible_len(),
2722 )
2723 }
2724
2725 fn visible_len(&self) -> usize {
2727 self.source_visible_len() + usize::from(self.draft.read().is_some())
2728 }
2729
2730 fn visible_node_at(&self, index: usize) -> Option<FlatNode<T>> {
2732 let draft = self.draft.read();
2733 if let Some(draft) = &draft {
2734 if index == draft.insert_index {
2735 return Some(draft.node.clone());
2736 }
2737 }
2738 let source_index = draft
2739 .as_ref()
2740 .filter(|draft| index > draft.insert_index)
2741 .map_or(index, |_| index.saturating_sub(1));
2742 self.model.as_ref().map_or_else(
2743 || {
2744 self.sync_snapshot_flat_cache();
2745 self.snapshot_flat_cache
2746 .borrow()
2747 .rows
2748 .get(source_index)
2749 .cloned()
2750 },
2751 |model| model.flat_node_at(source_index),
2752 )
2753 }
2754
2755 fn visible_nodes_range(&self, range: std::ops::Range<usize>) -> Vec<FlatNode<T>> {
2757 range
2758 .filter_map(|index| self.visible_node_at(index))
2759 .collect()
2760 }
2761
2762 fn set_current_nodes(&self, nodes: Vec<TreeNode<T>>) -> bool {
2764 let Some(bound) = &self.bound_nodes else {
2765 return false;
2766 };
2767 bound.set(nodes);
2768 true
2769 }
2770
2771 fn can_mutate_nodes(&self) -> bool {
2773 self.bound_nodes.is_some()
2774 || (self.model.is_some() && self.mutation_mode.read() == TreeMutationMode::IntentOnly)
2775 }
2776
2777 fn source_index_to_visible(&self, source_index: usize) -> usize {
2779 self.draft.read().map_or(source_index, |draft| {
2780 source_index + usize::from(source_index >= draft.insert_index)
2781 })
2782 }
2783
2784 fn retained_create_position(&self, request: &TreeCreateRequest<T>) -> Option<(usize, usize)> {
2786 let rows = (0..self.source_visible_len())
2787 .filter_map(|index| {
2788 self.model
2789 .as_ref()
2790 .and_then(|model| model.flat_node_at(index))
2791 })
2792 .collect::<Vec<_>>();
2793 match request.kind {
2794 TreeCreateKind::SiblingAfter => {
2795 let Some(after) = &request.after else {
2796 return Some((rows.len(), 0));
2797 };
2798 let row = rows.iter().position(|node| &node.id == after)?;
2799 let depth = rows[row].depth;
2800 Some((visible_subtree_end(&rows, row), depth))
2801 }
2802 TreeCreateKind::Child => {
2803 let parent = request.parent.as_ref()?;
2804 let row = rows.iter().position(|node| &node.id == parent)?;
2805 let depth = rows[row].depth.saturating_add(1);
2806 Some((visible_subtree_end(&rows, row), depth))
2807 }
2808 }
2809 }
2810
2811 fn begin_retained_create(&self, node: TreeNode<T>, request: TreeCreateRequest<T>) -> bool {
2815 if self.draft.read().is_some() || self.editing.read().is_some() {
2816 return false;
2817 }
2818 let Some((insert_index, depth)) = self.retained_create_position(&request) else {
2819 return false;
2820 };
2821 let flat = FlatNode {
2822 id: node.id,
2823 label: node.label,
2824 depth,
2825 branch: node.branch,
2826 disabled: node.disabled.read(),
2827 leading_icon: node.leading_icon,
2828 leading_icon_tint: node.leading_icon_tint,
2829 trailing_action: node.trailing_action,
2830 parent: request.parent.clone(),
2831 };
2832 let created_id = flat.id.clone();
2833 self.draft.set(Some(TreeDraft {
2834 node: flat.clone(),
2835 insert_index,
2836 }));
2837 if let Some(bound) = &self.bound_selected {
2838 bound.set(created_id);
2839 }
2840 self.active_index.set(Some(insert_index));
2841 self.begin_create_rename(&flat, request)
2842 }
2843
2844 fn expanded_values(&self) -> Vec<T> {
2846 unique_vec(self.expanded.read())
2847 }
2848
2849 fn selected_value(&self) -> Option<T> {
2851 self.selected.as_ref().map(Binding::read)
2852 }
2853
2854 fn visible_nodes(&self) -> Vec<FlatNode<T>> {
2856 (0..self.visible_len())
2857 .filter_map(|index| self.visible_node_at(index))
2858 .collect()
2859 }
2860
2861 fn visible_nodes_snapshot(&self) -> Vec<FlatNode<T>> {
2863 self.sync_snapshot_flat_cache();
2864 self.snapshot_flat_cache.borrow().rows.clone()
2865 }
2866
2867 fn sync_snapshot_flat_cache(&self) {
2872 let expanded = self.expanded_values();
2873 let nodes_revision = self.bound_nodes.as_ref().map_or(0, Signal::revision);
2874 {
2875 let cache = self.snapshot_flat_cache.borrow();
2876 if cache.initialized
2877 && cache.nodes_revision == nodes_revision
2878 && cache.expanded == expanded
2879 {
2880 return;
2881 }
2882 }
2883 let mut out = Vec::new();
2884 for node in &self.current_nodes() {
2885 flatten_node(node, 0, None, &expanded, &mut out);
2886 }
2887 let mut cache = self.snapshot_flat_cache.borrow_mut();
2888 cache.nodes_revision = nodes_revision;
2889 cache.initialized = true;
2890 cache.expanded = expanded;
2891 cache.rows = out;
2892 cache.rebuilds = cache.rebuilds.saturating_add(1);
2893 if let Some(diagnostics) = &self.diagnostics {
2894 let rows = cache.rows.len() as u64;
2895 let rebuilds = cache.rebuilds;
2896 diagnostics.update(|snapshot| {
2897 snapshot.flatten_rebuilds = rebuilds;
2898 snapshot.snapshot_rows_cloned = snapshot.snapshot_rows_cloned.saturating_add(rows);
2899 });
2900 }
2901 }
2902
2903 fn layout_row_range(
2905 &self,
2906 ctx: &LayoutCtx<'_>,
2907 constraints: Constraints,
2908 len: usize,
2909 ) -> std::ops::Range<usize> {
2910 if !self.virtualized || len == 0 {
2911 return 0..len;
2912 }
2913 if let Some(viewport) = ctx.virtual_viewport() {
2914 return row_range_with_overscan(
2915 viewport.rect.y,
2916 viewport.rect.h,
2917 self.style.padding_y,
2918 self.style.row_height,
2919 len,
2920 TREE_VIRTUAL_OVERSCAN_ROWS,
2921 );
2922 }
2923 if constraints.max_h.is_finite() {
2924 return row_range_with_overscan(
2925 0.0,
2926 constraints.max_h,
2927 self.style.padding_y,
2928 self.style.row_height,
2929 len,
2930 TREE_VIRTUAL_OVERSCAN_ROWS,
2931 );
2932 }
2933 0..len
2934 }
2935
2936 fn normalized_active_index_for_source(&self) -> Option<usize> {
2938 if self.draft.read().is_some() {
2939 let nodes = self.visible_nodes();
2940 return self.normalized_active_index(&nodes);
2941 }
2942 if let Some(model) = &self.model {
2943 if let Some(index) = self.active_index.read() {
2944 if model.flat_node_at(index).is_some_and(|node| !node.disabled) {
2945 return Some(index);
2946 }
2947 }
2948 if let Some(selected) = self.selected_value() {
2949 if let Some(index) = model.row_of(&selected) {
2950 if model.flat_node_at(index).is_some_and(|node| !node.disabled) {
2951 return Some(index);
2952 }
2953 }
2954 }
2955 return model.first_enabled_row();
2956 }
2957 let nodes = self.visible_nodes_snapshot();
2958 self.normalized_active_index(&nodes)
2959 }
2960
2961 fn row_rect(&self, bounds: Rect, index: usize) -> Rect {
2963 Rect::new(
2964 bounds.x + self.style.padding_x,
2965 bounds.y + self.style.padding_y + index as f32 * self.style.row_height,
2966 (bounds.w - self.style.padding_x * 2.0).max(0.0),
2967 self.style.row_height,
2968 )
2969 }
2970
2971 fn row_index_at(&self, bounds: Rect, y: f32, len: usize) -> Option<usize> {
2973 if let Some(diagnostics) = &self.diagnostics {
2974 diagnostics.update(|snapshot| {
2975 snapshot.hit_tests = snapshot.hit_tests.saturating_add(1);
2976 });
2977 }
2978 let local_y = y - bounds.y - self.style.padding_y;
2979 if local_y < 0.0 {
2980 return None;
2981 }
2982 let idx = (local_y / self.style.row_height).floor() as usize;
2983 let result = (idx < len).then_some(idx);
2984 if result.is_some() {
2985 if let Some(diagnostics) = &self.diagnostics {
2986 diagnostics.update(|snapshot| {
2987 snapshot.hit_test_rows_visited =
2988 snapshot.hit_test_rows_visited.saturating_add(1);
2989 });
2990 }
2991 }
2992 result
2993 }
2994
2995 fn paint_row_range(
2997 &self,
2998 ctx: &PaintCtx<'_>,
2999 bounds: Rect,
3000 len: usize,
3001 ) -> std::ops::Range<usize> {
3002 if !self.virtualized || len == 0 {
3003 return 0..len;
3004 }
3005 let clip = ctx.current_clip_bbox().unwrap_or(bounds);
3006 row_range_with_overscan(
3007 clip.y - bounds.y,
3008 clip.h,
3009 self.style.padding_y,
3010 self.style.row_height,
3011 len,
3012 TREE_VIRTUAL_OVERSCAN_ROWS,
3013 )
3014 }
3015
3016 fn chevron_rect(&self, row: Rect, node: &FlatNode<T>) -> Rect {
3018 let x = row.x + node.depth as f32 * self.style.indent;
3019 Rect::new(
3020 x,
3021 row.y + (row.h - self.style.chevron_size) * 0.5,
3022 self.style.chevron_size,
3023 self.style.chevron_size,
3024 )
3025 }
3026
3027 fn label_x(&self, row: Rect, node: &FlatNode<T>) -> f32 {
3029 let chevron = self.chevron_rect(row, node);
3030 let mut x = chevron.right() + self.style.gap;
3031 if node.leading_icon.is_some() {
3032 x += self.style.icon_size + self.style.gap;
3033 }
3034 x
3035 }
3036
3037 fn edit_rect(&self, row: Rect, node: &FlatNode<T>) -> Rect {
3039 let x = self.label_x(row, node);
3040 Rect::new(
3041 x - 4.0,
3042 row.y + 2.0,
3043 (row.right() - x + 4.0).max(32.0),
3044 (row.h - 4.0).max(18.0),
3045 )
3046 }
3047
3048 fn trailing_action_size(&self) -> f32 {
3050 self.style
3051 .row_height
3052 .min(28.0)
3053 .max(self.style.icon_size + 6.0)
3054 }
3055
3056 fn trailing_action_rect(&self, row: Rect) -> Rect {
3058 let size = self.trailing_action_size();
3059 Rect::new(row.right() - size, row.y + (row.h - size) * 0.5, size, size)
3060 }
3061
3062 fn trailing_action_icon_rect(&self, action: Rect) -> Rect {
3064 Rect::new(
3065 action.x + (action.w - self.style.icon_size) * 0.5,
3066 action.y + (action.h - self.style.icon_size) * 0.5,
3067 self.style.icon_size,
3068 self.style.icon_size,
3069 )
3070 }
3071
3072 fn edit_text_style(&self) -> TextInputStyle {
3074 let theme = Theme::default();
3075 let palette = theme.palette();
3076 TextInputStyle {
3077 bg: self.style.editing_background,
3078 border: self.style.editing_border,
3079 border_focused: self.style.editing_border,
3080 caret: palette.text,
3081 placeholder: palette.text_muted,
3082 selection_bg: palette.accent.with_alpha(0.34),
3083 radius: self.style.radius.tl,
3084 pad_x: 4.0,
3085 pad_y: 2.0,
3086 text: self.style.text,
3087 caret_w: 1.0,
3088 caret_blink_ms: 500,
3089 }
3090 }
3091
3092 fn paint_drop_target(&self, ctx: &mut PaintCtx<'_>, row: Rect, drop: &TreeDropTarget<T>) {
3094 match drop.position {
3095 TreeDropPosition::Before | TreeDropPosition::After => {
3096 let y = if drop.position == TreeDropPosition::Before {
3097 row.y
3098 } else {
3099 row.bottom() - 2.0
3100 };
3101 ctx.push(DrawCmd::Rect(DrawRect {
3102 rect: Rect::new(row.x, y, row.w, 2.0),
3103 color: self.style.drop_indicator,
3104 }));
3105 }
3106 TreeDropPosition::Inside => {
3107 ctx.push(DrawCmd::RRect(DrawRRect {
3108 rect: row,
3109 radius: self.style.radius.tl,
3110 color: self.style.drop_inside_background,
3111 }));
3112 ctx.push(DrawCmd::Border(DrawBorder {
3113 rect: row,
3114 radius: self.style.radius,
3115 border: Border::new(1.0, self.style.drop_indicator),
3116 }));
3117 }
3118 }
3119 }
3120
3121 fn paint_node(&self, ctx: &mut PaintCtx<'_>, paint: TreeNodePaint<'_, T>) {
3123 let TreeNodePaint {
3124 row,
3125 node,
3126 selected,
3127 opacity,
3128 layout,
3129 focused,
3130 editing,
3131 } = paint;
3132 let chevron = self.chevron_rect(row, node);
3133 if node.branch {
3134 let icon = if self.is_expanded(&node.id) {
3135 IconId::Lucide(LucideIcon::ChevronDown)
3136 } else {
3137 IconId::Lucide(LucideIcon::ChevronRight)
3138 };
3139 ctx.push(DrawCmd::Image(DrawImage {
3140 rect: chevron,
3141 icon,
3142 tint: self
3143 .style
3144 .chevron_tint
3145 .with_alpha(self.style.chevron_tint.a * opacity),
3146 rotation_rad: 0.0,
3147 }));
3148 }
3149
3150 let mut x = chevron.right() + self.style.gap;
3151 if let Some(icon) = &node.leading_icon {
3152 let rect = Rect::new(
3153 x,
3154 row.y + (row.h - self.style.icon_size) * 0.5,
3155 self.style.icon_size,
3156 self.style.icon_size,
3157 );
3158 let tint = if let Some(tint) = node.leading_icon_tint {
3159 tint
3160 } else if selected {
3161 self.style.selected_icon_tint
3162 } else {
3163 self.style.icon_tint
3164 };
3165 ctx.push(DrawCmd::Image(DrawImage {
3166 rect,
3167 icon: icon.clone(),
3168 tint: tint.with_alpha(tint.a * opacity),
3169 rotation_rad: 0.0,
3170 }));
3171 x += self.style.icon_size + self.style.gap;
3172 }
3173
3174 if editing.is_some() {
3175 let edit_rect = self.edit_rect(row, node);
3176 let style = self.edit_text_style();
3177 ctx.push(DrawCmd::RRect(DrawRRect {
3178 rect: edit_rect,
3179 radius: style.radius,
3180 color: style.bg,
3181 }));
3182 ctx.push(DrawCmd::Border(DrawBorder {
3183 rect: edit_rect,
3184 radius: Radius::uniform(style.radius),
3185 border: Border::new(
3186 1.0,
3187 if focused {
3188 style.border_focused
3189 } else {
3190 style.border
3191 },
3192 ),
3193 }));
3194 paint_single_line_text(
3195 ctx,
3196 edit_rect,
3197 layout,
3198 &self.edit_value,
3199 &self.edit_buffer,
3200 &self.edit_state,
3201 None,
3202 style,
3203 focused,
3204 );
3205 } else {
3206 paint_text_centered(ctx, &node.label, self.text_style(node), row, x, opacity);
3207 }
3208
3209 if selected {
3210 if let Some(action) = &node.trailing_action {
3211 let action_rect = self.trailing_action_rect(row);
3212 let bg = self
3213 .style
3214 .selected_background
3215 .with_alpha((self.style.selected_background.a + 0.10).min(0.42) * opacity);
3216 if bg.a > 0.0 {
3217 ctx.push(DrawCmd::RRect(DrawRRect {
3218 rect: action_rect,
3219 radius: self.style.radius.tl,
3220 color: bg,
3221 }));
3222 }
3223 let tint = self
3224 .style
3225 .selected_icon_tint
3226 .with_alpha(self.style.selected_icon_tint.a * opacity);
3227 ctx.push(DrawCmd::Image(DrawImage {
3228 rect: self.trailing_action_icon_rect(action_rect),
3229 icon: action.icon.clone(),
3230 tint,
3231 rotation_rad: 0.0,
3232 }));
3233 }
3234 }
3235 }
3236
3237 fn text_style(&self, node: &FlatNode<T>) -> TextStyle {
3239 if node.disabled || self.disabled.read() {
3240 self.style.disabled_text
3241 } else if self
3242 .selected_value()
3243 .as_ref()
3244 .is_some_and(|selected| selected == &node.id)
3245 {
3246 self.style.selected_text
3247 } else {
3248 self.style.text
3249 }
3250 }
3251
3252 fn normalized_active_index(&self, nodes: &[FlatNode<T>]) -> Option<usize> {
3254 let active = self.active_index.read();
3255 if let Some(idx) = active {
3256 if idx < nodes.len() && !nodes[idx].disabled {
3257 return Some(idx);
3258 }
3259 }
3260 if let Some(selected) = self.selected_value() {
3261 if let Some(idx) = nodes
3262 .iter()
3263 .position(|node| !node.disabled && node.id == selected)
3264 {
3265 return Some(idx);
3266 }
3267 }
3268 nodes.iter().position(|node| !node.disabled)
3269 }
3270
3271 fn handle_pointer(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
3273 let Some(idx) = self.row_index_at(bounds, pos.y, self.visible_len()) else {
3274 return;
3275 };
3276 let Some(node) = self.visible_node_at(idx) else {
3277 return;
3278 };
3279 if node.disabled {
3280 return;
3281 }
3282 self.active_index.set(Some(idx));
3283 let row = self.row_rect(bounds, idx);
3284 if node.branch && self.chevron_rect(row, &node).contains(pos.x, pos.y) {
3285 self.toggle_node(ctx, &node);
3286 } else {
3287 let click_count = self.register_row_click(ctx, &node, pos);
3288 self.select_node(ctx, &node);
3289 if click_count == 2 {
3290 self.activate_node(ctx, &node);
3291 }
3292 }
3293 }
3294
3295 fn handle_context_menu(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
3297 let Some(on_context_menu) = &self.on_context_menu else {
3298 return;
3299 };
3300 if let Some(idx) = self.row_index_at(bounds, pos.y, self.visible_len()) {
3301 let Some(node) = self.visible_node_at(idx) else {
3302 return;
3303 };
3304 if node.disabled {
3305 return;
3306 }
3307 self.active_index.set(Some(idx));
3308 let row = self.row_rect(bounds, idx);
3309 let selected = self.selected_value();
3310 if selected
3311 .as_ref()
3312 .is_none_or(|selected| selected != &node.id)
3313 {
3314 self.select_node(ctx, &node);
3315 }
3316 on_context_menu(
3317 ctx,
3318 TreeContextMenu::Row {
3319 row_id: node.id.clone(),
3320 pointer_position: pos,
3321 row_rect: row,
3322 },
3323 );
3324 ctx.request_repaint();
3325 ctx.stop_propagation();
3326 return;
3327 }
3328 on_context_menu(
3329 ctx,
3330 TreeContextMenu::Blank {
3331 pointer_position: pos,
3332 },
3333 );
3334 ctx.request_repaint();
3335 ctx.stop_propagation();
3336 }
3337
3338 fn handle_pointer_press(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
3340 let Some(idx) = self.row_index_at(bounds, pos.y, self.visible_len()) else {
3341 return;
3342 };
3343 let Some(node) = self.visible_node_at(idx) else {
3344 return;
3345 };
3346 if node.disabled {
3347 return;
3348 }
3349 self.active_index.set(Some(idx));
3350 let row = self.row_rect(bounds, idx);
3351 if self.trailing_action_hit(row, &node, pos) {
3352 ctx.stop_propagation();
3353 ctx.request_repaint();
3354 return;
3355 }
3356 if self.draggable.read()
3357 && self.can_mutate_nodes()
3358 && !self.chevron_rect(row, &node).contains(pos.x, pos.y)
3359 {
3360 self.drag.set(Some(TreeDragState {
3361 source: node.id.clone(),
3362 start: pos,
3363 active: false,
3364 target: None,
3365 }));
3366 ctx.stop_propagation();
3367 }
3368 }
3369
3370 fn handle_pointer_move(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
3372 let Some(mut drag) = self.drag.read() else {
3373 return;
3374 };
3375 if !drag.active {
3376 let dx = pos.x - drag.start.x;
3377 let dy = pos.y - drag.start.y;
3378 if (dx * dx + dy * dy).sqrt() > 4.0 {
3379 drag.active = true;
3380 }
3381 }
3382 if drag.active {
3383 drag.target = self.drop_target_at(bounds, pos, &drag.source);
3384 ctx.request_repaint();
3385 }
3386 self.drag.set(Some(drag));
3387 ctx.stop_propagation();
3388 }
3389
3390 fn handle_pointer_release(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
3392 if let Some(drag) = self.drag.read() {
3393 self.drag.set(None);
3394 if drag.active {
3395 if let Some(drop) = drag.target {
3396 self.apply_drop(ctx, drag.source, drop);
3397 } else {
3398 ctx.request_repaint();
3399 ctx.stop_propagation();
3400 }
3401 return;
3402 }
3403 }
3404 if let Some(idx) = self.row_index_at(bounds, pos.y, self.visible_len()) {
3405 let Some(node) = self.visible_node_at(idx) else {
3406 return;
3407 };
3408 let row = self.row_rect(bounds, idx);
3409 if self.trailing_action_hit(row, &node, pos) {
3410 self.active_index.set(Some(idx));
3411 self.emit_trailing_action(ctx, &node);
3412 return;
3413 }
3414 }
3415 if bounds.contains(pos.x, pos.y) {
3416 self.handle_pointer(ctx, bounds, pos);
3417 }
3418 }
3419
3420 fn trailing_action_hit(&self, row: Rect, node: &FlatNode<T>, pos: Point) -> bool {
3422 if node.disabled || node.trailing_action.is_none() {
3423 return false;
3424 }
3425 let Some(selected) = self.selected_value() else {
3426 return false;
3427 };
3428 if selected != node.id {
3429 return false;
3430 }
3431 self.trailing_action_rect(row).contains(pos.x, pos.y)
3432 }
3433
3434 fn emit_trailing_action(&self, ctx: &mut EventCtx<A>, node: &FlatNode<T>) {
3436 if node.disabled || node.trailing_action.is_none() {
3437 return;
3438 }
3439 if let Some(on_trailing_action) = &self.on_trailing_action {
3440 on_trailing_action(ctx, node.id.clone());
3441 ctx.request_repaint();
3442 ctx.stop_propagation();
3443 }
3444 }
3445
3446 fn drop_target_at(&self, bounds: Rect, pos: Point, source: &T) -> Option<TreeDropTarget<T>> {
3448 let nodes = self.visible_nodes();
3449 let idx = self.row_index_at(bounds, pos.y, nodes.len())?;
3450 let node = &nodes[idx];
3451 if node.disabled || &node.id == source {
3452 return None;
3453 }
3454 let row = self.row_rect(bounds, idx);
3455 let local_y = ((pos.y - row.y) / row.h.max(1.0)).clamp(0.0, 1.0);
3456 let position = if local_y < 0.33 {
3457 TreeDropPosition::Before
3458 } else if local_y > 0.66 {
3459 TreeDropPosition::After
3460 } else {
3461 TreeDropPosition::Inside
3462 };
3463 Some(TreeDropTarget {
3464 target: node.id.clone(),
3465 position,
3466 })
3467 }
3468
3469 fn handle_keyboard(&self, ctx: &mut EventCtx<A>, key: &KeyEvent) {
3471 let nodes = self.visible_nodes();
3472 if nodes.is_empty() || self.editing.read().is_some() {
3473 return;
3474 }
3475 let active = self.normalized_active_index(&nodes);
3476 let shortcut_target = self.shortcut_target_node(&nodes, active);
3477 if self.handle_keyboard_shortcut(ctx, key, shortcut_target) {
3478 return;
3479 }
3480 match &key.key {
3481 Key::Named(NamedKey::F(2)) => {
3482 if let Some(idx) = active {
3483 self.start_rename(ctx, &nodes[idx]);
3484 }
3485 }
3486 Key::Named(NamedKey::Delete) => {
3487 if let Some(idx) = active {
3488 self.delete_node(ctx, &nodes, idx);
3489 }
3490 }
3491 Key::Named(NamedKey::Insert) if key.modifiers.ctrl => {
3492 if let Some(idx) = active {
3493 self.create_node(ctx, &nodes, idx, TreeCreateKind::Child);
3494 }
3495 }
3496 Key::Named(NamedKey::Insert) => {
3497 if let Some(idx) = active {
3498 self.create_node(ctx, &nodes, idx, TreeCreateKind::SiblingAfter);
3499 }
3500 }
3501 Key::Named(NamedKey::ArrowDown) => {
3502 self.move_active(ctx, next_enabled(&nodes, active, 1));
3503 }
3504 Key::Named(NamedKey::ArrowUp) => {
3505 self.move_active(ctx, next_enabled(&nodes, active, -1));
3506 }
3507 Key::Named(NamedKey::Home) => {
3508 self.move_active(ctx, nodes.iter().position(|node| !node.disabled));
3509 }
3510 Key::Named(NamedKey::End) => {
3511 self.move_active(ctx, nodes.iter().rposition(|node| !node.disabled));
3512 }
3513 Key::Named(NamedKey::ArrowRight) => {
3514 if let Some(idx) = active {
3515 let node = &nodes[idx];
3516 if node.branch && !self.is_expanded(&node.id) {
3517 self.toggle_node(ctx, node);
3518 } else if node.branch {
3519 self.move_active(ctx, first_visible_child_index(&nodes, idx));
3520 }
3521 }
3522 }
3523 Key::Named(NamedKey::ArrowLeft) => {
3524 if let Some(idx) = active {
3525 let node = &nodes[idx];
3526 if node.branch && self.is_expanded(&node.id) {
3527 self.toggle_node(ctx, node);
3528 } else if let Some(parent) = &node.parent {
3529 self.move_active(ctx, nodes.iter().position(|row| &row.id == parent));
3530 }
3531 }
3532 }
3533 Key::Named(NamedKey::Enter) => {
3534 if let Some(idx) = active {
3535 if self.on_activate.is_some() {
3536 self.activate_node(ctx, &nodes[idx]);
3537 } else {
3538 self.select_node(ctx, &nodes[idx]);
3539 }
3540 }
3541 }
3542 Key::Named(NamedKey::Space) => {
3543 if let Some(idx) = active {
3544 let node = &nodes[idx];
3545 if node.branch {
3546 self.toggle_node(ctx, node);
3547 } else {
3548 self.select_node(ctx, node);
3549 }
3550 }
3551 }
3552 _ => {}
3553 }
3554 }
3555
3556 fn handle_keyboard_shortcut(
3560 &self,
3561 ctx: &mut EventCtx<A>,
3562 key: &KeyEvent,
3563 active: Option<&FlatNode<T>>,
3564 ) -> bool {
3565 let Some(on_shortcut) = &self.on_shortcut else {
3566 return false;
3567 };
3568 if key.modifiers.alt || key.modifiers.meta {
3569 return false;
3570 }
3571 let shortcut = match &key.key {
3572 Key::Named(NamedKey::Delete) => {
3573 let Some(active) = active else {
3574 return false;
3575 };
3576 Some(TreeShortcut::Delete {
3577 id: active.id.clone(),
3578 })
3579 }
3580 Key::Character(_) if key.modifiers.ctrl => match key_character_upper(key).as_deref() {
3581 Some("C") => active.map(|node| TreeShortcut::Copy {
3582 id: node.id.clone(),
3583 }),
3584 Some("X") => active.map(|node| TreeShortcut::Cut {
3585 id: node.id.clone(),
3586 }),
3587 Some("V") => Some(TreeShortcut::Paste {
3588 id: active.map(|node| node.id.clone()),
3589 }),
3590 _ => None,
3591 },
3592 _ => None,
3593 };
3594 let Some(shortcut) = shortcut else {
3595 return false;
3596 };
3597 on_shortcut(ctx, shortcut);
3598 ctx.request_repaint();
3599 ctx.stop_propagation();
3600 true
3601 }
3602
3603 fn shortcut_target_node<'a>(
3605 &self,
3606 nodes: &'a [FlatNode<T>],
3607 active: Option<usize>,
3608 ) -> Option<&'a FlatNode<T>> {
3609 if let Some(selected) = self.selected_value() {
3610 if let Some(node) = nodes
3611 .iter()
3612 .find(|node| !node.disabled && node.id == selected)
3613 {
3614 return Some(node);
3615 }
3616 }
3617 active.and_then(|idx| nodes.get(idx).filter(|node| !node.disabled))
3618 }
3619
3620 fn move_active(&self, ctx: &mut EventCtx<A>, next: Option<usize>) {
3622 if next != self.active_index.read() {
3623 self.active_index.set(next);
3624 ctx.request_repaint();
3625 ctx.stop_propagation();
3626 }
3627 }
3628
3629 fn select_node(&self, ctx: &mut EventCtx<A>, node: &FlatNode<T>) {
3631 if node.disabled {
3632 return;
3633 }
3634 let changed = self
3635 .selected_value()
3636 .as_ref()
3637 .is_none_or(|selected| selected != &node.id);
3638 if changed {
3639 if let Some(bound) = &self.bound_selected {
3640 bound.set(node.id.clone());
3641 }
3642 if let Some(on_select) = &self.on_select {
3643 on_select(ctx, node.id.clone());
3644 }
3645 ctx.request_repaint();
3646 ctx.stop_propagation();
3647 }
3648 }
3649
3650 fn activate_node(&self, ctx: &mut EventCtx<A>, node: &FlatNode<T>) {
3652 if node.disabled {
3653 return;
3654 }
3655 if let Some(on_activate) = &self.on_activate {
3656 on_activate(ctx, node.id.clone());
3657 ctx.request_repaint();
3658 ctx.stop_propagation();
3659 }
3660 }
3661
3662 fn register_row_click(&self, ctx: &EventCtx<A>, node: &FlatNode<T>, pos: Point) -> u8 {
3664 let now = ctx
3665 .event_meta()
3666 .map(|meta| TreeClickTimestamp::Event(meta.timestamp().duration()))
3667 .unwrap_or_else(|| TreeClickTimestamp::Legacy(Instant::now()));
3668 let next = self
3669 .last_click
3670 .read()
3671 .filter(|last| {
3672 last.id == node.id
3673 && now
3674 .elapsed_since(last.at)
3675 .is_some_and(|elapsed| elapsed <= TREE_ACTIVATE_MAX_DELAY)
3676 && point_distance_sq(last.pos, pos)
3677 <= TREE_ACTIVATE_MAX_DISTANCE * TREE_ACTIVATE_MAX_DISTANCE
3678 })
3679 .map(|last| last.count.saturating_add(1).min(3))
3680 .unwrap_or(1);
3681 self.last_click.set(Some(TreeClickState {
3682 at: now,
3683 pos,
3684 id: node.id.clone(),
3685 count: next,
3686 }));
3687 next
3688 }
3689
3690 fn toggle_node(&self, ctx: &mut EventCtx<A>, node: &FlatNode<T>) {
3696 if node.disabled || !node.branch {
3697 return;
3698 }
3699 let next_open = !self.is_expanded(&node.id);
3700 if let Some(model) = &self.model {
3701 if self.mutation_mode.read() == TreeMutationMode::ApplyLocal
3702 && !model.set_expanded(node.id.clone(), next_open)
3703 {
3704 return;
3705 }
3706 } else {
3707 let mut expanded = self.expanded_values();
3708 if next_open {
3709 if !expanded.iter().any(|id| id == &node.id) {
3710 expanded.push(node.id.clone());
3711 }
3712 } else {
3713 expanded.retain(|id| id != &node.id);
3714 }
3715 if let Some(bound) = &self.mutable_expanded {
3716 bound.set(expanded);
3717 }
3718 }
3719 if let Some(on_toggle) = &self.on_toggle {
3720 on_toggle(ctx, node.id.clone(), next_open);
3721 }
3722 let active = self.model.as_ref().map_or_else(
3723 || {
3724 self.visible_nodes_snapshot()
3725 .iter()
3726 .position(|row| !row.disabled && row.id == node.id)
3727 },
3728 |model| {
3729 let row = model.row_of(&node.id)?;
3730 Some(self.source_index_to_visible(row))
3731 },
3732 );
3733 self.active_index.set(active);
3734 ctx.request_repaint();
3735 ctx.stop_propagation();
3736 }
3737
3738 fn is_expanded(&self, id: &T) -> bool {
3740 self.model.as_ref().map_or_else(
3741 || self.expanded_values().iter().any(|expanded| expanded == id),
3742 |model| model.is_expanded(id),
3743 )
3744 }
3745
3746 fn handle_editing_event(
3750 &self,
3751 ctx: &mut EventCtx<A>,
3752 event: &Event,
3753 bounds: Rect,
3754 layout: &LayoutResult,
3755 ) -> bool {
3756 let Some(editing) = self.editing.read() else {
3757 return false;
3758 };
3759 let nodes = self.visible_nodes();
3760 let Some(idx) = nodes.iter().position(|node| node.id == editing.id) else {
3761 self.cancel_rename(ctx);
3762 return true;
3763 };
3764 let row = self.row_rect(bounds, idx);
3765 let edit_rect = self.edit_rect(row, &nodes[idx]);
3766 match event {
3767 Event::Focus(focus) if !focus.focused => {
3768 if !self.commit_rename(ctx) {
3769 self.cancel_rename(ctx);
3770 }
3771 true
3772 }
3773 Event::Keyboard(key)
3774 if key.state == KeyState::Pressed && key.key == Key::Named(NamedKey::Escape) =>
3775 {
3776 self.cancel_rename(ctx);
3777 ctx.stop_propagation();
3778 true
3779 }
3780 Event::Keyboard(key)
3781 if key.state == KeyState::Pressed && key.key == Key::Named(NamedKey::Enter) =>
3782 {
3783 self.commit_rename(ctx);
3784 ctx.stop_propagation();
3785 true
3786 }
3787 Event::Pointer(PointerEvent::Button {
3788 pos,
3789 button: MouseButton::Left,
3790 pressed: true,
3791 ..
3792 }) if !edit_rect.contains(pos.x, pos.y) => {
3793 self.commit_rename(ctx);
3794 ctx.stop_propagation();
3795 true
3796 }
3797 _ => handle_single_line_text_event(
3798 ctx,
3799 event,
3800 edit_rect,
3801 layout,
3802 &self.edit_value,
3803 &self.edit_buffer,
3804 &self.edit_state,
3805 self.edit_text_style(),
3806 TextFieldEventOptions {
3807 consume_handled_events: true,
3808 },
3809 ),
3810 }
3811 }
3812
3813 fn start_rename(&self, ctx: &mut EventCtx<A>, node: &FlatNode<T>) {
3815 if self.begin_rename(node) {
3816 ctx.request_repaint();
3817 ctx.stop_propagation();
3818 }
3819 }
3820
3821 fn begin_rename(&self, node: &FlatNode<T>) -> bool {
3823 if !self.editable.read() || !self.can_mutate_nodes() || node.disabled {
3824 return false;
3825 }
3826 let mut edit_state = TextEditState::new();
3827 edit_state.caret_byte = node.label.len();
3828 edit_state.selection = Some(TextSelection {
3829 anchor: 0,
3830 caret: node.label.len(),
3831 });
3832 self.editing.set(Some(TreeEditing {
3833 id: node.id.clone(),
3834 original: node.label.clone(),
3835 create: None,
3836 }));
3837 self.edit_value.set(node.label.clone());
3838 self.edit_buffer
3839 .set(TextBuffer::from_string(node.label.clone()));
3840 self.edit_state.set(edit_state);
3841 true
3842 }
3843
3844 fn begin_create_from_request(&self, request: TreeCreateRequest<T>) -> bool {
3846 if !self.creatable.read() || !self.can_mutate_nodes() {
3847 return false;
3848 }
3849 let Some(factory) = &self.create_node else {
3850 return false;
3851 };
3852 let Some(node) = factory(request.clone()) else {
3853 return false;
3854 };
3855 if self.model.is_some() && self.mutation_mode.read() == TreeMutationMode::IntentOnly {
3856 return self.begin_retained_create(node, request);
3857 }
3858 let created_id = node.id.clone();
3859 let mut nodes = self.current_nodes();
3860 if !insert_created_node(&mut nodes, &request, node) {
3861 return false;
3862 }
3863 self.set_current_nodes(nodes);
3864 if request.kind == TreeCreateKind::Child {
3865 if let Some(parent) = &request.parent {
3866 self.ensure_expanded(parent.clone());
3867 }
3868 }
3869 if let Some(bound) = &self.bound_selected {
3870 bound.set(created_id.clone());
3871 }
3872 self.active_index.set(
3873 self.visible_nodes()
3874 .iter()
3875 .position(|node| !node.disabled && node.id == created_id),
3876 );
3877 let nodes = self.visible_nodes();
3878 if let Some(node) = nodes.iter().find(|node| node.id == created_id) {
3879 return self.begin_create_rename(node, request);
3880 }
3881 true
3882 }
3883
3884 fn begin_create_rename(&self, node: &FlatNode<T>, request: TreeCreateRequest<T>) -> bool {
3886 if !self.editable.read() || !self.can_mutate_nodes() || node.disabled {
3887 return false;
3888 }
3889 let mut edit_state = TextEditState::new();
3890 edit_state.caret_byte = node.label.len();
3891 edit_state.selection = Some(TextSelection {
3892 anchor: 0,
3893 caret: node.label.len(),
3894 });
3895 self.editing.set(Some(TreeEditing {
3896 id: node.id.clone(),
3897 original: node.label.clone(),
3898 create: Some(request),
3899 }));
3900 self.edit_value.set(node.label.clone());
3901 self.edit_buffer
3902 .set(TextBuffer::from_string(node.label.clone()));
3903 self.edit_state.set(edit_state);
3904 true
3905 }
3906
3907 fn cancel_rename(&self, ctx: &mut EventCtx<A>) {
3909 if let Some(editing) = self.editing.read() {
3910 if let Some(request) = editing.create.clone() {
3911 if let Some(on_create_cancel) = &self.on_create_cancel {
3912 on_create_cancel(
3913 ctx,
3914 TreeCreateCancel {
3915 id: editing.id.clone(),
3916 request,
3917 },
3918 );
3919 }
3920 }
3921 if editing.create.is_some() {
3922 let mut nodes = self.current_nodes();
3923 if delete_node_by_id(&mut nodes, &editing.id).is_some() {
3924 let _ = self.set_current_nodes(nodes);
3925 self.remove_expanded_ids(&[editing.id]);
3926 }
3927 }
3928 }
3929 self.draft.set(None);
3930 self.editing.set(None);
3931 self.edit_value.set(String::new());
3932 self.edit_buffer.set(TextBuffer::from_string(String::new()));
3933 self.edit_state.set(TextEditState::new());
3934 ctx.request_repaint();
3935 }
3936
3937 fn commit_rename(&self, ctx: &mut EventCtx<A>) -> bool {
3943 let Some(editing) = self.editing.read() else {
3944 return false;
3945 };
3946 let new_label = self.edit_value.read().trim().to_string();
3947 if new_label.is_empty() {
3948 return false;
3949 }
3950 self.editing.set(None);
3951 let is_create = editing.create.is_some();
3952 if new_label == editing.original && !is_create {
3953 ctx.request_repaint();
3954 return true;
3955 }
3956 if let Some(request) = editing.create {
3957 if self.model.is_some() && self.mutation_mode.read() == TreeMutationMode::IntentOnly {
3958 self.draft.set(None);
3959 if let Some(on_create) = &self.on_create {
3960 on_create(
3961 ctx,
3962 TreeCreate {
3963 id: editing.id,
3964 parent: request.parent,
3965 after: request.after,
3966 kind: request.kind,
3967 label: new_label,
3968 },
3969 );
3970 }
3971 ctx.request_repaint();
3972 ctx.stop_propagation();
3973 return true;
3974 }
3975 let mut nodes = self.current_nodes();
3976 let _ = delete_node_by_id(&mut nodes, &editing.id);
3977 if !self.set_current_nodes(nodes) {
3978 return false;
3979 }
3980 if let Some(on_create) = &self.on_create {
3981 on_create(
3982 ctx,
3983 TreeCreate {
3984 id: editing.id,
3985 parent: request.parent,
3986 after: request.after,
3987 kind: request.kind,
3988 label: new_label,
3989 },
3990 );
3991 }
3992 } else if let Some(on_rename) = &self.on_rename {
3993 if self.model.is_some() && self.mutation_mode.read() == TreeMutationMode::IntentOnly {
3994 on_rename(
3995 ctx,
3996 TreeRename {
3997 id: editing.id,
3998 old_label: editing.original,
3999 new_label,
4000 },
4001 );
4002 ctx.request_repaint();
4003 ctx.stop_propagation();
4004 return true;
4005 }
4006 let mut nodes = self.current_nodes();
4007 let old_label = if new_label == editing.original {
4008 editing.original.clone()
4009 } else {
4010 let Some(old_label) = rename_node_label(&mut nodes, &editing.id, new_label.clone())
4011 else {
4012 return false;
4013 };
4014 old_label
4015 };
4016 if !self.set_current_nodes(nodes) {
4017 return false;
4018 }
4019 on_rename(
4020 ctx,
4021 TreeRename {
4022 id: editing.id,
4023 old_label,
4024 new_label,
4025 },
4026 );
4027 }
4028 ctx.request_repaint();
4029 ctx.stop_propagation();
4030 true
4031 }
4032
4033 fn apply_drop(&self, ctx: &mut EventCtx<A>, source: T, drop: TreeDropTarget<T>) {
4035 if !self.draggable.read() || !self.can_mutate_nodes() {
4036 return;
4037 }
4038 let apply_local = self.mutation_mode.read() == TreeMutationMode::ApplyLocal;
4039 if apply_local {
4040 let mut nodes = self.current_nodes();
4041 if !move_node(&mut nodes, &source, &drop.target, drop.position) {
4042 ctx.request_repaint();
4043 ctx.stop_propagation();
4044 return;
4045 }
4046 self.set_current_nodes(nodes);
4047 if drop.position == TreeDropPosition::Inside {
4048 self.ensure_expanded(drop.target.clone());
4049 }
4050 }
4051 if let Some(bound) = &self.bound_selected {
4052 bound.set(source.clone());
4053 }
4054 if let Some(on_move) = &self.on_move {
4055 on_move(
4056 ctx,
4057 TreeMove {
4058 source,
4059 target: drop.target,
4060 position: drop.position,
4061 },
4062 );
4063 }
4064 ctx.request_repaint();
4065 ctx.stop_propagation();
4066 }
4067
4068 fn create_node(
4070 &self,
4071 ctx: &mut EventCtx<A>,
4072 visible: &[FlatNode<T>],
4073 idx: usize,
4074 kind: TreeCreateKind,
4075 ) {
4076 if !self.creatable.read() || !self.can_mutate_nodes() {
4077 return;
4078 }
4079 let Some(factory) = &self.create_node else {
4080 return;
4081 };
4082 let target = &visible[idx];
4083 if target.disabled {
4084 return;
4085 }
4086 let request = match kind {
4087 TreeCreateKind::SiblingAfter => TreeCreateRequest {
4088 parent: target.parent.clone(),
4089 after: Some(target.id.clone()),
4090 kind,
4091 default_label: "New item".to_string(),
4092 },
4093 TreeCreateKind::Child => TreeCreateRequest {
4094 parent: Some(target.id.clone()),
4095 after: None,
4096 kind,
4097 default_label: "New item".to_string(),
4098 },
4099 };
4100 let Some(node) = factory(request.clone()) else {
4101 return;
4102 };
4103 if self.model.is_some() && self.mutation_mode.read() == TreeMutationMode::IntentOnly {
4104 if self.begin_retained_create(node, request) {
4105 ctx.request_repaint();
4106 ctx.stop_propagation();
4107 }
4108 return;
4109 }
4110 let created_id = node.id.clone();
4111 let created_label = node.label.clone();
4112 let mut nodes = self.current_nodes();
4113 if !insert_created_node(&mut nodes, &request, node) {
4114 return;
4115 }
4116 self.set_current_nodes(nodes);
4117 if kind == TreeCreateKind::Child {
4118 self.ensure_expanded(target.id.clone());
4119 }
4120 if let Some(bound) = &self.bound_selected {
4121 bound.set(created_id.clone());
4122 }
4123 if let Some(on_create) = &self.on_create {
4124 on_create(
4125 ctx,
4126 TreeCreate {
4127 id: created_id.clone(),
4128 parent: request.parent.clone(),
4129 after: request.after.clone(),
4130 kind,
4131 label: created_label.clone(),
4132 },
4133 );
4134 }
4135 self.start_rename(
4136 ctx,
4137 &FlatNode {
4138 id: created_id,
4139 label: created_label,
4140 depth: target.depth,
4141 branch: false,
4142 disabled: false,
4143 leading_icon: None,
4144 leading_icon_tint: None,
4145 trailing_action: None,
4146 parent: request.parent,
4147 },
4148 );
4149 ctx.request_repaint();
4150 ctx.stop_propagation();
4151 }
4152
4153 fn delete_node(&self, ctx: &mut EventCtx<A>, visible: &[FlatNode<T>], idx: usize) {
4155 if !self.deletable.read() || !self.can_mutate_nodes() {
4156 return;
4157 }
4158 let target = &visible[idx];
4159 if target.disabled {
4160 return;
4161 }
4162 if self.mutation_mode.read() == TreeMutationMode::IntentOnly {
4163 if let Some(on_delete) = &self.on_delete {
4164 on_delete(
4165 ctx,
4166 TreeDelete {
4167 id: target.id.clone(),
4168 parent: target.parent.clone(),
4169 },
4170 );
4171 }
4172 ctx.request_repaint();
4173 ctx.stop_propagation();
4174 return;
4175 }
4176 let mut nodes = self.current_nodes();
4177 let Some((deleted, parent)) = delete_node_by_id(&mut nodes, &target.id) else {
4178 return;
4179 };
4180 let deleted_ids = collect_node_ids(&deleted);
4181 self.set_current_nodes(nodes);
4182 self.remove_expanded_ids(&deleted_ids);
4183 let next_idx = next_enabled_after_delete(visible, idx, &deleted_ids);
4184 if let Some(bound) = &self.bound_selected {
4185 if let Some(next) = next_idx.and_then(|idx| visible.get(idx)) {
4186 bound.set(next.id.clone());
4187 }
4188 }
4189 self.active_index.set(next_idx);
4190 if let Some(on_delete) = &self.on_delete {
4191 on_delete(
4192 ctx,
4193 TreeDelete {
4194 id: deleted.id,
4195 parent,
4196 },
4197 );
4198 }
4199 ctx.request_repaint();
4200 ctx.stop_propagation();
4201 }
4202
4203 fn ensure_expanded(&self, id: T) {
4205 let Some(bound) = &self.mutable_expanded else {
4206 return;
4207 };
4208 let mut expanded = self.expanded_values();
4209 if !expanded.iter().any(|value| value == &id) {
4210 expanded.push(id);
4211 bound.set(expanded);
4212 }
4213 }
4214
4215 fn remove_expanded_ids(&self, ids: &[T]) {
4217 let Some(bound) = &self.mutable_expanded else {
4218 return;
4219 };
4220 let mut expanded = self.expanded_values();
4221 expanded.retain(|id| !ids.iter().any(|deleted| deleted == id));
4222 bound.set(expanded);
4223 }
4224}
4225
4226fn row_range_with_overscan(
4231 viewport_y: f32,
4232 viewport_height: f32,
4233 padding_y: f32,
4234 row_height: f32,
4235 len: usize,
4236 overscan_rows: usize,
4237) -> std::ops::Range<usize> {
4238 if len == 0 || row_height <= 0.0 || viewport_height <= 0.0 {
4239 return 0..0;
4240 }
4241 let top = viewport_y - padding_y;
4242 let bottom = viewport_y + viewport_height - padding_y;
4243 let first = (top / row_height).floor().max(0.0) as usize;
4244 let last = (bottom / row_height).ceil().max(0.0) as usize;
4245 let start = first.saturating_sub(overscan_rows).min(len);
4246 let end = last
4247 .saturating_add(overscan_rows)
4248 .saturating_add(1)
4249 .min(len);
4250 start..end.max(start)
4251}
4252
4253fn flatten_node<T: Clone + PartialEq>(
4255 node: &TreeNode<T>,
4256 depth: usize,
4257 parent: Option<T>,
4258 expanded: &[T],
4259 out: &mut Vec<FlatNode<T>>,
4260) {
4261 let branch = node.branch || !node.children.is_empty();
4262 let is_expanded = expanded.iter().any(|id| id == &node.id);
4263 out.push(FlatNode {
4264 id: node.id.clone(),
4265 label: node.label.clone(),
4266 depth,
4267 branch,
4268 disabled: node.disabled.read(),
4269 leading_icon: node.leading_icon.clone(),
4270 leading_icon_tint: node.leading_icon_tint,
4271 trailing_action: node.trailing_action.clone(),
4272 parent: parent.clone(),
4273 });
4274 if branch && is_expanded {
4275 for child in &node.children {
4276 flatten_node(child, depth + 1, Some(node.id.clone()), expanded, out);
4277 }
4278 }
4279}
4280
4281fn find_path<T: PartialEq>(nodes: &[TreeNode<T>], id: &T) -> Option<Vec<usize>> {
4283 for (idx, node) in nodes.iter().enumerate() {
4284 if &node.id == id {
4285 return Some(vec![idx]);
4286 }
4287 if let Some(mut child) = find_path(&node.children, id) {
4288 child.insert(0, idx);
4289 return Some(child);
4290 }
4291 }
4292 None
4293}
4294
4295fn path_is_descendant_or_self(path: &[usize], ancestor: &[usize]) -> bool {
4297 path.len() >= ancestor.len() && path.starts_with(ancestor)
4298}
4299
4300fn node_at_path<'a, T>(nodes: &'a [TreeNode<T>], path: &[usize]) -> Option<&'a TreeNode<T>> {
4302 let (first, rest) = path.split_first()?;
4303 let node = nodes.get(*first)?;
4304 if rest.is_empty() {
4305 Some(node)
4306 } else {
4307 node_at_path(&node.children, rest)
4308 }
4309}
4310
4311fn node_mut_at_path<'a, T>(
4313 nodes: &'a mut [TreeNode<T>],
4314 path: &[usize],
4315) -> Option<&'a mut TreeNode<T>> {
4316 let (first, rest) = path.split_first()?;
4317 let node = nodes.get_mut(*first)?;
4318 if rest.is_empty() {
4319 Some(node)
4320 } else {
4321 node_mut_at_path(&mut node.children, rest)
4322 }
4323}
4324
4325fn remove_node_at_path<T>(nodes: &mut Vec<TreeNode<T>>, path: &[usize]) -> Option<TreeNode<T>> {
4327 if path.len() == 1 {
4328 return (path[0] < nodes.len()).then(|| nodes.remove(path[0]));
4329 }
4330 let parent_path = &path[..path.len() - 1];
4331 let child_idx = *path.last()?;
4332 let parent = node_mut_at_path(nodes, parent_path)?;
4333 (child_idx < parent.children.len()).then(|| parent.children.remove(child_idx))
4334}
4335
4336fn insert_node_relative<T: Clone + PartialEq>(
4338 nodes: &mut Vec<TreeNode<T>>,
4339 target: &T,
4340 position: TreeDropPosition,
4341 node: TreeNode<T>,
4342) -> bool {
4343 let Some(target_path) = find_path(nodes, target) else {
4344 return false;
4345 };
4346 match position {
4347 TreeDropPosition::Inside => {
4348 if let Some(target_node) = node_mut_at_path(nodes, &target_path) {
4349 target_node.children.push(node);
4350 true
4351 } else {
4352 false
4353 }
4354 }
4355 TreeDropPosition::Before | TreeDropPosition::After => {
4356 let target_idx = *target_path.last().unwrap_or(&0);
4357 let insert_idx = if position == TreeDropPosition::Before {
4358 target_idx
4359 } else {
4360 target_idx + 1
4361 };
4362 if target_path.len() == 1 {
4363 nodes.insert(insert_idx.min(nodes.len()), node);
4364 true
4365 } else {
4366 let parent_path = &target_path[..target_path.len() - 1];
4367 if let Some(parent) = node_mut_at_path(nodes, parent_path) {
4368 parent
4369 .children
4370 .insert(insert_idx.min(parent.children.len()), node);
4371 true
4372 } else {
4373 false
4374 }
4375 }
4376 }
4377 }
4378}
4379
4380fn move_node<T: Clone + PartialEq>(
4384 nodes: &mut Vec<TreeNode<T>>,
4385 source: &T,
4386 target: &T,
4387 position: TreeDropPosition,
4388) -> bool {
4389 let original = nodes.clone();
4390 let Some(source_path) = find_path(nodes, source) else {
4391 return false;
4392 };
4393 let Some(target_path) = find_path(nodes, target) else {
4394 return false;
4395 };
4396 if path_is_descendant_or_self(&target_path, &source_path) {
4397 return false;
4398 }
4399 let source_disabled = node_at_path(nodes, &source_path)
4400 .map(|node| node.disabled.read())
4401 .unwrap_or(true);
4402 let target_disabled = node_at_path(nodes, &target_path)
4403 .map(|node| node.disabled.read())
4404 .unwrap_or(true);
4405 if source_disabled || target_disabled {
4406 return false;
4407 }
4408 let Some(moved) = remove_node_at_path(nodes, &source_path) else {
4409 return false;
4410 };
4411 if insert_node_relative(nodes, target, position, moved) {
4412 true
4413 } else {
4414 *nodes = original;
4415 false
4416 }
4417}
4418
4419fn rename_node_label<T: PartialEq>(
4421 nodes: &mut [TreeNode<T>],
4422 id: &T,
4423 new_label: String,
4424) -> Option<String> {
4425 for node in nodes {
4426 if &node.id == id {
4427 if node.disabled.read() {
4428 return None;
4429 }
4430 let old = std::mem::replace(&mut node.label, new_label);
4431 return Some(old);
4432 }
4433 if let Some(old) = rename_node_label(&mut node.children, id, new_label.clone()) {
4434 return Some(old);
4435 }
4436 }
4437 None
4438}
4439
4440fn insert_created_node<T: Clone + PartialEq>(
4442 nodes: &mut Vec<TreeNode<T>>,
4443 request: &TreeCreateRequest<T>,
4444 node: TreeNode<T>,
4445) -> bool {
4446 match request.kind {
4447 TreeCreateKind::SiblingAfter => {
4448 if let Some(after) = &request.after {
4449 insert_node_relative(nodes, after, TreeDropPosition::After, node)
4450 } else {
4451 nodes.push(node);
4452 true
4453 }
4454 }
4455 TreeCreateKind::Child => {
4456 let Some(parent) = &request.parent else {
4457 return false;
4458 };
4459 insert_node_relative(nodes, parent, TreeDropPosition::Inside, node)
4460 }
4461 }
4462}
4463
4464fn visible_subtree_end<T>(rows: &[FlatNode<T>], row: usize) -> usize {
4466 let depth = rows[row].depth;
4467 rows.iter()
4468 .enumerate()
4469 .skip(row + 1)
4470 .find_map(|(index, candidate)| (candidate.depth <= depth).then_some(index))
4471 .unwrap_or(rows.len())
4472}
4473
4474fn delete_node_by_id<T: Clone + PartialEq>(
4476 nodes: &mut Vec<TreeNode<T>>,
4477 id: &T,
4478) -> Option<(TreeNode<T>, Option<T>)> {
4479 let path = find_path(nodes, id)?;
4480 let node = node_at_path(nodes, &path)?;
4481 if node.disabled.read() {
4482 return None;
4483 }
4484 let parent = if path.len() > 1 {
4485 node_at_path(nodes, &path[..path.len() - 1]).map(|node| node.id.clone())
4486 } else {
4487 None
4488 };
4489 remove_node_at_path(nodes, &path).map(|node| (node, parent))
4490}
4491
4492fn collect_node_ids<T: Clone>(node: &TreeNode<T>) -> Vec<T> {
4494 let mut out = vec![node.id.clone()];
4495 for child in &node.children {
4496 out.extend(collect_node_ids(child));
4497 }
4498 out
4499}
4500
4501fn next_enabled_after_delete<T: PartialEq>(
4503 visible: &[FlatNode<T>],
4504 deleted_idx: usize,
4505 deleted_ids: &[T],
4506) -> Option<usize> {
4507 visible
4508 .iter()
4509 .enumerate()
4510 .skip(deleted_idx + 1)
4511 .find(|(_, node)| !node.disabled && !deleted_ids.iter().any(|id| id == &node.id))
4512 .map(|(idx, _)| idx)
4513 .or_else(|| {
4514 visible
4515 .iter()
4516 .enumerate()
4517 .take(deleted_idx)
4518 .rev()
4519 .find(|(_, node)| !node.disabled && !deleted_ids.iter().any(|id| id == &node.id))
4520 .map(|(idx, _)| idx)
4521 })
4522}
4523
4524fn unique_vec<T: PartialEq>(values: Vec<T>) -> Vec<T> {
4526 let mut out = Vec::new();
4527 for value in values {
4528 if !out.iter().any(|existing| existing == &value) {
4529 out.push(value);
4530 }
4531 }
4532 out
4533}
4534
4535fn next_enabled<T>(
4537 nodes: &[FlatNode<T>],
4538 active: Option<usize>,
4539 direction: isize,
4540) -> Option<usize> {
4541 if nodes.is_empty() {
4542 return None;
4543 }
4544 let start = active.unwrap_or(if direction >= 0 { 0 } else { nodes.len() - 1 });
4545 for step in 1..=nodes.len() {
4546 let idx = if direction >= 0 {
4547 (start + step) % nodes.len()
4548 } else {
4549 (start + nodes.len() - (step % nodes.len())) % nodes.len()
4550 };
4551 if !nodes[idx].disabled {
4552 return Some(idx);
4553 }
4554 }
4555 None
4556}
4557
4558fn first_visible_child_index<T>(nodes: &[FlatNode<T>], index: usize) -> Option<usize> {
4560 let parent_depth = nodes.get(index)?.depth;
4561 nodes
4562 .iter()
4563 .enumerate()
4564 .skip(index + 1)
4565 .find(|(_, node)| node.depth == parent_depth + 1 && !node.disabled)
4566 .map(|(idx, _)| idx)
4567}
4568
4569fn point_distance_sq(a: Point, b: Point) -> f32 {
4571 let dx = a.x - b.x;
4572 let dy = a.y - b.y;
4573 dx * dx + dy * dy
4574}
4575
4576fn key_character_upper(key: &KeyEvent) -> Option<String> {
4578 match &key.key {
4579 Key::Character(ch) => Some(ch.to_ascii_uppercase()),
4580 _ => None,
4581 }
4582}
4583
4584fn measure_text(ctx: &mut LayoutCtx<'_>, text: &str, style: TextStyle) -> Option<f32> {
4586 ctx.text_system.as_deref_mut().map(|text_system| {
4587 text_system
4588 .layout_cached(TextLayoutParams {
4589 text,
4590 style,
4591 max_width: None,
4592 wrap_mode: WrapMode::NoWrap,
4593 })
4594 .metrics
4595 .width
4596 })
4597}
4598
4599fn layout_text(
4601 ctx: &mut PaintCtx<'_>,
4602 text: &str,
4603 style: TextStyle,
4604) -> Option<Arc<PreparedTextLayout>> {
4605 ctx.text_system.as_deref_mut().map(|text_system| {
4606 text_system.layout_cached(TextLayoutParams {
4607 text,
4608 style,
4609 max_width: None,
4610 wrap_mode: WrapMode::NoWrap,
4611 })
4612 })
4613}
4614
4615fn paint_text_centered(
4617 ctx: &mut PaintCtx<'_>,
4618 text: &str,
4619 style: TextStyle,
4620 bounds: Rect,
4621 x: f32,
4622 opacity: f32,
4623) {
4624 let Some(layout) = layout_text(ctx, text, style) else {
4625 return;
4626 };
4627 let baseline = layout
4628 .lines
4629 .first()
4630 .map(|line| line.baseline_y)
4631 .unwrap_or(0.0);
4632 let y = bounds.y + (bounds.h - layout.metrics.height) * 0.5 + baseline;
4633 ctx.push(DrawCmd::Text(DrawText {
4634 pos: [x, y],
4635 color: style.color.with_alpha(style.color.a * opacity),
4636 decoration: ailloli_ui_core::TextDecoration::None,
4637 layout,
4638 }));
4639}