Skip to main content

iced_cube/data/
log_viewer.rs

1//! A live, searchable log: entries with a level, an optional timestamp and
2//! target, and a message, streamed in from threads or tasks.
3//!
4//! [`State`] keeps the newest entries up to a limit, dropping the oldest,
5//! so memory stays bounded however long the log runs. It filters by
6//! level, searches messages with every match marked, follows the newest
7//! line, pauses and resumes the stream, and selects lines to copy. Only
8//! the lines in view are built, as in a
9//! [virtual list](mod@crate::data::virtual_list).
10//!
11//! [`subscription`] creates a bounded channel and emits [`Event::Ready`]
12//! with its [`Sender`] once. Producers send [`Entry`] values through clones
13//! of the sender, and entries arrive in batches as [`Event::Received`].
14//!
15//! Copying returns [`Output::Copy`] with the text, for the app to write to
16//! the clipboard, and the search shortcut returns [`Output::FocusSearch`],
17//! for the app to answer with [`focus_search`]. Lines can carry a context
18//! menu, such as the one from [`menu()`], through
19//! [`LogViewer::context_menu`].
20//!
21//! ```no_run
22//! use iced::{Element, Subscription, Task};
23//! use iced_cube::data::log_viewer::{self, Event, Level, Output, State, entry, log_viewer};
24//!
25//! #[derive(Debug, Clone)]
26//! enum Message {
27//!     Logs(Event),
28//! }
29//!
30//! struct App {
31//!     logs: State,
32//!     sender: Option<log_viewer::Sender>,
33//! }
34//!
35//! impl App {
36//!     fn update(&mut self, message: Message) -> Task<Message> {
37//!         let Message::Logs(event) = message;
38//!         match self.logs.update(event) {
39//!             Some(Output::Ready(mut sender)) => {
40//!                 let _ = sender.try_send(entry(Level::Info, "Listening on :8080"));
41//!                 self.sender = Some(sender);
42//!                 Task::none()
43//!             }
44//!             Some(Output::Copy(text)) => iced::clipboard::write(text),
45//!             Some(Output::FocusSearch) => log_viewer::focus_search(&self.logs),
46//!             None => Task::none(),
47//!         }
48//!     }
49//!
50//!     fn view(&self) -> Element<'_, Message> {
51//!         log_viewer(&self.logs).height(400).on_event(Message::Logs).into()
52//!     }
53//!
54//!     fn subscription(&self) -> Subscription<Message> {
55//!         log_viewer::subscription().map(Message::Logs)
56//!     }
57//! }
58//! ```
59
60use std::collections::{BTreeSet, VecDeque};
61use std::fmt;
62use std::rc::Rc;
63
64use iced::futures::channel::mpsc;
65use iced::futures::{Stream, StreamExt, stream};
66use iced::keyboard::Modifiers;
67use iced::keyboard::key::Named;
68use iced::widget::text::{LineHeight, Wrapping};
69use iced::widget::{self, Space, column, container, responsive, row, text};
70use iced::{Alignment, Border, Color, Element, Length, Padding, Pixels, Subscription, Task, Theme};
71
72use crate::data::ellipsis::ellipsis;
73use crate::data::interaction::{
74    Look, RowMenu, match_count_label, pressable, ringed, row_menu, scope, search_count, search_keys,
75};
76use crate::data::marked::{find, marked};
77use crate::data::rows::rows;
78use crate::data::virtual_list::{self, Step, target};
79use crate::keys::{self, Chord, Keymap};
80use crate::overlay::context_menu;
81use crate::overlay::dropdown_menu::{item, separator};
82use crate::overlay::tooltip::Position;
83use crate::primitives::button::{self, button};
84use crate::primitives::icon_button::icon_button;
85use crate::primitives::input::{self, Shortcuts, input};
86use crate::primitives::toggle;
87use crate::primitives::toggle_group::{self, toggle_group};
88use crate::theme::{self, Tokens, fade, mix, radius, space, text_size};
89
90/// Height of a line that does not wrap.
91pub const ROW_HEIGHT: f32 = 24.0;
92/// Height of a line that does not wrap below the [`BREAKPOINT`], where the
93/// message sits under the timestamp, level and target.
94pub const STACKED_ROW_HEIGHT: f32 = 42.0;
95/// The most entries kept unless the state is given another limit.
96pub const DEFAULT_LIMIT: usize = 10_000;
97/// How many entries a producer can send before it has to wait.
98pub const CHANNEL_CAPACITY: usize = 1024;
99/// The most entries delivered in one [`Event::Received`].
100pub const BATCH_SIZE: usize = 512;
101/// The default widget id of the search field.
102pub const SEARCH_ID: widget::Id = widget::Id::new("iced-cube-log-viewer-search");
103/// Below this width the toolbar stacks its parts.
104pub const BREAKPOINT: f32 = 560.0;
105const LINE_HEIGHT: f32 = 18.0;
106const TIMESTAMP_WIDTH: f32 = 84.0;
107const LEVEL_WIDTH: f32 = 44.0;
108const TARGET_WIDTH: f32 = 120.0;
109const FRAME_PADDING: f32 = 4.0;
110
111/// How severe an entry is.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
113pub enum Level {
114    Trace,
115    Debug,
116    #[default]
117    Info,
118    Warn,
119    Error,
120}
121
122impl Level {
123    pub const ALL: [Level; 5] = [
124        Level::Trace,
125        Level::Debug,
126        Level::Info,
127        Level::Warn,
128        Level::Error,
129    ];
130
131    /// The short upper-case tag shown on each line, such as `WARN`.
132    pub const fn tag(self) -> &'static str {
133        match self {
134            Level::Trace => "TRACE",
135            Level::Debug => "DEBUG",
136            Level::Info => "INFO",
137            Level::Warn => "WARN",
138            Level::Error => "ERROR",
139        }
140    }
141
142    /// The name shown on the level filter, such as `Warn`.
143    pub const fn name(self) -> &'static str {
144        match self {
145            Level::Trace => "Trace",
146            Level::Debug => "Debug",
147            Level::Info => "Info",
148            Level::Warn => "Warn",
149            Level::Error => "Error",
150        }
151    }
152
153    const fn index(self) -> usize {
154        self as usize
155    }
156}
157
158impl fmt::Display for Level {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        f.write_str(self.tag())
161    }
162}
163
164/// One log line.
165#[derive(Debug, Clone, PartialEq, Eq, Default)]
166pub struct Entry {
167    pub level: Level,
168    /// Shown as given, so the app picks the format.
169    pub timestamp: Option<String>,
170    /// Where the entry came from, such as a module path.
171    pub target: Option<String>,
172    pub message: String,
173}
174
175/// Creates an entry. Add a timestamp and a target with the builder methods.
176pub fn entry(level: Level, message: impl Into<String>) -> Entry {
177    Entry {
178        level,
179        timestamp: None,
180        target: None,
181        message: message.into(),
182    }
183}
184
185impl Entry {
186    pub fn timestamp(mut self, timestamp: impl Into<String>) -> Self {
187        self.timestamp = Some(timestamp.into());
188        self
189    }
190
191    pub fn target(mut self, target: impl Into<String>) -> Self {
192        self.target = Some(target.into());
193        self
194    }
195
196    /// The entry as one line of plain text, as it is copied.
197    pub fn line(&self) -> String {
198        let mut line = String::new();
199        if let Some(timestamp) = &self.timestamp {
200            line.push_str(timestamp);
201            line.push(' ');
202        }
203        line.push_str(&format!("{:<5} ", self.level.tag()));
204        if let Some(target) = &self.target {
205            line.push_str(target);
206            line.push_str(": ");
207        }
208        line.push_str(&self.message);
209        line
210    }
211}
212
213/// Names a line for as long as it is kept: its position counted from the
214/// first entry the log ever received.
215pub type LineId = u64;
216
217/// The sending half of the channel entries arrive on. Clone it for each
218/// producer.
219pub type Sender = mpsc::Sender<Entry>;
220
221/// Everything that changes a log.
222#[derive(Debug, Clone)]
223pub enum Event {
224    /// The channel is open. Keep the sender and hand clones to producers.
225    Ready(Sender),
226    /// Entries from the channel, oldest first.
227    Received(Vec<Entry>),
228    /// The pointer pressed a line with these modifiers held.
229    Press(LineId, Modifiers),
230    /// The search text changed.
231    Search(String),
232    NextMatch,
233    PreviousMatch,
234    ClearSearch,
235    /// Asks the app to focus the search field.
236    FocusSearch,
237    /// Shows or hides a level.
238    ToggleLevel(Level),
239    /// The level filters were pressed.
240    Levels(toggle_group::Event<Level>),
241    /// Shows only the level of this line.
242    FilterToLevel(LineId),
243    ToggleWrap,
244    /// Pauses the stream, holding new entries back, or resumes it.
245    TogglePause,
246    /// Removes every entry.
247    Clear,
248    /// Copies the selected lines, or the highlighted one.
249    CopySelection,
250    /// Copies one line as plain text, as [`Entry::line`] formats it.
251    CopyLine(LineId),
252    /// Copies only the message of one line.
253    CopyMessage(LineId),
254    /// Selects or deselects the highlighted line, keeping the others.
255    ToggleHighlighted,
256    /// Starts or stops following the newest line. The log sends `false`
257    /// when the user scrolls away from the end, and `true` when they
258    /// scroll back.
259    Follow(bool),
260    Next,
261    Previous,
262    First,
263    /// Highlights the newest line and follows it.
264    Last,
265    NextPage,
266    PreviousPage,
267    ExtendNext,
268    ExtendPrevious,
269    SelectAll,
270    /// How many lines fit in the view. The log sends this itself.
271    Page(usize),
272    /// The log gained or lost focus. The log sends this itself.
273    Focus(bool),
274}
275
276/// What the app may need to act on after an [`Event`].
277#[derive(Debug, Clone)]
278pub enum Output {
279    Ready(Sender),
280    /// Write this text to the clipboard.
281    Copy(String),
282    /// Focus the search field, with [`focus_search`].
283    FocusSearch,
284}
285
286/// The kept entries, the filters, the search, the selection and whether the
287/// log follows its newest line.
288#[derive(Debug, Clone)]
289pub struct State {
290    entries: VecDeque<Entry>,
291    /// The id of the oldest kept entry.
292    first: LineId,
293    limit: usize,
294    counts: [usize; 5],
295    shown: [bool; 5],
296    /// The level filters as drawn, labelled with their counts.
297    levels: toggle_group::State<Level>,
298    /// Ids of the entries that pass the level filter, oldest first.
299    visible: VecDeque<LineId>,
300    /// Visible lines dropped from the front so far, so the lines in view
301    /// stay put as old ones go.
302    visible_dropped: u64,
303    query: String,
304    /// Visible lines whose message matches the search, oldest first.
305    matches: VecDeque<LineId>,
306    current: Option<LineId>,
307    selected: BTreeSet<LineId>,
308    anchor: Option<LineId>,
309    highlighted: Option<LineId>,
310    focused: bool,
311    following: bool,
312    paused: bool,
313    /// Entries held back while paused.
314    pending: VecDeque<Entry>,
315    /// Lines that arrived while not following.
316    unseen: usize,
317    wrap: bool,
318    page: usize,
319    reveal: Option<(LineId, u64)>,
320    requests: u64,
321    search_id: widget::Id,
322}
323
324impl Default for State {
325    fn default() -> Self {
326        Self {
327            entries: VecDeque::new(),
328            first: 0,
329            limit: DEFAULT_LIMIT,
330            counts: [0; 5],
331            shown: [true; 5],
332            levels: level_filters(&[0; 5], &[true; 5]),
333            visible: VecDeque::new(),
334            visible_dropped: 0,
335            query: String::new(),
336            matches: VecDeque::new(),
337            current: None,
338            selected: BTreeSet::new(),
339            anchor: None,
340            highlighted: None,
341            focused: false,
342            following: true,
343            paused: false,
344            pending: VecDeque::new(),
345            unseen: 0,
346            wrap: false,
347            page: virtual_list::DEFAULT_PAGE,
348            reveal: None,
349            requests: 0,
350            search_id: SEARCH_ID,
351        }
352    }
353}
354
355impl State {
356    /// An empty log that keeps [`DEFAULT_LIMIT`] entries, shows every
357    /// level and follows the newest line.
358    pub fn new() -> Self {
359        Self::default()
360    }
361
362    /// Keeps at most `limit` entries, dropping the oldest. A limit of zero
363    /// is treated as one.
364    pub fn with_limit(mut self, limit: usize) -> Self {
365        self.limit = limit.max(1);
366        self.trim();
367        self.sync_levels();
368        self
369    }
370
371    /// Shows only the given levels.
372    pub fn with_levels(mut self, levels: impl IntoIterator<Item = Level>) -> Self {
373        self.shown = [false; 5];
374        for level in levels {
375            self.shown[level.index()] = true;
376        }
377        self.refilter();
378        self
379    }
380
381    /// Starts with long lines wrapped.
382    pub fn with_wrap(mut self, wrap: bool) -> Self {
383        self.wrap = wrap;
384        self
385    }
386
387    /// Replaces [`SEARCH_ID`], so several logs on one screen each focus
388    /// their own field.
389    pub fn with_search_id(mut self, id: impl Into<widget::Id>) -> Self {
390        self.search_id = id.into();
391        self
392    }
393
394    /// Appends entries straight away, as the channel does.
395    pub fn extend(&mut self, entries: impl IntoIterator<Item = Entry>) {
396        if self.paused {
397            self.pending.extend(entries);
398            let over = self.pending.len().saturating_sub(self.limit);
399            self.pending.drain(..over);
400            return;
401        }
402        for entry in entries {
403            self.append(entry);
404        }
405        self.trim();
406        self.sync_levels();
407    }
408
409    /// Every kept entry, oldest first, whether shown or not.
410    pub fn entries(&self) -> impl Iterator<Item = &Entry> {
411        self.entries.iter()
412    }
413
414    /// How many entries are kept.
415    pub fn len(&self) -> usize {
416        self.entries.len()
417    }
418
419    pub fn is_empty(&self) -> bool {
420        self.entries.is_empty()
421    }
422
423    pub fn limit(&self) -> usize {
424        self.limit
425    }
426
427    /// The entry with `id`, if it is still kept.
428    pub fn entry(&self, id: LineId) -> Option<&Entry> {
429        let index = usize::try_from(id.checked_sub(self.first)?).ok()?;
430        self.entries.get(index)
431    }
432
433    /// The ids of the lines shown, oldest first.
434    pub fn visible(&self) -> impl Iterator<Item = LineId> + '_ {
435        self.visible.iter().copied()
436    }
437
438    /// How many lines are shown.
439    pub fn visible_len(&self) -> usize {
440        self.visible.len()
441    }
442
443    /// How many kept entries have this level.
444    pub fn count(&self, level: Level) -> usize {
445        self.counts[level.index()]
446    }
447
448    pub fn is_shown(&self, level: Level) -> bool {
449        self.shown[level.index()]
450    }
451
452    /// The level filters as a multiple-choice toggle group, each labelled
453    /// with its level's count.
454    pub fn levels(&self) -> &toggle_group::State<Level> {
455        &self.levels
456    }
457
458    pub fn query(&self) -> &str {
459        &self.query
460    }
461
462    /// The shown lines whose message matches the search, oldest first.
463    pub fn matches(&self) -> impl Iterator<Item = LineId> + '_ {
464        self.matches.iter().copied()
465    }
466
467    pub fn match_count(&self) -> usize {
468        self.matches.len()
469    }
470
471    /// The match the search last moved to, and its position counted from
472    /// one, if it is still shown.
473    pub fn current_match(&self) -> Option<(LineId, usize)> {
474        let id = self.current?;
475        let position = self.matches.binary_search(&id).ok()?;
476        Some((id, position + 1))
477    }
478
479    pub fn is_selected(&self, id: LineId) -> bool {
480        self.selected.contains(&id)
481    }
482
483    /// The selected lines that are shown, oldest first.
484    pub fn selected(&self) -> Vec<LineId> {
485        self.selected
486            .iter()
487            .copied()
488            .filter(|id| self.position(*id).is_some())
489            .collect()
490    }
491
492    /// The line the keyboard acts on.
493    pub fn highlighted(&self) -> Option<LineId> {
494        self.highlighted.filter(|id| self.position(*id).is_some())
495    }
496
497    pub fn is_focused(&self) -> bool {
498        self.focused
499    }
500
501    pub fn is_following(&self) -> bool {
502        self.following
503    }
504
505    pub fn is_paused(&self) -> bool {
506        self.paused
507    }
508
509    /// Entries held back while paused.
510    pub fn pending(&self) -> usize {
511        self.pending.len()
512    }
513
514    /// Lines that arrived since the log stopped following.
515    pub fn unseen(&self) -> usize {
516        self.unseen
517    }
518
519    pub fn is_wrapped(&self) -> bool {
520        self.wrap
521    }
522
523    pub fn search_id(&self) -> &widget::Id {
524        &self.search_id
525    }
526
527    /// Whether there is anything to copy: a shown selected line or a
528    /// highlight.
529    pub fn can_copy(&self) -> bool {
530        self.highlighted().is_some() || self.selected.iter().any(|&id| self.position(id).is_some())
531    }
532
533    /// The selected lines as text, one per line, or the highlighted line
534    /// when nothing is selected.
535    pub fn copy_text(&self) -> Option<String> {
536        let mut ids = self.selected();
537        if ids.is_empty() {
538            ids.extend(self.highlighted());
539        }
540        if ids.is_empty() {
541            return None;
542        }
543        let lines: Vec<String> = ids
544            .into_iter()
545            .filter_map(|id| self.entry(id).map(Entry::line))
546            .collect();
547        Some(lines.join("\n"))
548    }
549
550    /// Applies an event and returns what the app may need to act on.
551    pub fn update(&mut self, event: Event) -> Option<Output> {
552        match event {
553            Event::Ready(sender) => return Some(Output::Ready(sender)),
554            Event::Received(entries) => self.extend(entries),
555            Event::Press(id, modifiers) => self.press(id, modifiers),
556            Event::Search(query) => {
557                self.query = query;
558                self.current = None;
559                self.rematch();
560                self.jump_nearest();
561            }
562            Event::NextMatch => self.jump(true),
563            Event::PreviousMatch => self.jump(false),
564            Event::ClearSearch => {
565                self.query.clear();
566                self.current = None;
567                self.matches.clear();
568            }
569            Event::FocusSearch => return Some(Output::FocusSearch),
570            Event::ToggleLevel(level) => {
571                self.shown[level.index()] = !self.shown[level.index()];
572                self.refilter();
573            }
574            Event::Levels(event) => {
575                if self.levels.update(event).is_some() {
576                    for level in Level::ALL {
577                        self.shown[level.index()] = self.levels.is_selected(level);
578                    }
579                    self.refilter();
580                }
581            }
582            Event::FilterToLevel(id) => {
583                let level = self.entry(id)?.level;
584                self.shown = [false; 5];
585                self.shown[level.index()] = true;
586                self.refilter();
587            }
588            Event::ToggleWrap => self.wrap = !self.wrap,
589            Event::TogglePause => self.toggle_pause(),
590            Event::Clear => self.clear(),
591            Event::CopySelection => return self.copy_text().map(Output::Copy),
592            Event::CopyLine(id) => return self.entry(id).map(|entry| Output::Copy(entry.line())),
593            Event::CopyMessage(id) => {
594                return self
595                    .entry(id)
596                    .map(|entry| Output::Copy(entry.message.clone()));
597            }
598            Event::ToggleHighlighted => {
599                let id = self.highlighted()?;
600                self.press(id, Modifiers::COMMAND);
601            }
602            Event::Follow(follow) => self.follow(follow),
603            Event::Next => self.step(Step::Next),
604            Event::Previous => self.step(Step::Previous),
605            Event::First => self.step(Step::First),
606            Event::Last => {
607                self.step(Step::Last);
608                self.follow(true);
609            }
610            Event::NextPage => self.step(Step::NextPage),
611            Event::PreviousPage => self.step(Step::PreviousPage),
612            Event::ExtendNext => self.extend_selection(Step::Next),
613            Event::ExtendPrevious => self.extend_selection(Step::Previous),
614            Event::SelectAll => self.selected = self.visible.iter().copied().collect(),
615            Event::Page(lines) => self.page = lines.max(1),
616            Event::Focus(focused) => {
617                self.focused = focused;
618                // Focus lands on the newest line while following, or the
619                // first selected. It does not scroll.
620                if focused && self.highlighted().is_none() {
621                    let start = if self.following {
622                        self.visible.back()
623                    } else {
624                        self.visible.front()
625                    };
626                    self.highlighted = self.selected().first().or(start).copied();
627                }
628            }
629        }
630        None
631    }
632
633    /// Turns a key press into an event through `keymap`.
634    pub fn key_event(&self, keymap: &Keymap<Action>, key: &keys::Event) -> Option<Event> {
635        keymap.resolve_event(key)?.event(self)
636    }
637
638    /// Where a line sits among the shown lines.
639    fn position(&self, id: LineId) -> Option<usize> {
640        self.visible.binary_search(&id).ok()
641    }
642
643    fn matches_query(&self, entry: &Entry) -> bool {
644        !self.query.is_empty() && !find(&entry.message, &self.query).is_empty()
645    }
646
647    fn append(&mut self, entry: Entry) {
648        let id = self.first + self.entries.len() as u64;
649        self.counts[entry.level.index()] += 1;
650        if self.shown[entry.level.index()] {
651            self.visible.push_back(id);
652            if self.matches_query(&entry) {
653                self.matches.push_back(id);
654            }
655            if !self.following {
656                self.unseen += 1;
657            }
658        }
659        self.entries.push_back(entry);
660    }
661
662    /// Drops the oldest entries over the limit, and forgets them.
663    fn trim(&mut self) {
664        while self.entries.len() > self.limit {
665            let Some(entry) = self.entries.pop_front() else {
666                break;
667            };
668            let id = self.first;
669            self.first += 1;
670            self.counts[entry.level.index()] -= 1;
671            if self.visible.front() == Some(&id) {
672                let _ = self.visible.pop_front();
673                self.visible_dropped += 1;
674            }
675            if self.matches.front() == Some(&id) {
676                let _ = self.matches.pop_front();
677            }
678        }
679        let first = self.first;
680        self.selected = self.selected.split_off(&first);
681        let gone = |id: &LineId| *id < first;
682        if self.highlighted.as_ref().is_some_and(gone) {
683            self.highlighted = None;
684        }
685        if self.anchor.as_ref().is_some_and(gone) {
686            self.anchor = None;
687        }
688        if self.current.as_ref().is_some_and(gone) {
689            self.current = None;
690        }
691        if self.reveal.as_ref().is_some_and(|(id, _)| gone(id)) {
692            self.reveal = None;
693        }
694    }
695
696    /// Rebuilds the shown lines after the level filter changed, dropping
697    /// hidden lines from the selection.
698    fn refilter(&mut self) {
699        let first = self.first;
700        self.visible = self
701            .entries
702            .iter()
703            .enumerate()
704            .filter(|(_, entry)| self.shown[entry.level.index()])
705            .map(|(index, _)| first + index as u64)
706            .collect();
707        let visible: BTreeSet<LineId> = self.visible.iter().copied().collect();
708        self.selected.retain(|id| visible.contains(id));
709        self.sync_levels();
710        self.rematch();
711        if let Some(id) = self.highlighted() {
712            self.reveal_line(id);
713        }
714    }
715
716    /// Rebuilds the matches after the search or the filter changed.
717    fn rematch(&mut self) {
718        self.matches = self
719            .visible
720            .iter()
721            .copied()
722            .filter(|&id| {
723                self.entry(id)
724                    .is_some_and(|entry| self.matches_query(entry))
725            })
726            .collect();
727    }
728
729    fn clear(&mut self) {
730        self.first += self.entries.len() as u64;
731        self.entries.clear();
732        self.counts = [0; 5];
733        self.visible.clear();
734        self.matches.clear();
735        self.current = None;
736        self.selected.clear();
737        self.anchor = None;
738        self.highlighted = None;
739        self.reveal = None;
740        self.pending.clear();
741        self.unseen = 0;
742        self.following = true;
743        self.sync_levels();
744    }
745
746    /// Relabels the level filters with the current counts.
747    fn sync_levels(&mut self) {
748        self.levels = level_filters(&self.counts, &self.shown);
749    }
750
751    fn follow(&mut self, follow: bool) {
752        self.following = follow;
753        if follow {
754            self.unseen = 0;
755        }
756    }
757
758    fn toggle_pause(&mut self) {
759        if !self.paused {
760            self.paused = true;
761            return;
762        }
763        self.paused = false;
764        let pending = std::mem::take(&mut self.pending);
765        self.extend(pending);
766    }
767
768    fn reveal_line(&mut self, id: LineId) {
769        self.requests += 1;
770        self.reveal = Some((id, self.requests));
771    }
772
773    /// The row to keep in view and its request count, for the view.
774    fn reveal_target(&self) -> Option<(usize, u64)> {
775        let (id, request) = self.reveal?;
776        Some((self.position(id)?, request))
777    }
778
779    /// Highlights a line, scrolls it into view and follows only when it is
780    /// the newest.
781    fn move_to(&mut self, id: LineId) {
782        self.highlighted = Some(id);
783        self.reveal_line(id);
784        self.follow(self.visible.back() == Some(&id));
785    }
786
787    fn step(&mut self, step: Step) {
788        let current = self.highlighted().and_then(|id| self.position(id));
789        let Some(index) = target(step, current, self.visible.len(), self.page) else {
790            return;
791        };
792        if let Some(&id) = self.visible.get(index) {
793            self.move_to(id);
794        }
795    }
796
797    /// Moves to the next or previous match after the current one, or the
798    /// highlighted line, wrapping around at the ends.
799    fn jump(&mut self, forward: bool) {
800        let from = self
801            .current_match()
802            .map(|(id, _)| id)
803            .or(self.highlighted());
804        let next = match (forward, from) {
805            (true, Some(from)) => {
806                let after = self.matches.partition_point(|&id| id <= from);
807                self.matches.get(after).or(self.matches.front())
808            }
809            (true, None) => self.matches.front(),
810            (false, Some(from)) => {
811                let before = self.matches.partition_point(|&id| id < from);
812                before
813                    .checked_sub(1)
814                    .and_then(|index| self.matches.get(index))
815                    .or(self.matches.back())
816            }
817            (false, None) => self.matches.back(),
818        };
819        let Some(&id) = next else {
820            return;
821        };
822        self.current = Some(id);
823        self.move_to(id);
824    }
825
826    /// Moves to the match nearest the highlight: the first at or after it,
827    /// or else the last before it. Without a highlight it takes the newest
828    /// match while following, as the newest lines are in view, and the
829    /// oldest otherwise.
830    fn jump_nearest(&mut self) {
831        let nearest = match self.highlighted() {
832            Some(from) => {
833                let at = self.matches.partition_point(|&id| id < from);
834                self.matches.get(at).or(self.matches.back())
835            }
836            None if self.following => self.matches.back(),
837            None => self.matches.front(),
838        };
839        let Some(&id) = nearest else {
840            return;
841        };
842        self.current = Some(id);
843        self.move_to(id);
844    }
845
846    fn press(&mut self, id: LineId, modifiers: Modifiers) {
847        if self.position(id).is_none() {
848            return;
849        }
850        self.highlighted = Some(id);
851        if self.visible.back() != Some(&id) {
852            self.follow(false);
853        }
854        match (modifiers.shift(), modifiers.command(), self.anchor) {
855            (true, additive, Some(anchor)) => {
856                if !additive {
857                    self.selected.clear();
858                }
859                self.selected.extend(self.range(anchor, id));
860            }
861            (_, true, _) => {
862                if !self.selected.remove(&id) {
863                    let _ = self.selected.insert(id);
864                }
865                self.anchor = Some(id);
866            }
867            _ => {
868                self.selected = BTreeSet::from([id]);
869                self.anchor = Some(id);
870            }
871        }
872    }
873
874    /// The shown lines from `a` to `b`, in either order.
875    fn range(&self, a: LineId, b: LineId) -> Vec<LineId> {
876        let (Some(start), Some(end)) = (self.position(a), self.position(b)) else {
877            return vec![b];
878        };
879        let (start, end) = (start.min(end), start.max(end));
880        self.visible.range(start..=end).copied().collect()
881    }
882
883    fn extend_selection(&mut self, step: Step) {
884        let anchor = self.anchor.or(self.highlighted());
885        self.step(step);
886        let (Some(anchor), Some(highlighted)) = (anchor, self.highlighted()) else {
887            return;
888        };
889        self.anchor = Some(anchor);
890        self.selected = self.range(anchor, highlighted).into_iter().collect();
891    }
892}
893
894/// The level filters for these counts, with the shown levels on.
895fn level_filters(counts: &[usize; 5], shown: &[bool; 5]) -> toggle_group::State<Level> {
896    let items = Level::ALL.map(|level| {
897        let label = format!("{} {}", level.name(), counts[level.index()]);
898        toggle_group::item(level, label)
899    });
900    toggle_group::State::multiple(items)
901        .with_selected(Level::ALL.into_iter().filter(|level| shown[level.index()]))
902}
903
904/// What a log keyboard shortcut does.
905#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
906pub enum Action {
907    Next,
908    Previous,
909    First,
910    Last,
911    NextPage,
912    PreviousPage,
913    ExtendNext,
914    ExtendPrevious,
915    Select,
916    SelectAll,
917    CopySelection,
918    FocusSearch,
919    NextMatch,
920    PreviousMatch,
921    ClearSearch,
922    TogglePause,
923    ToggleWrap,
924    Clear,
925}
926
927impl Action {
928    /// The [`Event`] this action sends to `state`, or `None` when it does
929    /// nothing, so the key is left for others.
930    pub fn event(self, state: &State) -> Option<Event> {
931        let lines = state.visible_len() > 0;
932        match self {
933            Action::Select => state.highlighted().map(|_| Event::ToggleHighlighted),
934            Action::Next => lines.then_some(Event::Next),
935            Action::Previous => lines.then_some(Event::Previous),
936            Action::First => lines.then_some(Event::First),
937            Action::Last => Some(Event::Last),
938            Action::NextPage => lines.then_some(Event::NextPage),
939            Action::PreviousPage => lines.then_some(Event::PreviousPage),
940            Action::ExtendNext => lines.then_some(Event::ExtendNext),
941            Action::ExtendPrevious => lines.then_some(Event::ExtendPrevious),
942            Action::SelectAll => lines.then_some(Event::SelectAll),
943            Action::CopySelection => state.can_copy().then_some(Event::CopySelection),
944            Action::FocusSearch => Some(Event::FocusSearch),
945            Action::NextMatch => (state.match_count() > 0).then_some(Event::NextMatch),
946            Action::PreviousMatch => (state.match_count() > 0).then_some(Event::PreviousMatch),
947            Action::ClearSearch => (!state.query().is_empty()).then_some(Event::ClearSearch),
948            Action::TogglePause => Some(Event::TogglePause),
949            Action::ToggleWrap => Some(Event::ToggleWrap),
950            Action::Clear => (!state.is_empty()).then_some(Event::Clear),
951        }
952    }
953}
954
955impl keys::Action for Action {
956    const ALL: &'static [Self] = &[
957        Action::Next,
958        Action::Previous,
959        Action::First,
960        Action::Last,
961        Action::NextPage,
962        Action::PreviousPage,
963        Action::ExtendNext,
964        Action::ExtendPrevious,
965        Action::Select,
966        Action::SelectAll,
967        Action::CopySelection,
968        Action::FocusSearch,
969        Action::NextMatch,
970        Action::PreviousMatch,
971        Action::ClearSearch,
972        Action::TogglePause,
973        Action::ToggleWrap,
974        Action::Clear,
975    ];
976
977    fn defaults() -> Keymap<Self> {
978        default_keymap()
979    }
980
981    fn name(self) -> &'static str {
982        match self {
983            Action::Next => "Next",
984            Action::Previous => "Previous",
985            Action::First => "First",
986            Action::Last => "Last",
987            Action::NextPage => "NextPage",
988            Action::PreviousPage => "PreviousPage",
989            Action::ExtendNext => "ExtendNext",
990            Action::ExtendPrevious => "ExtendPrevious",
991            Action::Select => "Select",
992            Action::SelectAll => "SelectAll",
993            Action::CopySelection => "CopySelection",
994            Action::FocusSearch => "FocusSearch",
995            Action::NextMatch => "NextMatch",
996            Action::PreviousMatch => "PreviousMatch",
997            Action::ClearSearch => "ClearSearch",
998            Action::TogglePause => "TogglePause",
999            Action::ToggleWrap => "ToggleWrap",
1000            Action::Clear => "Clear",
1001        }
1002    }
1003
1004    fn description(self) -> &'static str {
1005        match self {
1006            Action::Next => "Highlights the next line.",
1007            Action::Previous => "Highlights the previous line.",
1008            Action::First => "Highlights the oldest line.",
1009            Action::Last => "Jumps to the newest line and follows new ones.",
1010            Action::NextPage => "Moves the highlight down by a page of lines.",
1011            Action::PreviousPage => "Moves the highlight up by a page of lines.",
1012            Action::ExtendNext => "Moves down and extends the selection.",
1013            Action::ExtendPrevious => "Moves up and extends the selection.",
1014            Action::Select => "Selects or deselects the highlighted line.",
1015            Action::SelectAll => "Selects every shown line.",
1016            Action::CopySelection => "Copies the selected lines, or the highlighted one.",
1017            Action::FocusSearch => "Focuses the search field.",
1018            Action::NextMatch => "Moves to the next line matching the search.",
1019            Action::PreviousMatch => "Moves to the previous line matching the search.",
1020            Action::ClearSearch => "Clears the search.",
1021            Action::TogglePause => "Pauses the stream, or resumes it with the held lines.",
1022            Action::ToggleWrap => "Wraps long lines, or ends them in an ellipsis.",
1023            Action::Clear => "Removes every line.",
1024        }
1025    }
1026}
1027
1028/// The default log shortcuts:
1029///
1030/// | Keys | Action |
1031/// | --- | --- |
1032/// | `ArrowDown` | [`Action::Next`] |
1033/// | `ArrowUp` | [`Action::Previous`] |
1034/// | `Home` | [`Action::First`] |
1035/// | `End` | [`Action::Last`] |
1036/// | `PageDown` | [`Action::NextPage`] |
1037/// | `PageUp` | [`Action::PreviousPage`] |
1038/// | `Shift+ArrowDown` | [`Action::ExtendNext`] |
1039/// | `Shift+ArrowUp` | [`Action::ExtendPrevious`] |
1040/// | `Space` | [`Action::Select`] |
1041/// | `Mod+A` (Ctrl, or Cmd on macOS) | [`Action::SelectAll`] |
1042/// | `Mod+C` | [`Action::CopySelection`] |
1043/// | `Mod+F` | [`Action::FocusSearch`] |
1044/// | `F3` | [`Action::NextMatch`] |
1045/// | `Shift+F3` | [`Action::PreviousMatch`] |
1046/// | `Escape` | [`Action::ClearSearch`] |
1047/// | `Ctrl+L` | [`Action::Clear`] |
1048///
1049/// The log resolves these itself, only while it has focus, which it takes
1050/// when any part of it is pressed. Keys the search field uses, such as
1051/// typing, Home and End, stay with the field. While the field has focus,
1052/// Enter and F3 step to the next match and Shift+Enter and Shift+F3 to the
1053/// previous one, Mod+F selects its text, and Escape clears the text, then
1054/// a second Escape leaves the field. [`Action::TogglePause`]
1055/// and [`Action::ToggleWrap`] are on the toolbar and have no chord until
1056/// one is bound. Pass a changed keymap with [`LogViewer::keymap`].
1057pub fn default_keymap() -> Keymap<Action> {
1058    Keymap::new()
1059        .bind(Chord::named(Named::ArrowDown), Action::Next)
1060        .bind(Chord::named(Named::ArrowUp), Action::Previous)
1061        .bind(Chord::named(Named::Home), Action::First)
1062        .bind(Chord::named(Named::End), Action::Last)
1063        .bind(Chord::named(Named::PageDown), Action::NextPage)
1064        .bind(Chord::named(Named::PageUp), Action::PreviousPage)
1065        .bind(Chord::named(Named::ArrowDown).shift(), Action::ExtendNext)
1066        .bind(Chord::named(Named::ArrowUp).shift(), Action::ExtendPrevious)
1067        .bind(Chord::named(Named::Space), Action::Select)
1068        .bind(Chord::character('a').command(), Action::SelectAll)
1069        .bind(Chord::character('c').command(), Action::CopySelection)
1070        .bind(Chord::character('f').command(), Action::FocusSearch)
1071        .bind(Chord::named(Named::F3), Action::NextMatch)
1072        .bind(Chord::named(Named::F3).shift(), Action::PreviousMatch)
1073        .bind(Chord::named(Named::Escape), Action::ClearSearch)
1074        .bind(Chord::character('l').ctrl(), Action::Clear)
1075}
1076
1077/// Owns the channel entries arrive on. Emits [`Event::Ready`] first, then
1078/// batches of up to [`BATCH_SIZE`] entries.
1079pub fn subscription() -> Subscription<Event> {
1080    Subscription::run(stream)
1081}
1082
1083/// The stream behind [`subscription`], for driving it without a runtime.
1084pub fn stream() -> impl Stream<Item = Event> {
1085    let (sender, receiver) = mpsc::channel(CHANNEL_CAPACITY);
1086    stream::once(async move { Event::Ready(sender) })
1087        .chain(receiver.ready_chunks(BATCH_SIZE).map(Event::Received))
1088}
1089
1090/// Focuses the search field of `state`'s log.
1091pub fn focus_search<T>(state: &State) -> Task<T> {
1092    widget::operation::focus(state.search_id.clone())
1093}
1094
1095/// The text beside the search field: "3 of 12" for the current match of
1096/// all matches, "12 found" before one is current, "None" when nothing
1097/// matches, and empty without a search.
1098pub fn match_label(state: &State) -> String {
1099    let current = state.current_match().map(|(_, position)| position);
1100    match_count_label(state.query(), state.match_count(), current)
1101}
1102
1103/// An entry of the context menu from [`menu`].
1104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1105pub enum MenuItem {
1106    CopyLine,
1107    CopyMessage,
1108    FilterToLevel,
1109}
1110
1111impl MenuItem {
1112    pub const ALL: [MenuItem; 3] = [
1113        MenuItem::CopyLine,
1114        MenuItem::CopyMessage,
1115        MenuItem::FilterToLevel,
1116    ];
1117
1118    /// The event the entry sends for the line the menu opened on.
1119    pub fn event(self, id: LineId) -> Event {
1120        match self {
1121            MenuItem::CopyLine => Event::CopyLine(id),
1122            MenuItem::CopyMessage => Event::CopyMessage(id),
1123            MenuItem::FilterToLevel => Event::FilterToLevel(id),
1124        }
1125    }
1126}
1127
1128/// A context menu to pass to [`LogViewer::context_menu`]: copy the line or
1129/// only its message, or show only lines of its level. Turn the chosen entry
1130/// into an event with [`MenuItem::event`].
1131pub fn menu() -> context_menu::State<MenuItem, LineId> {
1132    context_menu::State::new([
1133        item(MenuItem::CopyLine, "Copy line").icon(crate::lucide!(Copy)),
1134        item(MenuItem::CopyMessage, "Copy message").icon(crate::lucide!(TextQuote)),
1135        separator(),
1136        item(MenuItem::FilterToLevel, "Show only this level").icon(crate::lucide!(ListFilter)),
1137    ])
1138}
1139
1140/// The colour of a level's tag.
1141pub fn level_colour(tokens: &Tokens, level: Level) -> Color {
1142    // Bright status colours are darkened on light backgrounds so the small
1143    // tag stays readable.
1144    let legible = |colour: Color| {
1145        if tokens.is_dark {
1146            colour
1147        } else {
1148            mix(colour, tokens.foreground, 0.25)
1149        }
1150    };
1151    match level {
1152        Level::Trace => fade(tokens.muted_foreground, 0.7),
1153        Level::Debug => tokens.muted_foreground,
1154        Level::Info => legible(tokens.success),
1155        Level::Warn => legible(tokens.warning),
1156        Level::Error => legible(tokens.destructive),
1157    }
1158}
1159
1160/// How a line is shown.
1161pub type Status = virtual_list::Status;
1162
1163/// The colours of a line.
1164#[derive(Debug, Clone, Copy, PartialEq)]
1165pub struct LineStyle {
1166    pub background: Option<Color>,
1167    /// The ring around the line carrying the keyboard highlight.
1168    pub ring: Option<Color>,
1169    pub text: Color,
1170    /// Behind the parts of the message that match the search.
1171    pub mark: Color,
1172}
1173
1174/// Resolves a line's colours. Lines take the list rows' colours, with the
1175/// accent's text on a selected line, and an error line is tinted when
1176/// nothing else colours it. The current match is marked more strongly than
1177/// the others.
1178pub fn line_style(tokens: &Tokens, level: Level, current: bool, status: Status) -> LineStyle {
1179    let row = virtual_list::row_style(tokens, status);
1180    let tint = (level == Level::Error)
1181        .then(|| fade(tokens.destructive, if tokens.is_dark { 0.14 } else { 0.07 }));
1182    let selected = status.selected && !status.disabled;
1183    LineStyle {
1184        background: row.background.or(tint),
1185        ring: row.ring,
1186        text: if selected {
1187            tokens.accent_foreground
1188        } else {
1189            tokens.foreground
1190        },
1191        mark: fade(tokens.warning, if current { 0.7 } else { 0.35 }),
1192    }
1193}
1194
1195type OnEvent<'a, Message> = dyn Fn(Event) -> Message + 'a;
1196type BuildMenu<'a, Message> =
1197    dyn FnOnce(Keymap<context_menu::Action>) -> RowMenu<'a, LineId, Message> + 'a;
1198
1199/// A log viewer builder. Convert it into an [`Element`] to render.
1200pub struct LogViewer<'a, Message> {
1201    state: &'a State,
1202    width: Length,
1203    height: Length,
1204    toolbar: bool,
1205    placeholder: String,
1206    empty: String,
1207    keymap: Keymap<Action>,
1208    shortcuts: Shortcuts,
1209    menu: Option<Box<BuildMenu<'a, Message>>>,
1210    menu_keymap: Keymap<context_menu::Action>,
1211    on_event: Option<Box<OnEvent<'a, Message>>>,
1212}
1213
1214/// Renders `state`: a toolbar with the search, level filters and actions,
1215/// above the lines. Without [`on_event`](LogViewer::on_event) everything
1216/// renders disabled.
1217pub fn log_viewer<'a, Message>(state: &'a State) -> LogViewer<'a, Message> {
1218    LogViewer {
1219        state,
1220        width: Length::Fill,
1221        height: Length::Fill,
1222        toolbar: true,
1223        placeholder: "Search messages".to_owned(),
1224        empty: "No log lines yet".to_owned(),
1225        keymap: default_keymap(),
1226        shortcuts: Shortcuts::all(),
1227        menu: None,
1228        menu_keymap: context_menu::default_keymap(),
1229        on_event: None,
1230    }
1231}
1232
1233impl<Message> fmt::Debug for LogViewer<'_, Message> {
1234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1235        f.debug_struct("LogViewer")
1236            .field("lines", &self.state.visible_len())
1237            .field("width", &self.width)
1238            .field("height", &self.height)
1239            .field("toolbar", &self.toolbar)
1240            .field("placeholder", &self.placeholder)
1241            .field("empty", &self.empty)
1242            .field("keymap", &self.keymap)
1243            .finish_non_exhaustive()
1244    }
1245}
1246
1247impl<'a, Message> LogViewer<'a, Message> {
1248    pub fn width(mut self, width: impl Into<Length>) -> Self {
1249        self.width = width.into();
1250        self
1251    }
1252
1253    /// The height of the whole log, toolbar included. Fills by default.
1254    pub fn height(mut self, height: impl Into<Length>) -> Self {
1255        self.height = height.into();
1256        self
1257    }
1258
1259    /// Shows or hides the toolbar. Its actions stay on the keyboard.
1260    pub fn toolbar(mut self, toolbar: bool) -> Self {
1261        self.toolbar = toolbar;
1262        self
1263    }
1264
1265    /// The search field's placeholder.
1266    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
1267        self.placeholder = placeholder.into();
1268        self
1269    }
1270
1271    /// What shows while no lines are shown.
1272    pub fn empty(mut self, message: impl Into<String>) -> Self {
1273        self.empty = message.into();
1274        self
1275    }
1276
1277    /// Replaces the [`default_keymap`] the focused log resolves keys with.
1278    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
1279        self.keymap = keymap;
1280        self
1281    }
1282
1283    /// Sets which editing [`Shortcut`](input::Shortcut)s the search field
1284    /// handles. All of them by default.
1285    pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
1286        self.shortcuts = shortcuts;
1287        self
1288    }
1289
1290    pub fn on_event(mut self, on_event: impl Fn(Event) -> Message + 'a) -> Self {
1291        self.on_event = Some(Box::new(on_event));
1292        self
1293    }
1294
1295    /// Gives every line the context menu of `menu`, keyed by line, such as
1296    /// the one from [`menu()`]. It opens on a right-click or a long press,
1297    /// and on the highlighted line with its opening chord while the log has
1298    /// focus.
1299    pub fn context_menu<MenuId>(
1300        mut self,
1301        menu: &'a context_menu::State<MenuId, LineId>,
1302        on_event: impl Fn(context_menu::Event<MenuId, LineId>) -> Message + 'a,
1303    ) -> Self
1304    where
1305        MenuId: Copy + PartialEq + 'a,
1306        Message: Clone + 'a,
1307    {
1308        let on_event: Rc<dyn Fn(context_menu::Event<MenuId, LineId>) -> Message + 'a> =
1309            Rc::new(on_event);
1310        self.menu = Some(Box::new(move |keymap| row_menu(menu, keymap, on_event)));
1311        self
1312    }
1313
1314    /// Replaces the context menu's default keymap.
1315    pub fn context_menu_keymap(mut self, keymap: Keymap<context_menu::Action>) -> Self {
1316        self.menu_keymap = keymap;
1317        self
1318    }
1319
1320    pub fn is_enabled(&self) -> bool {
1321        self.on_event.is_some()
1322    }
1323}
1324
1325impl<'a, Message> From<LogViewer<'a, Message>> for Element<'a, Message>
1326where
1327    Message: Clone + 'a,
1328{
1329    fn from(viewer: LogViewer<'a, Message>) -> Self {
1330        let LogViewer {
1331            state,
1332            width,
1333            height,
1334            toolbar,
1335            placeholder,
1336            empty,
1337            keymap,
1338            shortcuts,
1339            menu,
1340            menu_keymap,
1341            on_event,
1342        } = viewer;
1343        let on_event: Option<Rc<OnEvent<'a, Message>>> = on_event.map(Rc::from);
1344        let menu = menu
1345            .filter(|_| on_event.is_some())
1346            .map(|build| Rc::new(build(menu_keymap)));
1347        let view = Rc::new(View {
1348            state,
1349            toolbar,
1350            placeholder,
1351            empty,
1352            shortcuts,
1353            menu: menu.clone(),
1354            on_event: on_event.clone(),
1355        });
1356        let body = responsive(move |size| view.body(size.width < BREAKPOINT))
1357            .width(width)
1358            .height(height);
1359
1360        let Some(on_event) = on_event else {
1361            return body.into();
1362        };
1363        let on_focus = on_event.clone();
1364        scope(body)
1365            .on_focus(move |focused| on_focus(Event::Focus(focused)))
1366            .on_key(move |key| {
1367                let opened = menu
1368                    .as_ref()
1369                    .zip(state.highlighted())
1370                    .and_then(|(menu, target)| menu.key(key, target));
1371                opened.or_else(|| state.key_event(&keymap, key).map(&*on_event))
1372            })
1373            .into()
1374    }
1375}
1376
1377/// Everything the log's parts are built from.
1378struct View<'a, Message> {
1379    state: &'a State,
1380    toolbar: bool,
1381    placeholder: String,
1382    empty: String,
1383    shortcuts: Shortcuts,
1384    menu: Option<Rc<RowMenu<'a, LineId, Message>>>,
1385    on_event: Option<Rc<OnEvent<'a, Message>>>,
1386}
1387
1388fn muted(theme: &Theme) -> Color {
1389    Tokens::of(theme).muted_foreground
1390}
1391
1392impl<'a, Message: Clone + 'a> View<'a, Message> {
1393    fn send(&self, event: Event) -> Option<Message> {
1394        self.on_event.as_ref().map(|on_event| on_event(event))
1395    }
1396
1397    fn body(&self, narrow: bool) -> Element<'a, Message> {
1398        let mut parts = column![].spacing(space::SM).height(Length::Fill);
1399        if self.toolbar {
1400            parts = parts.push(self.toolbar(narrow));
1401        }
1402        parts.push(self.lines(narrow)).into()
1403    }
1404
1405    fn toolbar(&self, narrow: bool) -> Element<'a, Message> {
1406        let state = self.state;
1407        let has_matches = state.match_count() > 0;
1408        let field = input(&self.placeholder, state.query())
1409            .id(state.search_id.clone())
1410            .icon(crate::lucide!(Search))
1411            .shortcuts(self.shortcuts)
1412            .size(input::Size::Sm)
1413            .width(if narrow {
1414                Length::Fill
1415            } else {
1416                Length::Fixed(240.0)
1417            })
1418            .on_input_maybe(
1419                self.on_event
1420                    .clone()
1421                    .map(|on_event| move |query| on_event(Event::Search(query))),
1422            );
1423        let search = search_keys(field, state.search_id.clone())
1424            .on_clear(
1425                self.send(Event::ClearSearch)
1426                    .filter(|_| !state.query().is_empty()),
1427            )
1428            .on_next(self.send(Event::NextMatch).filter(|_| has_matches))
1429            .on_previous(self.send(Event::PreviousMatch).filter(|_| has_matches));
1430        let found = search_count(match_label(state));
1431        let previous = icon_button(crate::lucide!(ChevronUp))
1432            .label("Previous match")
1433            .tooltip(Some(Position::Bottom))
1434            .size(button::Size::Sm)
1435            .on_press_maybe(self.send(Event::PreviousMatch).filter(|_| has_matches));
1436        let next = icon_button(crate::lucide!(ChevronDown))
1437            .label("Next match")
1438            .tooltip(Some(Position::Bottom))
1439            .size(button::Size::Sm)
1440            .on_press_maybe(self.send(Event::NextMatch).filter(|_| has_matches));
1441        let stepper = row![found, previous, next]
1442            .spacing(space::XS)
1443            .align_y(Alignment::Center);
1444
1445        let mut levels = toggle_group(&state.levels).size(toggle::Size::Sm);
1446        if let Some(on_event) = self.on_event.clone() {
1447            levels = levels.on_event(move |event| on_event(Event::Levels(event)));
1448        }
1449
1450        let can_copy = state.can_copy();
1451        let actions: [Element<'a, Message>; 4] = [
1452            icon_button(crate::lucide!(TextWrap))
1453                .label("Wrap lines")
1454                .tooltip(Some(Position::Bottom))
1455                .size(button::Size::Sm)
1456                .pressed(state.is_wrapped())
1457                .on_press_maybe(self.send(Event::ToggleWrap))
1458                .into(),
1459            icon_button(if state.is_paused() {
1460                crate::lucide!(Play)
1461            } else {
1462                crate::lucide!(Pause)
1463            })
1464            .label(if state.is_paused() { "Resume" } else { "Pause" })
1465            .tooltip(Some(Position::Bottom))
1466            .size(button::Size::Sm)
1467            .pressed(state.is_paused())
1468            .on_press_maybe(self.send(Event::TogglePause))
1469            .into(),
1470            icon_button(crate::lucide!(Copy))
1471                .label("Copy selected lines")
1472                .tooltip(Some(Position::Bottom))
1473                .size(button::Size::Sm)
1474                .on_press_maybe(self.send(Event::CopySelection).filter(|_| can_copy))
1475                .into(),
1476            icon_button(crate::lucide!(Trash))
1477                .label("Clear")
1478                .tooltip(Some(Position::Bottom))
1479                .size(button::Size::Sm)
1480                .on_press_maybe(self.send(Event::Clear).filter(|_| !state.is_empty()))
1481                .into(),
1482        ];
1483
1484        // Narrow, the search field, the filters and the actions each take a
1485        // row, the filters wrap, and the match stepper joins the actions so
1486        // the field keeps the full width.
1487        if narrow {
1488            let tools = row![
1489                row(actions).spacing(space::XS),
1490                Space::new().width(Length::Fill),
1491                stepper,
1492            ]
1493            .align_y(Alignment::Center);
1494            return column![search, levels, tools].spacing(space::SM).into();
1495        }
1496        column![
1497            row![
1498                search,
1499                stepper,
1500                Space::new().width(Length::Fill),
1501                row(actions).spacing(space::XS),
1502            ]
1503            .spacing(space::SM)
1504            .align_y(Alignment::Center),
1505            levels,
1506        ]
1507        .spacing(space::SM)
1508        .into()
1509    }
1510
1511    fn lines(&self, narrow: bool) -> Element<'a, Message> {
1512        let state = self.state;
1513        let frame = |content: Element<'a, Message>| {
1514            container(content)
1515                .padding(FRAME_PADDING)
1516                .width(Length::Fill)
1517                .height(Length::Fill)
1518                .style(|theme| virtual_list::frame_style(&Tokens::of(theme)))
1519        };
1520        if state.visible_len() == 0 {
1521            let message = text(self.empty.clone())
1522                .size(text_size::SM)
1523                .style(|theme| text::Style {
1524                    color: Some(muted(theme)),
1525                });
1526            return frame(container(message).center(Length::Fill).into()).into();
1527        }
1528
1529        let on_event = self.on_event.clone();
1530        let menu = self.menu.clone();
1531        let menu_target = menu.as_ref().and_then(|menu| menu.target());
1532        let wrap = state.is_wrapped();
1533        let build = move |range: std::ops::Range<usize>| -> Element<'a, Message> {
1534            column(range.filter_map(|index| {
1535                let id = *state.visible.get(index)?;
1536                let entry = state.entry(id)?;
1537                let ringed = ringed(
1538                    menu_target.as_ref(),
1539                    &id,
1540                    state.focused && state.highlighted == Some(id),
1541                );
1542                let line = line_view(state, id, entry, narrow, ringed, on_event.as_ref());
1543                let line = match &menu {
1544                    Some(menu) => menu.wrap(id, line),
1545                    None => line,
1546                };
1547                #[cfg(feature = "icedwright")]
1548                let line = icedwright_probe::semantic(line)
1549                    .role(icedwright_probe::role::ListItem)
1550                    .position(
1551                        u32::try_from(index + 1).unwrap_or(u32::MAX),
1552                        u32::try_from(state.visible_len()).unwrap_or(u32::MAX),
1553                    )
1554                    .click_clock(icedwright_probe::ClickClock::Probe)
1555                    .component("iced_cube::log_viewer")
1556                    .into();
1557                Some(line)
1558            }))
1559            .into()
1560        };
1561        let row_height = if narrow {
1562            STACKED_ROW_HEIGHT
1563        } else {
1564            ROW_HEIGHT
1565        };
1566        let mut list = rows(state.visible_len(), row_height, build)
1567            .reveal(state.reveal_target())
1568            .follow(state.is_following())
1569            .origin(state.visible_dropped)
1570            .height(Length::Fill);
1571        if wrap {
1572            list =
1573                list.measured(move |index| state.visible.get(index).copied().unwrap_or_default());
1574        }
1575        if let Some(on_event) = self.on_event.clone() {
1576            let on_page = on_event.clone();
1577            list = list
1578                .on_page(move |lines| on_page(Event::Page(lines)))
1579                .on_follow(move |follow| on_event(Event::Follow(follow)));
1580        }
1581
1582        // Below the lines, inside the frame, so the newest line stays in
1583        // view above it. The lines stay the column's first child whether
1584        // the pill shows or not, so they keep their scroll position.
1585        let pill = self.pill().map(|pill| -> Element<'a, Message> {
1586            container(pill)
1587                .align_right(Length::Fill)
1588                .padding(Padding::ZERO.top(FRAME_PADDING).right(space::XS))
1589                .into()
1590        });
1591        let list: Element<'a, Message> = list.into();
1592        #[cfg(feature = "icedwright")]
1593        let list = icedwright_probe::semantic(list)
1594            .role(icedwright_probe::role::List)
1595            .component("iced_cube::log_viewer")
1596            .into();
1597        frame(column(std::iter::once(list).chain(pill)).into()).into()
1598    }
1599
1600    /// A button under the lines: resume while paused, or jump to the newest
1601    /// line while not following.
1602    fn pill(&self) -> Option<Element<'a, Message>> {
1603        let state = self.state;
1604        if state.is_paused() {
1605            let label = match state.pending() {
1606                0 => "Resume".to_owned(),
1607                waiting => format!("Resume ({waiting} new)"),
1608            };
1609            let resume = button(label)
1610                .icon(crate::lucide!(Play))
1611                .size(button::Size::Sm)
1612                .variant(button::Variant::Secondary)
1613                .on_press_maybe(self.send(Event::TogglePause));
1614            return Some(resume.into());
1615        }
1616        if state.is_following() {
1617            return None;
1618        }
1619        let label = match state.unseen() {
1620            0 => "Jump to latest".to_owned(),
1621            unseen => format!("Jump to latest ({unseen} new)"),
1622        };
1623        let jump = button(label)
1624            .icon(crate::lucide!(ArrowDown))
1625            .size(button::Size::Sm)
1626            .variant(button::Variant::Secondary)
1627            .on_press_maybe(self.send(Event::Last));
1628        Some(jump.into())
1629    }
1630}
1631
1632/// One line: timestamp, level, target and the message with its matches
1633/// marked.
1634/// Below the breakpoint the message sits under the other parts, so it keeps
1635/// the full width.
1636fn line_view<'a, Message: Clone + 'a>(
1637    state: &'a State,
1638    id: LineId,
1639    entry: &'a Entry,
1640    stacked: bool,
1641    ringed: bool,
1642    on_event: Option<&Rc<OnEvent<'a, Message>>>,
1643) -> Element<'a, Message> {
1644    let status = Status {
1645        selected: state.selected.contains(&id),
1646        hovered: false,
1647        highlighted: ringed,
1648        disabled: on_event.is_none(),
1649    };
1650    let level = entry.level;
1651    let current = state.current == Some(id);
1652    let small = |content: &'a str, width: f32| {
1653        container(
1654            ellipsis(content)
1655                .size(text_size::XS, LINE_HEIGHT)
1656                .width(Length::Shrink)
1657                .colour(muted),
1658        )
1659        .max_width(width)
1660    };
1661
1662    let mut meta = row![].spacing(space::SM).align_y(Alignment::Start);
1663    if let Some(timestamp) = &entry.timestamp {
1664        meta = meta.push(small(timestamp, TIMESTAMP_WIDTH).width(TIMESTAMP_WIDTH));
1665    }
1666    meta = meta.push(
1667        text(level.tag())
1668            .size(text_size::XS)
1669            .line_height(LineHeight::Absolute(Pixels(LINE_HEIGHT)))
1670            .font(theme::semibold())
1671            .wrapping(Wrapping::None)
1672            .width(LEVEL_WIDTH)
1673            .style(move |theme| text::Style {
1674                color: Some(level_colour(&Tokens::of(theme), level)),
1675            }),
1676    );
1677    if let Some(target) = &entry.target {
1678        let width = if stacked { f32::INFINITY } else { TARGET_WIDTH };
1679        meta = meta.push(small(target, width));
1680    }
1681    let wrapping = if state.wrap {
1682        Wrapping::WordOrGlyph
1683    } else {
1684        Wrapping::None
1685    };
1686    let message = marked(
1687        &entry.message,
1688        find(&entry.message, &state.query),
1689        move |theme| line_style(&Tokens::of(theme), level, current, status).text,
1690        move |theme| line_style(&Tokens::of(theme), level, current, status).mark,
1691    )
1692    .size(text_size::XS)
1693    .line_height(LineHeight::Absolute(Pixels(LINE_HEIGHT)))
1694    .wrapping(wrapping);
1695    let (line, height): (Element<'a, Message>, f32) = if stacked {
1696        (column![meta, message].into(), STACKED_ROW_HEIGHT)
1697    } else {
1698        (meta.push(message).into(), ROW_HEIGHT)
1699    };
1700
1701    let padding = (ROW_HEIGHT - LINE_HEIGHT) / 2.0;
1702    let body = container(line)
1703        .padding(Padding::from([padding, space::SM]))
1704        .width(Length::Fill)
1705        .height(if state.wrap {
1706            Length::Shrink
1707        } else {
1708            Length::Fixed(height)
1709        })
1710        .clip(true);
1711    let row = pressable(body, move |theme, hovered| {
1712        let style = line_style(
1713            &Tokens::of(theme),
1714            level,
1715            current,
1716            Status { hovered, ..status },
1717        );
1718        Look {
1719            background: style.background,
1720            border: Border {
1721                color: style.ring.unwrap_or(Color::TRANSPARENT),
1722                width: if style.ring.is_some() { 1.0 } else { 0.0 },
1723                radius: radius::SM.into(),
1724            },
1725            divider: None,
1726        }
1727    });
1728    let Some(on_event) = on_event.cloned() else {
1729        return row.into();
1730    };
1731    row.on_press(move |modifiers| on_event(Event::Press(id, modifiers)))
1732        .into()
1733}
1734
1735#[cfg(test)]
1736mod tests {
1737    use super::*;
1738    use crate::keys::Action as _;
1739    use crate::theme::{dark, light};
1740    use iced::futures::SinkExt;
1741    use iced::futures::executor::block_on;
1742    use iced::keyboard::Key;
1743
1744    fn log(lines: &[(Level, &str)]) -> State {
1745        let mut state = State::new();
1746        state.extend(lines.iter().map(|&(level, message)| entry(level, message)));
1747        state
1748    }
1749
1750    fn sample() -> State {
1751        log(&[
1752            (Level::Info, "server started"),
1753            (Level::Debug, "loaded config"),
1754            (Level::Warn, "disk almost full"),
1755            (Level::Error, "request failed: timeout"),
1756            (Level::Info, "request served"),
1757        ])
1758    }
1759
1760    fn key(key: Key, modifiers: Modifiers) -> keys::Event {
1761        keys::Event { key, modifiers }
1762    }
1763
1764    #[test]
1765    fn entries_format_as_one_line() {
1766        let full = entry(Level::Warn, "slow query")
1767            .timestamp("12:00:01.250")
1768            .target("db::pool");
1769        assert_eq!(full.line(), "12:00:01.250 WARN  db::pool: slow query");
1770        assert_eq!(entry(Level::Error, "boom").line(), "ERROR boom");
1771        assert_eq!(Entry::default().level, Level::Info);
1772    }
1773
1774    #[test]
1775    fn levels_have_tags_names_and_an_order() {
1776        assert_eq!(Level::ALL.len(), 5);
1777        assert_eq!(Level::Warn.tag(), "WARN");
1778        assert_eq!(Level::Warn.name(), "Warn");
1779        assert_eq!(Level::Error.to_string(), "ERROR");
1780        assert!(Level::Trace < Level::Error);
1781        for (index, level) in Level::ALL.iter().enumerate() {
1782            assert_eq!(level.index(), index);
1783        }
1784    }
1785
1786    #[test]
1787    fn a_new_log_follows_and_shows_every_level() {
1788        let state = State::new();
1789        assert!(state.is_empty());
1790        assert!(state.is_following());
1791        assert!(!state.is_paused());
1792        assert!(!state.is_wrapped());
1793        assert_eq!(state.limit(), DEFAULT_LIMIT);
1794        assert_eq!(state.search_id(), &SEARCH_ID);
1795        assert!(Level::ALL.iter().all(|&level| state.is_shown(level)));
1796        assert!(State::new().with_wrap(true).is_wrapped());
1797        let custom = State::new().with_search_id(widget::Id::new("logs"));
1798        assert_eq!(custom.search_id(), &widget::Id::new("logs"));
1799    }
1800
1801    #[test]
1802    fn received_entries_are_counted_by_level() {
1803        let mut state = sample();
1804        assert_eq!(state.len(), 5);
1805        assert_eq!(state.visible_len(), 5);
1806        assert_eq!(state.count(Level::Info), 2);
1807        assert_eq!(state.count(Level::Trace), 0);
1808        let _ = state.update(Event::Received(vec![entry(Level::Error, "again")]));
1809        assert_eq!(state.count(Level::Error), 2);
1810        assert_eq!(
1811            state.entry(5).map(|entry| entry.message.as_str()),
1812            Some("again")
1813        );
1814        assert_eq!(state.entries().count(), 6);
1815    }
1816
1817    #[test]
1818    fn the_limit_keeps_the_newest_entries() {
1819        let mut state = sample().with_limit(3);
1820        assert_eq!(state.len(), 3);
1821        assert_eq!(state.entry(0), None, "dropped");
1822        assert_eq!(state.visible().collect::<Vec<_>>(), [2, 3, 4]);
1823        assert_eq!(state.count(Level::Info), 1);
1824        assert_eq!(state.count(Level::Debug), 0);
1825        assert_eq!(state.visible_dropped, 2);
1826        let _ = state.update(Event::Press(2, Modifiers::empty()));
1827        let _ = state.update(Event::Received(vec![
1828            entry(Level::Info, "a"),
1829            entry(Level::Info, "b"),
1830        ]));
1831        assert_eq!(state.visible().collect::<Vec<_>>(), [4, 5, 6]);
1832        assert!(state.selected().is_empty(), "the selected line was dropped");
1833        assert_eq!(state.highlighted(), None);
1834        assert_eq!(State::new().with_limit(0).limit(), 1);
1835    }
1836
1837    #[test]
1838    fn hiding_a_level_filters_lines_and_their_selection() {
1839        let mut state = sample();
1840        let _ = state.update(Event::Press(1, Modifiers::empty()));
1841        let _ = state.update(Event::ToggleLevel(Level::Debug));
1842        assert!(!state.is_shown(Level::Debug));
1843        assert_eq!(state.visible().collect::<Vec<_>>(), [0, 2, 3, 4]);
1844        assert!(state.selected().is_empty());
1845        let _ = state.update(Event::Received(vec![entry(Level::Debug, "hidden")]));
1846        assert_eq!(state.visible_len(), 4, "new hidden lines stay hidden");
1847        assert_eq!(state.count(Level::Debug), 2, "but are still counted");
1848        let _ = state.update(Event::ToggleLevel(Level::Debug));
1849        assert_eq!(state.visible_len(), 6);
1850
1851        let errors = sample().with_levels([Level::Warn, Level::Error]);
1852        assert_eq!(errors.visible().collect::<Vec<_>>(), [2, 3]);
1853    }
1854
1855    #[test]
1856    fn search_finds_messages_and_moves_between_matches() {
1857        let mut state = sample();
1858        let _ = state.update(Event::Search("REQUEST".into()));
1859        assert_eq!(state.query(), "REQUEST");
1860        assert_eq!(state.matches().collect::<Vec<_>>(), [3, 4]);
1861        assert_eq!(
1862            state.current_match(),
1863            Some((4, 2)),
1864            "typing jumps to the newest match while following"
1865        );
1866        assert!(state.is_following(), "the newest line keeps following");
1867        let _ = state.update(Event::NextMatch);
1868        assert_eq!(state.current_match(), Some((3, 1)), "wraps to the first");
1869        assert_eq!(state.highlighted(), Some(3));
1870        assert!(
1871            !state.is_following(),
1872            "a match above the end stops following"
1873        );
1874        let _ = state.update(Event::NextMatch);
1875        assert_eq!(state.current_match(), Some((4, 2)));
1876        assert!(state.is_following(), "the newest line follows again");
1877        let _ = state.update(Event::PreviousMatch);
1878        assert_eq!(state.current_match(), Some((3, 1)));
1879        let _ = state.update(Event::PreviousMatch);
1880        assert_eq!(state.current_match(), Some((4, 2)), "wraps to the last");
1881        let _ = state.update(Event::Received(vec![entry(Level::Info, "request queued")]));
1882        assert_eq!(
1883            state.match_count(),
1884            3,
1885            "new lines are searched as they arrive"
1886        );
1887        let _ = state.update(Event::ClearSearch);
1888        assert_eq!(state.query(), "");
1889        assert_eq!(state.match_count(), 0);
1890        assert_eq!(state.current_match(), None);
1891    }
1892
1893    #[test]
1894    fn typing_jumps_to_the_nearest_match_at_or_after_the_highlight() {
1895        let mut state = sample();
1896        let _ = state.update(Event::Press(1, Modifiers::empty()));
1897        let _ = state.update(Event::Search("request".into()));
1898        assert_eq!(state.current_match(), Some((3, 1)));
1899        assert_eq!(state.reveal_target().map(|(index, _)| index), Some(3));
1900        let _ = state.update(Event::Search("request s".into()));
1901        assert_eq!(state.current_match(), Some((4, 1)), "narrows onwards");
1902        let _ = state.update(Event::Search("server".into()));
1903        assert_eq!(
1904            state.current_match(),
1905            Some((0, 1)),
1906            "nothing after the highlight takes the last before it"
1907        );
1908
1909        let mut scrolled = sample();
1910        let _ = scrolled.update(Event::Follow(false));
1911        let _ = scrolled.update(Event::Search("request".into()));
1912        assert_eq!(
1913            scrolled.current_match(),
1914            Some((3, 1)),
1915            "the oldest while not following"
1916        );
1917    }
1918
1919    #[test]
1920    fn stepping_without_matches_does_nothing() {
1921        let mut none = sample();
1922        let _ = none.update(Event::Search("nothing like this".into()));
1923        let _ = none.update(Event::NextMatch);
1924        assert_eq!(none.current_match(), None);
1925        assert_eq!(none.highlighted(), None);
1926    }
1927
1928    #[test]
1929    fn matches_follow_the_level_filter() {
1930        let mut state = sample();
1931        let _ = state.update(Event::Search("request".into()));
1932        let _ = state.update(Event::ToggleLevel(Level::Error));
1933        assert_eq!(state.matches().collect::<Vec<_>>(), [4]);
1934    }
1935
1936    #[test]
1937    fn pausing_holds_entries_back_until_resumed() {
1938        let mut state = sample().with_limit(6);
1939        let _ = state.update(Event::TogglePause);
1940        assert!(state.is_paused());
1941        let _ = state.update(Event::Received(
1942            (0..10)
1943                .map(|n| entry(Level::Info, format!("held {n}")))
1944                .collect(),
1945        ));
1946        assert_eq!(state.len(), 5, "nothing shown while paused");
1947        assert_eq!(state.pending(), 6, "held entries are bounded by the limit");
1948        let _ = state.update(Event::TogglePause);
1949        assert!(!state.is_paused());
1950        assert_eq!(state.pending(), 0);
1951        assert_eq!(state.len(), 6);
1952        let last = state.entries().last().map(|entry| entry.message.clone());
1953        assert_eq!(last.as_deref(), Some("held 9"));
1954    }
1955
1956    #[test]
1957    fn clearing_removes_everything_and_follows() {
1958        let mut state = sample();
1959        let _ = state.update(Event::Press(1, Modifiers::empty()));
1960        let _ = state.update(Event::Clear);
1961        assert!(state.is_empty());
1962        assert_eq!(state.visible_len(), 0);
1963        assert_eq!(state.count(Level::Info), 0);
1964        assert!(state.selected().is_empty());
1965        assert!(state.is_following());
1966        let _ = state.update(Event::Received(vec![entry(Level::Info, "fresh")]));
1967        assert_eq!(state.visible().collect::<Vec<_>>(), [5], "ids carry on");
1968    }
1969
1970    #[test]
1971    fn copying_returns_the_selected_lines_in_order() {
1972        let mut state = sample();
1973        assert!(
1974            state.update(Event::CopySelection).is_none(),
1975            "nothing to copy"
1976        );
1977        assert!(!state.can_copy());
1978        let _ = state.update(Event::Press(3, Modifiers::empty()));
1979        assert!(state.can_copy());
1980        let _ = state.update(Event::Press(0, Modifiers::COMMAND));
1981        let Some(Output::Copy(text)) = state.update(Event::CopySelection) else {
1982            panic!("copies the selection");
1983        };
1984        assert_eq!(text, "INFO  server started\nERROR request failed: timeout");
1985        let _ = state.update(Event::Press(0, Modifiers::COMMAND));
1986        let _ = state.update(Event::Press(3, Modifiers::COMMAND));
1987        assert!(state.selected().is_empty());
1988        assert_eq!(
1989            state.copy_text().as_deref(),
1990            Some("ERROR request failed: timeout"),
1991            "falls back to the highlighted line"
1992        );
1993    }
1994
1995    #[test]
1996    fn shift_presses_and_keys_select_ranges_of_shown_lines() {
1997        let mut state = sample();
1998        let _ = state.update(Event::ToggleLevel(Level::Debug));
1999        let _ = state.update(Event::Press(0, Modifiers::empty()));
2000        let _ = state.update(Event::Press(3, Modifiers::SHIFT));
2001        assert_eq!(state.selected(), [0, 2, 3], "the hidden line is skipped");
2002        let _ = state.update(Event::ExtendNext);
2003        assert_eq!(state.selected(), [0, 2, 3, 4]);
2004        let _ = state.update(Event::Press(2, Modifiers::empty()));
2005        let _ = state.update(Event::ExtendPrevious);
2006        assert_eq!(state.selected(), [0, 2]);
2007        let _ = state.update(Event::SelectAll);
2008        assert_eq!(state.selected(), [0, 2, 3, 4]);
2009        let _ = state.update(Event::Press(1, Modifiers::empty()));
2010        assert_eq!(
2011            state.selected(),
2012            [0, 2, 3, 4],
2013            "a hidden line cannot be pressed"
2014        );
2015    }
2016
2017    #[test]
2018    fn navigation_follows_only_at_the_newest_line() {
2019        let mut state = sample();
2020        let _ = state.update(Event::Previous);
2021        assert_eq!(state.highlighted(), Some(4));
2022        assert!(state.is_following());
2023        let _ = state.update(Event::Previous);
2024        assert!(!state.is_following());
2025        let _ = state.update(Event::Received(vec![entry(Level::Info, "new")]));
2026        assert_eq!(state.unseen(), 1);
2027        let _ = state.update(Event::First);
2028        assert_eq!(state.highlighted(), Some(0));
2029        let _ = state.update(Event::Page(2));
2030        let _ = state.update(Event::NextPage);
2031        assert_eq!(state.highlighted(), Some(2));
2032        let _ = state.update(Event::PreviousPage);
2033        assert_eq!(state.highlighted(), Some(0));
2034        let _ = state.update(Event::Next);
2035        assert_eq!(state.highlighted(), Some(1));
2036        let _ = state.update(Event::Last);
2037        assert_eq!(state.highlighted(), Some(5));
2038        assert!(state.is_following());
2039        assert_eq!(state.unseen(), 0);
2040        assert_eq!(state.reveal_target().map(|(index, _)| index), Some(5));
2041    }
2042
2043    #[test]
2044    fn scrolling_away_stops_following_and_counts_new_lines() {
2045        let mut state = sample();
2046        let _ = state.update(Event::Follow(false));
2047        assert!(!state.is_following());
2048        let _ = state.update(Event::Received(vec![
2049            entry(Level::Info, "one"),
2050            entry(Level::Info, "two"),
2051        ]));
2052        assert_eq!(state.unseen(), 2);
2053        let _ = state.update(Event::Follow(true));
2054        assert!(state.is_following());
2055        assert_eq!(state.unseen(), 0);
2056    }
2057
2058    #[test]
2059    fn focus_lands_on_the_newest_line_without_scrolling() {
2060        let mut state = sample();
2061        let _ = state.update(Event::Focus(true));
2062        assert!(state.is_focused());
2063        assert_eq!(state.highlighted(), Some(4));
2064        assert_eq!(state.reveal_target(), None);
2065        let mut paused = sample();
2066        let _ = paused.update(Event::Follow(false));
2067        let _ = paused.update(Event::Focus(true));
2068        assert_eq!(paused.highlighted(), Some(0));
2069        let _ = paused.update(Event::Focus(false));
2070        assert!(!paused.is_focused());
2071    }
2072
2073    #[test]
2074    fn wrap_and_page_events_update_the_state() {
2075        let mut state = sample();
2076        let _ = state.update(Event::ToggleWrap);
2077        assert!(state.is_wrapped());
2078        let _ = state.update(Event::Page(0));
2079        assert_eq!(state.page, 1);
2080        assert!(matches!(
2081            state.update(Event::FocusSearch),
2082            Some(Output::FocusSearch)
2083        ));
2084        let (sender, _receiver) = mpsc::channel(1);
2085        assert!(matches!(
2086            state.update(Event::Ready(sender)),
2087            Some(Output::Ready(_))
2088        ));
2089    }
2090
2091    #[test]
2092    fn the_default_keymap_maps_to_events() {
2093        let mut state = sample();
2094        let keymap = default_keymap();
2095        let resolve = |state: &State, pressed: keys::Event| state.key_event(&keymap, &pressed);
2096        let named = |name: Named, modifiers| key(Key::Named(name), modifiers);
2097        let character = |c: &str, modifiers| key(Key::Character(c.into()), modifiers);
2098
2099        assert!(matches!(
2100            resolve(&state, character("f", Modifiers::COMMAND)),
2101            Some(Event::FocusSearch)
2102        ));
2103        assert!(matches!(
2104            resolve(&state, named(Named::End, Modifiers::empty())),
2105            Some(Event::Last)
2106        ));
2107        assert!(
2108            resolve(&state, named(Named::Space, Modifiers::empty())).is_none(),
2109            "nothing highlighted to select"
2110        );
2111        assert!(
2112            resolve(&state, character("w", Modifiers::empty())).is_none(),
2113            "no bare letters"
2114        );
2115        assert!(
2116            resolve(&state, named(Named::Enter, Modifiers::empty())).is_none(),
2117            "lines have no activation"
2118        );
2119        assert!(matches!(
2120            resolve(&state, character("l", Modifiers::CTRL)),
2121            Some(Event::Clear)
2122        ));
2123        assert!(
2124            resolve(&state, named(Named::F3, Modifiers::empty())).is_none(),
2125            "no search, so F3 is left for others"
2126        );
2127        assert!(resolve(&state, named(Named::Escape, Modifiers::empty())).is_none());
2128        assert!(resolve(&state, character("c", Modifiers::COMMAND)).is_none());
2129
2130        let _ = state.update(Event::Search("request".into()));
2131        assert!(matches!(
2132            resolve(&state, named(Named::F3, Modifiers::empty())),
2133            Some(Event::NextMatch)
2134        ));
2135        assert!(
2136            resolve(&state, named(Named::Enter, Modifiers::SHIFT)).is_none(),
2137            "Enter steps through matches only in the search field"
2138        );
2139        assert!(matches!(
2140            resolve(&state, named(Named::F3, Modifiers::SHIFT)),
2141            Some(Event::PreviousMatch)
2142        ));
2143        assert!(matches!(
2144            resolve(&state, named(Named::Escape, Modifiers::empty())),
2145            Some(Event::ClearSearch)
2146        ));
2147        let _ = state.update(Event::Press(0, Modifiers::empty()));
2148        assert!(matches!(
2149            resolve(&state, character("c", Modifiers::COMMAND)),
2150            Some(Event::CopySelection)
2151        ));
2152        assert!(matches!(
2153            resolve(&state, named(Named::ArrowDown, Modifiers::SHIFT)),
2154            Some(Event::ExtendNext)
2155        ));
2156        assert!(matches!(
2157            resolve(&state, named(Named::Space, Modifiers::empty())),
2158            Some(Event::ToggleHighlighted)
2159        ));
2160
2161        let empty = State::new();
2162        assert!(resolve(&empty, named(Named::ArrowDown, Modifiers::empty())).is_none());
2163        assert!(resolve(&empty, character("l", Modifiers::CTRL)).is_none());
2164        assert!(
2165            matches!(
2166                resolve(&empty, named(Named::End, Modifiers::empty())),
2167                Some(Event::Last)
2168            ),
2169            "End always resumes following"
2170        );
2171    }
2172
2173    #[test]
2174    fn keymaps_can_be_overridden_and_unbound() {
2175        let keymap = default_keymap()
2176            .bind(Chord::character('p'), Action::TogglePause)
2177            .unbind(&Chord::named(Named::Space));
2178        let state = sample();
2179        let p = key(Key::Character("p".into()), Modifiers::empty());
2180        assert!(matches!(
2181            state.key_event(&keymap, &p),
2182            Some(Event::TogglePause)
2183        ));
2184        let space = key(Key::Named(Named::Space), Modifiers::empty());
2185        assert!(state.key_event(&keymap, &space).is_none());
2186    }
2187
2188    #[test]
2189    fn every_action_is_named_described_and_bound_but_the_toolbar_toggles() {
2190        let toolbar_only = [Action::TogglePause, Action::ToggleWrap];
2191        for action in Action::ALL {
2192            assert!(!action.name().is_empty());
2193            assert!(action.description().ends_with('.'));
2194            let bound = !default_keymap().chords(action).is_empty();
2195            assert_eq!(bound, !toolbar_only.contains(action), "{action:?}");
2196        }
2197        let state = sample();
2198        assert!(matches!(
2199            Action::TogglePause.event(&state),
2200            Some(Event::TogglePause)
2201        ));
2202        assert!(matches!(
2203            Action::ToggleWrap.event(&state),
2204            Some(Event::ToggleWrap)
2205        ));
2206    }
2207
2208    #[test]
2209    fn no_default_chord_is_a_bare_letter_or_alt() {
2210        for (chord, _) in default_keymap().bindings() {
2211            let label = chord.to_string();
2212            assert!(!label.contains("Alt"), "{label}");
2213            let bare = label.chars().count() == 1;
2214            assert!(!bare, "{label}");
2215        }
2216    }
2217
2218    #[test]
2219    fn space_selects_the_highlighted_line_and_keeps_the_others() {
2220        let mut state = sample();
2221        let _ = state.update(Event::Press(1, Modifiers::empty()));
2222        let _ = state.update(Event::Next);
2223        let _ = state.update(Event::ToggleHighlighted);
2224        assert_eq!(state.selected(), [1, 2]);
2225        let _ = state.update(Event::ToggleHighlighted);
2226        assert_eq!(state.selected(), [1]);
2227        assert!(State::new().update(Event::ToggleHighlighted).is_none());
2228    }
2229
2230    #[test]
2231    fn the_level_filters_are_a_multiple_choice_group_with_counts() {
2232        let mut state = sample();
2233        let levels = state.levels();
2234        assert_eq!(levels.mode(), toggle_group::Mode::Multiple);
2235        assert_eq!(levels.selected(), Level::ALL);
2236        let labels: Vec<&str> = levels
2237            .items()
2238            .iter()
2239            .map(|item| item.label.as_str())
2240            .collect();
2241        assert_eq!(
2242            labels,
2243            ["Trace 0", "Debug 1", "Info 2", "Warn 1", "Error 1"]
2244        );
2245
2246        let _ = state.update(Event::Levels(toggle_group::Event::Toggle(Level::Info)));
2247        assert!(!state.is_shown(Level::Info));
2248        assert!(!state.levels().is_selected(Level::Info));
2249        assert_eq!(state.visible().collect::<Vec<_>>(), [1, 2, 3]);
2250
2251        let _ = state.update(Event::Received(vec![entry(Level::Info, "more")]));
2252        assert_eq!(state.levels().items()[2].label, "Info 3", "counts follow");
2253        assert!(!state.levels().is_selected(Level::Info), "and stay off");
2254        let _ = state.update(Event::ToggleLevel(Level::Info));
2255        assert!(state.levels().is_selected(Level::Info));
2256        let _ = state.update(Event::Clear);
2257        assert_eq!(state.levels().items()[2].label, "Info 0");
2258    }
2259
2260    #[test]
2261    fn the_menu_copies_and_filters_one_line() {
2262        let mut state = sample();
2263        let Some(Output::Copy(line)) = state.update(MenuItem::CopyLine.event(2)) else {
2264            panic!("copies the line");
2265        };
2266        assert_eq!(line, "WARN  disk almost full");
2267        let Some(Output::Copy(message)) = state.update(MenuItem::CopyMessage.event(3)) else {
2268            panic!("copies the message");
2269        };
2270        assert_eq!(message, "request failed: timeout");
2271        assert!(state.update(Event::CopyLine(99)).is_none());
2272
2273        let _ = state.update(MenuItem::FilterToLevel.event(0));
2274        assert_eq!(state.visible().collect::<Vec<_>>(), [0, 4]);
2275        assert_eq!(state.levels().selected(), [Level::Info]);
2276        let _ = state.update(Event::FilterToLevel(99));
2277        assert_eq!(state.visible_len(), 2, "a missing line changes nothing");
2278
2279        let menu = menu();
2280        assert_eq!(MenuItem::ALL.len(), 3);
2281        for item in MenuItem::ALL {
2282            assert!(menu.menu().item(item).is_some(), "{item:?}");
2283        }
2284    }
2285
2286    #[test]
2287    fn the_match_label_counts_matches() {
2288        let mut state = sample();
2289        assert_eq!(match_label(&state), "");
2290        let _ = state.update(Event::Search("request".into()));
2291        assert_eq!(match_label(&state), "2 of 2");
2292        let _ = state.update(Event::NextMatch);
2293        assert_eq!(match_label(&state), "1 of 2");
2294        let _ = state.update(Event::ToggleLevel(Level::Error));
2295        assert_eq!(
2296            match_label(&state),
2297            "1 found",
2298            "the current match was hidden"
2299        );
2300        let _ = state.update(Event::Search("nothing like this".into()));
2301        assert_eq!(match_label(&state), "None");
2302    }
2303
2304    #[test]
2305    fn level_colours_come_from_the_tokens() {
2306        for theme in [light(), dark()] {
2307            let tokens = Tokens::of(&theme);
2308            assert_eq!(level_colour(&tokens, Level::Debug), tokens.muted_foreground);
2309            let colours: Vec<Color> = Level::ALL
2310                .iter()
2311                .map(|&level| level_colour(&tokens, level))
2312                .collect();
2313            for (index, colour) in colours.iter().enumerate() {
2314                assert!(
2315                    !colours[index + 1..].contains(colour),
2316                    "levels look different: {colours:?}"
2317                );
2318            }
2319        }
2320        let dark = Tokens::of(&dark());
2321        assert_eq!(level_colour(&dark, Level::Error), dark.destructive);
2322    }
2323
2324    #[test]
2325    fn line_styles_cover_levels_matches_and_statuses() {
2326        for theme in [light(), dark()] {
2327            let tokens = Tokens::of(&theme);
2328            let idle = line_style(&tokens, Level::Info, false, Status::default());
2329            assert_eq!(idle.background, None);
2330            assert_eq!(idle.ring, None);
2331            assert_eq!(idle.text, tokens.foreground);
2332            let error = line_style(&tokens, Level::Error, false, Status::default());
2333            assert!(error.background.is_some(), "error lines are tinted");
2334            let selected = line_style(
2335                &tokens,
2336                Level::Error,
2337                false,
2338                Status {
2339                    selected: true,
2340                    ..Status::default()
2341                },
2342            );
2343            assert_eq!(selected.background, Some(tokens.accent), "selection wins");
2344            assert_eq!(selected.text, tokens.accent_foreground);
2345            let hovered = line_style(
2346                &tokens,
2347                Level::Warn,
2348                false,
2349                Status {
2350                    hovered: true,
2351                    ..Status::default()
2352                },
2353            );
2354            assert!(hovered.background.is_some());
2355            let highlighted = line_style(
2356                &tokens,
2357                Level::Info,
2358                false,
2359                Status {
2360                    highlighted: true,
2361                    ..Status::default()
2362                },
2363            );
2364            assert_eq!(highlighted.ring, Some(tokens.ring));
2365            let disabled = line_style(
2366                &tokens,
2367                Level::Info,
2368                false,
2369                Status {
2370                    disabled: true,
2371                    highlighted: true,
2372                    ..Status::default()
2373                },
2374            );
2375            assert_eq!(disabled.ring, None);
2376            let current = line_style(&tokens, Level::Info, true, Status::default());
2377            assert!(current.mark.a > idle.mark.a, "the current match stands out");
2378        }
2379    }
2380
2381    #[test]
2382    fn the_builder_has_sensible_defaults() {
2383        let state = sample();
2384        let viewer: LogViewer<'_, ()> = log_viewer(&state);
2385        assert!(!viewer.is_enabled());
2386        assert!(viewer.toolbar);
2387        assert_eq!(viewer.height, Length::Fill);
2388        assert!(viewer.menu.is_none());
2389        assert_eq!(viewer.menu_keymap, context_menu::default_keymap());
2390        let menu = menu();
2391        let viewer = viewer
2392            .toolbar(false)
2393            .height(300)
2394            .width(400)
2395            .placeholder("Filter")
2396            .empty("Quiet")
2397            .keymap(Keymap::new())
2398            .context_menu(&menu, |_| ())
2399            .context_menu_keymap(Keymap::new())
2400            .on_event(|_| ());
2401        assert!(viewer.menu.is_some());
2402        assert!(viewer.menu_keymap.is_empty());
2403        assert!(viewer.is_enabled());
2404        assert!(!viewer.toolbar);
2405        assert_eq!(viewer.height, Length::Fixed(300.0));
2406        assert_eq!(viewer.placeholder, "Filter");
2407        assert_eq!(viewer.empty, "Quiet");
2408        assert!(viewer.keymap.is_empty());
2409        assert!(format!("{viewer:?}").contains("LogViewer"));
2410    }
2411
2412    #[test]
2413    fn stream_emits_ready_first_then_batches() {
2414        let mut events = Box::pin(stream());
2415        let Some(Event::Ready(mut sender)) = block_on(events.next()) else {
2416            panic!("first event must be Ready");
2417        };
2418        block_on(async {
2419            for n in 0..3 {
2420                sender
2421                    .send(entry(Level::Info, format!("line {n}")))
2422                    .await
2423                    .expect("channel open");
2424            }
2425        });
2426        let Some(Event::Received(batch)) = block_on(events.next()) else {
2427            panic!("then a batch");
2428        };
2429        assert_eq!(batch.len(), 3);
2430        assert_eq!(batch[2].message, "line 2");
2431    }
2432
2433    #[test]
2434    fn bursts_arrive_in_batches_of_the_batch_size() {
2435        let items = stream::iter(0..BATCH_SIZE * 2 + 1);
2436        let sizes: Vec<usize> = block_on(
2437            items
2438                .ready_chunks(BATCH_SIZE)
2439                .map(|batch| batch.len())
2440                .collect(),
2441        );
2442        assert_eq!(sizes, [BATCH_SIZE, BATCH_SIZE, 1]);
2443    }
2444}