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)]
37#[must_use]
38pub struct Command {
39    id: day_core::ElementId,
40    label: TextSource,
41    enabled: Reactive<bool>,
42    checked: Option<Reactive<bool>>,
43    icon: Option<Icon>,
44    shortcut: Option<Shortcut>,
45    handler: Rc<dyn Fn()>,
46    owner: Scope,
47}
48
49impl Command {
50    /// A command with its default presentation id, its title (the same sources as a button:
51    /// a literal, a localized text, a signal, a closure) and its synchronous handler.
52    /// Availability is checked before the handler is called. Captures the current reactive
53    /// scope as the command's owner.
54    pub fn new<M>(
55        id: day_core::ElementId,
56        label: impl IntoText<M>,
57        action: impl Fn() + 'static,
58    ) -> Command {
59        Command {
60            id,
61            label: label.into_text(),
62            enabled: Reactive::Const(true),
63            checked: None,
64            icon: None,
65            shortcut: None,
66            handler: Rc::new(action),
67            owner: Scope::current(),
68        }
69    }
70
71    /// Availability shared by every presentation and checked again on every invocation.
72    pub fn enabled<M>(mut self, enabled: impl IntoReactive<bool, M>) -> Self {
73        self.enabled = enabled.into_reactive();
74        self
75    }
76
77    /// Optional check state. The handler owns mutations; invoking never flips this itself.
78    pub fn checked<M>(mut self, checked: impl IntoReactive<bool, M>) -> Self {
79        self.checked = Some(checked.into_reactive());
80        self
81    }
82
83    pub fn icon(mut self, symbol: Symbol) -> Self {
84        self.icon = Some(Icon::Symbol(symbol));
85        self
86    }
87
88    pub fn image(mut self, name: impl Into<day_spec::ImageName>) -> Self {
89        self.icon = Some(Icon::Image(name.into().as_str().to_owned()));
90        self
91    }
92
93    /// Menu accelerator metadata. Only installing a menu entry installs the shortcut.
94    pub fn shortcut(mut self, shortcut: Shortcut) -> Self {
95        self.shortcut = Some(shortcut);
96        self
97    }
98
99    #[must_use]
100    pub fn id(&self) -> &str {
101        self.id.as_str()
102    }
103
104    /// Current title, with tracked reads for reactive presentation builders.
105    #[must_use]
106    pub fn label(&self) -> String {
107        if self.owner.is_alive() {
108            self.label.resolve()
109        } else {
110            String::new()
111        }
112    }
113
114    #[must_use]
115    pub fn is_enabled(&self) -> bool {
116        self.owner.is_alive() && self.enabled.get()
117    }
118
119    #[must_use]
120    pub fn is_checked(&self) -> Option<bool> {
121        self.checked
122            .as_ref()
123            .map(|v| self.owner.is_alive() && v.get())
124    }
125
126    /// Run if still available. Returns whether the handler ran, not whether its work succeeded.
127    /// Reads are untracked; invoking inside an effect does not subscribe it to the handler.
128    pub fn invoke(&self) -> bool {
129        untrack(|| {
130            if !self.is_enabled() {
131                return false;
132            }
133            (self.handler)();
134            true
135        })
136    }
137
138    /// A live button with this command's default id, title, icon, availability, and handler.
139    /// A push button does not draw a check mark. Add presentation styling as usual.
140    pub fn button(&self) -> Decorated<Button> {
141        let (title, enabled, action) = (self.clone(), self.clone(), self.clone());
142        let mut button = crate::button(move || title.label())
143            .enabled(move || enabled.is_enabled())
144            .action(move || {
145                action.invoke();
146            });
147        button = match &self.icon {
148            Some(Icon::Symbol(s)) => button.icon(*s),
149            Some(Icon::Image(name)) => button.image(name.clone()),
150            None => button,
151        };
152        button.id(self.id.clone())
153    }
154
155    /// A live menu entry: its title, availability and check mark follow the command, and the
156    /// menu it sits in re-lowers when they change. Invocation always rechecks availability.
157    pub fn menu_item(&self) -> MenuEntry {
158        let (title, enabled, action) = (self.clone(), self.clone(), self.clone());
159        let mut item = crate::menu_item(move || title.label())
160            .id(self.id.clone())
161            .enabled(move || enabled.is_enabled())
162            .action(move || {
163                action.invoke();
164            });
165        if self.is_checked().is_some() {
166            let checked = self.clone();
167            item = item.checked(move || checked.is_checked().unwrap_or(false));
168        }
169        if let Some(shortcut) = &self.shortcut {
170            item = item.shortcut(shortcut.clone());
171        }
172        match &self.icon {
173            Some(Icon::Symbol(s)) => item.icon(*s),
174            Some(Icon::Image(name)) => item.image(name.clone()),
175            None => item,
176        }
177    }
178
179    /// Snapshot for a derived toolbar: `.toolbar(move || vec![command.toolbar_item()])`.
180    /// Checked commands draw a toggle; the handler remains the sole owner of its state.
181    /// Reactive builders refresh titles/checks; availability also gets a targeted live binding.
182    pub fn toolbar_item(&self) -> ToolbarEntry {
183        let (enabled, action) = (self.clone(), self.clone());
184        let mut item = crate::toolbar_button(self.id.clone(), self.label())
185            .enabled(move || enabled.is_enabled())
186            .action(move || {
187                action.invoke();
188            });
189        if self.is_checked().is_some() {
190            let checked = self.clone();
191            item = item.command_checked(Rc::new(move || checked.is_checked().unwrap_or(false)));
192        }
193        match &self.icon {
194            Some(Icon::Symbol(s)) => item.icon(*s),
195            Some(Icon::Image(name)) => item.image(name.clone()),
196            None => item,
197        }
198    }
199}