1pub mod filter;
63pub mod model;
64
65use std::sync::{Arc, Mutex};
66
67use crate::app_link::AppHandle;
68use crate::app_link::Outcome;
69use crate::shared::SelectionService;
70use egui::{
71 Context, Id, Modifiers, Rect, Response, Role, TextEdit, Ui, UiBuilder, WidgetInfo, pos2, vec2,
72};
73#[cfg(feature = "api")]
74use egui_pop_api::menus;
75use egui_pop_core::icon::Source;
76use egui_pop_core::kit::{KitCx, Part, State, Tone};
77use egui_pop_core::strings::{self, tr, tr_args};
78use egui_pop_core::theme::Tokens;
79use egui_pop_model::ids::{MenuId, StepId};
80use egui_pop_model::selection::SelectionItem;
81use serde_json::{Value as Json, json};
82
83pub use filter::{FilterField, Query};
84pub use model::{Children, Edit, Model, Node, Position, Row};
85
86use crate::item::{self, Disclosure, ItemAction};
87use crate::nav::{self, Nav, TypeAhead};
88use crate::rows::{self, Scroll};
89use crate::select::{Key, Mode, Proposal, Selection};
90use crate::shared;
91use crate::steps::{
92 self, TREE_ACTION, TREE_ACTIVATE, TREE_CONTEXT, TREE_DROP, TREE_EXPAND, TREE_LOAD, TREE_RENAME,
93 TREE_SELECT,
94};
95use crate::strings as s;
96
97pub trait TreeSource<K: Key> {
99 fn load(&self, parent: Option<&K>, sink: Sink<K>);
103
104 fn can_drop(&self, keys: &[K], target: &K, position: Position) -> Result<(), String> {
110 let _ = (keys, target, position);
111 Ok(())
112 }
113
114 fn match_text(&self, node: &Node<K>) -> String {
119 node.name().to_string()
120 }
121
122 fn item(&self, key: &K) -> SelectionItem {
127 SelectionItem::from_key(key)
128 }
129}
130
131pub const EDITS_WAITING: usize = 4096;
138
139struct Inbox<K> {
140 edits: Vec<Edit<K>>,
141 ctx: Option<Context>,
142 overflowed: bool,
144 dropped: u64,
146}
147
148pub struct TreeHandle<K> {
151 inbox: Arc<Mutex<Inbox<K>>>,
152}
153
154impl<K> Clone for TreeHandle<K> {
155 fn clone(&self) -> Self {
156 Self {
157 inbox: self.inbox.clone(),
158 }
159 }
160}
161
162impl<K> std::fmt::Debug for TreeHandle<K> {
163 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164 f.write_str("TreeHandle")
165 }
166}
167
168impl<K> TreeHandle<K> {
169 fn push(&self, edit: Edit<K>) {
170 let mut inbox = self.inbox.lock().unwrap_or_else(|e| e.into_inner());
171 if inbox.edits.len() >= EDITS_WAITING {
172 inbox.dropped += inbox.edits.len() as u64 + 1;
175 inbox.edits = Vec::new();
176 inbox.overflowed = true;
177 } else {
178 inbox.edits.push(edit);
179 }
180 if let Some(ctx) = &inbox.ctx {
181 ctx.request_repaint();
182 }
183 }
184
185 pub fn insert(&self, parent: Option<K>, index: Option<usize>, node: Node<K>) {
188 self.push(Edit::Insert {
189 parent,
190 index,
191 node,
192 });
193 }
194
195 pub fn remove(&self, key: K) {
197 self.push(Edit::Remove(key));
198 }
199
200 pub fn move_to(&self, key: K, parent: Option<K>, index: Option<usize>) {
202 self.push(Edit::Move { key, parent, index });
203 }
204
205 pub fn rename(&self, key: K, label: impl Into<String>) {
206 self.push(Edit::Rename {
207 key,
208 label: label.into(),
209 });
210 }
211
212 pub fn update(&self, node: Node<K>) {
214 self.push(Edit::Update(node));
215 }
216
217 pub fn reload(&self, parent: Option<K>) {
220 self.push(Edit::Reload(parent));
221 }
222
223 pub fn set_children(&self, parent: Option<K>, result: Result<Vec<Node<K>>, String>) {
226 self.push(Edit::Children {
227 parent,
228 ticket: None,
229 result,
230 });
231 }
232}
233
234#[derive(Debug)]
236pub struct Sink<K> {
237 handle: TreeHandle<K>,
238 parent: Option<K>,
239 ticket: u64,
240}
241
242impl<K> Sink<K> {
243 pub fn parent(&self) -> Option<&K> {
245 self.parent.as_ref()
246 }
247
248 pub fn deliver(self, children: Vec<Node<K>>) {
250 self.answer(Ok(children));
251 }
252
253 pub fn fail(self, reason: impl Into<String>) {
255 self.answer(Err(reason.into()));
256 }
257
258 fn answer(self, result: Result<Vec<Node<K>>, String>) {
259 self.handle.push(Edit::Children {
260 parent: self.parent,
261 ticket: Some(self.ticket),
262 result,
263 });
264 }
265}
266
267#[derive(Clone, Debug)]
268struct Renaming<K> {
269 key: K,
270 text: String,
271 focus: bool,
272}
273
274#[derive(Clone, Debug)]
275struct Drag<K> {
276 keys: Vec<K>,
277 target: Option<(K, Position)>,
280}
281
282pub struct TreeState<K: Key> {
285 model: Model<K>,
286 selection: Selection<K>,
287 inbox: Arc<Mutex<Inbox<K>>>,
288 scroll: Scroll,
289 type_ahead: TypeAhead,
290 renaming: Option<Renaming<K>>,
291 drag: Option<Drag<K>>,
292 context: Option<(K, K)>,
294 pending: Option<(Vec<K>, Option<K>)>,
296 reveal: Option<K>,
298 filter: String,
300 query: Query,
301 filter_fresh: bool,
303 filtered_at: Option<u64>,
305 pub(crate) field: Option<Id>,
307 pub(crate) field_focus: bool,
309 pub(crate) focus_tree: bool,
311 pub(crate) reported: Option<u64>,
313 seen: Option<(u64, u64)>,
316}
317
318impl<K: Key> Default for TreeState<K> {
319 fn default() -> Self {
320 Self {
321 model: Model::default(),
322 selection: Selection::default(),
323 inbox: Arc::new(Mutex::new(Inbox {
324 edits: Vec::new(),
325 ctx: None,
326 overflowed: false,
327 dropped: 0,
328 })),
329 scroll: Scroll::default(),
330 type_ahead: TypeAhead::default(),
331 renaming: None,
332 drag: None,
333 context: None,
334 pending: None,
335 reveal: None,
336 filter: String::new(),
337 query: Query::default(),
338 filter_fresh: false,
339 filtered_at: None,
340 field: None,
341 field_focus: false,
342 focus_tree: false,
343 reported: None,
344 seen: None,
345 }
346 }
347}
348
349impl<K: Key> std::fmt::Debug for TreeState<K> {
350 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
351 f.debug_struct("TreeState")
352 .field("nodes", &self.model.len())
353 .field("rows", &self.model.rows_now().len())
354 .field("selection", &self.selection)
355 .finish()
356 }
357}
358
359impl<K: Key> TreeState<K> {
360 pub fn new() -> Self {
361 Self::default()
362 }
363
364 pub fn handle(&self) -> TreeHandle<K> {
366 TreeHandle {
367 inbox: self.inbox.clone(),
368 }
369 }
370
371 pub fn selection(&self) -> &Selection<K> {
372 &self.selection
373 }
374
375 pub fn set_selection(&mut self, keys: impl IntoIterator<Item = K>, cursor: Option<K>) {
383 self.pending = Some((keys.into_iter().collect(), cursor));
384 self.settle(false);
385 }
386
387 pub fn pending_selection(&self) -> Option<(&[K], Option<&K>)> {
390 self.pending
391 .as_ref()
392 .map(|(k, c)| (k.as_slice(), c.as_ref()))
393 }
394
395 pub fn model(&self) -> &Model<K> {
397 &self.model
398 }
399
400 pub fn set_expanded(&mut self, key: &K, expanded: bool) {
403 self.model.set_expanded(key, expanded);
404 }
405
406 pub fn rename(&mut self, key: &K) {
409 if let Some(n) = self.model.node(key) {
410 self.renaming = Some(Renaming {
411 key: key.clone(),
412 text: n.name().to_string(),
413 focus: true,
414 });
415 }
416 }
417
418 pub fn reveal(&mut self, key: &K) {
421 self.reveal = Some(key.clone());
422 }
423
424 pub fn set_filter(&mut self, text: impl Into<String>) {
429 let text = text.into();
430 if text != self.filter {
431 self.query = Query::new(&text);
432 self.filter = text;
433 self.filter_fresh = true;
434 }
435 }
436
437 pub fn filter(&self) -> &str {
439 &self.filter
440 }
441
442 pub fn filter_count(&self) -> Option<(usize, usize)> {
445 self.model.matches().map(|n| (n, self.model.len()))
446 }
447
448 fn refilter(&mut self, source: &dyn TreeSource<K>) -> bool {
451 let fresh = std::mem::take(&mut self.filter_fresh);
452 if !fresh && self.filtered_at == Some(self.model.version()) {
453 return false;
454 }
455 self.filtered_at = Some(self.model.version());
456 let matched = (!self.query.is_empty()).then(|| {
457 self.model
458 .nodes()
459 .filter(|n| self.query.matches(&source.match_text(n)))
460 .map(|n| n.key.clone())
461 .collect()
462 });
463 self.model.set_matches(matched, fresh);
464 if fresh {
465 self.model.rows();
466 let cursor = self.selection.cursor().cloned();
467 if self.query.is_empty() {
468 self.reveal = cursor;
470 } else if cursor.as_ref().and_then(|c| self.row_of(c)).is_none() {
471 let first = self
472 .model
473 .rows_now()
474 .iter()
475 .filter_map(Row::key)
476 .find(|k| self.model.is_match(k))
477 .cloned();
478 if let Some(k) = &first {
479 self.reveal = Some(k.clone());
480 }
481 if first.is_some() {
482 self.selection.set_cursor(first);
483 }
484 }
485 }
486 fresh
487 }
488
489 pub fn renaming(&self) -> Option<&K> {
491 self.renaming.as_ref().map(|r| &r.key)
492 }
493
494 fn settle(&mut self, reveal: bool) {
498 let Some((keys, cursor)) = &self.pending else {
499 return;
500 };
501 let model = &self.model;
502 let known: Vec<K> = keys.iter().filter(|k| model.contains(k)).cloned().collect();
503 let at = cursor.clone().filter(|c| model.contains(c));
504 let complete = known.len() == keys.len() && at.is_some() == cursor.is_some();
505 self.selection.set(known, at.clone());
506 if complete {
507 self.pending = None;
508 if reveal {
509 self.reveal = at;
510 }
511 }
512 }
513
514 pub fn dropped(&self) -> u64 {
518 self.inbox.lock().unwrap_or_else(|e| e.into_inner()).dropped
519 }
520
521 pub fn waiting(&self) -> usize {
523 self.inbox
524 .lock()
525 .unwrap_or_else(|e| e.into_inner())
526 .edits
527 .len()
528 }
529
530 fn drain(&mut self) -> bool {
533 let (edits, overflowed) = {
534 let mut inbox = self.inbox.lock().unwrap_or_else(|e| e.into_inner());
535 (
536 std::mem::take(&mut inbox.edits),
537 std::mem::take(&mut inbox.overflowed),
538 )
539 };
540 if overflowed {
541 self.model.reload_all();
542 }
543 let any = !edits.is_empty() || overflowed;
544 let cursor_at = self
545 .selection
546 .cursor()
547 .and_then(|c| self.row_of(c))
548 .unwrap_or(0);
549 for e in edits {
550 self.model.apply(e);
551 }
552 if any {
553 let model = &self.model;
554 let had_cursor = self.selection.cursor().is_some();
555 self.selection.retain(|k| model.contains(k));
556 let queued = self.pending.is_some();
558 self.settle(true);
559 if self
560 .renaming
561 .as_ref()
562 .is_some_and(|r| !self.model.contains(&r.key))
563 {
564 self.renaming = None;
565 }
566 if had_cursor && !queued && self.selection.cursor().is_none() {
568 let rows = self.model.rows();
569 let near = (0..rows.len())
570 .map(|d| cursor_at.saturating_sub(d).min(rows.len() - 1))
571 .find_map(|i| rows[i].key().cloned());
572 self.selection.set_cursor(near);
573 }
574 }
575 any
576 }
577
578 fn row_of(&self, key: &K) -> Option<usize> {
579 self.model
580 .rows_now()
581 .iter()
582 .position(|r| r.key() == Some(key))
583 }
584}
585
586#[derive(Clone, Debug, PartialEq)]
588pub enum Signal<K> {
589 Load {
591 key: Option<K>,
592 },
593 Expand {
594 key: K,
595 expanded: bool,
596 },
597 Select {
598 keys: Vec<K>,
599 cursor: Option<K>,
600 },
601 Drop {
604 keys: Vec<K>,
605 target: K,
606 position: Position,
607 },
608 Rename {
613 key: K,
614 from: String,
615 to: String,
616 },
617 Activate {
619 key: K,
620 },
621 Context {
624 key: K,
625 },
626 Vetoed {
628 step: StepId,
629 reason: String,
630 },
631}
632
633#[derive(Debug)]
635pub struct TreeOutput<K> {
636 pub response: Response,
638 pub signals: Vec<Signal<K>>,
639}
640
641enum Action<K> {
642 Load(Option<K>),
643 Expand(K, bool),
644 Select(Proposal<K>),
645 Drop(Vec<K>, K, Position),
646 Rename(K, String),
647 Activate(K),
648}
649
650type IconFn<'a, K> = Box<dyn Fn(&Node<K>) -> Option<Source> + 'a>;
652type Allows<'a, K> = dyn Fn(&[K], &K, Position) -> Result<(), String> + 'a;
654type DropFn<'a, K> = Box<Allows<'a, K>>;
656type RowFn<'a, K> = Box<dyn FnMut(&mut Ui, &Node<K>) + 'a>;
658type TrailingFn<'a, K> = Box<dyn Fn(&Node<K>) -> Option<String> + 'a>;
660type ActionsFn<'a, K> = Box<dyn Fn(&Node<K>) -> Vec<ItemAction> + 'a>;
662type OnActionFn<'a, K> = Box<dyn FnMut(&K, &str) + 'a>;
664
665enum ContextMenu<'a, K> {
667 #[cfg_attr(
669 not(feature = "api"),
670 allow(dead_code, reason = "only the api feature builds declared menus")
671 )]
672 Declared(&'a AppHandle, MenuId),
673 Ui(RowFn<'a, K>),
675}
676
677pub struct TreeView<'a, K: Key> {
681 id: String,
682 label: Option<String>,
683 mode: Mode,
684 app: Option<&'a AppHandle>,
685 drag_drop: bool,
686 rename: bool,
687 activate_on_click: bool,
688 height: Option<f32>,
689 icon: Option<IconFn<'a, K>>,
690 guides: bool,
691 trailing: Option<TrailingFn<'a, K>>,
692 actions: Option<ActionsFn<'a, K>>,
693 on_action: Option<OnActionFn<'a, K>>,
694 row_widgets: Option<RowFn<'a, K>>,
695 context: Option<ContextMenu<'a, K>>,
696 can_drop: Option<DropFn<'a, K>>,
697 shared: Option<&'a SelectionService>,
698}
699
700impl<K: Key> std::fmt::Debug for TreeView<'_, K> {
701 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
702 f.debug_struct("TreeView")
703 .field("id", &self.id)
704 .field("label", &self.label)
705 .field("mode", &self.mode)
706 .field("app", &self.app.is_some())
707 .field("drag_drop", &self.drag_drop)
708 .field("rename", &self.rename)
709 .field("activate_on_click", &self.activate_on_click)
710 .field("height", &self.height)
711 .field("icon", &self.icon.is_some())
712 .field("guides", &self.guides)
713 .field("trailing", &self.trailing.is_some())
714 .field("actions", &self.actions.is_some())
715 .field("on_action", &self.on_action.is_some())
716 .field("row_widgets", &self.row_widgets.is_some())
717 .field("context", &self.context.is_some())
718 .field("can_drop", &self.can_drop.is_some())
719 .field("shared", &self.shared.is_some())
720 .finish()
721 }
722}
723
724impl<'a, K: Key> TreeView<'a, K> {
725 pub fn new(id: impl Into<String>) -> Self {
727 Self {
728 id: id.into(),
729 label: None,
730 mode: Mode::Single,
731 app: None,
732 drag_drop: false,
733 rename: false,
734 activate_on_click: false,
735 height: None,
736 icon: None,
737 guides: false,
738 trailing: None,
739 actions: None,
740 on_action: None,
741 row_widgets: None,
742 context: None,
743 can_drop: None,
744 shared: None,
745 }
746 }
747
748 pub fn label(mut self, label: impl Into<String>) -> Self {
750 self.label = Some(label.into());
751 self
752 }
753
754 pub fn mode(mut self, mode: Mode) -> Self {
755 self.mode = mode;
756 self
757 }
758
759 #[cfg(feature = "api")]
761 pub fn app(mut self, app: &'a AppHandle) -> Self {
762 self.app = Some(app);
763 self
764 }
765
766 #[cfg(feature = "api")]
775 pub fn shared(mut self, selection: &'a SelectionService) -> Self {
776 self.shared = Some(selection);
777 self
778 }
779
780 pub fn drag_drop(mut self, on: bool) -> Self {
782 self.drag_drop = on;
783 self
784 }
785
786 pub fn can_drop(
792 mut self,
793 allow: impl Fn(&[K], &K, Position) -> Result<(), String> + 'a,
794 ) -> Self {
795 self.can_drop = Some(Box::new(allow));
796 self
797 }
798
799 fn allows(
801 &self,
802 source: &dyn TreeSource<K>,
803 keys: &[K],
804 target: &K,
805 position: Position,
806 ) -> Result<(), String> {
807 source.can_drop(keys, target, position)?;
808 match &self.can_drop {
809 Some(allow) => allow(keys, target, position),
810 None => Ok(()),
811 }
812 }
813
814 pub fn rename(mut self, on: bool) -> Self {
816 self.rename = on;
817 self
818 }
819
820 pub fn activate_on_click(mut self, on: bool) -> Self {
824 self.activate_on_click = on;
825 self
826 }
827
828 pub fn height(mut self, height: f32) -> Self {
830 self.height = Some(height);
831 self
832 }
833
834 pub fn icon(mut self, icon: impl Fn(&Node<K>) -> Option<Source> + 'a) -> Self {
840 self.icon = Some(Box::new(icon));
841 self
842 }
843
844 pub fn guides(mut self, on: bool) -> Self {
847 self.guides = on;
848 self
849 }
850
851 pub fn trailing(mut self, text: impl Fn(&Node<K>) -> Option<String> + 'a) -> Self {
854 self.trailing = Some(Box::new(text));
855 self
856 }
857
858 pub fn actions(mut self, actions: impl Fn(&Node<K>) -> Vec<ItemAction> + 'a) -> Self {
866 self.actions = Some(Box::new(actions));
867 self
868 }
869
870 pub fn on_action(mut self, act: impl FnMut(&K, &str) + 'a) -> Self {
873 self.on_action = Some(Box::new(act));
874 self
875 }
876
877 pub fn row_widgets(mut self, widgets: impl FnMut(&mut Ui, &Node<K>) + 'a) -> Self {
882 self.row_widgets = Some(Box::new(widgets));
883 self
884 }
885
886 #[cfg(feature = "api")]
892 pub fn context_menu(mut self, app: &'a AppHandle, menu: MenuId) -> Self {
893 self.context = Some(ContextMenu::Declared(app, menu));
894 self
895 }
896
897 pub fn context_ui(mut self, menu: impl FnMut(&mut Ui, &Node<K>) + 'a) -> Self {
901 self.context = Some(ContextMenu::Ui(Box::new(menu)));
902 self
903 }
904
905 pub fn show(
907 self,
908 ui: &mut Ui,
909 state: &mut TreeState<K>,
910 source: &dyn TreeSource<K>,
911 ) -> TreeOutput<K> {
912 shared::surface(ui, self.shared.is_some(), |ui| {
913 if state.field.is_some() {
915 egui_pop_core::focus::scope(ui, filter::SURFACE, &[], |ui| {
916 self.draw(ui, state, source)
917 })
918 } else {
919 self.draw(ui, state, source)
920 }
921 })
922 }
923
924 fn draw(
925 mut self,
926 ui: &mut Ui,
927 state: &mut TreeState<K>,
928 source: &dyn TreeSource<K>,
929 ) -> TreeOutput<K> {
930 let id = Id::unique(("egui_pop_views::tree", &self.id));
931 state
932 .inbox
933 .lock()
934 .unwrap_or_else(|e| e.into_inner())
935 .ctx
936 .get_or_insert_with(|| ui.ctx().clone());
937 let mut signals = Vec::new();
938 let overflowed = state
939 .inbox
940 .lock()
941 .unwrap_or_else(|e| e.into_inner())
942 .overflowed;
943 state.drain();
944 if overflowed && let Some(app) = self.app {
945 app.publish(
947 "egui_pop.tree",
948 None,
949 "tree.overflowed",
950 json!({ "tree": self.id, "dropped": state.dropped() }),
951 );
952 }
953 for _ in 0..4 {
955 let wanted = state.model.take_wanted();
956 if wanted.is_empty() {
957 break;
958 }
959 for parent in wanted {
960 self.run(state, source, Action::Load(parent), &mut signals);
961 }
962 state.drain();
963 }
964 if state.refilter(source)
965 && let Some((n, total)) = state.filter_count()
966 {
967 egui_pop_core::a11y::announce(
968 ui.ctx(),
969 strings::tr_with(
970 ui.ctx(),
971 &s::TREE_FILTER_ANNOUNCE,
972 &[("count", n.into()), ("total", total.into())],
973 ),
974 egui_pop_core::a11y::Politeness::Polite,
975 );
976 }
977
978 if let Some(service) = self.shared {
979 let version = state.model.version();
980 let TreeState {
981 model,
982 selection,
983 seen,
984 ..
985 } = &mut *state;
986 shared::follow(
987 service,
988 selection,
989 seen,
990 version,
991 model.nodes().map(|n| (n.key.clone(), source.item(&n.key))),
992 );
993 }
994 egui_pop_core::focus::reads_keys(ui.ctx(), id, &nav::READS);
995 let focused = ui.memory(|m| m.has_focus(id));
996 if focused && state.field.is_some() && filter::take_request(ui.ctx()) {
998 state.field_focus = true;
999 ui.ctx().request_repaint();
1000 }
1001 let focus_tree = std::mem::take(&mut state.focus_tree);
1002 let mut actions = Vec::new();
1003 let row_h = rows::height(ui);
1004 if focused && state.renaming.is_none() {
1005 self.keys(ui, state, row_h, &mut actions);
1006 }
1007
1008 if let Some(key) = state.reveal.take() {
1009 state.model.rows();
1010 state.scroll.reveal = state.row_of(&key);
1011 }
1012 let label = self.label.clone().unwrap_or_else(|| tr(ui.ctx(), &s::TREE));
1013 let icon = self.icon.take();
1014 let trailing = self.trailing.take();
1015 let item_actions = self.actions.take();
1016 let focused_id = ui.memory(|m| m.focused());
1017 let mut late = None;
1020 let mut clicked: Vec<(K, String)> = Vec::new();
1021 let mut row_widgets = self.row_widgets.take();
1022 let mut context_menu = self.context.take();
1023 let tree = self.id.as_str();
1024 let app = self.app;
1025 state.model.rows();
1026 let TreeState {
1027 model,
1028 selection,
1029 scroll,
1030 renaming,
1031 drag,
1032 context,
1033 query,
1034 ..
1035 } = state;
1036 let count = model.rows_now().len();
1037 let no_match = count == 0 && model.is_filtered();
1039 let shown = if no_match { 1 } else { count };
1040 let mut take_focus = false;
1041 let shared = self.shared;
1042 let mut hovering: Option<SelectionItem> = None;
1043 let mut cursor_row = None;
1044 let (_, response, inner) = rows::show(
1045 ui,
1046 id,
1047 &label,
1048 Role::Tree,
1049 scroll,
1050 shown,
1051 row_h,
1052 self.height,
1053 |ui, visible| {
1054 let indent = ui.spacing().indent;
1055 let pointer = ui.input(|i| i.pointer.interact_pos());
1056 for i in visible.range.clone() {
1057 let rect = (visible.rect_of)(i);
1058 if no_match {
1059 pseudo(ui, rect, rect.left() + indent, |ui| {
1060 ui.weak(tr(ui.ctx(), &s::TREE_FILTER_NONE));
1061 });
1062 continue;
1063 }
1064 let row = model.rows_now()[i].clone();
1065 let depth = row.depth();
1066 let x = rect.left() + depth as f32 * indent;
1067 match row {
1068 Row::Node { key, .. } => {
1069 let node = match model.node(&key) {
1070 Some(n) => n.clone(),
1071 None => continue,
1072 };
1073 let r = ui.interact(rect, id.with(("row", &key)), rows::ROW_SENSE);
1074 let by_key = focused
1076 && context_menu.is_some()
1077 && selection.cursor() == Some(&key)
1078 && egui_pop_core::pointer::claim::menu_key(ui.ctx(), true);
1079 if by_key || egui_pop_core::pointer::claim::opens_context_menu(&r) {
1080 *context = open_context(app, tree, &key, &mut signals);
1081 }
1082 if let Some((_, target)) =
1084 context.as_ref().filter(|(row, _)| *row == key)
1085 {
1086 match context_menu.as_mut() {
1087 #[cfg(not(feature = "api"))]
1088 Some(ContextMenu::Declared(app, _)) => match **app {},
1089 #[cfg(feature = "api")]
1090 Some(ContextMenu::Declared(app, menu)) => {
1091 menus::context_menu_opened(
1092 &r,
1093 app,
1094 menu,
1095 json!({ "tree": tree, "key": target }),
1096 by_key,
1097 );
1098 }
1099 Some(ContextMenu::Ui(add)) => {
1100 if let Some(n) = model.node(target) {
1101 egui_pop_core::pointer::claim::context_menu_opened(
1102 &r,
1103 by_key,
1104 |ui| add(ui, n),
1105 );
1106 }
1107 }
1108 None => {}
1109 }
1110 }
1111 let selected = selection.contains(&key);
1112 let cursor = (focused && selection.cursor() == Some(&key))
1113 || r.context_menu_opened();
1114 if focused && selection.cursor() == Some(&key) {
1115 cursor_row = Some(r.id);
1116 }
1117 let mut hovered = r.contains_pointer() && drag.is_none();
1118 if let Some(service) = shared {
1120 let item = source.item(&key);
1121 if hovered {
1122 hovering = Some(item);
1123 } else {
1124 hovered = service.is_hovered(&item);
1125 }
1126 }
1127 let row_state = rows::state(
1128 selected,
1129 hovered,
1130 cursor && egui_pop_core::focus::ring_shown(ui.ctx()),
1131 );
1132 let source = icon.as_ref().and_then(|f| f(&node));
1133 let row_actions =
1134 item_actions.as_ref().map(|f| f(&node)).unwrap_or_default();
1135 let action_focused = focused_id.is_some_and(|f| {
1136 (0..row_actions.len()).any(|k| item::action_id(r.id, k) == f)
1137 });
1138 let at_cursor =
1139 selection.cursor() == Some(&key) && (focused || action_focused);
1140 let revealed =
1141 (r.contains_pointer() && drag.is_none()) || selected || at_cursor;
1142 let placed = item::Frame {
1143 kit: visible.kit,
1144 state: row_state,
1145 depth,
1146 guides: self.guides,
1147 disclosure: if node.branch {
1148 Disclosure::branch(model.is_open(&key))
1149 } else {
1150 Disclosure::Leaf
1151 },
1152 handle: false,
1153 icon: source.as_ref(),
1154 }
1155 .paint(ui, rect, revealed);
1156 let color = placed.color;
1157 let toggle = placed.toggle.unwrap_or(rect);
1158 if let Some(name) = source.as_ref().and_then(Source::icon_name) {
1159 egui_pop_core::icon::registry::record(
1160 ui.ctx(),
1161 "tree",
1162 &node.label,
1163 name,
1164 );
1165 }
1166 let left = placed.left;
1167 let mut right = rect.right();
1170 if let Some(add) = row_widgets.as_mut() {
1171 let mut child = ui.new_child(
1172 UiBuilder::new()
1173 .id_salt(("row_widgets", &key))
1174 .max_rect(Rect::from_min_max(
1175 pos2(left, rect.top()),
1176 rect.max,
1177 ))
1178 .layout(egui::Layout::right_to_left(egui::Align::Center)),
1179 );
1180 add(&mut child, &node);
1181 let used = child.min_rect();
1182 if used.width() > 0.0 {
1183 right = used.left() - ui.spacing().item_spacing.x;
1184 }
1185 }
1186 let shown: Vec<usize> = (0..row_actions.len())
1190 .filter(|&k| revealed || row_actions[k].is_pinned())
1191 .collect();
1192 let spots = item::action_rects(ui, rect, right, shown.len());
1193 if let Some(last) = spots.last() {
1194 right = last.left();
1195 }
1196 if at_cursor && !shown.is_empty() {
1197 late = Some((
1198 key.clone(),
1199 r.id,
1200 row_state,
1201 shown
1202 .iter()
1203 .map(|&k| row_actions[k].clone())
1204 .collect::<Vec<_>>(),
1205 shown.clone(),
1206 spots.clone(),
1207 ));
1208 } else {
1209 for (&k, spot) in shown.iter().zip(&spots) {
1210 let a = &row_actions[k];
1211 let id = item::action_id(r.id, k);
1212 if item::action_button(ui, visible.kit, id, *spot, a, row_state)
1213 .clicked()
1214 {
1215 clicked.push((key.clone(), a.id().to_string()));
1216 }
1217 }
1218 }
1219 if let Some(text) = trailing.as_ref().and_then(|f| f(&node)) {
1220 right = item::paint_trailing(
1221 ui,
1222 visible.kit,
1223 row_state,
1224 rect,
1225 left,
1226 right,
1227 &text,
1228 );
1229 }
1230 let text_rect = Rect::from_min_max(
1231 pos2(left, rect.top()),
1232 pos2(right.max(left), rect.bottom()),
1233 );
1234 let editing = renaming.as_ref().is_some_and(|r| r.key == key);
1235 let mut elided = false;
1236 if editing {
1237 let ren = renaming.as_mut().expect("renaming");
1238 let mut child = ui.new_child(
1239 UiBuilder::new()
1240 .max_rect(text_rect.shrink2(vec2(0.0, 1.0)))
1241 .layout(egui::Layout::left_to_right(egui::Align::Center)),
1242 );
1243 let edit = child.add(
1244 TextEdit::singleline(&mut ren.text)
1245 .id(id.with("rename"))
1246 .desired_width(text_rect.width() - 4.0),
1247 );
1248 egui_pop_core::a11y::name(
1249 &edit,
1250 Role::TextInput,
1251 &tr_args(ui.ctx(), &s::RENAME, &[("name", node.name())]),
1252 );
1253 if ren.focus {
1254 edit.request_focus();
1255 ren.focus = false;
1256 } else if edit.lost_focus() {
1257 if ui.input(|i| i.key_pressed(egui::Key::Enter)) {
1258 actions.push(Action::Rename(key.clone(), ren.text.clone()));
1259 }
1260 *renaming = None;
1261 take_focus = true;
1262 }
1263 } else {
1264 let font = egui::TextStyle::Body.resolve(ui.style());
1265 let hits = if model.is_filtered() {
1266 query.positions(&node.label)
1267 } else {
1268 Vec::new()
1269 };
1270 elided = if hits.is_empty() {
1271 item::paint_label(ui, rect, left, right, &node.label, color)
1272 } else {
1273 let strong = visible
1276 .kit
1277 .list_item
1278 .style_toned(Tone::Accent, row_state)
1279 .text;
1280 let job = filter::highlighted(
1281 &node.label,
1282 &hits,
1283 font,
1284 color,
1285 strong,
1286 );
1287 item::paint_label_job(ui, rect, left, right, job, color)
1288 };
1289 }
1290 let name = node.label.clone();
1291 r.widget_info(move || {
1292 WidgetInfo::selected(Role::Button, true, selected, &name)
1293 });
1294 if node.branch {
1297 let open = model.is_open(&key);
1298 ui.ctx()
1299 .accesskit_node_builder(r.id, |n| n.set_expanded(open));
1300 }
1301 let r = if elided {
1302 item::full_label_tip(r, &node.label)
1303 } else {
1304 r
1305 };
1306 let labels: Vec<String> =
1307 row_actions.iter().map(|a| a.label().to_string()).collect();
1308 item::custom_actions(ui, r.id, &labels);
1309 if let Some(a) =
1310 item::requested_action(ui, r.id).and_then(|k| row_actions.get(k))
1311 {
1312 clicked.push((key.clone(), a.id().to_string()));
1313 }
1314 let double = r.double_clicked();
1315 if double && self.activate_on_click {
1316 } else if double {
1318 if node.branch {
1319 actions.push(Action::Expand(key.clone(), !model.is_open(&key)));
1320 } else {
1321 actions.push(Action::Activate(key.clone()));
1322 }
1323 } else if r.clicked() {
1324 take_focus = true;
1325 let on_toggle = pointer.is_some_and(|p| toggle.contains(p));
1326 if node.branch && on_toggle {
1327 actions.push(Action::Expand(key.clone(), !model.is_open(&key)));
1328 } else if let Some(j) = node_index(model, i) {
1329 let nodes = model.node_rows();
1330 let key_at = |j: usize| {
1331 model.rows_now()[nodes[j]]
1332 .key()
1333 .cloned()
1334 .expect("a node row")
1335 };
1336 let mods = ui.input(|i| i.modifiers);
1337 actions.push(Action::Select(selection.click(
1338 self.mode,
1339 nodes.len(),
1340 &key_at,
1341 j,
1342 mods,
1343 )));
1344 if self.activate_on_click {
1345 actions.push(if node.branch {
1346 Action::Expand(key.clone(), !model.is_open(&key))
1347 } else {
1348 Action::Activate(key.clone())
1349 });
1350 }
1351 }
1352 }
1353 if self.drag_drop && r.drag_started() && renaming.is_none() {
1354 let keys = if selected && self.mode == Mode::Multiple {
1355 model
1357 .node_rows()
1358 .iter()
1359 .filter_map(|&j| model.rows_now()[j].key())
1360 .filter(|k| selection.contains(k))
1361 .cloned()
1362 .collect()
1363 } else {
1364 vec![key.clone()]
1365 };
1366 *drag = Some(Drag { keys, target: None });
1367 }
1368 }
1369 Row::Loading { .. } => {
1370 pseudo(ui, rect, x + indent, |ui| {
1371 ui.weak(tr(ui.ctx(), &s::LOADING));
1372 });
1373 }
1374 Row::Empty { .. } => {
1375 pseudo(ui, rect, x + indent, |ui| {
1376 ui.weak(tr(ui.ctx(), &s::EMPTY));
1377 });
1378 }
1379 Row::Failed { parent, reason, .. } => {
1380 pseudo(ui, rect, x + indent, |ui| {
1381 ui.colored_label(
1382 Tokens::of(ui.ctx()).status.danger,
1383 tr_args(ui.ctx(), &s::FAILED, &[("reason", &reason)]),
1384 );
1385 if ui.small_button(tr(ui.ctx(), &strings::RETRY)).clicked() {
1386 actions.push(Action::Load(parent.clone()));
1387 }
1388 });
1389 }
1390 }
1391 }
1392 if let Some(d) = drag.as_mut() {
1393 let allows = |keys: &[K], target: &K, position: Position| {
1394 self.allows(source, keys, target, position)
1395 };
1396 dragging(ui, d, model, &visible, pointer, indent, row_h, &allows);
1397 }
1398 },
1399 );
1400 rows::active_row(ui, response.id, cursor_row);
1401 if let Some((key, row, row_state, row_actions, shown, spots)) = late {
1404 let kit = egui_pop_core::kit::Kit::of(ui.ctx());
1407 for ((a, &k), spot) in row_actions.iter().zip(&shown).zip(&spots) {
1408 if !inner.contains_rect(*spot) {
1409 continue;
1410 }
1411 if item::action_button(ui, &kit, item::action_id(row, k), *spot, a, row_state)
1412 .clicked()
1413 {
1414 clicked.push((key.clone(), a.id().to_string()));
1415 }
1416 }
1417 }
1418 if let Some(d) = drag.as_ref() {
1420 let (released, down) =
1421 ui.input(|i| (i.pointer.primary_released(), i.pointer.primary_down()));
1422 let inside = ui
1423 .input(|i| i.pointer.interact_pos())
1424 .is_some_and(|p| inner.contains(p));
1425 if released || !down {
1426 if released
1427 && inside
1428 && let Some((target, position)) = d.target.clone()
1429 {
1430 actions.push(Action::Drop(d.keys.clone(), target, position));
1431 }
1432 *drag = None;
1433 } else if let Some(p) = ui.input(|i| i.pointer.interact_pos()) {
1434 let edge = row_h;
1436 let max = (count as f32 * row_h - inner.height()).max(0.0);
1437 if p.y < inner.top() + edge && scroll.offset > 0.0 {
1438 scroll.to = Some((scroll.offset - row_h / 2.0).max(0.0));
1439 } else if p.y > inner.bottom() - edge && scroll.offset < max {
1440 scroll.to = Some((scroll.offset + row_h / 2.0).min(max));
1441 }
1442 if scroll.to.is_some() {
1443 ui.ctx().request_repaint();
1444 }
1445 }
1446 }
1447 if take_focus || focus_tree {
1448 response.request_focus();
1449 }
1450 if let Some(service) = shared {
1451 service.hover(&self.id, hovering.as_ref());
1452 }
1453 let ran = !actions.is_empty();
1454 let before = state.selection.keys().to_vec();
1455 let first = signals.len();
1456 for a in actions {
1457 self.run(state, source, a, &mut signals);
1458 }
1459 if let Some(service) = shared
1460 && let Some(Signal::Select { keys, .. }) = signals[first..]
1461 .iter()
1462 .rev()
1463 .find(|s| matches!(s, Signal::Select { .. }))
1464 {
1465 let keep_others = ui.input(|i| i.modifiers.command);
1466 shared::write(service, &self.id, &before, keys, keep_others, &|k| {
1467 source.item(k)
1468 });
1469 state.seen = Some((service.revision(), state.model.version()));
1470 }
1471 if ran {
1472 state.drain();
1473 ui.ctx().request_repaint();
1474 }
1475 for (key, action) in clicked {
1476 let outcome = steps::run(
1477 self.app,
1478 &TREE_ACTION,
1479 json!({ "tree": self.id, "key": key, "action": action }),
1480 |_| Ok(Json::Null),
1481 );
1482 match outcome {
1483 Outcome::Done(Ok(_)) => {
1484 if let Some(act) = self.on_action.as_mut() {
1485 act(&key, &action);
1486 }
1487 }
1488 Outcome::Done(Err(reason)) | Outcome::Vetoed { reason, .. } => {
1489 signals.push(Signal::Vetoed {
1490 step: TREE_ACTION,
1491 reason,
1492 })
1493 }
1494 }
1495 ui.ctx().request_repaint();
1496 }
1497 filter::report(ui.ctx(), &self.id, state);
1498 TreeOutput { response, signals }
1499 }
1500
1501 fn keys(&self, ui: &Ui, state: &mut TreeState<K>, row_h: f32, actions: &mut Vec<Action<K>>) {
1503 let keys = nav::read(ui);
1504 if keys.is_empty() {
1505 return;
1506 }
1507 let model = &mut state.model;
1508 model.rows();
1509 let nodes = model.node_rows().to_vec();
1510 let rows = model.rows_now();
1511 let key_at = |j: usize| rows[nodes[j]].key().cloned().expect("a node row");
1512 let cursor = state
1513 .selection
1514 .cursor()
1515 .and_then(|c| nodes.iter().position(|&i| rows[i].key() == Some(c)));
1516 let page = rows::page(&state.scroll, row_h);
1517 let now = ui.input(|i| i.time);
1518 for (k, mods) in keys {
1519 let mut go = |j: usize, mods: Modifiers, actions: &mut Vec<Action<K>>| {
1520 actions.push(Action::Select(state.selection.move_to(
1521 self.mode,
1522 nodes.len(),
1523 &key_at,
1524 j,
1525 mods,
1526 )));
1527 state.scroll.reveal = Some(nodes[j]);
1528 };
1529 match k {
1530 Nav::Up | Nav::Down | Nav::PageUp | Nav::PageDown | Nav::Home | Nav::End => {
1531 if let Some(j) = nav::target(&k, cursor, nodes.len(), page) {
1532 go(j, mods, actions);
1533 }
1534 }
1535 Nav::Left | Nav::Right => {
1536 let Some(c) = cursor else { continue };
1537 let key = key_at(c);
1538 let Some(node) = model.node(&key) else {
1539 continue;
1540 };
1541 let open = node.branch && model.is_open(&key);
1542 match (k, open) {
1543 (Nav::Left, true) => actions.push(Action::Expand(key, false)),
1544 (Nav::Left, false) => {
1545 if let Some(Some(p)) = model.parent(&key)
1546 && let Some(j) =
1547 nodes.iter().position(|&i| rows[i].key() == Some(p))
1548 {
1549 go(j, Modifiers::NONE, actions);
1550 }
1551 }
1552 (_, false) if node.branch => actions.push(Action::Expand(key, true)),
1553 (_, true) => {
1554 if let Some(j) = model.loaded(Some(&key)).and_then(|v| {
1556 v.iter().find_map(|first| {
1557 nodes.iter().position(|&i| rows[i].key() == Some(first))
1558 })
1559 }) {
1560 go(j, Modifiers::NONE, actions);
1561 }
1562 }
1563 _ => {}
1564 }
1565 }
1566 Nav::Space => {
1567 if mods.command {
1568 if let Some(p) = state.selection.toggle_cursor(self.mode) {
1569 actions.push(Action::Select(p));
1570 }
1571 } else if let Some(c) = cursor {
1572 go(c, Modifiers::NONE, actions);
1573 }
1574 }
1575 Nav::All if self.mode == Mode::Multiple => {
1576 actions.push(Action::Select(state.selection.all(nodes.len(), &key_at)));
1577 }
1578 Nav::Activate => {
1579 let Some(c) = cursor else { continue };
1580 let key = key_at(c);
1581 match model.node(&key) {
1582 Some(n) if n.branch => {
1583 actions.push(Action::Expand(key.clone(), !model.is_open(&key)))
1584 }
1585 Some(_) => actions.push(Action::Activate(key)),
1586 None => {}
1587 }
1588 }
1589 Nav::Rename if self.rename => {
1590 if let Some(c) = cursor
1591 && let Some(n) = model.node(&key_at(c))
1592 {
1593 state.renaming = Some(Renaming {
1594 key: n.key.clone(),
1595 text: n.name().to_string(),
1596 focus: true,
1597 });
1598 return;
1599 }
1600 }
1601 Nav::Text(t) => {
1602 let search = state.type_ahead.push(&t, now).to_string();
1603 let label_at = |j: usize| {
1604 model
1605 .node(&key_at(j))
1606 .map(|n| n.name().to_string())
1607 .unwrap_or_default()
1608 };
1609 if let Some(j) = nav::find(&search, cursor, nodes.len(), &label_at) {
1610 go(j, Modifiers::NONE, actions);
1611 }
1612 }
1613 _ => {}
1614 }
1615 }
1616 }
1617
1618 fn run(
1620 &self,
1621 state: &mut TreeState<K>,
1622 source: &dyn TreeSource<K>,
1623 action: Action<K>,
1624 signals: &mut Vec<Signal<K>>,
1625 ) {
1626 let tree = self.id.as_str();
1627 let (step, outcome, signal) = match action {
1628 Action::Load(parent) => {
1629 let ticket = state.model.begin_load(parent.as_ref());
1630 let handle = state.handle();
1631 let asked = parent.clone();
1632 let outcome = steps::run(
1633 self.app,
1634 &TREE_LOAD,
1635 json!({ "tree": tree, "key": parent }),
1636 |args| {
1637 let parent: Option<K> = parse(&args["key"])?;
1638 let ticket = if parent == asked {
1639 ticket
1640 } else {
1641 state.model.begin_load(parent.as_ref())
1642 };
1643 source.load(
1644 parent.as_ref(),
1645 Sink {
1646 handle,
1647 parent: parent.clone(),
1648 ticket,
1649 },
1650 );
1651 Ok(json!("loading"))
1652 },
1653 );
1654 if let Some(reason) = outcome.vetoed() {
1655 state.model.fail(parent.as_ref(), reason);
1656 }
1657 (TREE_LOAD, outcome, Signal::Load { key: parent })
1658 }
1659 Action::Expand(key, expanded) if state.model.is_filtered() => {
1662 state.model.set_open(&key, expanded);
1663 return;
1664 }
1665 Action::Expand(key, expanded) => {
1666 let mut done = (key.clone(), expanded);
1667 let outcome = steps::run(
1668 self.app,
1669 &TREE_EXPAND,
1670 json!({ "tree": tree, "key": key, "expanded": expanded }),
1671 |args| {
1672 let key: K = parse(&args["key"])?;
1673 let expanded = args["expanded"].as_bool().unwrap_or(expanded);
1674 state.model.set_expanded(&key, expanded);
1675 done = (key, expanded);
1676 Ok(Json::Bool(expanded))
1677 },
1678 );
1679 (
1680 TREE_EXPAND,
1681 outcome,
1682 Signal::Expand {
1683 key: done.0,
1684 expanded: done.1,
1685 },
1686 )
1687 }
1688 Action::Select(p) => {
1689 state.pending = None;
1691 let mut done = p.clone();
1692 let selection = &mut state.selection;
1693 let outcome = steps::run(self.app, &TREE_SELECT, p.args("tree", tree), |args| {
1694 done = p.from_args(args)?;
1695 selection.apply(done.clone());
1696 Ok(json!(done.keys.len()))
1697 });
1698 (
1699 TREE_SELECT,
1700 outcome,
1701 Signal::Select {
1702 keys: done.keys,
1703 cursor: done.cursor,
1704 },
1705 )
1706 }
1707 Action::Drop(keys, target, position) => {
1708 let mut done = (keys.clone(), target.clone(), position);
1709 let model = &mut state.model;
1710 let allows = |keys: &[K], target: &K, position: Position| {
1711 self.allows(source, keys, target, position)
1712 };
1713 let outcome = steps::run(
1714 self.app,
1715 &TREE_DROP,
1716 json!({ "tree": tree, "keys": keys, "target": target, "position": position }),
1717 |args| {
1718 let keys: Vec<K> = parse(&args["keys"])?;
1719 let target: K = parse(&args["target"])?;
1720 let position: Position = parse(&args["position"])?;
1721 allows(&keys, &target, position)?;
1722 drop_into(model, &keys, &target, position)?;
1723 done = (keys, target, position);
1724 Ok(json!(done.0.len()))
1725 },
1726 );
1727 (
1728 TREE_DROP,
1729 outcome,
1730 Signal::Drop {
1731 keys: done.0,
1732 target: done.1,
1733 position: done.2,
1734 },
1735 )
1736 }
1737 Action::Rename(key, to) => {
1738 let Some(node) = state.model.node(&key).cloned() else {
1739 return;
1740 };
1741 let from = node.name().to_string();
1742 if to.trim().is_empty() || to == from {
1743 return;
1744 }
1745 let mut done = to.clone();
1746 let model = &mut state.model;
1747 let outcome = steps::run(
1748 self.app,
1749 &TREE_RENAME,
1750 json!({ "tree": tree, "key": key, "from": from, "to": to }),
1751 |args| {
1752 let to = args["to"].as_str().ok_or("`to` is not a text")?.to_string();
1753 let mut renamed = node;
1757 match &mut renamed.name {
1758 Some(name) => *name = to.clone(),
1759 None => renamed.label = to.clone(),
1760 }
1761 model.apply(Edit::Update(renamed));
1762 done = to;
1763 Ok(json!(done))
1764 },
1765 );
1766 (
1767 TREE_RENAME,
1768 outcome,
1769 Signal::Rename {
1770 key,
1771 from,
1772 to: done,
1773 },
1774 )
1775 }
1776 Action::Activate(key) => {
1777 let outcome = steps::run(
1778 self.app,
1779 &TREE_ACTIVATE,
1780 json!({ "tree": tree, "key": key }),
1781 |_| Ok(Json::Null),
1782 );
1783 (TREE_ACTIVATE, outcome, Signal::Activate { key })
1784 }
1785 };
1786 match outcome {
1787 Outcome::Done(Ok(_)) => signals.push(signal),
1788 Outcome::Done(Err(reason)) | Outcome::Vetoed { reason, .. } => {
1789 signals.push(Signal::Vetoed { step, reason })
1790 }
1791 }
1792 }
1793}
1794
1795fn open_context<K: Key>(
1798 app: Option<&AppHandle>,
1799 tree: &str,
1800 key: &K,
1801 signals: &mut Vec<Signal<K>>,
1802) -> Option<(K, K)> {
1803 let mut target = key.clone();
1804 let outcome = steps::run(
1805 app,
1806 &TREE_CONTEXT,
1807 json!({ "tree": tree, "key": key }),
1808 |args| {
1809 target = parse(&args["key"])?;
1810 Ok(Json::Bool(true))
1811 },
1812 );
1813 match outcome {
1814 Outcome::Done(Ok(_)) => {
1815 signals.push(Signal::Context {
1816 key: target.clone(),
1817 });
1818 Some((key.clone(), target))
1819 }
1820 Outcome::Done(Err(reason)) | Outcome::Vetoed { reason, .. } => {
1821 signals.push(Signal::Vetoed {
1822 step: TREE_CONTEXT,
1823 reason,
1824 });
1825 None
1826 }
1827 }
1828}
1829
1830fn parse<T: serde::de::DeserializeOwned>(v: &Json) -> Result<T, String> {
1831 serde_json::from_value(v.clone()).map_err(|e| e.to_string())
1832}
1833
1834fn node_index<K: Key>(model: &Model<K>, row: usize) -> Option<usize> {
1836 model.node_rows().binary_search(&row).ok()
1837}
1838
1839fn drop_into<K: Key>(
1841 model: &mut Model<K>,
1842 keys: &[K],
1843 target: &K,
1844 position: Position,
1845) -> Result<(), String> {
1846 if keys.iter().any(|k| model.is_within(target, k)) {
1847 return Err("a node cannot go into itself".into());
1848 }
1849 if !model.contains(target) {
1850 return Err("the target is gone".into());
1851 }
1852 model.move_many(keys, target, position);
1853 Ok(())
1854}
1855
1856#[allow(
1860 clippy::too_many_arguments,
1861 reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
1862)]
1863fn dragging<K: Key>(
1864 ui: &Ui,
1865 d: &mut Drag<K>,
1866 model: &Model<K>,
1867 visible: &rows::Visible<'_>,
1868 pointer: Option<egui::Pos2>,
1869 indent: f32,
1870 row_h: f32,
1871 allows: &Allows<'_, K>,
1872) {
1873 d.target = None;
1874 egui_pop_core::pointer::hold_drag_cursor(ui.ctx(), egui_pop_core::pointer::DragKind::Carry);
1875 let Some(p) = pointer else { return };
1876 let Some(i) = visible
1877 .range
1878 .clone()
1879 .find(|&i| (visible.rect_of)(i).contains(p))
1880 else {
1881 return;
1882 };
1883 let Row::Node { key, depth } = &model.rows_now()[i] else {
1884 return;
1885 };
1886 let Some(node) = model.node(key) else { return };
1887 if d.keys.iter().any(|k| model.is_within(key, k)) {
1888 return;
1889 }
1890 let rect = (visible.rect_of)(i);
1891 let f = (p.y - rect.top()) / row_h;
1892 let position = if node.branch {
1893 if f < 0.25 {
1894 Position::Before
1895 } else if f > 0.75 {
1896 Position::After
1897 } else {
1898 Position::Inside
1899 }
1900 } else if f < 0.5 {
1901 Position::Before
1902 } else {
1903 Position::After
1904 };
1905 let refused = allows(&d.keys, key, position).is_err();
1906 if refused {
1907 ui.ctx().set_cursor_icon(egui::CursorIcon::NotAllowed);
1908 }
1909 let x = rect.left() + (*depth as f32 + 1.0) * indent;
1910 let at = match position {
1912 Position::Inside => rect.shrink(1.0),
1913 Position::Before => Rect::from_min_max(pos2(x, rect.top()), rect.right_top()),
1914 Position::After => Rect::from_min_max(pos2(x, rect.bottom()), rect.max),
1915 };
1916 visible.kit.tree_drop_marker.paint(
1917 &KitCx {
1918 painter: ui.painter(),
1919 ppp: ui.ctx().pixels_per_point(),
1920 },
1921 &Part {
1922 rect: at,
1923 room: at,
1924 state: State::REST.with(State::DISABLED, refused),
1925 label: None,
1926 },
1927 );
1928 d.target = Some((key.clone(), position));
1929}
1930
1931fn pseudo(ui: &mut Ui, rect: Rect, x: f32, add: impl FnOnce(&mut Ui)) {
1933 let mut child = ui.new_child(
1934 UiBuilder::new()
1935 .max_rect(Rect::from_min_max(pos2(x, rect.top()), rect.max))
1936 .layout(egui::Layout::left_to_right(egui::Align::Center)),
1937 );
1938 add(&mut child);
1939}