1use std::cell::RefCell;
8use std::collections::HashMap;
9use std::hash::{DefaultHasher, Hash, Hasher};
10use std::rc::{Rc, Weak};
11
12use objc2::rc::Retained;
13use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject};
14use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
15use objc2_app_kit::{
16 NSControlTextEditingDelegate, NSImage, NSImageView, NSOutlineView, NSOutlineViewDataSource, NSOutlineViewDelegate,
17 NSScrollView, NSTableCellView, NSTableColumn, NSTableViewStyle, NSTextField, NSUserInterfaceItemIdentification, NSView,
18};
19use objc2_foundation::{NSIndexSet, NSInteger, NSNotification, NSString};
20
21use crate::signal::{Effect, Signal, untrack};
22use crate::view::{Cx, Identifiable, Kind, Node, Size, View};
23
24#[derive(Debug, Clone)]
26pub struct TreeNode<T> {
27 pub value: T,
29 pub children: Vec<TreeNode<T>>,
31}
32
33impl<T> TreeNode<T> {
34 pub fn leaf(value: T) -> Self {
36 TreeNode { value, children: Vec::new() }
37 }
38
39 pub fn branch(value: T, children: Vec<TreeNode<T>>) -> Self {
41 TreeNode { value, children }
42 }
43}
44
45struct Entry {
46 key: u64,
47 title: String,
48 icon: Option<(String, Option<crate::Color>)>,
50 badge: Option<String>,
52 columns: Vec<String>,
54 children: Vec<usize>,
55 expandable: bool,
56}
57
58#[derive(Default)]
59struct State {
60 entries: Vec<Entry>,
61 roots: Vec<usize>,
62 items: Vec<Retained<OutlineItem>>,
64 by_key: HashMap<u64, Retained<OutlineItem>>,
66 group_roots: bool,
67 on_select: Option<Box<dyn Fn(Option<usize>)>>,
68 on_expand: Option<Rc<dyn Fn(usize)>>,
71 quiet: bool,
73}
74
75define_class!(
76 #[unsafe(super(NSObject))]
78 #[thread_kind = MainThreadOnly]
79 #[name = "FerrokitOutlineItem"]
80 #[ivars = std::cell::Cell<usize>]
81 struct OutlineItem;
82);
83
84impl OutlineItem {
85 fn new(mtm: MainThreadMarker, index: usize) -> Retained<Self> {
86 let this = Self::alloc(mtm).set_ivars(std::cell::Cell::new(index));
87 unsafe { msg_send![super(this), init] }
89 }
90}
91
92define_class!(
93 #[unsafe(super(NSObject))]
95 #[thread_kind = MainThreadOnly]
96 #[name = "FerrokitOutlineSource"]
97 #[ivars = RefCell<Weak<RefCell<State>>>]
98 struct Source;
99
100 unsafe impl NSObjectProtocol for Source {}
101 unsafe impl NSControlTextEditingDelegate for Source {}
102
103 unsafe impl NSOutlineViewDataSource for Source {
104 #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
105 fn count(&self, _ov: &NSOutlineView, item: Option<&AnyObject>) -> NSInteger {
106 crate::failure::guard("an outline (count)", 0, || {
107 self.with(|s| match index_of(item) {
108 None => s.roots.len(),
109 Some(i) => s.entries.get(i).map_or(0, |e| e.children.len()),
110 }) as NSInteger
111 })
112 }
113
114 #[unsafe(method_id(outlineView:child:ofItem:))]
115 fn child(&self, _ov: &NSOutlineView, index: NSInteger, item: Option<&AnyObject>) -> Retained<AnyObject> {
116 let found = crate::failure::guard("an outline (child)", None, || {
119 let state = self.ivars().borrow().upgrade()?;
120 let s = state.borrow();
121 let list = match index_of(item) {
122 None => &s.roots,
123 Some(i) => &s.entries.get(i)?.children,
124 };
125 s.items.get(*list.get(index as usize)?).cloned()
126 });
127 match found {
128 Some(item) => Retained::into_super(Retained::into_super(item)),
129 None => Retained::into_super(NSObject::new()),
130 }
131 }
132
133 #[unsafe(method(outlineView:isItemExpandable:))]
134 fn expandable(&self, _ov: &NSOutlineView, item: &AnyObject) -> bool {
135 crate::failure::guard("an outline (expandable)", false, || {
136 self.with(|s| index_of(Some(item)).and_then(|i| s.entries.get(i)).is_some_and(|e| e.expandable))
137 })
138 }
139 }
140
141 unsafe impl NSOutlineViewDelegate for Source {
142 #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
143 fn view_for(&self, ov: &NSOutlineView, column: Option<&NSTableColumn>, item: &AnyObject) -> Option<Retained<NSView>> {
144 crate::failure::guard("an outline (view_for)", None, || {
145 let extra = column.and_then(|c| {
147 let id = c.identifier().to_string();
148 let (kind, n) = id.split_once('.')?;
149 Some((kind == "column-right", n.parse::<usize>().ok()?))
150 });
151 if let Some((right, n)) = extra {
152 let text = self.with(|s| index_of(Some(item)).and_then(|i| s.entries.get(i)).and_then(|e| e.columns.get(n).cloned()));
153 text.map(|t| column_cell(ov, &t, right))
154 } else {
155 self.tree_cell(ov, item)
156 }
157 })
158 }
159
160 #[unsafe(method(outlineView:isGroupItem:))]
161 fn is_group(&self, _ov: &NSOutlineView, item: &AnyObject) -> bool {
162 crate::failure::guard("an outline (is_group)", false, || {
163 self.with(|s| s.group_roots && index_of(Some(item)).is_some_and(|i| s.roots.contains(&i)))
164 })
165 }
166 #[unsafe(method(outlineView:shouldSelectItem:))]
167 fn should_select(&self, _ov: &NSOutlineView, item: &AnyObject) -> bool {
168 crate::failure::guard("an outline (should_select)", false, || {
169 !self.with(|s| s.group_roots && index_of(Some(item)).is_some_and(|i| s.roots.contains(&i)))
171 })
172 }
173
174 #[unsafe(method(outlineViewItemWillExpand:))]
175 fn will_expand(&self, notification: &NSNotification) {
176 let item = notification.userInfo().and_then(|u| u.objectForKey(&NSString::from_str("NSObject")));
177 let Some(index) = index_of(item.as_deref()) else { return };
178 let Some(state) = self.ivars().borrow().upgrade() else { return };
179 let s = state.borrow();
180 if s.quiet || s.entries.get(index).is_none_or(|e| !e.children.is_empty()) {
184 return;
185 }
186 if let Some(load) = s.on_expand.clone() {
187 let (key, state) = (s.entries[index].key, state.clone());
190 crate::later(move || {
191 let index = state.borrow().entries.iter().position(|e| e.key == key);
192 if let Some(index) = index {
193 crate::failure::entry("an outline's children", (), || crate::batch(|| load(index)));
194 }
195 });
196 }
197 }
198
199 #[unsafe(method(outlineViewSelectionDidChange:))]
200 fn selection_did_change(&self, notification: &NSNotification) {
201 let Some(ov) = notification.object().and_then(|o| o.downcast::<NSOutlineView>().ok()) else { return };
202 let Some(state) = self.ivars().borrow().upgrade() else { return };
203 if state.borrow().quiet {
204 return;
205 }
206 let row = ov.selectedRow();
207 let index = (row >= 0).then(|| ov.itemAtRow(row)).flatten().and_then(|i| index_of(Some(&i)));
208 let cb = state.borrow_mut().on_select.take();
210 if let Some(cb) = &cb {
211 crate::failure::entry("an outline's selection", (), || cb(index));
212 }
213 let mut s = state.borrow_mut();
214 if s.on_select.is_none() {
215 s.on_select = cb;
216 }
217 }
218 }
219);
220
221impl Source {
222 fn new(mtm: MainThreadMarker, state: &Rc<RefCell<State>>) -> Retained<Self> {
223 let this = Self::alloc(mtm).set_ivars(RefCell::new(Rc::downgrade(state)));
224 unsafe { msg_send![super(this), init] }
226 }
227
228 fn tree_cell(&self, ov: &NSOutlineView, item: &AnyObject) -> Option<Retained<NSView>> {
229 let found = self.with(|s| {
230 index_of(Some(item)).and_then(|i| {
231 s.entries.get(i).map(|e| (e.title.clone(), e.icon.clone(), e.badge.clone(), s.group_roots && s.roots.contains(&i)))
232 })
233 });
234 found.map(|(title, icon, badge, group)| cell(ov, &title, icon.as_ref().map(|(n, c)| (n.as_str(), *c)), badge.as_deref(), group))
235 }
236
237 fn with<R: Default>(&self, f: impl FnOnce(&State) -> R) -> R {
238 self.ivars().borrow().upgrade().map(|s| f(&s.borrow())).unwrap_or_default()
239 }
240}
241
242fn index_of(item: Option<&AnyObject>) -> Option<usize> {
243 item.and_then(|i| i.downcast_ref::<OutlineItem>()).map(|i| i.ivars().get())
244}
245
246const BADGE_TAG: isize = 0x0bad6e;
248
249fn cell(ov: &NSOutlineView, title: &str, icon: Option<(&str, Option<crate::Color>)>, badge: Option<&str>, group: bool) -> Retained<NSView> {
251 let mtm = MainThreadMarker::from(ov);
252 let ident = NSString::from_str(if group { "group" } else if icon.is_some() { "icon" } else { "plain" });
253 let reused = unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.and_then(|v| v.downcast::<NSTableCellView>().ok());
255 let view = reused.unwrap_or_else(|| {
256 let v = NSTableCellView::new(mtm);
257 v.setIdentifier(Some(&ident));
258 let text = NSTextField::labelWithString(&NSString::new(), mtm);
259 text.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
260 if group {
261 text.setFont(Some(&objc2_app_kit::NSFont::boldSystemFontOfSize(objc2_app_kit::NSFont::smallSystemFontSize())));
264 text.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
265 }
266 v.addSubview(&text);
267 unsafe { v.setTextField(Some(&text)) };
269 let center = |sub: &NSView| {
272 sub.setTranslatesAutoresizingMaskIntoConstraints(false);
273 sub.centerYAnchor().constraintEqualToAnchor(&v.centerYAnchor()).setActive(true);
274 };
275 center(&text);
276 if group {
277 text.trailingAnchor().constraintLessThanOrEqualToAnchor_constant(&v.trailingAnchor(), -2.0).setActive(true);
278 } else {
279 let badge = NSTextField::labelWithString(&NSString::new(), mtm);
282 badge.setTag(BADGE_TAG);
283 badge.setFont(Some(&objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(objc2_app_kit::NSFont::smallSystemFontSize(), 0.0)));
284 badge.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
285 badge.setAlignment(objc2_app_kit::NSTextAlignment::Right);
286 badge.setHidden(true);
287 v.addSubview(&badge);
288 center(&badge);
289 badge.trailingAnchor().constraintEqualToAnchor_constant(&v.trailingAnchor(), -6.0).setActive(true);
290 badge.setContentCompressionResistancePriority_forOrientation(750.0, objc2_app_kit::NSLayoutConstraintOrientation::Horizontal);
291 text.trailingAnchor().constraintLessThanOrEqualToAnchor_constant(&badge.leadingAnchor(), -6.0).setActive(true);
292 }
293 text.setContentCompressionResistancePriority_forOrientation(250.0, objc2_app_kit::NSLayoutConstraintOrientation::Horizontal);
295 if icon.is_some() {
296 let image = NSImageView::new(mtm);
297 objc2_app_kit::NSAccessibility::setAccessibilityElement(&*image, false);
301 if let Some(cell) = image.cell() {
302 let () = unsafe { objc2::msg_send![&*cell, setAccessibilityElement: false] };
304 }
305 v.addSubview(&image);
306 unsafe { v.setImageView(Some(&image)) };
308 center(&image);
309 image.leadingAnchor().constraintEqualToAnchor_constant(&v.leadingAnchor(), 2.0).setActive(true);
310 image.widthAnchor().constraintEqualToConstant(20.0).setActive(true);
311 text.leadingAnchor().constraintEqualToAnchor_constant(&image.trailingAnchor(), 6.0).setActive(true);
312 } else {
313 text.leadingAnchor().constraintEqualToAnchor_constant(&v.leadingAnchor(), 2.0).setActive(true);
314 }
315 v
316 });
317 if let Some(t) = unsafe { view.textField() } {
319 t.setStringValue(&NSString::from_str(title));
320 }
321 if let Some(b) = view.viewWithTag(BADGE_TAG).and_then(|b| b.downcast::<NSTextField>().ok()) {
322 b.setStringValue(&NSString::from_str(badge.unwrap_or_default()));
323 b.setHidden(badge.is_none_or(str::is_empty));
324 }
325 if let (Some((name, tint)), Some(iv)) = (icon, unsafe { view.imageView() }) {
326 iv.setImage(NSImage::imageWithSystemSymbolName_accessibilityDescription(&NSString::from_str(name), None).as_deref());
327 iv.setContentTintColor(tint.map(|c| c.ns()).as_deref());
329 }
330 Retained::into_super(view)
331}
332
333fn column_cell(ov: &NSOutlineView, text: &str, right: bool) -> Retained<NSView> {
336 let mtm = MainThreadMarker::from(ov);
337 let ident = NSString::from_str(if right { "column-right" } else { "column" });
338 let reused = unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.and_then(|v| v.downcast::<NSTableCellView>().ok());
340 let view = reused.unwrap_or_else(|| {
341 let v = NSTableCellView::new(mtm);
342 v.setIdentifier(Some(&ident));
343 let field = NSTextField::labelWithString(&NSString::new(), mtm);
344 field.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
345 field.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
346 if right {
347 field.setAlignment(objc2_app_kit::NSTextAlignment::Right);
348 field.setFont(Some(&objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(objc2_app_kit::NSFont::systemFontSize(), 0.0)));
349 }
350 v.addSubview(&field);
351 unsafe { v.setTextField(Some(&field)) };
353 field.setTranslatesAutoresizingMaskIntoConstraints(false);
354 field.centerYAnchor().constraintEqualToAnchor(&v.centerYAnchor()).setActive(true);
355 field.leadingAnchor().constraintEqualToAnchor_constant(&v.leadingAnchor(), 2.0).setActive(true);
356 field.trailingAnchor().constraintEqualToAnchor_constant(&v.trailingAnchor(), -2.0).setActive(true);
357 field.setContentCompressionResistancePriority_forOrientation(250.0, objc2_app_kit::NSLayoutConstraintOrientation::Horizontal);
358 v
359 });
360 if let Some(t) = unsafe { view.textField() } {
362 t.setStringValue(&NSString::from_str(text));
363 }
364 Retained::into_super(view)
365}
366
367fn key_of<K: Hash>(id: &K) -> u64 {
368 let mut h = DefaultHasher::new();
369 id.hash(&mut h);
370 h.finish()
371}
372
373type Roots<T> = Box<dyn Fn() -> Vec<TreeNode<T>>>;
374type IconFn<T> = dyn Fn(&T) -> Option<String>;
376type TintFn<T> = dyn Fn(&T) -> Option<crate::Color>;
378type BadgeFn<T> = dyn Fn(&T) -> Option<String>;
380type TextFn<T> = dyn Fn(&T) -> String;
382type HasFn<T> = dyn Fn(&T) -> bool;
384type Lazy<T> = (Rc<HasFn<T>>, Rc<dyn Fn(<T as Identifiable>::Id)>);
386type LookFn<T> = dyn Fn(&T) -> Option<(String, Option<crate::Color>)>;
388
389pub struct Outline<T: Identifiable + 'static> {
391 roots: Roots<T>,
392 title: Rc<dyn Fn(&T) -> String>,
393 icon: Option<Rc<IconFn<T>>>,
394 tint: Option<Rc<TintFn<T>>>,
395 badge: Option<Rc<BadgeFn<T>>>,
396 columns: Vec<OutlineColumn<T>>,
397 lazy: Option<Lazy<T>>,
398 selection: Option<Signal<Option<T::Id>>>,
399 sidebar: bool,
400 expanded: bool,
401 transparent: bool,
402}
403
404struct OutlineColumn<T> {
406 title: String,
407 width: f64,
408 right: bool,
409 value: Rc<TextFn<T>>,
410}
411
412impl<T: Identifiable + 'static> Outline<T> {
413 pub fn expanded(mut self) -> Self {
416 self.expanded = true;
417 self
418 }
419
420 pub fn transparent_background(mut self) -> Self {
425 self.transparent = true;
426 self
427 }
428
429 pub fn icon(mut self, f: impl Fn(&T) -> Option<String> + 'static) -> Self {
431 self.icon = Some(Rc::new(f));
432 self
433 }
434
435 pub fn icon_color(mut self, f: impl Fn(&T) -> Option<crate::Color> + 'static) -> Self {
438 self.tint = Some(Rc::new(f));
439 self
440 }
441
442 pub fn badge(mut self, f: impl Fn(&T) -> Option<String> + 'static) -> Self {
446 self.badge = Some(Rc::new(f));
447 self
448 }
449
450 pub fn column(mut self, title: &str, width: f64, value: impl Fn(&T) -> String + 'static) -> Self {
455 self.columns.push(OutlineColumn { title: title.into(), width, right: false, value: Rc::new(value) });
456 self
457 }
458
459 pub fn number_column(mut self, title: &str, width: f64, value: impl Fn(&T) -> String + 'static) -> Self {
462 self.columns.push(OutlineColumn { title: title.into(), width, right: true, value: Rc::new(value) });
463 self
464 }
465
466 pub fn lazy_children(mut self, has_children: impl Fn(&T) -> bool + 'static, load: impl Fn(T::Id) + 'static) -> Self {
472 self.lazy = Some((Rc::new(has_children), Rc::new(load)));
473 self
474 }
475
476 pub fn selection(mut self, selected: &Signal<Option<T::Id>>) -> Self {
478 self.selection = Some(*selected);
479 self
480 }
481}
482
483impl<T: Identifiable + 'static> View for Outline<T> {
484 fn build(self, cx: &mut Cx) -> Node {
485 let mtm = cx.mtm;
486 let ov = NSOutlineView::new(mtm);
487 let column = NSTableColumn::initWithIdentifier(NSTableColumn::alloc(mtm), &NSString::from_str("title"));
488 ov.addTableColumn(&column);
489 unsafe { ov.setOutlineTableColumn(Some(&column)) };
491 if self.columns.is_empty() {
492 ov.setHeaderView(None);
493 } else {
494 column.setTitle(&NSString::from_str(&crate::t("Name")));
495 column.setWidth(220.0);
496 column.setMinWidth(80.0);
497 for (n, c) in self.columns.iter().enumerate() {
498 let kind = if c.right { "column-right" } else { "column" };
499 let extra = NSTableColumn::initWithIdentifier(NSTableColumn::alloc(mtm), &NSString::from_str(&format!("{kind}.{n}")));
500 extra.setTitle(&NSString::from_str(&c.title));
501 extra.setWidth(c.width);
502 extra.setMinWidth(40.0);
503 ov.addTableColumn(&extra);
504 }
505 ov.setColumnAutoresizingStyle(objc2_app_kit::NSTableViewColumnAutoresizingStyle::FirstColumnOnlyAutoresizingStyle);
506 }
507 if self.sidebar {
508 ov.setStyle(NSTableViewStyle::SourceList);
509 ov.setFloatsGroupRows(false);
510 ov.setRowSizeStyle(objc2_app_kit::NSTableViewRowSizeStyle::Default);
513 }
514 let scroll = NSScrollView::new(mtm);
515 scroll.setDocumentView(Some(&ov));
516 scroll.setHasVerticalScroller(true);
517 scroll.setAutohidesScrollers(true);
518 if self.sidebar || self.transparent {
519 scroll.setDrawsBackground(false);
520 }
521 if self.transparent {
522 ov.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
523 }
524
525 let state = Rc::new(RefCell::new(State { group_roots: self.sidebar, ..State::default() }));
526 let source = Source::new(mtm, &state);
527 unsafe {
529 ov.setDataSource(Some(ProtocolObject::from_ref(&*source)));
530 ov.setDelegate(Some(ProtocolObject::from_ref(&*source)));
531 }
532
533 let ids: Rc<RefCell<Vec<T::Id>>> = Rc::default();
535 if let Some(sel) = &self.selection {
536 let (sel, ids) = (*sel, ids.clone());
537 state.borrow_mut().on_select = Some(Box::new(move |i| {
538 sel.set(i.and_then(|i| ids.borrow().get(i).cloned()));
539 }));
540 }
541
542 let lazy = self.lazy.clone();
543 if let Some((_, load)) = &self.lazy {
544 let (load, ids) = (load.clone(), ids.clone());
545 state.borrow_mut().on_expand = Some(Rc::new(move |i| {
546 let id = ids.borrow().get(i).cloned();
547 if let Some(id) = id {
548 load(id);
549 }
550 }));
551 }
552 let (mut node, _) = Node::leaf(cx, Retained::into_super(scroll), (true, true), Size { w: 160.0, h: 120.0 });
553 if let Kind::Leaf(l) = &node.kind {
554 l.content.set(Some(Size { w: 160.0, h: 120.0 }));
555 }
556
557 let restore: Rc<dyn Fn()> = {
561 let (st, ids, ov3, sel) = (state.clone(), ids.clone(), ov.clone(), self.selection);
562 Rc::new(move || {
563 let Some(sel) = &sel else { return };
564 let want = sel.get();
565 untrack(|| {
566 let index = want.and_then(|id| ids.borrow().iter().position(|x| *x == id));
567 let item = index.and_then(|i| st.borrow().items.get(i).cloned());
568 let row = item.map_or(-1, |it| unsafe { ov3.rowForItem(Some(&it)) });
570 if ov3.selectedRow() != row {
571 st.borrow_mut().quiet = true;
572 if row >= 0 {
573 ov3.selectRowIndexes_byExtendingSelection(&NSIndexSet::indexSetWithIndex(row as usize), false);
574 } else {
575 unsafe { ov3.deselectAll(None) };
577 }
578 st.borrow_mut().quiet = false;
579 }
580 });
581 })
582 };
583
584 let (roots_fn, title, sidebar, expanded) = (self.roots, self.title, self.sidebar, self.expanded);
586 let tint = self.tint;
587 let badge = self.badge;
588 let columns: Vec<Rc<TextFn<T>>> = self.columns.iter().map(|c| c.value.clone()).collect();
589 let has_children: Option<Rc<HasFn<T>>> = lazy.map(|(h, _)| h);
590 let icon: Option<Rc<LookFn<T>>> = self.icon.map(|f| Rc::new(move |v: &T| f(v).map(|name| (name, tint.as_ref().and_then(|t| t(v))))) as Rc<LookFn<T>>);
591 let (st, ids2, ov2, restore2) = (state.clone(), ids.clone(), ov.clone(), restore.clone());
592 node.own(Effect::new(move || {
593 let roots = roots_fn();
594 untrack(|| {
595 let shown: Vec<(u64, Retained<OutlineItem>)> = {
599 let s = st.borrow();
600 s.entries.iter().zip(&s.items).map(|(e, it)| (e.key, it.clone())).collect()
601 };
602 let open: std::collections::HashSet<u64> = shown
603 .into_iter()
604 .filter(|(_, it)| unsafe { ov2.isItemExpanded(Some(it)) })
606 .map(|(key, _)| key)
607 .collect();
608 let mut s = st.borrow_mut();
609 let old = std::mem::take(&mut s.by_key);
610 let (mut entries, mut items, mut keys, mut typed) = (Vec::new(), Vec::new(), HashMap::new(), Vec::new());
611 struct Look<'a, T> {
612 title: &'a dyn Fn(&T) -> String,
613 icon: Option<&'a LookFn<T>>,
614 badge: Option<&'a BadgeFn<T>>,
615 columns: &'a [Rc<TextFn<T>>],
616 has_children: Option<&'a HasFn<T>>,
617 }
618 fn walk<T: Identifiable>(n: TreeNode<T>, out: &mut Vec<Entry>, typed: &mut Vec<T::Id>, look: &Look<T>) -> usize {
619 let index = out.len();
620 let id = n.value.id();
621 out.push(Entry {
622 key: key_of(&id),
623 title: (look.title)(&n.value),
624 icon: look.icon.and_then(|f| f(&n.value)),
625 badge: look.badge.and_then(|f| f(&n.value)),
626 columns: look.columns.iter().map(|f| f(&n.value)).collect(),
627 children: Vec::new(),
628 expandable: !n.children.is_empty() || look.has_children.is_some_and(|f| f(&n.value)),
629 });
630 typed.push(id);
631 let kids: Vec<usize> = n.children.into_iter().map(|c| walk(c, out, typed, look)).collect();
632 out[index].children = kids;
633 index
634 }
635 let look = Look { title: &*title, icon: icon.as_deref(), badge: badge.as_deref(), columns: &columns, has_children: has_children.as_deref() };
636 let root_idx: Vec<usize> = roots.into_iter().map(|r| walk(r, &mut entries, &mut typed, &look)).collect();
637 for (i, e) in entries.iter().enumerate() {
638 let item = old.get(&e.key).cloned().unwrap_or_else(|| OutlineItem::new(mtm, i));
639 item.ivars().set(i);
640 keys.insert(e.key, item.clone());
641 items.push(item);
642 }
643 s.entries = entries;
644 s.roots = root_idx;
645 s.items = items;
646 s.by_key = keys;
647 *ids2.borrow_mut() = typed;
648 s.quiet = true;
649 drop(s);
650 ov2.reloadData();
651 let again: Vec<_> = {
654 let s = st.borrow();
655 s.entries.iter().zip(&s.items).filter(|(e, _)| open.contains(&e.key)).map(|(_, it)| it.clone()).collect()
656 };
657 for it in again {
658 unsafe { ov2.expandItem(Some(&it)) };
660 }
661 if expanded {
662 unsafe { ov2.expandItem_expandChildren(None, true) };
664 } else if sidebar {
665 let roots: Vec<_> = {
669 let s = st.borrow();
670 s.roots.iter().filter(|&&i| !old.contains_key(&s.entries[i].key)).map(|&i| s.items[i].clone()).collect()
671 };
672 for r in roots {
673 unsafe { ov2.expandItem(Some(&r)) };
675 }
676 }
677 st.borrow_mut().quiet = false;
678 untrack(|| restore2());
679 });
680 }));
681
682 if self.selection.is_some() {
684 node.own(Effect::new(move || restore()));
685 }
686 node.keep(Retained::into_super(source));
687 node.hold(state);
688 node
689 }
690}
691
692pub fn outline<T: Identifiable + 'static>(
695 roots: impl Fn() -> Vec<TreeNode<T>> + 'static,
696 title: impl Fn(&T) -> String + 'static,
697) -> Outline<T> {
698 Outline { roots: Box::new(roots), title: Rc::new(title), icon: None, tint: None, badge: None, columns: Vec::new(), lazy: None, selection: None, sidebar: false, expanded: false, transparent: false }
699}
700
701pub fn sidebar<T: Identifiable + 'static>(
704 sections: impl Fn() -> Vec<TreeNode<T>> + 'static,
705 title: impl Fn(&T) -> String + 'static,
706) -> Outline<T> {
707 Outline { sidebar: true, ..outline(sections, title) }
708}