Skip to main content

iced_cube/application/
status_bar.rs

1//! A thin bar along the bottom edge of a window, with start, centre and
2//! end sections of small items: text, an icon with text, a clickable
3//! item, a spinner, a progress bar and a badge.
4//!
5//! Status usually comes from outside the UI thread, such as a sync job, a
6//! build or the editor's cursor, so items arrive through a channel.
7//! [`subscription`] creates a bounded channel, emits [`Event::Ready`] with
8//! its [`Sender`] once, then delivers whatever producers send in batches as
9//! [`Event::Received`]. Producers send [`Update`]s: set an item by its id,
10//! replacing any item with the same id, or remove one. [`animation`] ticks
11//! only while a spinner is showing.
12//!
13//! ```no_run
14//! use iced::{Element, Subscription};
15//! use iced_cube::status_bar::{self, Section, Update, status_bar};
16//!
17//! #[derive(Debug, Clone)]
18//! enum Message {
19//!     Status(status_bar::Event<&'static str>),
20//! }
21//!
22//! #[derive(Default)]
23//! struct App {
24//!     status: status_bar::State<&'static str>,
25//!     sender: Option<status_bar::Sender<&'static str>>,
26//! }
27//!
28//! impl App {
29//!     fn update(&mut self, message: Message) {
30//!         let Message::Status(event) = message;
31//!         if let Some(status_bar::Output::Ready(mut sender)) = self.status.update(event) {
32//!             // Hand clones of the sender to worker threads or tasks.
33//!             let _ = sender.try_send(Update::Set(
34//!                 status_bar::text("cursor", "Ln 1, Col 1").section(Section::End),
35//!             ));
36//!             self.sender = Some(sender);
37//!         }
38//!     }
39//!
40//!     fn view(&self) -> Element<'_, Message> {
41//!         status_bar(&self.status).on_event(Message::Status).into()
42//!     }
43//!
44//!     fn subscription(&self) -> Subscription<Message> {
45//!         Subscription::batch([
46//!             status_bar::subscription(),
47//!             status_bar::animation(&self.status),
48//!         ])
49//!         .map(Message::Status)
50//!     }
51//! }
52//! ```
53
54use std::rc::Rc;
55
56use iced::futures::channel::mpsc;
57use iced::futures::{Stream, StreamExt, stream};
58use iced::time::Instant;
59use iced::widget::text::LineHeight;
60use iced::widget::{self, column, container, responsive, row, space};
61use iced::{Alignment, Background, Element, Length, Padding, Subscription, Theme, window};
62
63use crate::feedback::badge::{self};
64use crate::feedback::progress::{self, progress as progress_bar};
65use crate::feedback::spinner::{self, advance, spinner as spinning};
66use crate::focus::{Ring, focusable_message};
67use crate::icon::{Glyph, opacity, themed};
68use crate::overlay::tooltip::{Position, tooltip};
69use crate::primitives::button::{self, Variant};
70use crate::theme::{Tokens, radius, space as gap, text_size};
71
72/// How many updates a producer can send before it has to wait.
73pub const CHANNEL_CAPACITY: usize = 32;
74/// The most updates delivered in one [`Event::Received`].
75pub const BATCH_SIZE: usize = 16;
76/// The id [`subscription`] runs under, so iced keeps one stream alive.
77pub const SUBSCRIPTION_ID: &str = "iced-cube-status-bar";
78/// Below this width the sections wrap onto several lines.
79pub const COMPACT_WIDTH: f32 = 480.0;
80/// Height of every item's line.
81pub const LINE: f32 = 16.0;
82/// Width of a progress item's bar.
83pub const PROGRESS_WIDTH: f32 = 80.0;
84
85const ICON_SIZE: f32 = 14.0;
86
87/// Where an item sits along the bar.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
89pub enum Section {
90    #[default]
91    Start,
92    Centre,
93    End,
94}
95
96impl Section {
97    pub const ALL: [Section; 3] = [Section::Start, Section::Centre, Section::End];
98}
99
100/// What an item shows besides its label and icon.
101#[derive(Debug, Clone, Copy, PartialEq)]
102pub enum Content {
103    /// Muted text.
104    Text,
105    /// A small ghost button that sends [`Event::Press`].
106    Action,
107    /// A spinner before the label, animated by [`animation`].
108    Spinner,
109    /// A short progress bar after the label, from 0.0 to 1.0.
110    Progress(f32),
111    /// A badge holding the label.
112    Badge(badge::Variant),
113}
114
115/// One item of the bar.
116#[derive(Debug, Clone, PartialEq)]
117pub struct Item<Id> {
118    pub id: Id,
119    pub section: Section,
120    pub label: String,
121    pub icon: Option<Glyph>,
122    pub tooltip: Option<String>,
123    pub content: Content,
124}
125
126fn new_item<Id>(id: Id, label: impl Into<String>, content: Content) -> Item<Id> {
127    Item {
128        id,
129        section: Section::default(),
130        label: label.into(),
131        icon: None,
132        tooltip: None,
133        content,
134    }
135}
136
137/// Muted text, such as a cursor position. Add `.icon(...)` for an icon.
138pub fn text<Id>(id: Id, label: impl Into<String>) -> Item<Id> {
139    new_item(id, label, Content::Text)
140}
141
142/// A clickable item, drawn as a small ghost button.
143pub fn action<Id>(id: Id, label: impl Into<String>) -> Item<Id> {
144    new_item(id, label, Content::Action)
145}
146
147/// A spinner with a label, for work in progress.
148pub fn spinner<Id>(id: Id, label: impl Into<String>) -> Item<Id> {
149    new_item(id, label, Content::Spinner)
150}
151
152/// A short progress bar, clamped to 0.0..=1.0. Add `.label(...)` to
153/// show text before it.
154pub fn progress<Id>(id: Id, value: f32) -> Item<Id> {
155    new_item(id, "", Content::Progress(progress::clamp(value)))
156}
157
158/// A badge, such as an error count.
159pub fn badge<Id>(id: Id, label: impl Into<String>, variant: badge::Variant) -> Item<Id> {
160    new_item(id, label, Content::Badge(variant))
161}
162
163impl<Id> Item<Id> {
164    pub fn section(mut self, section: Section) -> Self {
165        self.section = section;
166        self
167    }
168
169    pub fn label(mut self, label: impl Into<String>) -> Self {
170        self.label = label.into();
171        self
172    }
173
174    /// Adds a Lucide icon before the label.
175    pub fn icon(mut self, glyph: Glyph) -> Self {
176        self.icon = Some(glyph);
177        self
178    }
179
180    /// Shown above the item while the pointer rests on it.
181    pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self {
182        self.tooltip = Some(tooltip.into());
183        self
184    }
185}
186
187/// What a producer sends through the channel.
188#[derive(Debug, Clone, PartialEq)]
189pub enum Update<Id> {
190    /// Adds an item, or replaces the item with the same id where it stands.
191    Set(Item<Id>),
192    Remove(Id),
193    Clear,
194}
195
196/// The sending half of the status channel. Clone it for each producer.
197pub type Sender<Id> = mpsc::Sender<Update<Id>>;
198
199/// Changes to a status bar.
200#[derive(Debug, Clone)]
201pub enum Event<Id> {
202    /// The channel is open. Keep the sender and hand clones to producers.
203    Ready(Sender<Id>),
204    /// Updates from the channel, oldest first.
205    Received(Vec<Update<Id>>),
206    /// A window frame, which moves the spinners on.
207    Frame(Instant),
208    /// A clickable item was pressed.
209    Press(Id),
210}
211
212/// What the app may need to act on after an [`Event`].
213#[derive(Debug, Clone)]
214pub enum Output<Id> {
215    Ready(Sender<Id>),
216    /// A clickable item was pressed.
217    Pressed(Id),
218}
219
220/// The items and the spinners' phase.
221#[derive(Debug, Clone, PartialEq)]
222pub struct State<Id> {
223    items: Vec<Item<Id>>,
224    phase: f32,
225    last_frame: Option<Instant>,
226}
227
228impl<Id> Default for State<Id> {
229    fn default() -> Self {
230        Self {
231            items: Vec::new(),
232            phase: 0.0,
233            last_frame: None,
234        }
235    }
236}
237
238impl<Id: PartialEq> State<Id> {
239    /// An empty bar.
240    pub fn new() -> Self {
241        Self::default()
242    }
243
244    /// A bar starting with `items`, as if each had been set in turn.
245    pub fn with_items(mut self, items: impl IntoIterator<Item = Item<Id>>) -> Self {
246        for item in items {
247            self.apply(Update::Set(item));
248        }
249        self
250    }
251
252    /// Every item, in the order it was first set.
253    pub fn items(&self) -> &[Item<Id>] {
254        &self.items
255    }
256
257    pub fn item(&self, id: &Id) -> Option<&Item<Id>> {
258        self.items.iter().find(|item| item.id == *id)
259    }
260
261    /// The items in one section, in order.
262    pub fn section(&self, section: Section) -> impl Iterator<Item = &Item<Id>> {
263        self.items
264            .iter()
265            .filter(move |item| item.section == section)
266    }
267
268    pub fn is_empty(&self) -> bool {
269        self.items.is_empty()
270    }
271
272    /// The spinners' phase, in turns.
273    pub fn phase(&self) -> f32 {
274        self.phase
275    }
276
277    /// Whether any spinner is showing, so frames are needed.
278    pub fn needs_frames(&self) -> bool {
279        self.items
280            .iter()
281            .any(|item| item.content == Content::Spinner)
282    }
283
284    /// Applies one update, as the channel does.
285    pub fn apply(&mut self, update: Update<Id>) {
286        match update {
287            Update::Set(item) => match self.items.iter_mut().find(|old| old.id == item.id) {
288                Some(old) => *old = item,
289                None => self.items.push(item),
290            },
291            Update::Remove(id) => self.items.retain(|item| item.id != id),
292            Update::Clear => self.items.clear(),
293        }
294        if !self.needs_frames() {
295            self.last_frame = None;
296        }
297    }
298
299    /// Applies an event and returns what the app may need to act on.
300    pub fn update(&mut self, event: Event<Id>) -> Option<Output<Id>> {
301        match event {
302            Event::Ready(sender) => return Some(Output::Ready(sender)),
303            Event::Received(batch) => {
304                for update in batch {
305                    self.apply(update);
306                }
307            }
308            Event::Frame(now) => {
309                if let Some(last) = self.last_frame {
310                    self.phase = advance(self.phase, now.saturating_duration_since(last));
311                }
312                self.last_frame = Some(now);
313            }
314            Event::Press(id) => {
315                let pressable = self
316                    .item(&id)
317                    .is_some_and(|item| item.content == Content::Action);
318                return pressable.then_some(Output::Pressed(id));
319            }
320        }
321        None
322    }
323}
324
325/// Owns the status channel. Emits [`Event::Ready`] first, then batches.
326/// It runs under [`SUBSCRIPTION_ID`], so iced keeps the same stream
327/// however often the app asks for it.
328pub fn subscription<Id: Send + 'static>() -> Subscription<Event<Id>> {
329    Subscription::run_with(SUBSCRIPTION_ID, |_| stream::<Id>())
330}
331
332/// The stream behind [`subscription`], for driving it without a runtime.
333pub fn stream<Id: Send + 'static>() -> impl Stream<Item = Event<Id>> {
334    let (sender, receiver) = mpsc::channel(CHANNEL_CAPACITY);
335    stream::once(async move { Event::Ready(sender) }).chain(batches(receiver).map(Event::Received))
336}
337
338/// Groups whatever is already waiting in the channel into one batch.
339pub fn batches<T>(receiver: impl Stream<Item = T>) -> impl Stream<Item = Vec<T>> {
340    receiver.ready_chunks(BATCH_SIZE)
341}
342
343/// Window frames while a spinner is showing, and nothing otherwise.
344pub fn animation<Id: PartialEq + 'static>(state: &State<Id>) -> Subscription<Event<Id>> {
345    if !state.needs_frames() {
346        return Subscription::none();
347    }
348    window::frames().map(Event::Frame)
349}
350
351/// The bar: the page background with muted text, below a line along its
352/// top edge. Progress tracks and badges read against it in both themes.
353pub fn bar_style(tokens: &Tokens) -> container::Style {
354    container::Style {
355        background: Some(Background::Color(tokens.background)),
356        text_color: Some(tokens.muted_foreground),
357        ..container::Style::default()
358    }
359}
360
361/// The colour of text and icons in the bar.
362pub fn text_colour(tokens: &Tokens) -> iced::Color {
363    tokens.muted_foreground
364}
365
366type OnEvent<'a, Id, Message> = Rc<dyn Fn(Event<Id>) -> Message + 'a>;
367
368/// A status bar builder. Convert it into an [`Element`] to render.
369pub struct StatusBar<'a, Id, Message> {
370    state: &'a State<Id>,
371    compact_below: f32,
372    on_event: Option<Box<dyn Fn(Event<Id>) -> Message + 'a>>,
373}
374
375impl<Id: std::fmt::Debug, Message> std::fmt::Debug for StatusBar<'_, Id, Message> {
376    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
377        f.debug_struct("StatusBar")
378            .field("state", self.state)
379            .field("compact_below", &self.compact_below)
380            .finish_non_exhaustive()
381    }
382}
383
384/// Renders the items of `state`. Without [`on_event`](StatusBar::on_event)
385/// clickable items render disabled.
386pub fn status_bar<'a, Id, Message>(state: &'a State<Id>) -> StatusBar<'a, Id, Message> {
387    StatusBar {
388        state,
389        compact_below: COMPACT_WIDTH,
390        on_event: None,
391    }
392}
393
394impl<'a, Id, Message> StatusBar<'a, Id, Message> {
395    /// Below this width, the items flow onto as many lines as they need
396    /// instead of splitting into three sections. Defaults to
397    /// [`COMPACT_WIDTH`].
398    pub fn compact_below(mut self, width: f32) -> Self {
399        self.compact_below = width;
400        self
401    }
402
403    pub fn on_event(mut self, on_event: impl Fn(Event<Id>) -> Message + 'a) -> Self {
404        self.on_event = Some(Box::new(on_event));
405        self
406    }
407}
408
409impl<'a, Id, Message> From<StatusBar<'a, Id, Message>> for Element<'a, Message>
410where
411    Id: Clone + PartialEq + 'a,
412    Message: Clone + 'a,
413{
414    fn from(bar: StatusBar<'a, Id, Message>) -> Self {
415        let StatusBar {
416            state,
417            compact_below,
418            on_event,
419        } = bar;
420        let on_event: Option<OnEvent<'a, Id, Message>> = on_event.map(Rc::from);
421
422        let content = responsive(move |size| {
423            let items = |section: Section| -> Vec<Element<'a, Message>> {
424                state
425                    .section(section)
426                    .map(|item| view_item(item, state.phase, on_event.as_ref()))
427                    .collect()
428            };
429            if size.width < compact_below {
430                let all = Section::ALL.into_iter().flat_map(items);
431                return row(all)
432                    .spacing(gap::MD)
433                    .align_y(Alignment::Center)
434                    .wrap()
435                    .vertical_spacing(gap::XS)
436                    .into();
437            }
438            let section = |section| {
439                row(items(section))
440                    .spacing(gap::MD)
441                    .align_y(Alignment::Center)
442            };
443            row![
444                section(Section::Start),
445                space::horizontal(),
446                section(Section::Centre),
447                space::horizontal(),
448                section(Section::End),
449            ]
450            .spacing(gap::MD)
451            .align_y(Alignment::Center)
452            .into()
453        })
454        .height(Length::Shrink);
455
456        let bar: Element<'a, Message> = container(content)
457            .padding(Padding::from([gap::XS, gap::SM]))
458            .width(Length::Fill)
459            .style(|theme| bar_style(&Tokens::of(theme)))
460            .into();
461        #[cfg(feature = "icedwright")]
462        let bar: Element<'a, Message> = icedwright_probe::semantic(bar)
463            .role(icedwright_probe::role::Status)
464            .component("iced_cube::status_bar")
465            .into();
466        column![crate::application::edge(), bar]
467            .width(Length::Fill)
468            .into()
469    }
470}
471
472fn muted_text<'a>(label: String) -> widget::Text<'a, Theme> {
473    widget::text(label)
474        .size(text_size::XS)
475        .line_height(LineHeight::Absolute(LINE.into()))
476        .wrapping(widget::text::Wrapping::None)
477}
478
479fn glyph<'a, Message: 'a>(glyph: Glyph, enabled: bool) -> Element<'a, Message> {
480    themed(glyph, ICON_SIZE, opacity(enabled), |theme| {
481        text_colour(&Tokens::of(theme))
482    })
483    .into()
484}
485
486fn view_item<'a, Id, Message>(
487    item: &Item<Id>,
488    phase: f32,
489    on_event: Option<&OnEvent<'a, Id, Message>>,
490) -> Element<'a, Message>
491where
492    Id: Clone + 'a,
493    Message: Clone + 'a,
494{
495    let label = || -> Option<Element<'a, Message>> {
496        (!item.label.is_empty()).then(|| {
497            muted_text(item.label.clone())
498                .style(|theme| widget::text::Style {
499                    color: Some(text_colour(&Tokens::of(theme))),
500                })
501                .into()
502        })
503    };
504    let icon = item.icon.map(|icon| glyph(icon, true));
505
506    let element: Element<'a, Message> = match item.content {
507        Content::Text => labelled(icon.into_iter().chain(label())),
508        Content::Spinner => {
509            labelled(std::iter::once(spinning(phase).size(spinner::Size::Sm).into()).chain(label()))
510        }
511        Content::Progress(value) => labelled(
512            icon.into_iter().chain(label()).chain(std::iter::once(
513                progress_bar(value)
514                    .size(progress::Size::Sm)
515                    .width(PROGRESS_WIDTH)
516                    .into(),
517            )),
518        ),
519        Content::Badge(variant) => {
520            let badge = badge::badge(item.label.clone()).variant(variant);
521            match item.icon {
522                Some(icon) => badge.icon(icon).into(),
523                None => badge.into(),
524            }
525        }
526        Content::Action => action_button(item, on_event),
527    };
528    match &item.tooltip {
529        Some(label) => tooltip(element, label.clone())
530            .position(Position::Top)
531            .into(),
532        None => element,
533    }
534}
535
536fn labelled<'a, Message: 'a>(
537    parts: impl Iterator<Item = Element<'a, Message>>,
538) -> Element<'a, Message> {
539    row(parts)
540        .spacing(gap::XS + 2.0)
541        .align_y(Alignment::Center)
542        .into()
543}
544
545fn action_button<'a, Id, Message>(
546    item: &Item<Id>,
547    on_event: Option<&OnEvent<'a, Id, Message>>,
548) -> Element<'a, Message>
549where
550    Id: Clone + 'a,
551    Message: Clone + 'a,
552{
553    let enabled = on_event.is_some();
554    let mut content = row![].spacing(gap::XS + 2.0).align_y(Alignment::Center);
555    if let Some(icon) = item.icon {
556        content = content.push(themed(icon, ICON_SIZE, opacity(enabled), |theme| {
557            Tokens::of(theme).foreground
558        }));
559    }
560    content = content.push(muted_text(item.label.clone()));
561    let message = on_event.map(|on_event| on_event(Event::Press(item.id.clone())));
562    let button = widget::button(content)
563        .padding(Padding::from([2.0, 6.0]))
564        .style(|theme, status| button::style(&Tokens::of(theme), Variant::Ghost, status))
565        .on_press_maybe(message.clone());
566    let button: Element<'a, Message> =
567        focusable_message(button, message, Ring::around(radius::MD)).into();
568    #[cfg(feature = "icedwright")]
569    let button = {
570        icedwright_probe::semantic(button)
571            .role(icedwright_probe::role::Button)
572            .name(item.label.clone())
573            .disabled(!enabled)
574            .component("iced_cube::status_bar")
575            .into()
576    };
577    button
578}
579
580#[cfg(test)]
581mod tests {
582    use super::*;
583    use crate::theme::{dark, light};
584    use iced::futures::SinkExt;
585    use iced::futures::executor::block_on;
586
587    fn sample() -> State<&'static str> {
588        State::new().with_items([
589            text("branch", "main").icon(crate::lucide!(GitBranch)),
590            spinner("sync", "Syncing"),
591            progress("build", 0.4)
592                .label("Building")
593                .section(Section::Centre),
594            action("problems", "2 problems").section(Section::End),
595            badge("mode", "Insert", badge::Variant::Secondary).section(Section::End),
596        ])
597    }
598
599    #[test]
600    fn builders_set_every_field() {
601        let item = text("cursor", "Ln 1, Col 1")
602            .icon(crate::lucide!(MousePointer))
603            .section(Section::End)
604            .tooltip("Go to line");
605        assert_eq!(item.id, "cursor");
606        assert_eq!(item.label, "Ln 1, Col 1");
607        assert_eq!(item.icon, Some(crate::lucide!(MousePointer)));
608        assert_eq!(item.section, Section::End);
609        assert_eq!(item.tooltip.as_deref(), Some("Go to line"));
610        assert_eq!(item.content, Content::Text);
611
612        assert_eq!(action(1, "Run").content, Content::Action);
613        assert_eq!(spinner(1, "Busy").content, Content::Spinner);
614        assert_eq!(progress(1, 1.5).content, Content::Progress(1.0));
615        assert_eq!(progress(1, f32::NAN).content, Content::Progress(0.0));
616        assert!(progress(1, 0.5).label.is_empty());
617        assert_eq!(
618            badge(1, "3", badge::Variant::Destructive).content,
619            Content::Badge(badge::Variant::Destructive)
620        );
621        assert_eq!(Section::default(), Section::Start);
622    }
623
624    #[test]
625    fn items_keep_their_order_within_sections() {
626        let state = sample();
627        let start: Vec<_> = state.section(Section::Start).map(|item| item.id).collect();
628        let end: Vec<_> = state.section(Section::End).map(|item| item.id).collect();
629        assert_eq!(start, ["branch", "sync"]);
630        assert_eq!(end, ["problems", "mode"]);
631        assert_eq!(state.items().len(), 5);
632        assert!(!state.is_empty());
633    }
634
635    #[test]
636    fn set_replaces_in_place_and_remove_and_clear_delete() {
637        let mut state = sample();
638        state.apply(Update::Set(text("sync", "Synced")));
639        assert_eq!(state.items()[1].label, "Synced");
640        assert_eq!(state.items()[1].content, Content::Text);
641        assert_eq!(state.items().len(), 5);
642
643        state.apply(Update::Remove("build"));
644        assert!(state.item(&"build").is_none());
645        state.apply(Update::Remove("missing"));
646        assert_eq!(state.items().len(), 4);
647
648        state.apply(Update::Clear);
649        assert!(state.is_empty());
650    }
651
652    #[test]
653    fn a_batch_applies_in_order() {
654        let mut state: State<&str> = State::new();
655        let output = state.update(Event::Received(vec![
656            Update::Set(text("a", "one")),
657            Update::Set(text("b", "two")),
658            Update::Set(text("a", "three")),
659            Update::Remove("b"),
660        ]));
661        assert!(output.is_none());
662        assert_eq!(state.items().len(), 1);
663        assert_eq!(state.items()[0].label, "three");
664        assert!(state.update(Event::Received(Vec::new())).is_none());
665    }
666
667    #[test]
668    fn frames_move_the_spinners_only_while_one_shows() {
669        let mut state = sample();
670        assert!(state.needs_frames());
671        let start = Instant::now();
672        let _ = state.update(Event::Frame(start));
673        assert_eq!(state.phase(), 0.0, "the first frame only starts the clock");
674        let _ = state.update(Event::Frame(start + spinner::PERIOD / 4));
675        assert!((state.phase() - 0.25).abs() < 1e-3);
676
677        state.apply(Update::Remove("sync"));
678        assert!(!state.needs_frames());
679        assert!(
680            state.last_frame.is_none(),
681            "the clock stops with the spinner"
682        );
683    }
684
685    #[test]
686    fn only_clickable_items_report_presses() {
687        let mut state = sample();
688        assert!(matches!(
689            state.update(Event::Press("problems")),
690            Some(Output::Pressed("problems"))
691        ));
692        assert!(state.update(Event::Press("branch")).is_none());
693        assert!(state.update(Event::Press("missing")).is_none());
694    }
695
696    #[test]
697    fn ready_hands_the_sender_back() {
698        let (sender, _receiver) = mpsc::channel(1);
699        let output = State::<u8>::new().update(Event::Ready(sender));
700        assert!(matches!(output, Some(Output::Ready(_))));
701    }
702
703    #[test]
704    fn stream_emits_ready_first_then_batches() {
705        let mut events = Box::pin(stream::<u8>());
706        let Some(Event::Ready(mut sender)) = block_on(events.next()) else {
707            panic!("first event must be Ready");
708        };
709        block_on(async {
710            for n in 0..3 {
711                sender.send(Update::Set(text(n, format!("{n}")))).await.ok();
712            }
713        });
714        let Some(Event::Received(batch)) = block_on(events.next()) else {
715            panic!("expected a batch");
716        };
717        assert_eq!(batch.len(), 3);
718    }
719
720    #[test]
721    fn batches_split_bursts_at_batch_size() {
722        let items = stream::iter(0..BATCH_SIZE + 3);
723        let sizes: Vec<_> = block_on(batches(items).map(|batch| batch.len()).collect());
724        assert_eq!(sizes, [BATCH_SIZE, 3]);
725    }
726
727    #[test]
728    fn builder_defaults_and_overrides() {
729        let state = sample();
730        let bar: StatusBar<'_, &str, ()> = status_bar(&state);
731        assert_eq!(bar.compact_below, COMPACT_WIDTH);
732        assert!(bar.on_event.is_none());
733        let bar: StatusBar<'_, &str, ()> = status_bar(&state).compact_below(0.0).on_event(|_| ());
734        assert_eq!(bar.compact_below, 0.0);
735        assert!(bar.on_event.is_some());
736    }
737
738    #[test]
739    fn the_bar_has_muted_text_in_both_themes() {
740        for theme in [light(), dark()] {
741            let tokens = Tokens::of(&theme);
742            let style = bar_style(&tokens);
743            assert_eq!(style.background, Some(Background::Color(tokens.background)));
744            assert_eq!(style.text_color, Some(tokens.muted_foreground));
745            assert_eq!(text_colour(&tokens), tokens.muted_foreground);
746        }
747    }
748}