Skip to main content

ferrokit/
outline.rs

1//! A native outline (`NSOutlineView`) over a tree from signals, and the
2//! source-list sidebar built on it.
3//!
4//! Each item gets a stable Objective-C object, reused by id when the tree
5//! changes, so AppKit keeps expansion and selection across updates.
6
7use 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/// One item of a tree, with its children.
25#[derive(Debug, Clone)]
26pub struct TreeNode<T> {
27    /// The item.
28    pub value: T,
29    /// Its children (empty for a leaf).
30    pub children: Vec<TreeNode<T>>,
31}
32
33impl<T> TreeNode<T> {
34    /// A leaf.
35    pub fn leaf(value: T) -> Self {
36        TreeNode { value, children: Vec::new() }
37    }
38
39    /// An item with children.
40    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    /// An SF Symbol and its colour.
49    icon: Option<(String, Option<crate::Color>)>,
50    /// A count or short word at the row's end.
51    badge: Option<String>,
52    /// The text of each extra column (see `Outline::column`).
53    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    /// The object AppKit sees for each entry (index-aligned).
63    items: Vec<Retained<OutlineItem>>,
64    /// Item objects by key, kept across rebuilds (stable identity).
65    by_key: HashMap<u64, Retained<OutlineItem>>,
66    group_roots: bool,
67    on_select: Option<Box<dyn Fn(Option<usize>)>>,
68    /// An item whose children load on demand was expanded (see
69    /// `Outline::lazy_children`).
70    on_expand: Option<Rc<dyn Fn(usize)>>,
71    /// Set while the outline changes selection itself (no callback).
72    quiet: bool,
73}
74
75define_class!(
76    // AppKit's handle for one tree item: the index of its entry.
77    #[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        // SAFETY: NSObject's designated initialiser.
88        unsafe { msg_send![super(this), init] }
89    }
90}
91
92define_class!(
93    // Data source and delegate for one outline view.
94    #[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            // An item AppKit asks for that isn't there (the tree changed
117            // under it) is an empty one, not a panic inside AppKit.
118            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                // An extra column's cell: its text ("column.2", "column-right.3").
146                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                // Section headers of a sidebar aren't selectable.
170                !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            // Only an item that has no children yet: load them, after
181            // AppKit has expanded it (the tree is rebuilt when they arrive,
182            // and stays expanded).
183            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                // By its key: the tree may be rebuilt before this runs, and
188                // the same place in it be another item's.
189                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            // Take the callback out while it runs: it may update the tree.
209            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        // SAFETY: NSObject's designated initialiser.
225        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
246/// The badge's label in a cell (its tag).
247const BADGE_TAG: isize = 0x0bad6e;
248
249/// A row: optional SF Symbol, a title and a badge (reused by identifier).
250fn 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    // SAFETY: reuse lookup by identifier; owner may be nil.
254    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            // Section headings: small, bold and secondary, as in Finder's
262            // and Mail's sidebars.
263            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        // SAFETY: the cell view keeps its subviews; these are weak conveniences.
268        unsafe { v.setTextField(Some(&text)) };
269        // Centred in the row, whatever its height: the sidebar's rows follow
270        // the user's sidebar icon size (System Settings › Appearance).
271        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            // The badge: secondary, its digits all one width, at the end
280            // (hidden while there's none).
281            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        // (Lower priority than the outline's own width.)
294        text.setContentCompressionResistancePriority_forOrientation(250.0, objc2_app_kit::NSLayoutConstraintOrientation::Horizontal);
295        if icon.is_some() {
296            let image = NSImageView::new(mtm);
297            // The icon is decoration: the title names the row. (macOS 15 and
298            // 26 otherwise read an unnamed image in every row.) The view's
299            // cell answers for it there, so hide both.
300            objc2_app_kit::NSAccessibility::setAccessibilityElement(&*image, false);
301            if let Some(cell) = image.cell() {
302                // SAFETY: NSAccessibility's setter taking a BOOL.
303                let () = unsafe { objc2::msg_send![&*cell, setAccessibilityElement: false] };
304            }
305            v.addSubview(&image);
306            // SAFETY: as above.
307            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    // SAFETY: reading the cell's outlets on the main thread.
318    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        // A reused cell keeps its last tint unless it's set every time.
328        iv.setContentTintColor(tint.map(|c| c.ns()).as_deref());
329    }
330    Retained::into_super(view)
331}
332
333/// An extra column's cell: its text, secondary, right-aligned with digits
334/// all one width for numbers (as the Finder's Size column).
335fn 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    // SAFETY: reuse lookup by identifier; owner may be nil.
339    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        // SAFETY: the cell view keeps its subviews; this is a weak convenience.
352        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    // SAFETY: reading the cell's outlet on the main thread.
361    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>>>;
374/// An item's SF Symbol name, if any.
375type IconFn<T> = dyn Fn(&T) -> Option<String>;
376/// An item's icon colour, if it has its own.
377type TintFn<T> = dyn Fn(&T) -> Option<crate::Color>;
378/// An item's badge, if any.
379type BadgeFn<T> = dyn Fn(&T) -> Option<String>;
380/// An extra column's text for an item.
381type TextFn<T> = dyn Fn(&T) -> String;
382/// Whether an item has children not read yet.
383type HasFn<T> = dyn Fn(&T) -> bool;
384/// Lazy children: which items have them, and what loads them.
385type Lazy<T> = (Rc<HasFn<T>>, Rc<dyn Fn(<T as Identifiable>::Id)>);
386/// An item's symbol and colour.
387type LookFn<T> = dyn Fn(&T) -> Option<(String, Option<crate::Color>)>;
388
389/// A native outline view over a tree (see the module docs).
390pub 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
404/// An extra column of an outline (see [`Outline::column`]).
405struct 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    /// Every item shown expanded, each time the tree changes (a plan, a
414    /// document's outline: trees read whole).
415    pub fn expanded(mut self) -> Self {
416        self.expanded = true;
417        self
418    }
419
420    /// No background of its own: the rows sit on whatever is behind the
421    /// outline (a card, a tinted panel), as a sidebar's do. Without it an
422    /// outline draws the system's content background, which in Dark Mode
423    /// differs from a card's control background.
424    pub fn transparent_background(mut self) -> Self {
425        self.transparent = true;
426        self
427    }
428
429    /// An SF Symbol per item (or `None`).
430    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    /// A colour per item's icon (or `None` for the sidebar's own), as
436    /// Mail's mailboxes and Reminders' lists show theirs.
437    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    /// A badge per item (or `None`): a count or a short word at the end of
443    /// its row, in secondary text, as Mail's unread counts are. It's read
444    /// when the tree is, so a signal the tree reads updates it.
445    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    /// A column beside the tree, as the Finder's list view has (Date
451    /// Modified, Kind): its title, width and each item's text. With columns
452    /// the outline shows a header, and the tree's own column is titled
453    /// "Name".
454    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    /// A column of numbers or sizes: as [`Outline::column`], right-aligned
460    /// with digits all one width (the Finder's Size).
461    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    /// Items for which `has_children` is true are expandable before their
467    /// children are known (a folder not read yet): expanding one calls
468    /// `load` with its id, which reads them and puts them in the tree the
469    /// outline shows (setting a signal it reads). Expanded items stay
470    /// expanded when the tree changes.
471    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    /// Two-way selection by item id.
477    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        // SAFETY: the column was just added to this outline.
490        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            // The user's sidebar icon size (small, medium, large), as in
511            // Finder and Mail; the cells' fonts and symbols follow it.
512            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        // SAFETY: data source and delegate are weak in AppKit; the node keeps the source.
528        unsafe {
529            ov.setDataSource(Some(ProtocolObject::from_ref(&*source)));
530            ov.setDelegate(Some(ProtocolObject::from_ref(&*source)));
531        }
532
533        // Typed ids, index-aligned with the entries.
534        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        // Selects the item whose id the selection signal holds (quietly);
558        // used when the signal changes and after a reload, which clears
559        // AppKit's selection.
560        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                    // SAFETY: an item object this outline returned.
569                    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                            // SAFETY: nil sender.
576                            unsafe { ov3.deselectAll(None) };
577                        }
578                        st.borrow_mut().quiet = false;
579                    }
580                });
581            })
582        };
583
584        // Rebuild when the tree's signals change; keep item objects by id.
585        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                // What the user has expanded, kept through the reload. (Asked
596                // before the state is borrowed: AppKit may ask the data
597                // source while it answers.)
598                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                    // SAFETY: an item object this outline returned.
605                    .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                // Parents come before their children (the entries are in
652                // tree order), so each is expanded inside an expanded one.
653                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                    // SAFETY: an item object this outline returned.
659                    unsafe { ov2.expandItem(Some(&it)) };
660                }
661                if expanded {
662                    // SAFETY: nil expands every root, with its children.
663                    unsafe { ov2.expandItem_expandChildren(None, true) };
664                } else if sidebar {
665                    // Sections start expanded: the ones new in this tree.
666                    // One the user closed stays closed when the tree is
667                    // rebuilt (a badge changed).
668                    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                        // SAFETY: an item object this outline returned.
674                        unsafe { ov2.expandItem(Some(&r)) };
675                    }
676                }
677                st.borrow_mut().quiet = false;
678                untrack(|| restore2());
679            });
680        }));
681
682        // Selection signal → outline (quietly).
683        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
692/// A native outline: `roots` (reading signals) gives the tree, `title` each
693/// item's text.
694pub 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
701/// A Mac sidebar: an outline in the source-list style whose top-level items
702/// are section headers, expanded.
703pub 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}