Skip to main content

day_pieces/
commands.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Reusable application commands. See `docs/commands.md` for ownership and presentation rules.
5
6use std::rc::Rc;
7
8use day_reactive::{Scope, untrack};
9use day_spec::{Icon, Shortcut, Symbol};
10
11use crate::{
12    Button, Decorate, Decorated, IntoReactive, IntoText, MenuEntry, Reactive, TextSource,
13    ToolbarEntry,
14};
15
16/// An application operation shared by buttons, menus, toolbars, and direct callers
17/// (docs/commands.md): one id, one title, one availability, one handler, presented through
18/// [`button`](Command::button), [`menu_item`](Command::menu_item) and
19/// [`toolbar_item`](Command::toolbar_item).
20///
21/// Built with [`Command::new`] in the scope that owns it. Clones share the handler and reactive
22/// sources. Builders configure a copy, not existing presentations. Invocation after the owning
23/// scope's disposal is a no-op. This is a UI-thread value, not a global registry or a native
24/// edit role.
25///
26/// ```
27/// use day_pieces::prelude::*;
28/// use day_reactive::Signal;
29///
30/// let count = Signal::new(0);
31/// let add = Command::new(day_core::id!(add), "Add one", move || count.update(|n| *n += 1))
32///     .enabled(move || count.get() < 3);
33/// assert!(add.invoke());
34/// assert_eq!(count.get(), 1);
35/// ```
36#[derive(Clone)]
37pub struct Command {
38    id: day_core::ElementId,
39    label: TextSource,
40    enabled: Reactive<bool>,
41    checked: Option<Reactive<bool>>,
42    icon: Option<Icon>,
43    shortcut: Option<Shortcut>,
44    handler: Rc<dyn Fn()>,
45    owner: Scope,
46}
47
48impl Command {
49    /// A command with its default presentation id, its title (the same sources as a button:
50    /// a literal, a localized text, a signal, a closure) and its synchronous handler.
51    /// Availability is checked before the handler is called. Captures the current reactive
52    /// scope as the command's owner.
53    pub fn new<M>(
54        id: day_core::ElementId,
55        label: impl IntoText<M>,
56        action: impl Fn() + 'static,
57    ) -> Command {
58        Command {
59            id,
60            label: label.into_text(),
61            enabled: Reactive::Const(true),
62            checked: None,
63            icon: None,
64            shortcut: None,
65            handler: Rc::new(action),
66            owner: Scope::current(),
67        }
68    }
69
70    /// Availability shared by every presentation and checked again on every invocation.
71    pub fn enabled<M>(mut self, enabled: impl IntoReactive<bool, M>) -> Self {
72        self.enabled = enabled.into_reactive();
73        self
74    }
75
76    /// Optional check state. The handler owns mutations; invoking never flips this itself.
77    pub fn checked<M>(mut self, checked: impl IntoReactive<bool, M>) -> Self {
78        self.checked = Some(checked.into_reactive());
79        self
80    }
81
82    pub fn icon(mut self, symbol: Symbol) -> Self {
83        self.icon = Some(Icon::Symbol(symbol));
84        self
85    }
86
87    pub fn image(mut self, name: impl Into<day_spec::ImageName>) -> Self {
88        self.icon = Some(Icon::Image(name.into().as_str().to_owned()));
89        self
90    }
91
92    /// Menu accelerator metadata. Only installing a menu entry installs the shortcut.
93    pub fn shortcut(mut self, shortcut: Shortcut) -> Self {
94        self.shortcut = Some(shortcut);
95        self
96    }
97
98    pub fn id(&self) -> &str {
99        self.id.as_str()
100    }
101
102    /// Current title, with tracked reads for reactive presentation builders.
103    pub fn label(&self) -> String {
104        if self.owner.is_alive() {
105            self.label.resolve()
106        } else {
107            String::new()
108        }
109    }
110
111    pub fn is_enabled(&self) -> bool {
112        self.owner.is_alive() && self.enabled.get()
113    }
114
115    pub fn is_checked(&self) -> Option<bool> {
116        self.checked
117            .as_ref()
118            .map(|v| self.owner.is_alive() && v.get())
119    }
120
121    /// Run if still available. Returns whether the handler ran, not whether its work succeeded.
122    /// Reads are untracked; invoking inside an effect does not subscribe it to the handler.
123    pub fn invoke(&self) -> bool {
124        untrack(|| {
125            if !self.is_enabled() {
126                return false;
127            }
128            (self.handler)();
129            true
130        })
131    }
132
133    /// A live button with this command's default id, title, icon, availability, and handler.
134    /// A push button does not draw a check mark. Add presentation styling as usual.
135    pub fn button(&self) -> Decorated<Button> {
136        let (title, enabled, action) = (self.clone(), self.clone(), self.clone());
137        let mut button = crate::button(move || title.label())
138            .enabled(move || enabled.is_enabled())
139            .action(move || {
140                action.invoke();
141            });
142        button = match &self.icon {
143            Some(Icon::Symbol(s)) => button.icon(*s),
144            Some(Icon::Image(name)) => button.image(name.clone()),
145            None => button,
146        };
147        button.id(self.id.clone())
148    }
149
150    /// A live menu entry: its title, availability and check mark follow the command, and the
151    /// menu it sits in re-lowers when they change. Invocation always rechecks availability.
152    pub fn menu_item(&self) -> MenuEntry {
153        let (title, enabled, action) = (self.clone(), self.clone(), self.clone());
154        let mut item = crate::menu_item(move || title.label())
155            .id(self.id.clone())
156            .enabled(move || enabled.is_enabled())
157            .action(move || {
158                action.invoke();
159            });
160        if self.is_checked().is_some() {
161            let checked = self.clone();
162            item = item.checked(move || checked.is_checked().unwrap_or(false));
163        }
164        if let Some(shortcut) = &self.shortcut {
165            item = item.shortcut(shortcut.clone());
166        }
167        match &self.icon {
168            Some(Icon::Symbol(s)) => item.icon(*s),
169            Some(Icon::Image(name)) => item.image(name.clone()),
170            None => item,
171        }
172    }
173
174    /// Snapshot for a derived toolbar: `.toolbar(move || vec![command.toolbar_item()])`.
175    /// Checked commands draw a toggle; the handler remains the sole owner of its state.
176    /// Reactive builders refresh titles/checks; availability also gets a targeted live binding.
177    pub fn toolbar_item(&self) -> ToolbarEntry {
178        let (enabled, action) = (self.clone(), self.clone());
179        let mut item = crate::toolbar_button(self.id.clone(), self.label())
180            .enabled(move || enabled.is_enabled())
181            .action(move || {
182                action.invoke();
183            });
184        if self.is_checked().is_some() {
185            let checked = self.clone();
186            item = item.command_checked(Rc::new(move || checked.is_checked().unwrap_or(false)));
187        }
188        match &self.icon {
189            Some(Icon::Symbol(s)) => item.icon(*s),
190            Some(Icon::Image(name)) => item.image(name.clone()),
191            None => item,
192        }
193    }
194}