Skip to main content

ferrokit/
widgets.rs

1//! More standard controls: tabs, radio groups, links, gauges and ratings,
2//! token fields and path controls. Each is AppKit's own control, bound two
3//! ways to a signal like the controls in `controls.rs`.
4
5use std::path::{Path, PathBuf};
6use std::rc::Rc;
7
8use ferrokit_core::kept::{UiCell, UiLocal as _};
9
10use objc2::rc::Retained;
11use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject};
12use objc2::{DefinedClass, MainThreadOnly, define_class, msg_send, sel};
13use objc2_app_kit::{
14    NSButton, NSControlStateValueOff, NSControlStateValueOn, NSControlTextEditingDelegate, NSLevelIndicator, NSLevelIndicatorStyle, NSPathControl,
15    NSTabView, NSTabViewDelegate, NSTabViewItem, NSTabViewType, NSTextField, NSTextFieldDelegate, NSTokenField, NSTokenFieldDelegate, NSView,
16};
17use objc2_foundation::{NSArray, NSAttributedString, NSDictionary, NSNotification, NSString, NSURL};
18
19use crate::appkit_views::ActionTarget;
20use crate::signal::{Effect, Signal, batch};
21use crate::view::{AnyView, Axis, Cx, Kind, Node, Size, View, hstack, spacer, vstack};
22
23fn as_view<T: objc2::ClassType>(v: &Retained<T>) -> Retained<NSView> {
24    // SAFETY: only called with NSView subclasses.
25    unsafe { Retained::cast_unchecked(v.clone()) }
26}
27
28fn wire(control: &objc2_app_kit::NSControl, target: &ActionTarget) {
29    // SAFETY: the target responds to `fire:`; the caller's node keeps it.
30    unsafe {
31        control.setTarget(Some(target));
32        control.setAction(Some(sel!(fire:)));
33    }
34}
35
36// ---- tabs ----
37
38/// How [`tabs`] shows its tabs.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
40#[non_exhaustive]
41pub enum TabStyle {
42    /// AppKit's tab view: tabs along the top of a bordered box, as in
43    /// System Settings' older panes and many inspectors.
44    #[default]
45    Bordered,
46    /// A segmented control above borderless content, as in Finder's Get
47    /// Info sections and most modern Mac apps.
48    Segmented,
49}
50
51/// Panes chosen by tabs (see [`tabs`]).
52pub struct Tabs<T> {
53    value: Signal<T>,
54    pages: Vec<(String, T, AnyView)>,
55    style: TabStyle,
56}
57
58impl<T> Tabs<T> {
59    /// How the tabs look ([`TabStyle::Bordered`] by default).
60    pub fn style(mut self, style: TabStyle) -> Self {
61        self.style = style;
62        self
63    }
64}
65
66/// Releases the panes' view trees with the tab view.
67struct Hosted(Vec<Retained<NSView>>);
68
69impl Drop for Hosted {
70    fn drop(&mut self) {
71        for root in &self.0 {
72            crate::drop_hosted(root);
73        }
74    }
75}
76
77define_class!(
78    // A tab chosen by the user → the signal.
79    #[unsafe(super(NSObject))]
80    #[thread_kind = MainThreadOnly]
81    #[name = "FerrokitTabDelegate"]
82    #[ivars = Box<dyn Fn(usize)>]
83    struct TabDelegate;
84
85    unsafe impl NSObjectProtocol for TabDelegate {}
86
87    unsafe impl NSTabViewDelegate for TabDelegate {
88        #[unsafe(method(tabView:didSelectTabViewItem:))]
89        fn did_select(&self, tab_view: &NSTabView, item: Option<&NSTabViewItem>) {
90            crate::failure::guard("a control (did_select)", (), || {
91                if let Some(item) = item {
92                    let i = tab_view.indexOfTabViewItem(item);
93                    if i >= 0 {
94                        batch(|| (self.ivars())(i as usize));
95                    }
96                }
97            })
98        }
99    }
100);
101
102/// The native tab view of [`Tabs`], with or without its own tabs.
103struct TabView<T> {
104    value: Signal<T>,
105    pages: Vec<(String, T, AnyView)>,
106    tabless: bool,
107}
108
109impl<T: PartialEq + Clone + 'static> View for TabView<T> {
110    fn build(self, cx: &mut Cx) -> Node {
111        let mtm = cx.mtm;
112        let tab_view = NSTabView::new(mtm);
113        if self.tabless {
114            tab_view.setTabViewType(NSTabViewType::NoTabsNoBorder);
115        }
116        let mut roots = Vec::new();
117        let mut biggest = NSSizeLike::default();
118        let mut values = Vec::new();
119        for (title, value, view) in self.pages {
120            // Each pane is laid out like a window's content, in the room
121            // the tab view gives it.
122            // At the top left, unless it fills the pane (a chart, a list).
123            let view = AnyView::new(crate::view::zstack((view,)).alignment(crate::Align::Start, crate::Align::Start));
124            let (root, size) = crate::host_view(view);
125            biggest.w = biggest.w.max(size.width);
126            biggest.h = biggest.h.max(size.height);
127            // SAFETY: an item with no identifier object.
128            let item = unsafe { NSTabViewItem::initWithIdentifier(objc2::AnyThread::alloc(), None) };
129            item.setLabel(&NSString::from_str(&title));
130            item.setView(Some(&root));
131            tab_view.addTabViewItem(&item);
132            roots.push(root);
133            values.push(value);
134        }
135        let values = Rc::new(values);
136        let (signal, vs) = (self.value, values.clone());
137        let delegate = TabDelegate::alloc(mtm).set_ivars(Box::new(move |i: usize| {
138            if let Some(v) = vs.get(i) {
139                signal.set_if_changed(v.clone());
140            }
141        }) as Box<dyn Fn(usize)>);
142        // SAFETY: NSObject's designated initialiser.
143        let delegate: Retained<TabDelegate> = unsafe { msg_send![super(delegate), init] };
144        tab_view.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
145        // The tabs and border around the largest pane.
146        let chrome = {
147            let frame = tab_view.frame().size;
148            let content = tab_view.contentRect().size;
149            (frame.width - content.width, frame.height - content.height)
150        };
151        let min = Size { w: biggest.w + chrome.0.max(0.0), h: biggest.h + chrome.1.max(0.0) };
152        let (mut node, _) = Node::leaf(cx, as_view(&tab_view), (true, true), min);
153        let value = self.value;
154        node.own(Effect::new(move || {
155            let current = value.get();
156            if let Some(i) = values.iter().position(|v| *v == current) {
157                let selected = tab_view.selectedTabViewItem().map(|t| tab_view.indexOfTabViewItem(&t));
158                if selected != Some(i as isize) {
159                    tab_view.selectTabViewItemAtIndex(i as isize);
160                }
161            }
162        }));
163        node.keep(Retained::into_super(delegate));
164        node.hold(Rc::new(Hosted(roots)));
165        node
166    }
167}
168
169#[derive(Default)]
170struct NSSizeLike {
171    w: f64,
172    h: f64,
173}
174
175impl<T: PartialEq + Clone + 'static> View for Tabs<T> {
176    fn build(self, cx: &mut Cx) -> Node {
177        match self.style {
178            TabStyle::Bordered => TabView { value: self.value, pages: self.pages, tabless: false }.build(cx),
179            TabStyle::Segmented => {
180                let options: Vec<(String, T)> = self.pages.iter().map(|(t, v, _)| (t.clone(), v.clone())).collect();
181                let picker = crate::controls::segmented(&self.value, options.iter().map(|(t, v)| (t.as_str(), v.clone())).collect());
182                vstack((hstack((spacer(), picker, spacer())), TabView { value: self.value, pages: self.pages, tabless: true }))
183                    .spacing(12.0)
184                    .build(cx)
185            }
186        }
187    }
188}
189
190/// Panes chosen by tabs, bound two ways to `value`: one per page (its tab
191/// title, the value that selects it, its content). Every pane is built
192/// once and keeps its state while hidden.
193///
194/// ```no_run
195/// use ferrokit::*;
196///
197/// let page = Signal::new(0);
198/// let view = tabs(&page, vec![
199///     ("General", 0, AnyView::new(text("General settings"))),
200///     ("Advanced", 1, AnyView::new(text("Advanced settings"))),
201/// ])
202/// .style(TabStyle::Segmented);
203/// # let _ = view;
204/// ```
205pub fn tabs<T: PartialEq + Clone + 'static>(value: &Signal<T>, pages: Vec<(&str, T, AnyView)>) -> Tabs<T> {
206    Tabs { value: *value, pages: pages.into_iter().map(|(t, v, p)| (t.to_string(), v, p)).collect(), style: TabStyle::default() }
207}
208
209// ---- radio group ----
210
211thread_local! {
212    /// The radio group actions not in use, and how many were ever made.
213    static GROUP_ACTIONS: UiCell<(Vec<usize>, usize)> = const { UiCell::new((Vec::new(), 0)) };
214}
215
216/// One radio group's action: `fire:` under a name of its own, taken from
217/// a pool so groups that come and go don't keep adding names.
218struct GroupAction(usize);
219
220impl GroupAction {
221    fn take() -> Self {
222        GroupAction(GROUP_ACTIONS.with_borrow_mut(|(free, made)| {
223            free.pop().unwrap_or_else(|| {
224                *made += 1;
225                *made - 1
226            })
227        }))
228    }
229
230    fn selector(&self) -> objc2::runtime::Sel {
231        use objc2::ClassType;
232        let name = std::ffi::CString::new(format!("fireGroup{}:", self.0)).unwrap_or_default();
233        let sel = objc2::runtime::Sel::register(&name);
234        let class = ActionTarget::class();
235        if class.instance_method(sel).is_none()
236            && let Some(fire) = class.instance_method(sel!(fire:))
237        {
238            // SAFETY: the new method is `fire:` itself (its code and its
239            // types: no result, one object), under another name.
240            unsafe { objc2::ffi::class_addMethod(std::ptr::from_ref(class).cast_mut(), sel, fire.implementation(), c"v@:@".as_ptr()) };
241        }
242        sel
243    }
244}
245
246impl Drop for GroupAction {
247    fn drop(&mut self) {
248        GROUP_ACTIONS.with_borrow_mut(|(free, _)| free.push(self.0));
249    }
250}
251
252/// Radio buttons choosing one of several values (see [`radio_group`]).
253pub struct RadioGroup<T> {
254    value: Signal<T>,
255    options: Vec<(String, T)>,
256    horizontal: bool,
257}
258
259impl<T> RadioGroup<T> {
260    /// The buttons side by side instead of one above another.
261    pub fn horizontal(mut self) -> Self {
262        self.horizontal = true;
263        self
264    }
265}
266
267impl<T: PartialEq + Clone + 'static> View for RadioGroup<T> {
268    fn build(self, cx: &mut Cx) -> Node {
269        let mut children = Vec::new();
270        let mut buttons = Vec::new();
271        let mut targets = Vec::new();
272        // AppKit takes radio buttons with the same parent view and the same
273        // action for one group, and every view here has the window's
274        // parent: an action of its own keeps this group apart from others.
275        let action = GroupAction::take();
276        for (title, v) in &self.options {
277            // SAFETY: no target yet; set below.
278            let b = unsafe { NSButton::radioButtonWithTitle_target_action(&NSString::from_str(title), None, None, cx.mtm) };
279            let (signal, v) = (self.value, v.clone());
280            let target = ActionTarget::new(cx.mtm, move || signal.set_if_changed(v.clone()));
281            // SAFETY: the target responds to the group's action (the same
282            // code as `fire:`); the node keeps it.
283            unsafe {
284                b.setTarget(Some(&*target));
285                b.setAction(Some(action.selector()));
286            }
287            let (node, _) = Node::leaf(cx, as_view(&b), (false, false), Size::default());
288            children.push(node);
289            buttons.push(b);
290            targets.push(target);
291        }
292        let axis = if self.horizontal { Axis::Horizontal } else { Axis::Vertical };
293        let mut node = Node::new(Kind::Stack { axis, spacing: if self.horizontal { 14.0 } else { 6.0 }, align: Some(crate::Align::Start), children });
294        let (value, options) = (self.value, self.options);
295        node.own(Effect::new(move || {
296            // Kept with the buttons: the action is free again when they go.
297            let _ = &action;
298            let current = value.get();
299            for (b, (_, v)) in buttons.iter().zip(&options) {
300                let want = if *v == current { NSControlStateValueOn } else { NSControlStateValueOff };
301                if b.state() != want {
302                    b.setState(want);
303                }
304            }
305        }));
306        for t in targets {
307            node.keep(Retained::into_super(t));
308        }
309        node
310    }
311}
312
313/// Radio buttons bound two ways to `value`, one per option (title, value),
314/// one above another (or [`horizontal`](RadioGroup::horizontal)).
315pub fn radio_group<T: PartialEq + Clone + 'static>(value: &Signal<T>, options: Vec<(&str, T)>) -> RadioGroup<T> {
316    RadioGroup { value: *value, options: options.into_iter().map(|(t, v)| (t.to_string(), v)).collect(), horizontal: false }
317}
318
319// ---- link ----
320
321define_class!(
322    // A label holding a link: VoiceOver reads it as a link, and pressing
323    // it there opens the link as a click does.
324    #[unsafe(super(NSTextField, objc2_app_kit::NSControl, NSView, objc2_app_kit::NSResponder, NSObject))]
325    #[thread_kind = MainThreadOnly]
326    #[name = "FerrokitLink"]
327    #[ivars = Retained<NSURL>]
328    struct LinkField;
329
330    impl LinkField {
331        #[unsafe(method_id(accessibilityRole))]
332        fn ax_role(&self) -> Option<Retained<NSString>> {
333            crate::failure::guard("a control (ax_role)", None, || {
334                // SAFETY: AppKit's role constant.
335                Some(objc2_foundation::NSCopying::copy(unsafe { objc2_app_kit::NSAccessibilityLinkRole }))
336            })
337        }
338
339        #[unsafe(method(accessibilityPerformPress))]
340        fn ax_press(&self) -> bool {
341            crate::failure::guard("a control (ax_press)", false, || {
342                objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(self.ivars())
343            })
344        }
345    }
346);
347
348/// A link to a web page or file (see [`link`]).
349pub struct Link {
350    title: String,
351    url: String,
352}
353
354impl View for Link {
355    fn build(self, cx: &mut Cx) -> Node {
356        let Some(url) = NSURL::URLWithString(&NSString::from_str(&self.url)) else {
357            return crate::appkit_views::text(&self.title).build(cx);
358        };
359        let link = url.clone();
360        // SAFETY: AppKit's attribute name, with an NSURL value.
361        let attrs = unsafe {
362            NSDictionary::from_retained_objects(
363                &[objc2_app_kit::NSLinkAttributeName, objc2_app_kit::NSFontAttributeName],
364                &[Retained::<AnyObject>::from(Retained::into_super(link)), Retained::<AnyObject>::from(Retained::into_super(objc2_app_kit::NSFont::systemFontOfSize(objc2_app_kit::NSFont::systemFontSize())))],
365            )
366        };
367        // SAFETY: a string with plain attributes.
368        let text = unsafe { NSAttributedString::initWithString_attributes(objc2::AnyThread::alloc(), &NSString::from_str(&self.title), Some(&attrs)) };
369        let field = LinkField::alloc(cx.mtm).set_ivars(url.clone());
370        // SAFETY: NSTextField's designated initialiser.
371        let field: Retained<LinkField> = unsafe { msg_send![super(field), initWithFrame: objc2_foundation::NSRect::ZERO] };
372        // A selectable label with link attributes opens the link when
373        // clicked, with the pointing hand over it.
374        field.setBezeled(false);
375        field.setDrawsBackground(false);
376        field.setEditable(false);
377        field.setSelectable(true);
378        field.setAllowsEditingTextAttributes(true);
379        field.setAttributedStringValue(&text);
380        Node::leaf(cx, as_view(&field), (false, false), Size::default()).0
381    }
382}
383
384/// A link titled `title` that opens `url` (a web page, `mailto:`, or a
385/// `file://` URL) in its app when clicked. VoiceOver reads it as a link.
386pub fn link(title: &str, url: &str) -> Link {
387    Link { title: title.into(), url: url.into() }
388}
389
390// ---- gauge and rating ----
391
392/// A level indicator (see [`gauge`] and [`rating`]).
393pub struct Gauge {
394    value: GaugeValue,
395    max: f64,
396    style: NSLevelIndicatorStyle,
397    warning: Option<f64>,
398    critical: Option<f64>,
399}
400
401enum GaugeValue {
402    Shown(Box<dyn Fn() -> f64>),
403    Edited(Signal<f64>),
404}
405
406impl Gauge {
407    /// Segments instead of a continuous bar.
408    pub fn discrete(mut self) -> Self {
409        self.style = NSLevelIndicatorStyle::DiscreteCapacity;
410        self
411    }
412
413    /// Turns yellow from `value` up (or down, if it's above the critical
414    /// value): a disk filling up, a battery running down.
415    pub fn warning(mut self, value: f64) -> Self {
416        self.warning = Some(value);
417        self
418    }
419
420    /// Turns red from `value` up (or down, if it's below the warning value).
421    pub fn critical(mut self, value: f64) -> Self {
422        self.critical = Some(value);
423        self
424    }
425}
426
427impl View for Gauge {
428    fn build(self, cx: &mut Cx) -> Node {
429        let g = NSLevelIndicator::new(cx.mtm);
430        g.setLevelIndicatorStyle(self.style);
431        g.setMinValue(0.0);
432        g.setMaxValue(self.max);
433        if let Some(w) = self.warning {
434            g.setWarningValue(w);
435        }
436        if let Some(c) = self.critical {
437            g.setCriticalValue(c);
438        }
439        let rating = self.style == NSLevelIndicatorStyle::Rating;
440        let flex = (!rating, false);
441        let min = if rating { Size::default() } else { Size { w: 120.0, h: 0.0 } };
442        let (mut node, _) = Node::leaf(cx, as_view(&g), flex, min);
443        match self.value {
444            GaugeValue::Shown(f) => {
445                let g2 = g.clone();
446                node.own(Effect::new(move || g2.setDoubleValue(f())));
447            }
448            GaugeValue::Edited(signal) => {
449                g.setEditable(true);
450                let g2 = g.clone();
451                let target = ActionTarget::new(cx.mtm, move || signal.set_if_changed(g2.doubleValue()));
452                wire(&g, &target);
453                node.keep(Retained::into_super(target));
454                let g3 = g.clone();
455                node.own(Effect::new(move || {
456                    let v = signal.get();
457                    if g3.doubleValue() != v {
458                        g3.setDoubleValue(v);
459                    }
460                }));
461            }
462        }
463        node
464    }
465}
466
467/// A level indicator showing `value` (a closure reading signals, or a fixed value) out of `max` (0 to `max`), redrawn
468/// when the signals it reads change: storage used, a battery, signal
469/// strength. Give it a [`warning`](Gauge::warning) and
470/// [`critical`](Gauge::critical) level to colour it.
471pub fn gauge(value: impl crate::IntoValue<f64>, max: f64) -> Gauge {
472    let value = value.into_value();
473    Gauge { value: GaugeValue::Shown(Box::new(move || value.get())), max, style: NSLevelIndicatorStyle::ContinuousCapacity, warning: None, critical: None }
474}
475
476/// Stars from 0 to `max`, bound two ways to `value`: clicking a star sets
477/// it, as in Music and Photos.
478pub fn rating(value: &Signal<f64>, max: u32) -> Gauge {
479    Gauge { value: GaugeValue::Edited(*value), max: max as f64, style: NSLevelIndicatorStyle::Rating, warning: None, critical: None }
480}
481
482// ---- token field ----
483
484/// What a token field's delegate needs.
485struct TokenState {
486    value: Signal<Vec<String>>,
487    suggestions: Vec<String>,
488}
489
490define_class!(
491    // Edits of a token field → its signal; completions from suggestions.
492    #[unsafe(super(NSObject))]
493    #[thread_kind = MainThreadOnly]
494    #[name = "FerrokitTokenDelegate"]
495    #[ivars = TokenState]
496    struct TokenDelegate;
497
498    unsafe impl NSObjectProtocol for TokenDelegate {}
499
500    unsafe impl NSControlTextEditingDelegate for TokenDelegate {
501        #[unsafe(method(controlTextDidChange:))]
502        fn did_change(&self, notification: &NSNotification) {
503            crate::failure::guard("a control (did_change)", (), || {
504                self.read(notification);
505            })
506        }
507
508        #[unsafe(method(controlTextDidEndEditing:))]
509        fn did_end(&self, notification: &NSNotification) {
510            crate::failure::guard("a control (did_end)", (), || {
511                self.read(notification);
512            })
513        }
514    }
515
516    unsafe impl NSTextFieldDelegate for TokenDelegate {}
517
518    unsafe impl NSTokenFieldDelegate for TokenDelegate {
519        #[unsafe(method_id(tokenField:completionsForSubstring:indexOfToken:indexOfSelectedItem:))]
520        fn completions(&self, _field: &NSTokenField, substring: &NSString, _index: isize, _selected: *mut isize) -> Option<Retained<NSArray>> {
521            crate::failure::guard("a control (completions)", None, || {
522                let typed = substring.to_string().to_lowercase();
523                let matches: Vec<Retained<NSString>> =
524                    self.ivars().suggestions.iter().filter(|s| s.to_lowercase().starts_with(&typed)).map(|s| NSString::from_str(s)).collect();
525                Retained::into_super(NSArray::from_retained_slice(&matches)).downcast().ok()
526            })
527        }
528    }
529);
530
531impl TokenDelegate {
532    fn read(&self, notification: &NSNotification) {
533        let Some(field) = notification.object().and_then(|o| o.downcast::<NSTokenField>().ok()) else { return };
534        let tokens = tokens_of(&field);
535        let signal = self.ivars().value;
536        batch(|| signal.set_if_changed(tokens));
537    }
538}
539
540/// The tokens a token field holds (finished ones; the text being typed
541/// becomes one when it's done).
542fn tokens_of(field: &NSTokenField) -> Vec<String> {
543    let Some(value) = field.objectValue() else { return Vec::new() };
544    match value.downcast::<NSArray>() {
545        Ok(array) => array.iter().filter_map(|o| o.downcast::<NSString>().ok()).map(|s| s.to_string()).filter(|s| !s.is_empty()).collect(),
546        Err(other) => other.downcast::<NSString>().ok().map(|s| s.to_string()).filter(|s| !s.is_empty()).into_iter().collect(),
547    }
548}
549
550/// A token field (see [`token_field`]).
551pub struct TokenField {
552    value: Signal<Vec<String>>,
553    suggestions: Vec<String>,
554    placeholder: Option<String>,
555}
556
557impl TokenField {
558    /// Completions offered as the user types (those starting with what
559    /// they've typed, ignoring case).
560    pub fn suggestions(mut self, suggestions: &[&str]) -> Self {
561        self.suggestions = suggestions.iter().map(|s| s.to_string()).collect();
562        self
563    }
564
565    /// Grey text shown while it's empty.
566    pub fn placeholder(mut self, text: &str) -> Self {
567        self.placeholder = Some(text.into());
568        self
569    }
570}
571
572impl View for TokenField {
573    fn build(self, cx: &mut Cx) -> Node {
574        let field = NSTokenField::new(cx.mtm);
575        if let Some(p) = &self.placeholder {
576            field.setPlaceholderString(Some(&NSString::from_str(p)));
577        }
578        let delegate = TokenDelegate::alloc(cx.mtm).set_ivars(TokenState { value: self.value, suggestions: self.suggestions });
579        // SAFETY: NSObject's designated initialiser.
580        let delegate: Retained<TokenDelegate> = unsafe { msg_send![super(delegate), init] };
581        // SAFETY: the node keeps the delegate alive as long as the field.
582        unsafe { field.setDelegate(Some(ProtocolObject::from_ref(&*delegate))) };
583        let (mut node, handle) = Node::leaf(cx, as_view(&field), (true, false), Size { w: 160.0, h: 0.0 });
584        // A modest natural width: it fills the room it's given.
585        handle.content.set(Some(Size { w: 160.0, h: field.fittingSize().height }));
586        let value = self.value;
587        node.own(Effect::new(move || {
588            let tokens = value.get();
589            if tokens_of(&field) != tokens {
590                let strings: Vec<Retained<NSString>> = tokens.iter().map(|t| NSString::from_str(t)).collect();
591                // SAFETY: an array of strings is a token field's value.
592                unsafe { field.setObjectValue(Some(&NSArray::from_retained_slice(&strings))) };
593            }
594        }));
595        node.keep(Retained::into_super(delegate));
596        node
597    }
598}
599
600/// A token field bound two ways to `value`: words or names as tokens
601/// (tags, recipients), finished with Return or a comma.
602pub fn token_field(value: &Signal<Vec<String>>) -> TokenField {
603    TokenField { value: *value, suggestions: Vec::new(), placeholder: None }
604}
605
606// ---- path control ----
607
608/// A path control (see [`path_control`]).
609pub struct PathControl(Signal<PathBuf>);
610
611impl View for PathControl {
612    fn build(self, cx: &mut Cx) -> Node {
613        let control = NSPathControl::new(cx.mtm);
614        let signal = self.0;
615        let c = control.clone();
616        // A click on a folder in the path chooses it.
617        let target = ActionTarget::new(cx.mtm, move || {
618            let url = c.clickedPathItem().and_then(|i| i.URL()).or_else(|| c.URL());
619            if let Some(path) = url.and_then(|u| u.path()) {
620                signal.set_if_changed(PathBuf::from(path.to_string()));
621            }
622        });
623        wire(&control, &target);
624        // Its height is measured with a path in it.
625        control.setURL(Some(&file_url(&crate::signal::untrack(|| signal.get()))));
626        let (mut node, handle) = Node::leaf(cx, as_view(&control), (true, false), Size { w: 160.0, h: 0.0 });
627        // Not the whole path's width: it fills the room it's given, and
628        // shortens the middle folders to fit.
629        handle.content.set(Some(Size { w: 160.0, h: control.fittingSize().height }));
630        node.own(Effect::new(move || {
631            let path = signal.get();
632            let current = control.URL().and_then(|u| u.path()).map(|p| PathBuf::from(p.to_string()));
633            if current.as_deref() != Some(path.as_path()) {
634                control.setURL(Some(&file_url(&path)));
635            }
636        }));
637        node.keep(Retained::into_super(target));
638        node
639    }
640}
641
642fn file_url(path: &Path) -> Retained<NSURL> {
643    NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
644}
645
646/// The folders down to a file or folder, as the Finder's path bar shows
647/// them, bound two ways to `path`: clicking a folder sets `path` to it.
648pub fn path_control(path: &Signal<PathBuf>) -> PathControl {
649    PathControl(*path)
650}