Skip to main content

day_pieces/
tabs.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Independently owned document tabs. Selection and order never identify a document;
5//! stable keys do. A close request is separate from removal so apps can ask about edits.
6
7use crate::{Decorate, IntoText, NavStyle, Route, TextSource, item, nav};
8use day_core::with_tree;
9use day_core::{AnyPiece, BuildCx, Dimension, Piece, RNode};
10use day_reactive::{Signal, batch};
11use std::cell::RefCell;
12use std::rc::Rc;
13
14/// Ordered document identities and the selected document. Own this above the tab host.
15/// Payloads (editor buffers, browser profiles, etc.) remain application-owned.
16pub struct TabSet<K: Clone + PartialEq + 'static> {
17    order: Signal<Vec<K>>,
18    selected: Signal<Option<K>>,
19}
20impl<K: Clone + PartialEq + 'static> Copy for TabSet<K> {}
21#[expect(
22    clippy::expl_impl_clone_on_copy,
23    reason = "a derive would require `K: Copy`; the handle is `Copy` for every key type"
24)]
25impl<K: Clone + PartialEq + 'static> Clone for TabSet<K> {
26    fn clone(&self) -> Self {
27        *self
28    }
29}
30impl<K: Clone + PartialEq + 'static> Default for TabSet<K> {
31    fn default() -> Self {
32        Self::new()
33    }
34}
35impl<K: Clone + PartialEq + 'static> TabSet<K> {
36    pub fn new() -> Self {
37        Self {
38            order: Signal::new(Vec::new()),
39            selected: Signal::new(None),
40        }
41    }
42    #[must_use]
43    pub fn keys(self) -> Vec<K> {
44        self.order.get()
45    }
46    #[must_use]
47    pub fn selected(self) -> Option<K> {
48        self.selected.get()
49    }
50    pub fn contains(self, key: &K) -> bool {
51        self.order.get_untracked().contains(key)
52    }
53    /// Add a document once. Background insertion preserves the current selection.
54    pub fn open(self, key: K, foreground: bool) {
55        batch(|| {
56            if !self.contains(&key) {
57                self.order.update(|keys| keys.push(key.clone()));
58            }
59            if foreground || self.selected.get_untracked().is_none() {
60                self.selected.set(Some(key));
61            }
62        });
63    }
64    pub fn select(self, key: &K) -> bool {
65        if !self.contains(key) {
66            return false;
67        }
68        self.selected.set(Some(key.clone()));
69        true
70    }
71    /// Remove after the app accepts a close request. Prefer the following neighbor,
72    /// or the preceding one when closing the last tab. Closing the final tab selects None.
73    pub fn close(self, key: &K) -> bool {
74        let mut keys = self.order.get_untracked();
75        let Some(index) = keys.iter().position(|k| k == key) else {
76            return false;
77        };
78        keys.remove(index);
79        batch(|| {
80            if self.selected.get_untracked().as_ref() == Some(key) {
81                self.selected
82                    .set(keys.get(index).or_else(|| keys.last()).cloned());
83            }
84            self.order.set(keys);
85        });
86        true
87    }
88    /// Move a document to its final index, preserving selected identity.
89    pub fn move_to(self, key: &K, index: usize) -> bool {
90        let mut keys = self.order.get_untracked();
91        let Some(from) = keys.iter().position(|k| k == key) else {
92            return false;
93        };
94        let to = index.min(keys.len() - 1);
95        if from == to {
96            return true;
97        }
98        let key = keys.remove(from);
99        keys.insert(to, key);
100        self.order.set(keys);
101        true
102    }
103    pub fn select_next(self, backwards: bool) {
104        let keys = self.order.get_untracked();
105        if keys.is_empty() {
106            return;
107        }
108        let current = self.selected.get_untracked();
109        let at = keys
110            .iter()
111            .position(|k| Some(k) == current.as_ref())
112            .unwrap_or(0);
113        let next = if backwards {
114            (at + keys.len() - 1) % keys.len()
115        } else {
116            (at + 1) % keys.len()
117        };
118        self.selected.set(Some(keys[next].clone()));
119    }
120}
121
122type TabTitle<K> = Rc<dyn Fn(&K) -> String>;
123type TabContent<K> = Rc<dyn Fn(&K) -> AnyPiece>;
124/// A resident, closable document surface. Content is built once per key and disposed
125/// on removal. A selected document owns its native focus and command context.
126#[must_use]
127pub struct DocumentTabs<K: Route> {
128    tabs: TabSet<K>,
129    title: TabTitle<K>,
130    content: TabContent<K>,
131    new_label: TextSource,
132    close_label: TextSource,
133    on_new: Option<Rc<dyn Fn()>>,
134    on_close: Option<Rc<dyn Fn(K)>>,
135    native: Rc<dyn Fn() -> bool>,
136    hide_when_empty: bool,
137    chrome: Option<Rc<dyn Fn(TabActions<K>) -> AnyPiece>>,
138    layout: Option<Box<dyn FnOnce(AnyPiece, AnyPiece) -> AnyPiece>>,
139    strip_id: Option<day_core::ElementId>,
140}
141/// Labels are required rather than supplying untranslated English chrome.
142pub fn document_tabs<K: Route, P: Piece, N, C>(
143    tabs: TabSet<K>,
144    new_label: impl IntoText<N>,
145    close_label: impl IntoText<C>,
146    title: impl Fn(&K) -> String + 'static,
147    content: impl Fn(&K) -> P + 'static,
148) -> DocumentTabs<K> {
149    DocumentTabs {
150        tabs,
151        title: Rc::new(title),
152        content: Rc::new(move |k| AnyPiece::new(content(k))),
153        new_label: new_label.into_text(),
154        close_label: close_label.into_text(),
155        on_new: None,
156        on_close: None,
157        native: Rc::new(|| true),
158        hide_when_empty: false,
159        chrome: None,
160        layout: None,
161        strip_id: None,
162    }
163}
164impl<K: Route> DocumentTabs<K> {
165    /// Name the default strip's elements for scripts and tests: `{prefix}-strip` on the row of
166    /// tabs, `{prefix}-tab-{key}` and `{prefix}-close-{key}` per document, `{prefix}-new` on
167    /// the add button. Without it the prefix is `day-documents-{n}`, unique per host.
168    pub fn strip_id(mut self, id: day_core::ElementId) -> Self {
169        self.strip_id = Some(id);
170        self
171    }
172    /// Reactive preference. Switching chrome preserves every resident page and native view.
173    pub fn native(mut self, native: impl Fn() -> bool + 'static) -> Self {
174        self.native = Rc::new(native);
175        self
176    }
177    /// Keep the owning window hidden when no documents remain. The host and its scope
178    /// stay alive, so a later open can present documents again. Intended for a dedicated
179    /// document window; the default keeps the empty host visible.
180    pub fn hide_when_empty(mut self, hide: bool) -> Self {
181        self.hide_when_empty = hide;
182        self
183    }
184    /// Fully app-owned emulated chrome. Use the supplied actions for shared close/reorder semantics.
185    pub fn chrome<P: Piece>(mut self, build: impl Fn(TabActions<K>) -> P + 'static) -> Self {
186        self.chrome = Some(Rc::new(move |actions| AnyPiece::new(build(actions))));
187        self
188    }
189    /// Place chrome anywhere around the resident content (top, bottom, side, or overlay).
190    /// The chrome is empty while native presentation is active; content is never rebuilt.
191    pub fn layout<P: Piece>(
192        mut self,
193        build: impl FnOnce(AnyPiece, AnyPiece) -> P + 'static,
194    ) -> Self {
195        self.layout = Some(Box::new(move |bar, content| {
196            AnyPiece::new(build(bar, content))
197        }));
198        self
199    }
200
201    pub fn on_new(mut self, f: impl Fn() + 'static) -> Self {
202        self.on_new = Some(Rc::new(f));
203        self
204    }
205    /// Installing a handler makes it responsible for calling `TabSet::close` when accepted.
206    pub fn on_close(mut self, f: impl Fn(K) + 'static) -> Self {
207        self.on_close = Some(Rc::new(f));
208        self
209    }
210}
211impl<K: Route> Piece for DocumentTabs<K> {
212    fn build(self, cx: &mut BuildCx) -> RNode {
213        static NEXT_HOST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
214        let host_id = NEXT_HOST.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
215        let strip_prefix = Rc::new(
216            self.strip_id
217                .unwrap_or_else(|| day_core::id!(document_strip, host_id)),
218        );
219        let tabs = self.tabs;
220        let preference = self.native;
221        let window_tabs = day_core::windows::native_window_tabs();
222        let toolkit_tabs = with_tree(|t| t.native_document_tabs());
223        let native: Rc<dyn Fn() -> bool> =
224            Rc::new(move || preference() && (window_tabs || toolkit_tabs));
225        let custom_chrome = self.chrome;
226        let layout = self.layout;
227        let mounted = Rc::new(RefCell::new(Vec::<MountedTab<K>>::new()));
228        let revision = Signal::new(0u64);
229        let controller_title = self.title.clone();
230        let controller_close = self.on_close.clone();
231        let controller_new = self.on_new.clone();
232        let native_windows = native.clone();
233        let title = self.title;
234        let content = self.content;
235        let on_new = self.on_new;
236        let chrome_new = on_new.clone();
237        let chrome_add = on_new.clone();
238        let on_close = self.on_close;
239        let chrome_close = on_close.clone();
240        let chrome_title = title.clone();
241        let config = day_spec::props::DocumentTabsConfig {
242            new_label: self.new_label.initial(),
243            close_label: self.close_label.initial(),
244            can_add: on_new.is_some(),
245        };
246        let actions = TabActions {
247            tabs,
248            host_id,
249            on_new: on_new.clone(),
250            on_close: on_close.clone(),
251        };
252        let pages = mounted.clone();
253        let page_native = native.clone();
254        let new_label = config.new_label.clone();
255        let close_label = config.close_label.clone();
256        let host = nav(tabs.selected)
257            .style(NavStyle::Tabs)
258            .local()
259            .items(crate::nav_items(
260                move || tabs.keys(),
261                move |key| item(Some(key.clone()), title(key)),
262            ))
263            .destination(move |key: &Option<K>| match key {
264                Some(k) => AnyPiece::new(MountTab {
265                    key: k.clone(),
266                    tabs,
267                    native: if window_tabs {
268                        page_native.clone()
269                    } else {
270                        Rc::new(|| false)
271                    },
272                    content: content(k),
273                    pages: pages.clone(),
274                    revision,
275                }),
276                None => AnyPiece::new(crate::spacer()),
277            })
278            .document_mode(config, move |event| {
279                if let day_spec::Event::Custom { tag, num, text } = event {
280                    match *tag {
281                        "day:tab-new" => {
282                            if let Some(f) = &on_new {
283                                f();
284                            }
285                        }
286                        "day:tab-close" => {
287                            if let Some(key) = K::from_key(text).filter(|k| tabs.contains(k)) {
288                                if let Some(f) = &on_close {
289                                    f(key);
290                                } else {
291                                    tabs.close(&key);
292                                }
293                            }
294                        }
295                        "day:tab-move" => {
296                            if let Some(key) = K::from_key(text).filter(|k| tabs.contains(k))
297                                && num.is_finite()
298                                && *num >= 0.0
299                            {
300                                tabs.move_to(&key, *num as usize);
301                            }
302                        }
303                        _ => {}
304                    }
305                }
306            });
307        let host = AnyPiece::new(TabChromeHost {
308            content: AnyPiece::new(host),
309            native: native.clone(),
310            window_tabs,
311        });
312        // The toolkit still owns the resident-page container. Where no closable document
313        // strip exists, compose one from native buttons, scrolling, and drag sessions. The
314        // current document's button is a selected button, not a disabled one: it keeps its
315        // focus stop, re-activating it is harmless, and assistive tech hears "selected".
316        let default_chrome = move || {
317            let chrome_title = chrome_title.clone();
318            let chrome_close = chrome_close.clone();
319            let chrome_new = chrome_new.clone();
320            let chrome_add = chrome_add.clone();
321            let new_label = new_label.clone();
322            let close_label = close_label.clone();
323            let prefix = strip_prefix.clone();
324            let tab_prefix = prefix.clone();
325            let strip = crate::scroll(
326                crate::row((crate::each(
327                    crate::items(move || tabs.keys(), |key: &K| key.key()),
328                    move |slot| {
329                        let title = chrome_title.clone();
330                        let key = slot.get();
331                        let select_key = key.clone();
332                        let selected_key = key.clone();
333                        let announced_key = key.clone();
334                        let close_key = key.clone();
335                        let drag_key = key.clone();
336                        let drop_key = key.clone();
337                        let close = chrome_close.clone();
338                        let close_menu = close.clone();
339                        let menu_key = key.clone();
340                        crate::row((
341                            crate::button(move || title(&slot.get()))
342                                .selected(move || tabs.selected().as_ref() == Some(&selected_key))
343                                .action(move || {
344                                    tabs.select(&select_key);
345                                })
346                                .id(day_core::id!(
347                                    document_tab,
348                                    format!("{}:{}", tab_prefix.as_str(), key.key())
349                                ))
350                                .a11y(move |a| {
351                                    a.role(day_spec::Role::Tab).selected(move || {
352                                        tabs.selected().as_ref() == Some(&announced_key)
353                                    })
354                                }),
355                            crate::button(close_label.clone())
356                                .icon(day_spec::Symbol::Close)
357                                .icon_only()
358                                .action(move || {
359                                    if let Some(f) = &close {
360                                        f(close_key.clone());
361                                    } else {
362                                        tabs.close(&close_key);
363                                    }
364                                })
365                                .id(day_core::id!(
366                                    document_close,
367                                    format!("{}:{}", tab_prefix.as_str(), key.key())
368                                )),
369                        ))
370                        .spacing(2.0)
371                        .context_menu(vec![crate::menu_item(close_label.clone()).action(
372                            move || {
373                                if let Some(f) = &close_menu {
374                                    f(menu_key.clone());
375                                } else {
376                                    tabs.close(&menu_key);
377                                }
378                            },
379                        )])
380                        .drag_source(move |_| {
381                            Some(day_spec::transfer::Offer {
382                                items: vec![day_spec::transfer::Item::new(vec![
383                                    day_spec::transfer::Representation::new(
384                                        "application/vnd.day.document-tab",
385                                        format!("{host_id}:{}", drag_key.key()).into_bytes(),
386                                    ),
387                                ])],
388                            })
389                        })
390                        .drop_target(
391                            day_spec::transfer::Target::new(["application/vnd.day.document-tab"])
392                                .accept(|location| {
393                                    if location.local
394                                        && location.has("application/vnd.day.document-tab")
395                                    {
396                                        day_spec::transfer::Operation::Move
397                                    } else {
398                                        day_spec::transfer::Operation::None
399                                    }
400                                })
401                                .on_drop(move |drop| {
402                                    let Some(key) = drop
403                                        .items
404                                        .first()
405                                        .and_then(|item| {
406                                            item.get("application/vnd.day.document-tab")
407                                        })
408                                        .and_then(|bytes| std::str::from_utf8(bytes).ok())
409                                        .and_then(|text| text.strip_prefix(&format!("{host_id}:")))
410                                        .and_then(K::from_key)
411                                    else {
412                                        return false;
413                                    };
414                                    let Some(index) =
415                                        tabs.keys().iter().position(|key| key == &drop_key)
416                                    else {
417                                        return false;
418                                    };
419                                    tabs.move_to(&key, index)
420                                }),
421                        )
422                    },
423                ),))
424                .spacing(4.0)
425                .id((*prefix).clone())
426                .a11y(|a| a.role(day_spec::Role::TabList)),
427            )
428            .horizontal()
429            .height(44.0);
430            let add = crate::when(
431                move || chrome_new.is_some(),
432                move || {
433                    let on_new = chrome_add.clone();
434                    crate::button(new_label.clone())
435                        .action(move || {
436                            if let Some(f) = &on_new {
437                                f();
438                            }
439                        })
440                        .id(day_core::id!(document_new, prefix.as_str()))
441                },
442            );
443            AnyPiece::new(crate::row((strip.grow(Dimension::Both), add)).spacing(4.0))
444        };
445        let bar = AnyPiece::new(crate::when(
446            move || !native(),
447            move || match &custom_chrome {
448                Some(build) => build(actions.clone()),
449                None => default_chrome(),
450            },
451        ));
452        let root = match layout {
453            Some(build) => build(bar, host).build(cx),
454            None => crate::column((bar, host.grow(Dimension::Both))).build(cx),
455        };
456        if window_tabs {
457            install_window_tabs(
458                host_id,
459                tabs,
460                mounted,
461                revision,
462                native_windows,
463                controller_title,
464                controller_new,
465                controller_close,
466                self.hide_when_empty,
467            );
468        }
469        root
470    }
471}
472
473#[cfg(test)]
474mod tests {
475    use super::*;
476    #[test]
477    fn document_order_and_selection_are_independent() {
478        let scope = day_reactive::Scope::detached();
479        scope.enter(|| {
480            let tabs = TabSet::new();
481            tabs.open(10, true);
482            tabs.open(20, false);
483            tabs.open(30, false);
484            assert_eq!(tabs.selected(), Some(10));
485            tabs.move_to(&10, 2);
486            assert_eq!(tabs.keys(), vec![20, 30, 10]);
487            assert_eq!(tabs.selected(), Some(10));
488            tabs.close(&10);
489            assert_eq!(tabs.selected(), Some(30));
490            tabs.select_next(false);
491            assert_eq!(tabs.selected(), Some(20));
492            tabs.close(&30);
493            assert_eq!(tabs.selected(), Some(20));
494            tabs.close(&20);
495            assert_eq!(tabs.selected(), None);
496            assert!(!tabs.select(&40));
497            assert!(!tabs.move_to(&40, 0));
498        });
499        scope.dispose();
500    }
501}
502
503/// Commands shared by native and application-drawn tab chrome.
504#[derive(Clone)]
505pub struct TabActions<K: Route> {
506    pub tabs: TabSet<K>,
507    host_id: u64,
508    on_new: Option<Rc<dyn Fn()>>,
509    on_close: Option<Rc<dyn Fn(K)>>,
510}
511impl<K: Route> TabActions<K> {
512    pub fn new_tab(&self) {
513        if let Some(f) = &self.on_new {
514            f();
515        }
516    }
517    pub fn close(&self, key: K) {
518        if let Some(f) = &self.on_close {
519            f(key);
520        } else {
521            self.tabs.close(&key);
522        }
523    }
524    /// Local drag data, scoped to this collection so unrelated tab hosts cannot collide.
525    pub fn drag(&self, key: &K) -> day_spec::transfer::Offer {
526        day_spec::transfer::Offer {
527            items: vec![day_spec::transfer::Item::new(vec![
528                day_spec::transfer::Representation::new(
529                    "application/vnd.day.document-tab",
530                    format!("{}:{}", self.host_id, key.key()).into_bytes(),
531                ),
532            ])],
533        }
534    }
535    /// A drop target that moves a tab before this key, preserving document identity.
536    pub fn drop_before(&self, key: K) -> day_spec::transfer::Target {
537        let actions = self.clone();
538        day_spec::transfer::Target::new(["application/vnd.day.document-tab"])
539            .accept(|location| {
540                if location.local && location.has("application/vnd.day.document-tab") {
541                    day_spec::transfer::Operation::Move
542                } else {
543                    day_spec::transfer::Operation::None
544                }
545            })
546            .on_drop(move |drop| {
547                let Some(moving) = drop
548                    .items
549                    .first()
550                    .and_then(|item| item.get("application/vnd.day.document-tab"))
551                    .and_then(|bytes| std::str::from_utf8(bytes).ok())
552                    .and_then(|text| text.strip_prefix(&format!("{}:", actions.host_id)))
553                    .and_then(K::from_key)
554                else {
555                    return false;
556                };
557                let Some(index) = actions.tabs.keys().iter().position(|k| k == &key) else {
558                    return false;
559                };
560                let from = actions.tabs.keys().iter().position(|k| k == &moving);
561                actions.tabs.move_to(
562                    &moving,
563                    index.saturating_sub(usize::from(from.is_some_and(|from| from < index))),
564                )
565            })
566    }
567}
568
569struct TabChromeHost {
570    content: AnyPiece,
571    native: Rc<dyn Fn() -> bool>,
572    window_tabs: bool,
573}
574impl Piece for TabChromeHost {
575    fn build(self, cx: &mut BuildCx) -> RNode {
576        let host = self.content.build(cx);
577        day_reactive::bind(
578            move || (self.native)() && !self.window_tabs,
579            move |native| {
580                with_tree(|t| {
581                    t.patch(
582                        host,
583                        Box::new(day_spec::props::DocumentTabsPatch { native: *native }),
584                        true,
585                    );
586                });
587            },
588        );
589        host
590    }
591}
592struct MountedTab<K> {
593    scope: day_reactive::Scope,
594    key: K,
595    node: RNode,
596    home: RNode,
597    home_window: RNode,
598    chrome_window: day_core::toolbar::DocumentWindow,
599    window: Option<day_core::windows::WindowHandle>,
600}
601struct MountTab<K: Route> {
602    key: K,
603    tabs: TabSet<K>,
604    native: Rc<dyn Fn() -> bool>,
605    content: AnyPiece,
606    pages: Rc<RefCell<Vec<MountedTab<K>>>>,
607    revision: Signal<u64>,
608}
609impl<K: Route> Piece for MountTab<K> {
610    fn build(self, cx: &mut BuildCx) -> RNode {
611        let home = cx.parent();
612        let home_window = day_core::current_page_window();
613        let chrome_window = day_core::toolbar::DocumentWindow::new(home_window);
614        day_reactive::Scope::current().provide(chrome_window.clone());
615        let key = self.key.clone();
616        let gate: Rc<dyn Fn() -> bool> =
617            Rc::new(move || (self.native)() || self.tabs.selected().as_ref() == Some(&key));
618        let node = crate::nav::with_document_active(gate.clone(), || {
619            day_core::with_page_in(
620                home,
621                Some(gate),
622                day_spec::ToolbarColumn::Detail,
623                home_window,
624                || self.content.build(cx),
625            )
626        });
627        self.pages.borrow_mut().push(MountedTab {
628            scope: day_reactive::Scope::current(),
629            key: self.key.clone(),
630            node,
631            home,
632            home_window,
633            chrome_window,
634            window: None,
635        });
636        self.revision.update(|n| *n += 1);
637        day_reactive::Scope::current().on_cleanup(move || {
638            let page = {
639                let mut pages = self.pages.borrow_mut();
640                pages
641                    .iter()
642                    .position(|p| p.key == self.key)
643                    .map(|i| pages.remove(i))
644            };
645            if let Some(page) = page {
646                with_tree(|t| {
647                    t.reparent(page.node, page.home);
648                });
649                if let Some(window) = page.window {
650                    window.close();
651                }
652            }
653        });
654        node
655    }
656}
657struct MoveTab(RNode);
658impl Piece for MoveTab {
659    fn build(self, cx: &mut BuildCx) -> RNode {
660        if with_tree(|t| t.reparent(self.0, cx.parent())) {
661            self.0
662        } else {
663            // A queued open may outlive its document. Leave an empty host to close safely.
664            crate::spacer().build(cx)
665        }
666    }
667}
668#[allow(clippy::too_many_arguments)]
669fn install_window_tabs<K: Route>(
670    host: u64,
671    tabs: TabSet<K>,
672    pages: Rc<RefCell<Vec<MountedTab<K>>>>,
673    revision: Signal<u64>,
674    native: Rc<dyn Fn() -> bool>,
675    title: TabTitle<K>,
676    on_new: Option<Rc<dyn Fn()>>,
677    on_close: Option<Rc<dyn Fn(K)>>,
678    hide_when_empty: bool,
679) {
680    let group = format!("day.documents.{host}");
681    if let Some(f) = on_new {
682        day_core::windows::register_tab_new(group.clone(), f);
683    }
684    let initial = day_core::windows::current_window();
685    let previous = Rc::new(RefCell::new(Vec::<K>::new()));
686    // The window callbacks below outlive the host: closing a document's window on disposal
687    // reports back after the host's scope, and its signals, are gone. Once the scope is
688    // cleaned up every callback is a no-op.
689    let alive = Rc::new(std::cell::Cell::new(true));
690    {
691        let alive = alive.clone();
692        day_reactive::Scope::current().on_cleanup(move || alive.set(false));
693    }
694    let mode = native.clone();
695    let focus_native = native.clone();
696    let observed_alive = alive.clone();
697    let observed_pages = pages.clone();
698    let observed_previous = previous.clone();
699    let observe: Rc<dyn Fn()> = Rc::new(move || {
700        if !observed_alive.get() || !mode() {
701            return;
702        }
703        let windows = observed_pages
704            .borrow()
705            .iter()
706            .filter_map(|p| p.window.clone().map(|w| (p.key.clone(), w)))
707            .collect::<Vec<_>>();
708        let mut order = tabs.keys();
709        for (_, window) in &windows {
710            let group = window.tab_order();
711            let keys = group
712                .iter()
713                .filter_map(|id| {
714                    windows
715                        .iter()
716                        .find(|(_, w)| day_core::windows::window_node_id(w) == *id)
717                        .map(|(k, _)| k.clone())
718                })
719                .collect::<Vec<_>>();
720            let positions = order
721                .iter()
722                .enumerate()
723                .filter_map(|(i, k)| keys.contains(k).then_some(i))
724                .collect::<Vec<_>>();
725            for (i, key) in positions.into_iter().zip(keys) {
726                order[i] = key;
727            }
728        }
729        if order != tabs.keys() {
730            (*observed_previous.borrow_mut()).clone_from(&order);
731            batch(|| {
732                for (i, key) in order.iter().enumerate() {
733                    tabs.move_to(key, i);
734                }
735            });
736        }
737    });
738
739    let last_selected = Rc::new(RefCell::new(None::<K>));
740    day_reactive::bind(
741        move || {
742            (
743                revision.get(),
744                native(),
745                tabs.keys()
746                    .into_iter()
747                    .map(|key| {
748                        let text = title(&key);
749                        (key, text)
750                    })
751                    .collect::<Vec<_>>(),
752                tabs.selected(),
753            )
754        },
755        move |(_, native, entries, selected)| {
756            if !native {
757                let windows = {
758                    let mut pages = pages.borrow_mut();
759                    pages
760                        .iter_mut()
761                        .filter_map(|page| {
762                            let window = page.window.take()?;
763                            page.chrome_window.set(page.home_window);
764                            with_tree(|t| {
765                                t.reparent(page.node, page.home);
766                            });
767                            Some(window)
768                        })
769                        .collect::<Vec<_>>()
770                };
771                for window in windows {
772                    window.close();
773                }
774                previous.borrow_mut().clear();
775                *last_selected.borrow_mut() = None;
776                if let Some(initial) = &initial {
777                    initial.set_visible(!hide_when_empty || !entries.is_empty());
778                }
779                return;
780            }
781            let existing = pages
782                .borrow()
783                .iter()
784                .filter_map(|p| p.window.clone().map(|w| (p.key.clone(), w)))
785                .collect::<Vec<_>>();
786            let known = existing
787                .iter()
788                .map(|(_, w)| day_core::windows::window_node_id(w))
789                .collect::<Vec<_>>();
790            let target = existing
791                .iter()
792                .find(|(key, _)| Some(key) == selected.as_ref())
793                .or_else(|| {
794                    existing
795                        .iter()
796                        .find(|(key, _)| Some(key) == last_selected.borrow().as_ref())
797                })
798                .or_else(|| existing.first());
799            let mut target_group = target.map_or_default(|(_, w)| w.tab_order());
800            if target_group.is_empty()
801                && let Some((_, w)) = target
802            {
803                target_group.push(day_core::windows::window_node_id(w));
804            }
805            let mut added = false;
806            for (key, title) in entries {
807                let node = pages
808                    .borrow()
809                    .iter()
810                    .find(|p| &p.key == key && p.window.is_none())
811                    .map(|p| p.node);
812                if let Some(node) = node {
813                    let size = initial
814                        .as_ref()
815                        .and_then(day_core::WindowHandle::frame)
816                        .map_or(day_spec::Size::new(1000.0, 740.0), |r| r.size);
817                    let window = day_core::windows::open_window(
818                        day_spec::WindowOptions {
819                            title: title.clone(),
820                            size,
821                            start_hidden: true,
822                            tabbing: day_spec::WindowTabbing::Group(group.clone()),
823                            key: Some(format!("{group}:{}", key.key())),
824                            ..Default::default()
825                        },
826                        move || MoveTab(node),
827                    );
828                    let close_observer = observe.clone();
829                    window.on_close(move || close_observer());
830                    let close_key = key.clone();
831                    let close = on_close.clone();
832                    let close_observer = observe.clone();
833                    let close_alive = alive.clone();
834                    window.on_close_request(move || {
835                        if !close_alive.get() {
836                            return;
837                        }
838                        close_observer();
839                        if let Some(f) = &close {
840                            f(close_key.clone());
841                        } else {
842                            tabs.close(&close_key);
843                        }
844                    });
845                    let focus_key = key.clone();
846                    let native_selection = last_selected.clone();
847                    let focus_observer = observe.clone();
848                    let focus_alive = alive.clone();
849                    let focus_mode = focus_native.clone();
850                    window.on_focus(move || {
851                        // Returning to the composed strip closes the windows one by one, and
852                        // the platform makes the next one key as each goes: that focus is
853                        // not a choice, so it must not move the selection.
854                        if !focus_alive.get() || !focus_mode() {
855                            return;
856                        }
857                        focus_observer();
858                        if tabs.contains(&focus_key) {
859                            // Native activation already selected this window. Echoing it
860                            // back through focus() can oscillate between queued Qt events.
861                            *native_selection.borrow_mut() = Some(focus_key.clone());
862                            tabs.select(&focus_key);
863                        }
864                    });
865                    if let Some(page) = pages.borrow_mut().iter_mut().find(|p| &p.key == key) {
866                        window.set_content_scope(page.scope);
867                        let root =
868                            day_core::id_to_rnode(day_core::windows::window_node_id(&window));
869                        page.chrome_window.set(root);
870                        page.window = Some(window);
871                    }
872                    added = true;
873                }
874            }
875            let windows = entries
876                .iter()
877                .filter_map(|(key, title)| {
878                    let window = pages
879                        .borrow()
880                        .iter()
881                        .find(|p| &p.key == key)?
882                        .window
883                        .clone()?;
884                    window.set_title(title);
885                    Some((key.clone(), window))
886                })
887                .collect::<Vec<_>>();
888            let order = windows
889                .iter()
890                .map(|(key, _)| key.clone())
891                .collect::<Vec<_>>();
892            if added || *previous.borrow() != order {
893                if added {
894                    let group = windows
895                        .iter()
896                        .filter(|(_, w)| {
897                            let id = day_core::windows::window_node_id(w);
898                            !known.contains(&id) || target_group.contains(&id)
899                        })
900                        .map(|(_, w)| w.clone())
901                        .collect::<Vec<_>>();
902                    day_core::windows::group_windows(&group);
903                } else {
904                    let mut seen = Vec::new();
905                    for (_, window) in &windows {
906                        let id = day_core::windows::window_node_id(window);
907                        if seen.contains(&id) {
908                            continue;
909                        }
910                        let group = window.tab_order();
911                        seen.extend(group.iter().copied());
912                        let group = windows
913                            .iter()
914                            .filter(|(_, w)| group.contains(&day_core::windows::window_node_id(w)))
915                            .map(|(_, w)| w.clone())
916                            .collect::<Vec<_>>();
917                        if group.len() > 1 {
918                            day_core::windows::group_windows(&group);
919                        }
920                    }
921                }
922                *previous.borrow_mut() = order;
923            }
924            if let Some(initial) = &initial {
925                initial.set_visible(!hide_when_empty && windows.is_empty());
926            }
927            if added || *last_selected.borrow() != *selected {
928                (*last_selected.borrow_mut()).clone_from(selected);
929                if let Some((_, window)) = windows
930                    .iter()
931                    .find(|(key, _)| Some(key) == selected.as_ref())
932                {
933                    window.focus();
934                }
935            }
936        },
937    );
938}
939
940/// The document tabs' cases (docs/testing.md): the composed strip on every toolkit, the model's
941/// corner cases, and the OS window groups where a toolkit has them.
942#[cfg(feature = "conformance")]
943pub(crate) mod conformance {
944    use super::*;
945    use crate::*;
946    use day_core::conformance::{Case, Drive, FrameExpect, NativeExpect, TestResult};
947    use day_spec::{Cap, kinds};
948
949    /// The documents a case can open, in the order the controls open them.
950    const KEYS: [&str; 3] = ["a", "b", "c"];
951
952    /// How a fixture answers close requests.
953    #[derive(Clone, Copy, PartialEq)]
954    enum Closing {
955        /// No handler: a request removes the key.
956        Direct,
957        /// A handler that vetoes the first request and accepts every later one.
958        VetoFirst,
959    }
960
961    /// One host and the controls that drive its model from the app's side: open, close, move,
962    /// cycle, rename, and the native-presentation preference. Every document is a label, a
963    /// counter and a button that bumps it, so resident content is observable through its
964    /// state. The strip takes the `docs` prefix; `selected` and `order` read the model back.
965    fn fixture(closing: Closing, with_new: bool, native: bool) -> impl Piece {
966        let tabs = TabSet::<String>::new();
967        let pref = Signal::new(native);
968        let renames = Signal::new(0u32);
969        let vetoes = Signal::new(0u32);
970        let closes = Signal::new(Vec::<String>::new());
971        let next = Signal::new(0u32);
972        let mut host = document_tabs(
973            tabs,
974            "New document",
975            "Close document",
976            move |key: &String| {
977                let n = renames.get();
978                if n == 0 {
979                    format!("Doc {key}")
980                } else {
981                    format!("Doc {key} ({n})")
982                }
983            },
984            |key: &String| {
985                let count = Signal::new(0u32);
986                let key = key.clone();
987                column((
988                    label(format!("Document {key}")).id(day_core::id!(doc, key.clone())),
989                    button("Bump")
990                        .action(move || count.update(|n| *n += 1))
991                        .id(day_core::id!(document_bump, key.clone())),
992                    label(move || count.get().to_string())
993                        .id(day_core::id!(document_count, key.clone())),
994                ))
995                .spacing(4.0)
996            },
997        )
998        .strip_id(day_core::id!(docs))
999        .native(move || pref.get());
1000        if closing == Closing::VetoFirst {
1001            host = host.on_close(move |key: String| {
1002                if vetoes.get_untracked() == 0 {
1003                    vetoes.update(|n| *n += 1);
1004                } else {
1005                    closes.update(|c| c.push(key.clone()));
1006                    tabs.close(&key);
1007                }
1008            });
1009        }
1010        if with_new {
1011            host = host.on_new(move || {
1012                next.update(|n| *n += 1);
1013                tabs.open(format!("n{}", next.get_untracked()), true);
1014            });
1015        }
1016        let opens = KEYS.map(|key| {
1017            button(format!("Open {key}"))
1018                .action(move || tabs.open(key.to_string(), true))
1019                .id(day_core::id!(document_open, key.to_owned()))
1020        });
1021        let [open_a, open_b, open_c] = opens;
1022        column((
1023            row((
1024                open_a,
1025                open_b,
1026                open_c,
1027                button("Open c behind")
1028                    .action(move || tabs.open("c".to_string(), false))
1029                    .id(day_core::id!(open_c_bg)),
1030                button("Close b")
1031                    .action(move || {
1032                        tabs.close(&"b".to_string());
1033                    })
1034                    .id(day_core::id!(close_b)),
1035            ))
1036            .spacing(4.0),
1037            row((
1038                button("Next")
1039                    .action(move || tabs.select_next(false))
1040                    .id(day_core::id!(next)),
1041                button("Previous")
1042                    .action(move || tabs.select_next(true))
1043                    .id(day_core::id!(prev)),
1044                button("Last first")
1045                    .action(move || {
1046                        if let Some(last) = tabs.keys().last() {
1047                            tabs.move_to(last, 0);
1048                        }
1049                    })
1050                    .id(day_core::id!(move_last_first)),
1051                button("A far")
1052                    .action(move || {
1053                        tabs.move_to(&"a".to_string(), 99);
1054                    })
1055                    .id(day_core::id!(move_a_far)),
1056                button("Rename")
1057                    .action(move || renames.update(|n| *n += 1))
1058                    .id(day_core::id!(rename)),
1059                toggle(pref).id(day_core::id!(native_pref)),
1060            ))
1061            .spacing(4.0),
1062            row((
1063                label(move || format!("selected {}", tabs.selected().unwrap_or("none".into())))
1064                    .id(day_core::id!(selected)),
1065                label(move || format!("order {}", tabs.keys().join(","))).id(day_core::id!(order)),
1066                label(move || format!("vetoes {}", vetoes.get())).id(day_core::id!(vetoes)),
1067                label(move || format!("closes {}", closes.get().join(",")))
1068                    .id(day_core::id!(closes)),
1069            ))
1070            .spacing(8.0),
1071            host.grow(Dimension::Both),
1072        ))
1073        .spacing(8.0)
1074    }
1075
1076    /// The current document's tab is a selected button, enabled and focusable, not a disabled
1077    /// one; tapping another tab moves the selection, in Day and natively.
1078    #[day_macros::test(day_core)]
1079    fn document_tabs_strip_selects_and_stays_enabled() -> Case {
1080        Case::new()
1081            .proves(kinds::NAV)
1082            .proves_modifier("selected")
1083            .page(|| fixture(Closing::Direct, false, false))
1084            .drive(|d: Drive| async move {
1085                // A foreground open selects what it opens.
1086                d.tap("document_open:a").await?;
1087                d.tap("document_open:b").await?;
1088                d.assert_text("selected", "selected b").await?;
1089                d.assert_text("doc:b", "Document b").await?;
1090                d.assert_text("document_tab:docs%3Aa", "Doc a").await?;
1091                d.assert_enabled("document_tab:docs%3Aa", true).await?;
1092                d.assert_enabled("document_tab:docs%3Ab", true).await?;
1093                d.assert_on("document_tab:docs%3Ab", true).await?;
1094                d.assert_on("document_tab:docs%3Aa", false).await?;
1095                d.assert_native(
1096                    "document_tab:docs%3Ab",
1097                    NativeExpect {
1098                        checked: Some(true),
1099                        ..Default::default()
1100                    },
1101                )
1102                .await?;
1103                d.assert_native(
1104                    "document_tab:docs%3Aa",
1105                    NativeExpect {
1106                        checked: Some(false),
1107                        ..Default::default()
1108                    },
1109                )
1110                .await?;
1111                d.shot("two-tabs").await?;
1112                d.tap("document_tab:docs%3Aa").await?;
1113                d.assert_text("selected", "selected a").await?;
1114                d.assert_text("doc:a", "Document a").await?;
1115                d.assert_on("document_tab:docs%3Ab", false).await?;
1116                d.assert_on("document_tab:docs%3Aa", true).await?;
1117                d.assert_native(
1118                    "document_tab:docs%3Aa",
1119                    NativeExpect {
1120                        checked: Some(true),
1121                        enabled: Some(true),
1122                        ..Default::default()
1123                    },
1124                )
1125                .await?;
1126                d.assert_native(
1127                    "document_tab:docs%3Ab",
1128                    NativeExpect {
1129                        checked: Some(false),
1130                        enabled: Some(true),
1131                        ..Default::default()
1132                    },
1133                )
1134                .await?;
1135                // Re-activating the current tab is harmless.
1136                d.tap("document_tab:docs%3Aa").await?;
1137                d.assert_text("selected", "selected a").await?;
1138                d.assert_on("document_tab:docs%3Aa", true).await
1139            })
1140    }
1141
1142    /// Closing the selected document selects the following neighbor, then the preceding last
1143    /// one, and the final close leaves no selection and no tabs.
1144    #[day_macros::test(day_core)]
1145    fn document_tabs_close_selects_neighbor() -> Case {
1146        Case::new()
1147            .proves(kinds::NAV)
1148            .page(|| fixture(Closing::Direct, false, false))
1149            .drive(|d: Drive| async move {
1150                d.tap("document_open:a").await?;
1151                d.tap("document_open:b").await?;
1152                d.tap("document_open:c").await?;
1153                d.tap("document_tab:docs%3Ab").await?;
1154                d.assert_text("order", "order a,b,c").await?;
1155                d.tap("document_close:docs%3Ab").await?;
1156                d.assert_text("selected", "selected c").await?;
1157                d.assert_text("order", "order a,c").await?;
1158                d.assert_missing("doc:b").await?;
1159                d.assert_missing("document_tab:docs%3Ab").await?;
1160                d.tap("document_close:docs%3Ac").await?;
1161                d.assert_text("selected", "selected a").await?;
1162                d.assert_text("order", "order a").await?;
1163                d.tap("document_close:docs%3Aa").await?;
1164                d.assert_text("selected", "selected none").await?;
1165                d.assert_text("order", "order ").await?;
1166                d.assert_missing("document_tab:docs%3Aa").await?;
1167                d.assert_missing("doc:a").await
1168            })
1169    }
1170
1171    /// A close handler receives a request: keeping the key vetoes it, and only the handler's
1172    /// own `TabSet::close` removes the document.
1173    #[day_macros::test(day_core)]
1174    fn document_tabs_close_request_can_be_vetoed() -> Case {
1175        Case::new()
1176            .proves(kinds::NAV)
1177            .page(|| fixture(Closing::VetoFirst, false, false))
1178            .drive(|d: Drive| async move {
1179                d.tap("document_open:a").await?;
1180                d.tap("document_open:b").await?;
1181                d.tap("document_close:docs%3Aa").await?;
1182                d.assert_text("vetoes", "vetoes 1").await?;
1183                d.assert_text("order", "order a,b").await?;
1184                d.assert_text("doc:a", "Document a").await?;
1185                d.tap("document_close:docs%3Aa").await?;
1186                d.assert_text("closes", "closes a").await?;
1187                d.assert_text("order", "order b").await?;
1188                d.assert_text("selected", "selected b").await?;
1189                d.assert_missing("doc:a").await
1190            })
1191    }
1192
1193    /// Reordering permutes the strip and the pages without rebuilding them: a counter bumped
1194    /// before the move still shows its count after it, and the first tab sits at the strip's
1195    /// leading edge. A move past the end lands on the last slot; the selection follows its key.
1196    #[day_macros::test(day_core)]
1197    fn document_tabs_reorder_keeps_resident_content() -> Case {
1198        Case::new()
1199            .proves(kinds::NAV)
1200            .page(|| fixture(Closing::Direct, false, false))
1201            .drive(|d: Drive| async move {
1202                d.tap("document_open:a").await?;
1203                d.tap("document_open:b").await?;
1204                d.tap("document_open:c").await?;
1205                d.tap("document_tab:docs%3Ab").await?;
1206                d.tap("document_bump:b").await?;
1207                d.tap("document_bump:b").await?;
1208                d.assert_text("document_count:b", "2").await?;
1209                d.tap("move_last_first").await?;
1210                d.assert_text("order", "order c,a,b").await?;
1211                d.assert_text("selected", "selected b").await?;
1212                d.assert_text("document_count:b", "2").await?;
1213                d.wait_idle().await?;
1214                d.assert_frame(
1215                    "document_tab:docs%3Ac",
1216                    FrameExpect {
1217                        x: Some(0.0),
1218                        relative_to: Some("docs".into()),
1219                        ..Default::default()
1220                    },
1221                )
1222                .await?;
1223                d.tap("move_a_far").await?;
1224                d.assert_text("order", "order c,b,a").await?;
1225                d.assert_text("selected", "selected b").await?;
1226                d.assert_text("document_count:b", "2").await?;
1227                d.tap("document_tab:docs%3Aa").await?;
1228                d.assert_text("selected", "selected a").await?;
1229                d.assert_text("doc:a", "Document a").await
1230            })
1231    }
1232
1233    /// A background open adds the document, builds it, and leaves the selection alone; an
1234    /// open of a key already present changes nothing.
1235    #[day_macros::test(day_core)]
1236    fn document_tabs_background_open_keeps_selection() -> Case {
1237        Case::new()
1238            .proves(kinds::NAV)
1239            .page(|| fixture(Closing::Direct, false, false))
1240            .drive(|d: Drive| async move {
1241                d.tap("document_open:a").await?;
1242                d.tap("open_c_bg").await?;
1243                d.assert_text("order", "order a,c").await?;
1244                d.assert_text("selected", "selected a").await?;
1245                d.assert_text("doc:c", "Document c").await?;
1246                d.assert_on("document_tab:docs%3Ac", false).await?;
1247                d.tap("document_open:a").await?;
1248                d.tap("open_c_bg").await?;
1249                d.assert_text("order", "order a,c").await?;
1250                d.assert_text("selected", "selected a").await?;
1251                d.tap("next").await?;
1252                d.assert_text("selected", "selected c").await?;
1253                d.assert_on("document_tab:docs%3Ac", true).await
1254            })
1255    }
1256
1257    /// `select_next` cycles through the collection in both directions and wraps at the ends.
1258    #[day_macros::test(day_core)]
1259    fn document_tabs_select_next_wraps() -> Case {
1260        Case::new()
1261            .proves(kinds::NAV)
1262            .page(|| fixture(Closing::Direct, false, false))
1263            .drive(|d: Drive| async move {
1264                d.tap("next").await?;
1265                d.assert_text("selected", "selected none").await?;
1266                d.tap("document_open:a").await?;
1267                d.tap("document_open:b").await?;
1268                d.tap("document_open:c").await?;
1269                d.tap("document_tab:docs%3Aa").await?;
1270                d.tap("next").await?;
1271                d.assert_text("selected", "selected b").await?;
1272                d.tap("next").await?;
1273                d.assert_text("selected", "selected c").await?;
1274                d.tap("next").await?;
1275                d.assert_text("selected", "selected a").await?;
1276                d.tap("prev").await?;
1277                d.assert_text("selected", "selected c").await?;
1278                d.assert_on("document_tab:docs%3Ac", true).await?;
1279                d.assert_on("document_tab:docs%3Aa", false).await
1280            })
1281    }
1282
1283    /// The strip's add button and the app's `on_new` handler: the app allocates the key and
1284    /// opens it in front; without a handler the strip shows no add button.
1285    #[day_macros::test(day_core)]
1286    fn document_tabs_new_button_delegates_to_app() -> Case {
1287        Case::new()
1288            .proves(kinds::NAV)
1289            .page(|| fixture(Closing::Direct, true, false))
1290            .drive(|d: Drive| async move {
1291                d.tap("document_open:a").await?;
1292                d.assert_text("document_new:docs", "New document").await?;
1293                d.tap("document_new:docs").await?;
1294                d.assert_text("order", "order a,n1").await?;
1295                d.assert_text("selected", "selected n1").await?;
1296                d.assert_text("doc:n1", "Document n1").await?;
1297                d.tap("document_new:docs").await?;
1298                d.assert_text("order", "order a,n1,n2").await?;
1299                d.assert_text("selected", "selected n2").await?;
1300                d.tap("document_close:docs%3An2").await?;
1301                d.assert_text("selected", "selected n1").await
1302            })
1303    }
1304
1305    /// Without an `on_new` handler the strip has no add button, and an empty collection shows
1306    /// an empty strip and no selection until a document opens.
1307    #[day_macros::test(day_core)]
1308    fn document_tabs_empty_host_shows_nothing() -> Case {
1309        Case::new()
1310            .proves(kinds::NAV)
1311            .page(|| fixture(Closing::Direct, false, false))
1312            .drive(|d: Drive| async move {
1313                d.assert_text("selected", "selected none").await?;
1314                d.assert_missing("document_tab:docs%3Aa").await?;
1315                d.assert_missing("document_new:docs").await?;
1316                d.tap("document_open:b").await?;
1317                d.assert_text("selected", "selected b").await?;
1318                d.assert_text("document_tab:docs%3Ab", "Doc b").await?;
1319                d.assert_frame(
1320                    "document_tab:docs%3Ab",
1321                    FrameExpect {
1322                        x: Some(0.0),
1323                        relative_to: Some("docs".into()),
1324                        ..Default::default()
1325                    },
1326                )
1327                .await
1328            })
1329    }
1330
1331    /// Titles follow the app's title function: a rename re-labels every tab in place, and the
1332    /// native widget shows the new title.
1333    #[day_macros::test(day_core)]
1334    fn document_tabs_titles_follow_model() -> Case {
1335        Case::new()
1336            .proves(kinds::NAV)
1337            .page(|| fixture(Closing::Direct, false, false))
1338            .drive(|d: Drive| async move {
1339                d.tap("document_open:a").await?;
1340                d.tap("document_open:b").await?;
1341                d.assert_text("document_tab:docs%3Ab", "Doc b").await?;
1342                d.tap("rename").await?;
1343                d.assert_text("document_tab:docs%3Aa", "Doc a (1)").await?;
1344                d.assert_text("document_tab:docs%3Ab", "Doc b (1)").await?;
1345                d.assert_native(
1346                    "document_tab:docs%3Ab",
1347                    NativeExpect {
1348                        text: Some("Doc b (1)".into()),
1349                        ..Default::default()
1350                    },
1351                )
1352                .await
1353            })
1354    }
1355
1356    /// Switching between native and composed presentation keeps every document's content and
1357    /// state, repeatedly; where a toolkit has no native presentation the switch is a no-op and
1358    /// the same invariants hold.
1359    #[day_macros::test(day_core)]
1360    fn document_tabs_presentation_switch_keeps_content() -> Case {
1361        Case::new()
1362            .proves(kinds::NAV)
1363            .proves_duty("native_document_tabs")
1364            .timeout(90.0)
1365            .page(|| fixture(Closing::Direct, false, false))
1366            .drive(|d: Drive| async move {
1367                d.tap("document_open:a").await?;
1368                d.tap("document_open:b").await?;
1369                d.tap("document_tab:docs%3Aa").await?;
1370                d.tap("document_bump:a").await?;
1371                let mut count = 1;
1372                d.assert_text("document_count:a", &count.to_string())
1373                    .await?;
1374                for _ in 0..2 {
1375                    d.toggle("native_pref", true).await?;
1376                    d.wait_idle().await?;
1377                    d.assert_text("document_count:a", &count.to_string())
1378                        .await?;
1379                    d.assert_text("selected", "selected a").await?;
1380                    d.assert_text("doc:b", "Document b").await?;
1381                    // A bump while presented natively lands on the same counter.
1382                    d.tap("document_bump:a").await?;
1383                    count += 1;
1384                    d.assert_text("document_count:a", &count.to_string())
1385                        .await?;
1386                    d.toggle("native_pref", false).await?;
1387                    d.wait_idle().await?;
1388                    d.assert_text("document_count:a", &count.to_string())
1389                        .await?;
1390                    d.assert_text("doc:a", "Document a").await?;
1391                    d.assert_text("document_tab:docs%3Aa", "Doc a").await?;
1392                    d.assert_on("document_tab:docs%3Aa", true).await?;
1393                }
1394                d.assert_text("document_count:a", "3").await?;
1395                d.assert_text("order", "order a,b").await?;
1396                d.tap("document_tab:docs%3Ab").await?;
1397                d.assert_text("selected", "selected b").await
1398            })
1399    }
1400
1401    /// Where the toolkit has OS window tabs, native presentation opens one window per document
1402    /// in the host's group, a model close closes its window, and composed presentation takes
1403    /// the documents back and closes every window.
1404    #[day_macros::test(day_core)]
1405    fn document_tabs_window_groups_follow_model() -> Case {
1406        Case::new()
1407            .proves(kinds::NAV)
1408            .proves_duty("native_window_tabs")
1409            .proves_duty("group_windows")
1410            .proves_duty("window_tab_order")
1411            .requires(Cap::WindowTabbing)
1412            .timeout(90.0)
1413            .page(|| fixture(Closing::Direct, false, true))
1414            .drive(|d: Drive| async move {
1415                // Likewise each count below is given a few turns to settle before it is judged.
1416                async fn windows(d: &Drive, what: &str, base: usize, want: usize) -> TestResult {
1417                    let mut got = day_core::windows::open_window_count();
1418                    for _ in 0..40 {
1419                        if got == want {
1420                            break;
1421                        }
1422                        d.pause(0.05).await?;
1423                        got = day_core::windows::open_window_count();
1424                    }
1425                    d.check(
1426                        got == want,
1427                        &format!("{what}: {got} windows open, expected {want} ({base} before)"),
1428                    )
1429                }
1430                // The previous case's windows may still be closing: a native close reports
1431                // back through the platform's own loop. The baseline is the count once it has
1432                // held still for a few turns.
1433                let mut base = day_core::windows::open_window_count();
1434                let mut held = 0;
1435                for _ in 0..60 {
1436                    d.pause(0.05).await?;
1437                    let now = day_core::windows::open_window_count();
1438                    if now == base {
1439                        held += 1;
1440                        if held >= 6 {
1441                            break;
1442                        }
1443                    } else {
1444                        base = now;
1445                        held = 0;
1446                    }
1447                }
1448                d.tap("document_open:a").await?;
1449                d.tap("document_open:b").await?;
1450                d.wait_idle().await?;
1451                d.assert_text("selected", "selected b").await?;
1452                windows(&d, "after opening a and b", base, base + 2).await?;
1453                d.tap("document_bump:b").await?;
1454                d.assert_text("document_count:b", "1").await?;
1455                d.tap("close_b").await?;
1456                d.wait_idle().await?;
1457                d.assert_text("order", "order a").await?;
1458                d.assert_missing("doc:b").await?;
1459                windows(&d, "after closing b", base, base + 1).await?;
1460                d.tap("document_open:c").await?;
1461                d.wait_idle().await?;
1462                d.assert_text("selected", "selected c").await?;
1463                windows(&d, "after opening c", base, base + 2).await?;
1464                d.toggle("native_pref", false).await?;
1465                d.wait_idle().await?;
1466                windows(&d, "after returning to the composed strip", base, base).await?;
1467                d.assert_text("doc:a", "Document a").await?;
1468                d.assert_text("doc:c", "Document c").await?;
1469                d.assert_text("document_tab:docs%3Ac", "Doc c").await?;
1470                d.assert_on("document_tab:docs%3Ac", true).await
1471            })
1472    }
1473
1474    /// App-owned chrome: `.chrome` replaces the strip and `TabActions` carries close, new and
1475    /// the model; `.layout` places it after the content.
1476    #[day_macros::test(day_core)]
1477    fn document_tabs_custom_chrome_uses_actions() -> Case {
1478        Case::new()
1479            .proves(kinds::NAV)
1480            .page(|| {
1481                let tabs = TabSet::<String>::new();
1482                let next = Signal::new(0u32);
1483                let host = document_tabs(
1484                    tabs,
1485                    "New",
1486                    "Close",
1487                    |key: &String| format!("Doc {key}"),
1488                    |key: &String| {
1489                        label(format!("Document {key}")).id(day_core::id!(doc, key.to_owned()))
1490                    },
1491                )
1492                .native(|| false)
1493                .on_new(move || {
1494                    next.update(|n| *n += 1);
1495                    tabs.open(format!("n{}", next.get_untracked()), true);
1496                })
1497                .chrome(|actions: TabActions<String>| {
1498                    let tabs = actions.tabs;
1499                    let closer = actions.clone();
1500                    row((
1501                        each(
1502                            items(move || tabs.keys(), |key: &String| key.clone()),
1503                            move |slot| {
1504                                let key = slot.get();
1505                                let select_key = key.clone();
1506                                let selected_key = key.clone();
1507                                let close_key = key.clone();
1508                                let closer = closer.clone();
1509                                row((
1510                                    button(format!("Doc {key}"))
1511                                        .selected(move || {
1512                                            tabs.selected().as_ref() == Some(&selected_key)
1513                                        })
1514                                        .action(move || {
1515                                            tabs.select(&select_key);
1516                                        })
1517                                        .id(day_core::id!(custom_tab, key.clone())),
1518                                    button("x")
1519                                        .action(move || closer.close(close_key.clone()))
1520                                        .id(day_core::id!(custom_close, key.clone())),
1521                                ))
1522                            },
1523                        ),
1524                        button("+")
1525                            .action(move || actions.new_tab())
1526                            .id(day_core::id!(custom_new)),
1527                    ))
1528                    .id(day_core::id!(custom_bar))
1529                })
1530                .layout(|bar, content| column((content.grow(Dimension::Both), bar)));
1531                column((
1532                    label(move || format!("selected {}", tabs.selected().unwrap_or("none".into())))
1533                        .id(day_core::id!(selected)),
1534                    host.grow(Dimension::Both),
1535                ))
1536            })
1537            .drive(|d: Drive| async move {
1538                d.assert_missing("docs").await?;
1539                d.tap("custom_new").await?;
1540                d.tap("custom_new").await?;
1541                d.assert_text("selected", "selected n2").await?;
1542                d.assert_text("doc:n1", "Document n1").await?;
1543                d.assert_on("custom_tab:n2", true).await?;
1544                d.assert_on("custom_tab:n1", false).await?;
1545                d.tap("custom_tab:n1").await?;
1546                d.assert_text("selected", "selected n1").await?;
1547                d.assert_on("custom_tab:n1", true).await?;
1548                d.tap("custom_close:n1").await?;
1549                d.assert_text("selected", "selected n2").await?;
1550                d.assert_missing("doc:n1").await?;
1551                d.wait_idle().await?;
1552                // The bar sits below the content (`.layout`), at the host's trailing edge.
1553                d.assert_frame(
1554                    "doc:n2",
1555                    FrameExpect {
1556                        y: Some(0.0),
1557                        relative_to: Some("selected".into()),
1558                        tolerance: Some(40.0),
1559                        ..Default::default()
1560                    },
1561                )
1562                .await
1563            })
1564    }
1565
1566    /// The model alone: an open of a present key is one tab, unknown keys are refused, a move
1567    /// past the end clamps, and closing picks the neighbor the contract names.
1568    #[day_macros::test(day_core)]
1569    fn document_tabs_model_contract() -> Case {
1570        Case::headless().run(|t: Drive| async move {
1571            let scope = day_reactive::Scope::detached();
1572            let result = scope.enter(|| {
1573                let tabs = TabSet::<u32>::new();
1574                t.check_eq(tabs.selected(), None)?;
1575                t.check_eq(tabs.keys(), Vec::<u32>::new())?;
1576                tabs.open(1, false);
1577                t.check_eq(tabs.selected(), Some(1))?;
1578                tabs.open(2, false);
1579                tabs.open(1, true);
1580                t.check_eq(tabs.keys(), vec![1, 2])?;
1581                t.check_eq(tabs.selected(), Some(1))?;
1582                t.check(!tabs.select(&9), "selecting an unknown key is refused")?;
1583                t.check(!tabs.move_to(&9, 0), "moving an unknown key is refused")?;
1584                t.check(!tabs.close(&9), "closing an unknown key is refused")?;
1585                t.check(tabs.move_to(&1, 99), "a move past the end is accepted")?;
1586                t.check_eq(tabs.keys(), vec![2, 1])?;
1587                t.check_eq(tabs.selected(), Some(1))?;
1588                tabs.open(3, false);
1589                t.check_eq(tabs.keys(), vec![2, 1, 3])?;
1590                t.check(tabs.close(&1), "closing the selected key")?;
1591                t.check_eq(tabs.selected(), Some(3))?;
1592                t.check(tabs.close(&3), "closing the selected last key")?;
1593                t.check_eq(tabs.selected(), Some(2))?;
1594                tabs.select_next(false);
1595                t.check_eq(tabs.selected(), Some(2))?;
1596                t.check(tabs.close(&2), "closing the final key")?;
1597                t.check_eq(tabs.selected(), None)?;
1598                tabs.select_next(true);
1599                t.check_eq(tabs.selected(), None)
1600            });
1601            scope.dispose();
1602            result
1603        })
1604    }
1605}