Skip to main content

day_core/
toolbar.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Toolbar contributions (docs/toolbars.md). The model ([`day_spec::ToolbarItem`]) is
5//! toolkit-neutral and carries only ids for its commands; the closures live here, keyed by
6//! id, the same shape as [`crate::menu`] and the same id space, so one closure can
7//! back both a toolbar button and its menu-bar twin.
8//!
9//! Any piece can declare items. Where it sits decides which chrome carries them (the window's
10//! own, or one navigation page's), and its scope decides how long they stay: a contribution is
11//! withdrawn when the piece that registered it is disposed, so a command leaves with the content
12//! it acts on. Several pieces may contribute to one chrome; this module merges them in
13//! registration order and hands the result to the toolkit as one model.
14
15use std::cell::{Cell, RefCell};
16use std::collections::HashMap;
17use std::rc::Rc;
18
19use day_spec::{ToolbarItem, ToolbarPatch, ToolbarValue};
20
21use crate::tree::{RNode, with_tree};
22
23/// A toolbar item's value callback: what a search field's text or a toggle's state runs.
24type ValueAction = Rc<dyn Fn(&ToolbarValue)>;
25
26/// Which chrome a contribution lands on.
27///
28/// Not a placement; [`day_spec::ToolbarPlacement`] says where on a chrome an item sits. This
29/// says which chrome, and it is never written by an app: it follows from the piece that declared
30/// the items, which is what the design is built around (docs/toolbars.md).
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32pub enum Chrome {
33    /// The window's own chrome, shown on every page of that window.
34    Window(RNode),
35    /// One navigation page's chrome. Which surface draws it follows from the page's
36    /// [`day_spec::props::Pane`].
37    Page(RNode),
38}
39
40/// One navigation page being built: the node contributions land on, whether it is on screen, and
41/// which column of the window it is.
42struct PageFrame {
43    page: RNode,
44    active: Option<Rc<dyn Fn() -> bool>>,
45    column: day_spec::ToolbarColumn,
46    /// The window this page belongs to, captured when its host was built. A destination page is
47    /// built lazily, on the first selection, long after its window's build has returned, and
48    /// `window_being_built()` then answers the primary window, so a second window's pages
49    /// would contribute to the first one's bar.
50    window: RNode,
51}
52
53/// One piece's declared items, alive as long as that piece is.
54struct Contribution {
55    chrome: Chrome,
56    /// Registration order within its chrome. Stable across an update, so re-deriving a list does
57    /// not move it past a neighbor that was declared later.
58    seq: u64,
59    items: Vec<ToolbarItem>,
60    /// The window this contribution's chrome belongs to.
61    window: RNode,
62    document_window: Option<DocumentWindow>,
63    /// Whether the page carrying it is on screen. One bar serves the window, so a pane that is
64    /// collapsed or a destination that is not the one showing must not leave its commands on it;
65    /// that is what made a sidebar row's chrome look one level out of step (docs/toolbars.md).
66    /// `None` for a window's items, which are always showing.
67    active: Option<Rc<dyn Fn() -> bool>>,
68}
69
70/// A resident document's mutable presentation window. Contributions inherit this
71/// context so moving the document also moves its commands without rebuilding them.
72#[derive(Clone)]
73pub struct DocumentWindow(Rc<Cell<RNode>>);
74impl DocumentWindow {
75    #[must_use]
76    pub fn new(root: RNode) -> Self {
77        Self(Rc::new(Cell::new(root)))
78    }
79    pub fn set(&self, root: RNode) {
80        if self.0.replace(root) != root {
81            schedule_recompose();
82        }
83    }
84}
85impl Contribution {
86    fn window(&self) -> RNode {
87        self.document_window
88            .as_ref()
89            .map_or(self.window, |w| w.0.get())
90    }
91}
92
93day_reactive::tls_slots! {
94    toolbar;
95    /// Value callbacks (search text, toggle state) by dispatch id. Plain buttons don't appear
96    /// here; they register with [`crate::menu::register_menu_action`] and arrive as
97    /// `Event::MenuAction`.
98    static VALUE_ACTIONS: RefCell<HashMap<u64, ValueAction>> = RefCell::new(HashMap::new());
99    /// Live contributions by token.
100    static CONTRIBUTIONS: RefCell<HashMap<u64, Contribution>> = RefCell::new(HashMap::new());
101    /// Each chrome's merged model as last lowered; dayscript resolves an item's action here,
102    /// and a recompose compares against it to skip an install that would change nothing. Items
103    /// carry slot ids here, never closure ids (the toolbar slot model).
104    static MODELS: RefCell<Vec<(Chrome, Vec<ToolbarItem>)>> = const { RefCell::new(Vec::new()) };
105    /// Each window's dispatch slots: (window, item key) → the id the toolkit holds for that item
106    /// (the toolbar slot model).
107    static SLOT_IDS: RefCell<HashMap<(RNode, String), u64>> = RefCell::new(HashMap::new());
108    /// Slot id → the closure id it dispatches to right now.
109    static SLOT_TARGETS: RefCell<HashMap<u64, u64>> = RefCell::new(HashMap::new());
110    /// Each window's bar as its toolkit holds it: what an edit is computed against. Separate
111    /// from [`MODELS`], which is the bar the window should carry (and what dayscript reads), so
112    /// an edit the toolkit never received is not mistaken for one it did: the next recompose
113    /// sends it again, the way a whole-bar install used to heal on the next change.
114    static DELIVERED: RefCell<HashMap<RNode, Vec<ToolbarItem>>> = RefCell::new(HashMap::new());
115    /// A recompose is owed at the end of this turn ([`schedule_recompose`]).
116    static RECOMPOSE_PENDING: Cell<bool> = const { Cell::new(false) };
117    static RECOMPOSING: Cell<bool> = const { Cell::new(false) };
118    static RECOMPOSE_AGAIN: Cell<bool> = const { Cell::new(false) };
119    /// Next contribution token, and the registration counter behind `Contribution::seq`.
120    static NEXT_TOKEN: Cell<u64> = const { Cell::new(1) };
121    /// The window whose content is being built right now (see [`with_window`]).
122    static BUILDING: Cell<Option<RNode>> = const { Cell::new(None) };
123    /// The navigation pages this build is inside, innermost last, each with the predicate that
124    /// says whether it is on screen. A contribution registered with a non-empty stack belongs to
125    /// the innermost page; one registered with an empty stack belongs to the window.
126    static PAGE_STACK: RefCell<Vec<PageFrame>> = RefCell::new(Vec::new());
127}
128
129/// Run `f` with `root` as the window contributions inside it belong to. day-core wraps each
130/// window's content build in this, and a presented cover wraps its content, so a navigation
131/// stack inside the cover puts its toolbar on the cover's own bar; nesting restores the
132/// previous window on the way out.
133pub fn with_window<R>(root: RNode, f: impl FnOnce() -> R) -> R {
134    // Restored on unwind too (the anim.rs `Restore` rule): a contained panic during a
135    // secondary window's build would otherwise leave `BUILDING` pointing at a dead window,
136    // silently redirecting every later contribution.
137    let previous = BUILDING.with(|b| b.replace(Some(root)));
138    let _restore =
139        std::mem::DropGuard::new(previous, |previous| BUILDING.with(|b| b.set(previous)));
140    f()
141}
142
143/// Run `f` with `page` as the navigation page contributions inside it belong to. The pieces layer
144/// wraps each destination, sidebar and content-list build in this.
145pub fn with_page<R>(page: RNode, f: impl FnOnce() -> R) -> R {
146    with_page_in(
147        page,
148        None,
149        day_spec::ToolbarColumn::Detail,
150        window_being_built(),
151        f,
152    )
153}
154
155/// [`with_page_gated`] naming the window explicitly. Callers that build pages lazily (every
156/// navigation host) pass the window they were built in.
157pub fn with_page_in<R>(
158    page: RNode,
159    active: Option<Rc<dyn Fn() -> bool>>,
160    column: day_spec::ToolbarColumn,
161    window: RNode,
162    f: impl FnOnce() -> R,
163) -> R {
164    PAGE_STACK.with(|s| {
165        s.borrow_mut().push(PageFrame {
166            page,
167            active,
168            column,
169            window,
170        });
171    });
172    let _restore = std::mem::DropGuard::new((), |()| {
173        PAGE_STACK.with(|s| {
174            s.borrow_mut().pop();
175        });
176    });
177    f()
178}
179
180/// [`with_page`] with the predicate that says whether this page is on screen (a collapsed
181/// content-list pane, a destination that is not the one showing, a page covered by a push). The
182/// window's one bar carries only the chromes that predicate admits (docs/toolbars.md).
183pub fn with_page_gated<R>(
184    page: RNode,
185    active: Option<Rc<dyn Fn() -> bool>>,
186    column: day_spec::ToolbarColumn,
187    f: impl FnOnce() -> R,
188) -> R {
189    with_page_in(page, active, column, window_being_built(), f)
190}
191
192/// The window the page being built belongs to, else the one being built.
193pub fn current_page_window() -> RNode {
194    PAGE_STACK
195        .with(|s| s.borrow().last().map(|f| f.window))
196        .unwrap_or_else(window_being_built)
197}
198
199/// The predicate for the page being built, if it has one.
200#[must_use]
201pub fn current_page_gate() -> Option<Rc<dyn Fn() -> bool>> {
202    PAGE_STACK.with(|s| s.borrow().last().and_then(|f| f.active.clone()))
203}
204
205/// Which column the page being built is; [`day_spec::ToolbarColumn::Window`] at the window root.
206#[must_use]
207pub fn current_page_column() -> day_spec::ToolbarColumn {
208    PAGE_STACK.with(|s| {
209        s.borrow()
210            .last()
211            .map_or(day_spec::ToolbarColumn::Window, |f| f.column)
212    })
213}
214
215/// The window being built, else the primary root. Shared with the ambient environment lookup, which scopes
216/// the same way for the same reason: an app's one `size_class()` call inside a shared
217/// `build_shell` must mean "this window".
218#[must_use]
219pub fn window_being_built() -> RNode {
220    BUILDING
221        .with(std::cell::Cell::get)
222        .unwrap_or_else(|| with_tree(|t| t.root_node()))
223}
224
225/// The chrome a contribution registered right now belongs to: the innermost navigation page
226/// being built, else the window being built, else the primary window.
227///
228/// Captured once, at registration. A derived contribution re-runs long after its build, when
229/// neither stack says anything, so reading this later would send its items to the primary
230/// window's chrome.
231#[must_use]
232pub fn current_chrome() -> Chrome {
233    match PAGE_STACK.with(|s| s.borrow().last().map(|f| f.page)) {
234        Some(page) => Chrome::Page(page),
235        None => Chrome::Window(window_being_built()),
236    }
237}
238
239/// Register a value callback for a search or toggle item and return its dispatch id (nonzero).
240/// The id comes from the menu action counter, so toolbar and menu ids never collide.
241pub fn register_toolbar_value(f: Rc<dyn Fn(&ToolbarValue)>) -> u64 {
242    let id = crate::menu::next_action_id();
243    VALUE_ACTIONS.with(|m| m.borrow_mut().insert(id, f));
244    id
245}
246
247/// Run the value callback registered for `action` (no-op if none). Called by the event pump on
248/// `Event::ToolbarChanged`, inside a reactive batch so multiple signal writes coalesce. `action`
249/// is the slot id the toolkit holds (the toolbar slot model); a raw closure id works too.
250pub fn dispatch_toolbar_value(action: u64, value: &ToolbarValue) {
251    mirror_value(action, value);
252    let target = resolve_slot(action);
253    let f = VALUE_ACTIONS.with(|m| m.borrow().get(&target).cloned());
254    if let Some(f) = f {
255        day_reactive::batch(|| f(value));
256    }
257}
258
259/// Synthetic input to a bar item (dayscript's `toolbar:` step): paint the widget the way an app
260/// write would, then dispatch the value as the native control would. Both halves are needed, as
261/// for a text field (`crate::synthesize_text`): a real keystroke reaches Day with the field
262/// already showing it, so the dispatch alone records the text without touching the widget, and a
263/// synthesized one left the field empty while the app acted on the query.
264pub fn synthesize_toolbar_value(action: u64, value: &ToolbarValue) {
265    if let ToolbarValue::Text(text) = value {
266        let target = MODELS.with(|m| {
267            m.borrow().iter().find_map(|(c, items)| match c {
268                Chrome::Window(root) => items
269                    .iter()
270                    .find(|i| i.action == action)
271                    .map(|i| (*root, i.id.clone())),
272                Chrome::Page(_) => None,
273            })
274        });
275        if let Some((root, item)) = target {
276            let patch = ToolbarPatch::Text {
277                item,
278                text: text.clone(),
279            };
280            if with_tree(|t| t.patch_window_toolbar(root, patch.clone())) {
281                deliver_value(root, &patch);
282            }
283        }
284    }
285    dispatch_toolbar_value(action, value);
286}
287
288/// The closure id a toolkit-held slot id dispatches to now; any other id is returned as is.
289/// The menu rail resolves through here too, since toolbar buttons ride it.
290pub(crate) fn resolve_slot(id: u64) -> u64 {
291    SLOT_TARGETS.with(|m| m.borrow().get(&id).copied().unwrap_or(id))
292}
293
294/// Add one piece's items to `chrome` and return the token that owns them. The caller withdraws
295/// them with [`unregister_contribution`], normally from its own scope cleanup.
296#[must_use]
297pub fn register_contribution(chrome: Chrome, items: Vec<ToolbarItem>) -> u64 {
298    register_contribution_gated(chrome, items, None)
299}
300
301/// [`register_contribution`] for a page, with the predicate that says whether that page is on
302/// screen. The caller also re-reads it inside an effect, which is what re-composes the bar when
303/// a pane collapses or the destination changes.
304#[must_use]
305pub fn register_contribution_gated(
306    chrome: Chrome,
307    items: Vec<ToolbarItem>,
308    active: Option<Rc<dyn Fn() -> bool>>,
309) -> u64 {
310    let token = NEXT_TOKEN.with(|n| {
311        let t = n.get();
312        n.set(t + 1);
313        t
314    });
315    let window = current_page_window();
316    CONTRIBUTIONS.with(|m| {
317        m.borrow_mut().insert(
318            token,
319            Contribution {
320                chrome,
321                seq: token,
322                items,
323                window,
324                document_window: day_reactive::Scope::current().use_context::<DocumentWindow>(),
325                active,
326            },
327        )
328    });
329    let _ = chrome;
330    schedule_recompose();
331    token
332}
333
334/// One window's whole bar for a toolkit that draws only one: its items, then every page
335/// chrome on screen under it, in registration order (docs/toolbars.md).
336fn merged_window(root: RNode) -> Vec<ToolbarItem> {
337    let mut live: Vec<(u64, Vec<ToolbarItem>)> = CONTRIBUTIONS.with(|m| {
338        m.borrow()
339            .values()
340            .filter(|c| c.window() == root)
341            .filter(|c| {
342                c.active
343                    .as_ref()
344                    .is_none_or(|f| day_reactive::untrack(|| f()))
345            })
346            .map(|c| (c.seq, c.items.clone()))
347            .collect()
348    });
349    live.sort_by_key(|(seq, _)| *seq);
350    let mut out: Vec<ToolbarItem> = live.into_iter().flat_map(|(_, items)| items).collect();
351    out.sort_by_key(|i| placement_rank(i.placement));
352    out
353}
354
355/// Replace one contribution's items in place, keeping its position among its neighbors.
356pub fn update_contribution(token: u64, items: Vec<ToolbarItem>) {
357    let old = CONTRIBUTIONS.with(|m| {
358        let mut m = m.borrow_mut();
359        let c = m.get_mut(&token)?;
360        Some(std::mem::replace(&mut c.items, items))
361    });
362    if let Some(old) = old {
363        forget_closures(&old);
364        schedule_recompose();
365    }
366}
367
368/// Give a contribution's items new labels and tooltips, one `(label, tooltip)` per item in
369/// order, keeping everything else as it now stands (actions, a search field's typed text): a
370/// language change relabeling a fixed toolbar (docs/toolbars.md).
371pub fn relabel_contribution(token: u64, texts: &[(String, Option<String>)]) {
372    let Some(mut items) = CONTRIBUTIONS.with(|m| m.borrow().get(&token).map(|c| c.items.clone()))
373    else {
374        return;
375    };
376    for (item, (label, tooltip)) in items.iter_mut().zip(texts) {
377        item.label.clone_from(label);
378        item.tooltip.clone_from(tooltip);
379    }
380    update_contribution(token, items);
381}
382
383/// Withdraw a contribution. Its items leave the chrome, and the closures only it owned go with
384/// them.
385pub fn unregister_contribution(token: u64) {
386    let old = CONTRIBUTIONS.with(|m| m.borrow_mut().remove(&token).map(|c| c.items));
387    if let Some(old) = old {
388        forget_closures(&old);
389        schedule_recompose();
390    }
391}
392
393/// Drop the closures `items` registered that no live contribution still carries, so a page
394/// visited a hundred times does not hold a hundred generations of its commands.
395///
396/// Only the item-level ids: a button's or a toggle's own closure, registered fresh by each
397/// lowering. A pull-down's entries can name Day's standing dispatchers (a new-window item), so
398/// they stay registered, as they did before.
399fn forget_closures(items: &[ToolbarItem]) {
400    let live: std::collections::HashSet<u64> = CONTRIBUTIONS.with(|m| {
401        m.borrow()
402            .values()
403            .flat_map(|c| c.items.iter().map(|i| i.action))
404            .collect()
405    });
406    for item in items
407        .iter()
408        .filter(|i| i.action != 0 && !live.contains(&i.action))
409    {
410        VALUE_ACTIONS.with(|m| m.borrow_mut().remove(&item.action));
411        if matches!(
412            item.kind,
413            day_spec::ToolbarItemKind::Button | day_spec::ToolbarItemKind::Menu { .. }
414        ) {
415            crate::menu::forget_action(item.action);
416        }
417    }
418}
419
420/// The order the buckets draw in, leading to trailing. `Bottom` sorts with `Secondary`: a chrome
421/// with no bottom bar draws it there, and one with a bottom bar takes it out of this list before
422/// ordering matters.
423fn placement_rank(p: day_spec::ToolbarPlacement) -> u8 {
424    use day_spec::ToolbarPlacement as P;
425    match p {
426        P::Navigation => 0,
427        P::Principal => 1,
428        P::Automatic => 2,
429        P::Primary => 3,
430        P::Secondary | P::Bottom => 4,
431    }
432}
433
434/// Record a value the user put into a live item, without touching the widget that reported it.
435///
436/// The widget already shows it; what is stale is Day's copy. Both copies (the owning
437/// contribution's, which a re-compose merges from, and the window's model, which the toolkit
438/// drew and dayscript reads) must learn it, or the next rebuild seeds the item with whatever Day
439/// last pushed. That is how a search field typed into came back empty after a page change, with
440/// the list still filtered by the text it had lost, and how clearing it afterwards reported
441/// nothing new (the field held the stale seed already).
442fn mirror_value(action: u64, value: &ToolbarValue) {
443    // A page's own bar (a phone's navigation item) is a model of its own; the desktops merge
444    // the showing page into the window's. Either way the item's chrome is where Day's copy lives.
445    // A window's bar first: where a page merges into it, that is the bar the toolkit drew.
446    let Some((chrome, id)) = MODELS.with(|m| {
447        let m = m.borrow();
448        let found = |window: bool| {
449            m.iter().find_map(|(c, items)| {
450                (matches!(c, Chrome::Window(_)) == window)
451                    .then(|| items.iter().find(|i| i.action == action))
452                    .flatten()
453                    .map(|i| (*c, i.id.clone()))
454            })
455        };
456        found(true).or_else(|| found(false))
457    }) else {
458        return;
459    };
460    let patch = match value {
461        ToolbarValue::Text(text) => ToolbarPatch::Text {
462            item: id,
463            text: text.clone(),
464        },
465        ToolbarValue::On(on) => ToolbarPatch::On { item: id, on: *on },
466        ToolbarValue::Selected(index) => ToolbarPatch::Selected {
467            item: id,
468            index: *index,
469        },
470        // A submission leaves the field's text as the last `Text` set it.
471        ToolbarValue::Submit(_) => return,
472    };
473    CONTRIBUTIONS.with(|m| {
474        for c in m.borrow_mut().values_mut().filter(|c| match chrome {
475            Chrome::Window(root) => c.window() == root,
476            Chrome::Page(_) => c.chrome == chrome,
477        }) {
478            apply_to_model(&mut c.items, &patch);
479        }
480    });
481    MODELS.with(|m| {
482        if let Some((_, items)) = m.borrow_mut().iter_mut().find(|(c, _)| *c == chrome) {
483            apply_to_model(items, &patch);
484        }
485    });
486    if let Chrome::Window(root) = chrome {
487        deliver_value(root, &patch);
488    }
489}
490
491/// Owe the windows a recompose, paid once when the current turn settles.
492///
493/// Every change to what a bar carries lands here: a contribution registered, re-derived or
494/// withdrawn, a page gate flipping. A single user action makes several of them. Swapping the
495/// page withdraws the old page's items and contributes the new page's, and handing each step to
496/// the toolkit rebuilt the bar twice, through an intermediate bar nobody should see, when the
497/// bar before and after was the same. Deferring to the end of the turn composes only the settled
498/// result, and [`recompose_windows`] then finds nothing to install. Outside a turn (a window's
499/// first build) it runs right away.
500fn schedule_recompose() {
501    if RECOMPOSE_PENDING.with(|p| p.replace(true)) {
502        return;
503    }
504    day_reactive::at_turn_end(recompose_windows);
505}
506
507/// Hand every window whose composed bar changed its new model, and nothing to the rest.
508///
509/// A bar is re-installed only when something the toolkit draws changed: an item added,
510/// removed or reordered, a label, an icon, a kind. What changes on every derivation, the
511/// closures, never reaches the model: each item is handed to the toolkit under a stable slot
512/// id (the toolbar slot model), so a page re-built with the same commands composes a model equal to
513/// the installed one. Values the user or the app change (search text, a toggle) reach the model
514/// through the same patches that update the widget, so they never differ either.
515fn recompose_windows() {
516    recompose_serially(recompose_windows_inner);
517}
518
519// Native toolbar edits can enqueue layout/focus events. `with_tree` drains those events
520// before returning, and their handlers can request another toolbar composition. Finish
521// recording DELIVERED first: nested diffs against the old baseline insert an item twice,
522// which raises an Objective-C exception in NSToolbar.
523fn recompose_serially(mut apply: impl FnMut()) {
524    if RECOMPOSING.with(|busy| busy.replace(true)) {
525        RECOMPOSE_AGAIN.with(|again| again.set(true));
526        return;
527    }
528    let _reset = std::mem::DropGuard::new((), |()| {
529        RECOMPOSING.with(|busy| busy.set(false));
530        RECOMPOSE_AGAIN.with(|again| again.set(false));
531    });
532    loop {
533        RECOMPOSE_AGAIN.with(|again| again.set(false));
534        apply();
535        if !RECOMPOSE_AGAIN.with(std::cell::Cell::get) {
536            break;
537        }
538    }
539}
540
541fn recompose_windows_inner() {
542    RECOMPOSE_PENDING.with(|p| p.set(false));
543    let roots: Vec<RNode> = {
544        let mut v: Vec<RNode> =
545            CONTRIBUTIONS.with(|m| m.borrow().values().map(Contribution::window).collect());
546        // A window whose last contribution left still has a bar to take down.
547        v.extend(MODELS.with(|m| {
548            m.borrow()
549                .iter()
550                .filter_map(|(c, _)| match c {
551                    Chrome::Window(r) => Some(*r),
552                    Chrome::Page(_) => None,
553                })
554                .collect::<Vec<_>>()
555        }));
556        v.sort();
557        v.dedup();
558        v
559    };
560    for root in roots {
561        let items = slot_model(root, unique_ids(merged_window(root)));
562        MODELS.with(|m| {
563            let mut m = m.borrow_mut();
564            match m.iter_mut().find(|(c, _)| *c == Chrome::Window(root)) {
565                Some(entry) => entry.1.clone_from(&items),
566                None => m.push((Chrome::Window(root), items.clone())),
567            }
568        });
569        let prev = DELIVERED.with(|d| d.borrow().get(&root).cloned().unwrap_or_default());
570        let (ops, patches) = diff_bar(&prev, &items);
571        if ops.is_empty() && patches.is_empty() {
572            continue;
573        }
574        debug_assert!(edit_is_ordered(&ops), "toolbar edit out of order: {ops:?}");
575        // Recorded as the toolkit's only once it has the edit. A window whose root has no native
576        // handle yet takes none; its bar goes out whole on the next recompose instead.
577        let delivered = ops.is_empty() || with_tree(|t| t.edit_window_toolbar(root, ops));
578        if !delivered {
579            continue;
580        }
581        for patch in patches {
582            with_tree(|t| t.patch_window_toolbar(root, patch));
583        }
584        DELIVERED.with(|d| d.borrow_mut().insert(root, items));
585    }
586}
587
588/// The order backends rely on (`Toolkit::edit_toolbar`): every removal, then the insertions in
589/// ascending position.
590fn edit_is_ordered(ops: &[day_spec::ToolbarOp]) -> bool {
591    use day_spec::ToolbarOp as O;
592    let first_insert = ops
593        .iter()
594        .position(|o| matches!(o, O::Insert { .. }))
595        .unwrap_or(ops.len());
596    let inserts: Vec<usize> = ops[first_insert..]
597        .iter()
598        .filter_map(|o| match o {
599            O::Insert { index, .. } => Some(*index),
600            O::Remove { .. } => None,
601        })
602        .collect();
603    inserts.len() == ops.len() - first_insert && inserts.windows(2).all(|w| w[0] < w[1])
604}
605
606/// Record a value the toolkit already shows (a patch it took, or input it reported) in its copy
607/// of the bar, so the next edit is computed against what is on screen.
608fn deliver_value(root: RNode, patch: &ToolbarPatch) {
609    DELIVERED.with(|d| {
610        if let Some(items) = d.borrow_mut().get_mut(&root) {
611            patch.apply_to(items);
612        }
613    });
614}
615
616/// The bar without the items whose id an earlier one already has.
617///
618/// An id is an item's identity on the bar (the native identifier, the key an edit and a patch
619/// address), so it must be unique, and two showing pages declaring the same one is an app bug.
620/// Keeping the first, and saying so once, leaves the bar coherent rather than editing two
621/// natives under one name.
622fn unique_ids(items: Vec<ToolbarItem>) -> Vec<ToolbarItem> {
623    let mut seen = std::collections::HashSet::new();
624    items
625        .into_iter()
626        .filter(|i| {
627            let fresh = seen.insert(i.id.clone());
628            if !fresh {
629                log::warn!(
630                    "toolbar item id {:?} appears twice in one window's bar; only the first is \
631                     shown (docs/toolbars.md: ids are unique within a bar)",
632                    i.id
633                );
634            }
635            fresh
636        })
637        .collect()
638}
639
640/// The edit that turns bar `prev` into bar `next`, and the value patches for the items it keeps
641/// (docs/toolbars.md).
642///
643/// Items are matched by id. One the toolkit already draws is kept when it is drawn the same way
644/// (everything but its values: words, search text, prompt and completions, toggle state, selection,
645/// enablement) and when keeping it does not reorder it past another kept item; the kept set is
646/// the longest run of matched items already in order, so a reshuffle costs the fewest items.
647/// Everything else is removed and inserted. A kept item whose values moved gets the patches that
648/// bring it current, the same patches a bound signal would have sent.
649fn diff_bar(
650    prev: &[ToolbarItem],
651    next: &[ToolbarItem],
652) -> (Vec<day_spec::ToolbarOp>, Vec<ToolbarPatch>) {
653    use day_spec::ToolbarOp;
654    // For each item of `next`, the position of its unchanged counterpart in `prev`.
655    let matched: Vec<Option<usize>> = next
656        .iter()
657        .map(|n| {
658            prev.iter()
659                .position(|p| p.id == n.id)
660                .filter(|&at| shape_of(&prev[at]) == shape_of(n))
661        })
662        .collect();
663    let kept = longest_increasing(&matched);
664
665    let mut ops: Vec<ToolbarOp> = prev
666        .iter()
667        .enumerate()
668        .filter(|(at, _)| !kept.iter().any(|&k| matched[k] == Some(*at)))
669        .map(|(_, p)| ToolbarOp::Remove { id: p.id.clone() })
670        .collect();
671    let mut patches = Vec::new();
672    for (index, item) in next.iter().enumerate() {
673        if kept.contains(&index) {
674            let before = &prev[matched[index].unwrap_or_default()];
675            patches.extend(value_patches(before, item));
676        } else {
677            ops.push(ToolbarOp::Insert {
678                index,
679                item: item.clone(),
680            });
681        }
682    }
683    (ops, patches)
684}
685
686/// The indices into `seq` of a longest strictly increasing subsequence of its `Some` values.
687fn longest_increasing(seq: &[Option<usize>]) -> Vec<usize> {
688    // Patience sorting: `tails[k]` is the index of the smallest tail of an increasing run of
689    // length k + 1, and `back` links each element to its predecessor in the run.
690    let mut tails: Vec<usize> = Vec::new();
691    let mut back: Vec<Option<usize>> = vec![None; seq.len()];
692    for (i, v) in seq.iter().enumerate() {
693        let Some(v) = *v else { continue };
694        let k = tails.partition_point(|&t| seq[t].unwrap_or_default() < v);
695        back[i] = k.checked_sub(1).map(|p| tails[p]);
696        if k == tails.len() {
697            tails.push(i);
698        } else {
699            tails[k] = i;
700        }
701    }
702    let mut out = Vec::new();
703    let mut at = tails.last().copied();
704    while let Some(i) = at {
705        out.push(i);
706        at = back[i];
707    }
708    out.reverse();
709    out
710}
711
712/// The patches that bring a kept item's values from `was` to `now`.
713fn value_patches(was: &ToolbarItem, now: &ToolbarItem) -> Vec<ToolbarPatch> {
714    use day_spec::ToolbarItemKind as K;
715    let item = now.id.clone();
716    let mut out = Vec::new();
717    match (&was.kind, &now.kind) {
718        (
719            K::Search {
720                text: t0,
721                suggestions: s0,
722                placeholder: p0,
723            },
724            K::Search {
725                text: t1,
726                suggestions: s1,
727                placeholder: p1,
728            },
729        ) => {
730            if t0 != t1 {
731                out.push(ToolbarPatch::Text {
732                    item: item.clone(),
733                    text: t1.clone(),
734                });
735            }
736            if s0 != s1 {
737                out.push(ToolbarPatch::Suggestions {
738                    item: item.clone(),
739                    list: s1.clone(),
740                });
741            }
742            if p0 != p1 {
743                out.push(ToolbarPatch::Placeholder {
744                    item: item.clone(),
745                    text: p1.clone(),
746                });
747            }
748        }
749        (K::Toggle { on: a }, K::Toggle { on: b }) if a != b => out.push(ToolbarPatch::On {
750            item: item.clone(),
751            on: *b,
752        }),
753        (K::Segmented { selected: a, .. }, K::Segmented { selected: b, .. }) if a != b => {
754            out.push(ToolbarPatch::Selected {
755                item: item.clone(),
756                index: *b,
757            });
758        }
759        _ => {}
760    }
761    if was.label != now.label || was.tooltip != now.tooltip {
762        out.push(ToolbarPatch::Label {
763            item: item.clone(),
764            label: now.label.clone(),
765            tooltip: now.tooltip.clone(),
766        });
767    }
768    if was.enabled != now.enabled {
769        out.push(ToolbarPatch::Enabled {
770            item,
771            on: now.enabled,
772        });
773    }
774    out
775}
776
777/// Swap each item's closure id for the window's stable slot id for that item, and point the
778/// slot at the closure.
779///
780/// An item's identity is its id, so the same command on the next page, or the same page built
781/// again, gets the slot it had. The toolkit keeps dispatching the id it was given, and the id keeps reaching the
782/// current closure: no install to repoint it, and nothing for a toolkit to diff. A pull-down's
783/// entries get slots the same way, by their path under the item.
784fn slot_model(root: RNode, mut items: Vec<ToolbarItem>) -> Vec<ToolbarItem> {
785    let mut live: Vec<u64> = Vec::new();
786    for item in &mut items {
787        let key = item.id.clone();
788        item.action = slot_for(root, &key, item.action, &mut live);
789        if let day_spec::ToolbarItemKind::Menu { items: entries } = &mut item.kind {
790            slot_menu(root, &key, entries, &mut live);
791        }
792    }
793    // Slots this window no longer shows dispatch nothing; the ids stay reserved for the item's
794    // return.
795    let keep: std::collections::HashSet<u64> = live.into_iter().collect();
796    SLOT_IDS.with(|ids| {
797        SLOT_TARGETS.with(|t| {
798            let mut t = t.borrow_mut();
799            for ((r, _), slot) in ids.borrow().iter() {
800                if *r == root && !keep.contains(slot) {
801                    t.remove(slot);
802                }
803            }
804        });
805    });
806    items
807}
808
809fn slot_menu(root: RNode, parent: &str, entries: &mut [day_spec::MenuItem], live: &mut Vec<u64>) {
810    for (i, entry) in entries.iter_mut().enumerate() {
811        let key = format!("{parent}/{i}");
812        match entry {
813            day_spec::MenuItem::Action { action, .. } => {
814                *action = slot_for(root, &key, *action, live);
815            }
816            day_spec::MenuItem::Submenu { items, .. } => slot_menu(root, &key, items, live),
817            day_spec::MenuItem::Separator => {}
818        }
819    }
820}
821
822/// The slot for `key` in `root`'s bar, now dispatching to `target`. `0` stays `0`: an item with
823/// nothing to run has nothing to address.
824fn slot_for(root: RNode, key: &str, target: u64, live: &mut Vec<u64>) -> u64 {
825    if target == 0 {
826        return 0;
827    }
828    let slot = SLOT_IDS.with(|ids| {
829        *ids.borrow_mut()
830            .entry((root, key.to_string()))
831            .or_insert_with(crate::menu::next_action_id)
832    });
833    SLOT_TARGETS.with(|t| t.borrow_mut().insert(slot, target));
834    live.push(slot);
835    slot
836}
837
838/// The pieces layer, after a change to what is on screen (a push, a pop, a tab switch), so a
839/// one-bar-per-window toolkit is handed the showing pages' items. No-op where every page has a
840/// bar of its own.
841pub fn chrome_changed() {
842    schedule_recompose();
843}
844
845/// Apply a targeted item update wherever the item lives: the path a bound signal writes through,
846/// so a search field keeps its focus and its insertion point.
847pub fn patch_toolbar(patch: ToolbarPatch) {
848    let owner = MODELS.with(|m| {
849        m.borrow()
850            .iter()
851            .find(|(_, items)| items.iter().any(|i| i.id == patch.item()))
852            .map(|(c, _)| *c)
853    });
854    if let Some(chrome) = owner {
855        patch_chrome(chrome, patch);
856    }
857}
858
859/// [`patch_toolbar`] against an explicit chrome. Also updates the retained model, so a later
860/// full replace does not resurrect the stale value.
861#[expect(
862    clippy::needless_pass_by_value,
863    reason = "public signature; callers build the patch at the call site"
864)]
865pub fn patch_chrome(chrome: Chrome, patch: ToolbarPatch) {
866    // The contribution that owns the item keeps its own copy, so a later re-compose rebuilds
867    // from the current value rather than the one the item was declared with.
868    let window = CONTRIBUTIONS.with(|m| {
869        let mut m = m.borrow_mut();
870        let mut window = None;
871        for c in m.values_mut() {
872            if c.chrome == chrome {
873                apply_to_model(&mut c.items, &patch);
874                window = Some(c.window());
875            }
876        }
877        window
878    });
879    // …and so does the window's model, which is the one the toolkit draws and dayscript reads.
880    //
881    // A page's chrome has no model of its own: everything is composed into the window's before
882    // it crosses (see `lower`). Patching a per-chrome copy left the drawn bar carrying the value
883    // the item was built with, which is how a page command declared while nothing was selected
884    // stayed disabled on a window that never re-composed afterwards, and did nothing when tapped.
885    let Some(root) = window else { return };
886    MODELS.with(|m| {
887        let mut m = m.borrow_mut();
888        if let Some((_, items)) = m.iter_mut().find(|(c, _)| *c == Chrome::Window(root)) {
889            apply_to_model(items, &patch);
890        }
891    });
892    if with_tree(|t| t.patch_window_toolbar(root, patch.clone())) {
893        deliver_value(root, &patch);
894    }
895}
896
897/// Mirror a patch into the retained model.
898fn apply_to_model(items: &mut [ToolbarItem], patch: &ToolbarPatch) {
899    patch.apply_to(items);
900}
901
902/// An item as the toolkit draws it: everything but its values, which travel as patches, and its
903/// action, whose slot id never changes while the item is on the bar.
904fn shape_of(item: &ToolbarItem) -> ToolbarItem {
905    use day_spec::ToolbarItemKind as K;
906    let mut i = item.clone();
907    i.enabled = true;
908    // Words are values too: a language change patches them on the live item.
909    i.label.clear();
910    i.tooltip = None;
911    match &mut i.kind {
912        K::Search {
913            text,
914            suggestions,
915            placeholder,
916        } => {
917            text.clear();
918            suggestions.clear();
919            placeholder.clear();
920        }
921        K::Toggle { on } => *on = false,
922        K::Segmented { selected, .. } => *selected = 0,
923        _ => {}
924    }
925    i
926}
927
928/// Every live item, across every chrome. dayscript's `toolbar:` step walks it to resolve an
929/// item's dispatch id, and an app has one bar per window at a time, so a duplicate id across two
930/// chromes would be an app bug rather than an ambiguity to resolve here.
931#[must_use]
932pub fn toolbar_model() -> Vec<ToolbarItem> {
933    MODELS.with(|m| m.borrow().iter().flat_map(|(_, i)| i.clone()).collect())
934}
935
936/// Show/hide the sidebar pane of the navigation host `host`: the behavior behind the sidebar
937/// affordance a nav host contributes for itself (`day_spec::SIDEBAR_TOGGLE_ID`). `false` when
938/// the toolkit has no pane to toggle there. The item's action makes this call, and dayscript's
939/// `toolbar:` step presses the item like any other, so a walkthrough drives the same path a
940/// click does (docs/toolbars.md).
941pub fn toggle_sidebar(host: RNode) -> bool {
942    with_tree(|t| t.toggle_sidebar(host))
943}
944
945/// Drop a closed window's contributions, chrome model and the value closures only they owned.
946///
947/// Called before the window's scope is disposed. Disposal runs every contribution's cleanup,
948/// and each one re-composes the window it belonged to, a merge that asks the other
949/// contributions' gates whether their page is showing, through signals the same disposal has
950/// already dropped. Withdrawing the whole window here first leaves those cleanups nothing to
951/// re-compose (a token that is already gone is a no-op), so a closed window never merges its
952/// own dying bar.
953pub(crate) fn forget_window(root: RNode) {
954    let gone: Vec<ToolbarItem> = CONTRIBUTIONS.with(|m| {
955        let mut m = m.borrow_mut();
956        let mut gone = Vec::new();
957        m.retain(|_, c| {
958            let mine = c.window() == root;
959            if mine {
960                gone.extend(c.items.clone());
961            }
962            !mine
963        });
964        gone
965    });
966    forget_closures(&gone);
967    MODELS.with(|m| {
968        m.borrow_mut()
969            .retain(|(c, _)| !matches!(c, Chrome::Window(r) if *r == root));
970    });
971    DELIVERED.with(|d| {
972        d.borrow_mut().remove(&root);
973    });
974    SLOT_IDS.with(|ids| {
975        SLOT_TARGETS.with(|t| {
976            let mut t = t.borrow_mut();
977            ids.borrow_mut().retain(|(r, _), slot| {
978                if *r == root {
979                    t.remove(slot);
980                }
981                *r != root
982            });
983        });
984    });
985}
986
987/// Reset every chrome's toolbar state (tests; pairs with `uninstall_tree`).
988pub fn reset_toolbars() {
989    MODELS.with(|m| m.borrow_mut().clear());
990    CONTRIBUTIONS.with(|m| m.borrow_mut().clear());
991    VALUE_ACTIONS.with(|m| m.borrow_mut().clear());
992    SLOT_IDS.with(|m| m.borrow_mut().clear());
993    SLOT_TARGETS.with(|m| m.borrow_mut().clear());
994    DELIVERED.with(|m| m.borrow_mut().clear());
995    RECOMPOSE_PENDING.with(|p| p.set(false));
996    PAGE_STACK.with(|s| s.borrow_mut().clear());
997    BUILDING.with(|b| b.set(None));
998}
999
1000/// Focus the active window's search control, revealing a collapsed desktop search item.
1001/// Returns false when the active window has no toolbar search contribution.
1002#[must_use]
1003pub fn focus_toolbar_search() -> bool {
1004    let root = crate::windows::focused_root();
1005    let has = MODELS.with(|models| {
1006        models.borrow().iter().any(|(chrome, items)| {
1007            *chrome == Chrome::Window(root)
1008                && items.iter().any(|item| item.id == day_spec::SEARCH_ITEM_ID)
1009        })
1010    });
1011    if has {
1012        with_tree(|t| {
1013            t.patch_window_toolbar(
1014                root,
1015                ToolbarPatch::Focus {
1016                    item: day_spec::SEARCH_ITEM_ID.to_owned(),
1017                },
1018            )
1019        });
1020    }
1021    has
1022}
1023
1024#[cfg(test)]
1025mod tests {
1026
1027    #[test]
1028    fn native_events_recompose_after_the_delivered_baseline_is_recorded() {
1029        let passes = std::cell::Cell::new(0);
1030        let delivered = std::cell::Cell::new(false);
1031        super::recompose_serially(|| {
1032            passes.set(passes.get() + 1);
1033            if passes.get() == 1 {
1034                // Simulate a native edit draining an event before the caller records delivery.
1035                super::recompose_serially(|| panic!("must not diff the stale baseline"));
1036                super::recompose_serially(|| panic!("nested requests must coalesce"));
1037                delivered.set(true);
1038            } else {
1039                assert!(delivered.get());
1040            }
1041        });
1042        assert_eq!(passes.get(), 2);
1043        super::recompose_serially(|| passes.set(passes.get() + 1));
1044        assert_eq!(passes.get(), 3, "the guard releases after a settled update");
1045    }
1046    use super::*;
1047    use day_spec::{ToolbarItemKind as K, ToolbarMirror, ToolbarOp};
1048
1049    fn item(id: &str, label: &str) -> ToolbarItem {
1050        ToolbarItem {
1051            id: id.into(),
1052            kind: K::Button,
1053            label: label.into(),
1054            tooltip: None,
1055            icon: None,
1056            enabled: true,
1057            action: 0,
1058            placement: day_spec::ToolbarPlacement::Automatic,
1059            label_style: day_spec::LabelStyle::Automatic,
1060            prominent: false,
1061            column: day_spec::ToolbarColumn::Window,
1062        }
1063    }
1064
1065    /// Apply the diff the way a backend does and compare with the target.
1066    fn check(prev: &[ToolbarItem], next: &[ToolbarItem]) -> Vec<ToolbarOp> {
1067        let (ops, patches) = diff_bar(prev, next);
1068        let mut mirror = ToolbarMirror::default();
1069        for (i, p) in prev.iter().enumerate() {
1070            mirror.insert(i, p.clone());
1071        }
1072        // Removals first, then insertions in ascending position: the contract backends rely on.
1073        let first_insert = ops
1074            .iter()
1075            .position(|o| matches!(o, ToolbarOp::Insert { .. }))
1076            .unwrap_or(ops.len());
1077        assert!(
1078            ops[first_insert..]
1079                .iter()
1080                .all(|o| matches!(o, ToolbarOp::Insert { .. }))
1081        );
1082        for op in &ops {
1083            mirror.apply(op);
1084        }
1085        for p in &patches {
1086            mirror.patch(p);
1087        }
1088        assert_eq!(mirror.items(), next);
1089        ops
1090    }
1091
1092    #[test]
1093    fn identical_bars_need_no_edit() {
1094        let bar = vec![item("a", "A"), item("b", "B")];
1095        assert_eq!(check(&bar, &bar), [] as [day_spec::ToolbarOp; 0]);
1096    }
1097
1098    #[test]
1099    fn inserts_and_removes_touch_only_their_items() {
1100        let prev = vec![item("a", "A"), item("b", "B"), item("search", "S")];
1101        let next = vec![item("a", "A"), item("c", "C"), item("search", "S")];
1102        let ops = check(&prev, &next);
1103        assert_eq!(ops.len(), 2);
1104        assert!(ops.iter().all(|o| match o {
1105            ToolbarOp::Remove { id } => id == "b",
1106            ToolbarOp::Insert { item, index } => item.id == "c" && *index == 1,
1107        }));
1108    }
1109
1110    #[test]
1111    fn a_reorder_moves_the_fewest_items() {
1112        let prev = vec![
1113            item("a", "A"),
1114            item("b", "B"),
1115            item("c", "C"),
1116            item("d", "D"),
1117        ];
1118        let next = vec![
1119            item("d", "D"),
1120            item("a", "A"),
1121            item("b", "B"),
1122            item("c", "C"),
1123        ];
1124        let ops = check(&prev, &next);
1125        // `d` moves; `a`, `b` and `c` stay put.
1126        assert_eq!(ops.len(), 2, "{ops:?}");
1127    }
1128
1129    #[test]
1130    fn a_value_change_is_a_patch_and_a_label_change_an_edit() {
1131        let mut toggled = item("t", "T");
1132        toggled.kind = K::Toggle { on: false };
1133        let mut on = toggled.clone();
1134        on.kind = K::Toggle { on: true };
1135        on.enabled = false;
1136        let (ops, patches) = diff_bar(std::slice::from_ref(&toggled), std::slice::from_ref(&on));
1137        assert_eq!(ops, [] as [day_spec::ToolbarOp; 0]);
1138        assert_eq!(patches.len(), 2);
1139        check(&[item("x", "Old")], &[item("x", "New")]);
1140    }
1141
1142    #[test]
1143    fn longest_increasing_skips_unmatched() {
1144        assert_eq!(
1145            longest_increasing(&[Some(2), None, Some(0), Some(1), Some(3)]),
1146            vec![2, 3, 4]
1147        );
1148        assert_eq!(longest_increasing(&[None, None]), [] as [usize; 0]);
1149    }
1150}