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                Some(match &menu {
1544                    Some(menu) => menu.wrap(id, line),
1545                    None => line,
1546                })
1547            }))
1548            .into()
1549        };
1550        let row_height = if narrow {
1551            STACKED_ROW_HEIGHT
1552        } else {
1553            ROW_HEIGHT
1554        };
1555        let mut list = rows(state.visible_len(), row_height, build)
1556            .reveal(state.reveal_target())
1557            .follow(state.is_following())
1558            .origin(state.visible_dropped)
1559            .height(Length::Fill);
1560        if wrap {
1561            list =
1562                list.measured(move |index| state.visible.get(index).copied().unwrap_or_default());
1563        }
1564        if let Some(on_event) = self.on_event.clone() {
1565            let on_page = on_event.clone();
1566            list = list
1567                .on_page(move |lines| on_page(Event::Page(lines)))
1568                .on_follow(move |follow| on_event(Event::Follow(follow)));
1569        }
1570
1571        // Below the lines, inside the frame, so the newest line stays in
1572        // view above it. The lines stay the column's first child whether
1573        // the pill shows or not, so they keep their scroll position.
1574        let pill = self.pill().map(|pill| -> Element<'a, Message> {
1575            container(pill)
1576                .align_right(Length::Fill)
1577                .padding(Padding::ZERO.top(FRAME_PADDING).right(space::XS))
1578                .into()
1579        });
1580        frame(column(std::iter::once(list.into()).chain(pill)).into()).into()
1581    }
1582
1583    /// A button under the lines: resume while paused, or jump to the newest
1584    /// line while not following.
1585    fn pill(&self) -> Option<Element<'a, Message>> {
1586        let state = self.state;
1587        if state.is_paused() {
1588            let label = match state.pending() {
1589                0 => "Resume".to_owned(),
1590                waiting => format!("Resume ({waiting} new)"),
1591            };
1592            let resume = button(label)
1593                .icon(crate::lucide!(Play))
1594                .size(button::Size::Sm)
1595                .variant(button::Variant::Secondary)
1596                .on_press_maybe(self.send(Event::TogglePause));
1597            return Some(resume.into());
1598        }
1599        if state.is_following() {
1600            return None;
1601        }
1602        let label = match state.unseen() {
1603            0 => "Jump to latest".to_owned(),
1604            unseen => format!("Jump to latest ({unseen} new)"),
1605        };
1606        let jump = button(label)
1607            .icon(crate::lucide!(ArrowDown))
1608            .size(button::Size::Sm)
1609            .variant(button::Variant::Secondary)
1610            .on_press_maybe(self.send(Event::Last));
1611        Some(jump.into())
1612    }
1613}
1614
1615/// One line: timestamp, level, target and the message with its matches
1616/// marked.
1617/// Below the breakpoint the message sits under the other parts, so it keeps
1618/// the full width.
1619fn line_view<'a, Message: Clone + 'a>(
1620    state: &'a State,
1621    id: LineId,
1622    entry: &'a Entry,
1623    stacked: bool,
1624    ringed: bool,
1625    on_event: Option<&Rc<OnEvent<'a, Message>>>,
1626) -> Element<'a, Message> {
1627    let status = Status {
1628        selected: state.selected.contains(&id),
1629        hovered: false,
1630        highlighted: ringed,
1631        disabled: on_event.is_none(),
1632    };
1633    let level = entry.level;
1634    let current = state.current == Some(id);
1635    let small = |content: &'a str, width: f32| {
1636        container(
1637            ellipsis(content)
1638                .size(text_size::XS, LINE_HEIGHT)
1639                .width(Length::Shrink)
1640                .colour(muted),
1641        )
1642        .max_width(width)
1643    };
1644
1645    let mut meta = row![].spacing(space::SM).align_y(Alignment::Start);
1646    if let Some(timestamp) = &entry.timestamp {
1647        meta = meta.push(small(timestamp, TIMESTAMP_WIDTH).width(TIMESTAMP_WIDTH));
1648    }
1649    meta = meta.push(
1650        text(level.tag())
1651            .size(text_size::XS)
1652            .line_height(LineHeight::Absolute(Pixels(LINE_HEIGHT)))
1653            .font(theme::semibold())
1654            .wrapping(Wrapping::None)
1655            .width(LEVEL_WIDTH)
1656            .style(move |theme| text::Style {
1657                color: Some(level_colour(&Tokens::of(theme), level)),
1658            }),
1659    );
1660    if let Some(target) = &entry.target {
1661        let width = if stacked { f32::INFINITY } else { TARGET_WIDTH };
1662        meta = meta.push(small(target, width));
1663    }
1664    let wrapping = if state.wrap {
1665        Wrapping::WordOrGlyph
1666    } else {
1667        Wrapping::None
1668    };
1669    let message = marked(
1670        &entry.message,
1671        find(&entry.message, &state.query),
1672        move |theme| line_style(&Tokens::of(theme), level, current, status).text,
1673        move |theme| line_style(&Tokens::of(theme), level, current, status).mark,
1674    )
1675    .size(text_size::XS)
1676    .line_height(LineHeight::Absolute(Pixels(LINE_HEIGHT)))
1677    .wrapping(wrapping);
1678    let (line, height): (Element<'a, Message>, f32) = if stacked {
1679        (column![meta, message].into(), STACKED_ROW_HEIGHT)
1680    } else {
1681        (meta.push(message).into(), ROW_HEIGHT)
1682    };
1683
1684    let padding = (ROW_HEIGHT - LINE_HEIGHT) / 2.0;
1685    let body = container(line)
1686        .padding(Padding::from([padding, space::SM]))
1687        .width(Length::Fill)
1688        .height(if state.wrap {
1689            Length::Shrink
1690        } else {
1691            Length::Fixed(height)
1692        })
1693        .clip(true);
1694    let row = pressable(body, move |theme, hovered| {
1695        let style = line_style(
1696            &Tokens::of(theme),
1697            level,
1698            current,
1699            Status { hovered, ..status },
1700        );
1701        Look {
1702            background: style.background,
1703            border: Border {
1704                color: style.ring.unwrap_or(Color::TRANSPARENT),
1705                width: if style.ring.is_some() { 1.0 } else { 0.0 },
1706                radius: radius::SM.into(),
1707            },
1708            divider: None,
1709        }
1710    });
1711    let Some(on_event) = on_event.cloned() else {
1712        return row.into();
1713    };
1714    row.on_press(move |modifiers| on_event(Event::Press(id, modifiers)))
1715        .into()
1716}
1717
1718#[cfg(test)]
1719mod tests {
1720    use super::*;
1721    use crate::keys::Action as _;
1722    use crate::theme::{dark, light};
1723    use iced::futures::SinkExt;
1724    use iced::futures::executor::block_on;
1725    use iced::keyboard::Key;
1726
1727    fn log(lines: &[(Level, &str)]) -> State {
1728        let mut state = State::new();
1729        state.extend(lines.iter().map(|&(level, message)| entry(level, message)));
1730        state
1731    }
1732
1733    fn sample() -> State {
1734        log(&[
1735            (Level::Info, "server started"),
1736            (Level::Debug, "loaded config"),
1737            (Level::Warn, "disk almost full"),
1738            (Level::Error, "request failed: timeout"),
1739            (Level::Info, "request served"),
1740        ])
1741    }
1742
1743    fn key(key: Key, modifiers: Modifiers) -> keys::Event {
1744        keys::Event { key, modifiers }
1745    }
1746
1747    #[test]
1748    fn entries_format_as_one_line() {
1749        let full = entry(Level::Warn, "slow query")
1750            .timestamp("12:00:01.250")
1751            .target("db::pool");
1752        assert_eq!(full.line(), "12:00:01.250 WARN  db::pool: slow query");
1753        assert_eq!(entry(Level::Error, "boom").line(), "ERROR boom");
1754        assert_eq!(Entry::default().level, Level::Info);
1755    }
1756
1757    #[test]
1758    fn levels_have_tags_names_and_an_order() {
1759        assert_eq!(Level::ALL.len(), 5);
1760        assert_eq!(Level::Warn.tag(), "WARN");
1761        assert_eq!(Level::Warn.name(), "Warn");
1762        assert_eq!(Level::Error.to_string(), "ERROR");
1763        assert!(Level::Trace < Level::Error);
1764        for (index, level) in Level::ALL.iter().enumerate() {
1765            assert_eq!(level.index(), index);
1766        }
1767    }
1768
1769    #[test]
1770    fn a_new_log_follows_and_shows_every_level() {
1771        let state = State::new();
1772        assert!(state.is_empty());
1773        assert!(state.is_following());
1774        assert!(!state.is_paused());
1775        assert!(!state.is_wrapped());
1776        assert_eq!(state.limit(), DEFAULT_LIMIT);
1777        assert_eq!(state.search_id(), &SEARCH_ID);
1778        assert!(Level::ALL.iter().all(|&level| state.is_shown(level)));
1779        assert!(State::new().with_wrap(true).is_wrapped());
1780        let custom = State::new().with_search_id(widget::Id::new("logs"));
1781        assert_eq!(custom.search_id(), &widget::Id::new("logs"));
1782    }
1783
1784    #[test]
1785    fn received_entries_are_counted_by_level() {
1786        let mut state = sample();
1787        assert_eq!(state.len(), 5);
1788        assert_eq!(state.visible_len(), 5);
1789        assert_eq!(state.count(Level::Info), 2);
1790        assert_eq!(state.count(Level::Trace), 0);
1791        let _ = state.update(Event::Received(vec![entry(Level::Error, "again")]));
1792        assert_eq!(state.count(Level::Error), 2);
1793        assert_eq!(
1794            state.entry(5).map(|entry| entry.message.as_str()),
1795            Some("again")
1796        );
1797        assert_eq!(state.entries().count(), 6);
1798    }
1799
1800    #[test]
1801    fn the_limit_keeps_the_newest_entries() {
1802        let mut state = sample().with_limit(3);
1803        assert_eq!(state.len(), 3);
1804        assert_eq!(state.entry(0), None, "dropped");
1805        assert_eq!(state.visible().collect::<Vec<_>>(), [2, 3, 4]);
1806        assert_eq!(state.count(Level::Info), 1);
1807        assert_eq!(state.count(Level::Debug), 0);
1808        assert_eq!(state.visible_dropped, 2);
1809        let _ = state.update(Event::Press(2, Modifiers::empty()));
1810        let _ = state.update(Event::Received(vec![
1811            entry(Level::Info, "a"),
1812            entry(Level::Info, "b"),
1813        ]));
1814        assert_eq!(state.visible().collect::<Vec<_>>(), [4, 5, 6]);
1815        assert!(state.selected().is_empty(), "the selected line was dropped");
1816        assert_eq!(state.highlighted(), None);
1817        assert_eq!(State::new().with_limit(0).limit(), 1);
1818    }
1819
1820    #[test]
1821    fn hiding_a_level_filters_lines_and_their_selection() {
1822        let mut state = sample();
1823        let _ = state.update(Event::Press(1, Modifiers::empty()));
1824        let _ = state.update(Event::ToggleLevel(Level::Debug));
1825        assert!(!state.is_shown(Level::Debug));
1826        assert_eq!(state.visible().collect::<Vec<_>>(), [0, 2, 3, 4]);
1827        assert!(state.selected().is_empty());
1828        let _ = state.update(Event::Received(vec![entry(Level::Debug, "hidden")]));
1829        assert_eq!(state.visible_len(), 4, "new hidden lines stay hidden");
1830        assert_eq!(state.count(Level::Debug), 2, "but are still counted");
1831        let _ = state.update(Event::ToggleLevel(Level::Debug));
1832        assert_eq!(state.visible_len(), 6);
1833
1834        let errors = sample().with_levels([Level::Warn, Level::Error]);
1835        assert_eq!(errors.visible().collect::<Vec<_>>(), [2, 3]);
1836    }
1837
1838    #[test]
1839    fn search_finds_messages_and_moves_between_matches() {
1840        let mut state = sample();
1841        let _ = state.update(Event::Search("REQUEST".into()));
1842        assert_eq!(state.query(), "REQUEST");
1843        assert_eq!(state.matches().collect::<Vec<_>>(), [3, 4]);
1844        assert_eq!(
1845            state.current_match(),
1846            Some((4, 2)),
1847            "typing jumps to the newest match while following"
1848        );
1849        assert!(state.is_following(), "the newest line keeps following");
1850        let _ = state.update(Event::NextMatch);
1851        assert_eq!(state.current_match(), Some((3, 1)), "wraps to the first");
1852        assert_eq!(state.highlighted(), Some(3));
1853        assert!(
1854            !state.is_following(),
1855            "a match above the end stops following"
1856        );
1857        let _ = state.update(Event::NextMatch);
1858        assert_eq!(state.current_match(), Some((4, 2)));
1859        assert!(state.is_following(), "the newest line follows again");
1860        let _ = state.update(Event::PreviousMatch);
1861        assert_eq!(state.current_match(), Some((3, 1)));
1862        let _ = state.update(Event::PreviousMatch);
1863        assert_eq!(state.current_match(), Some((4, 2)), "wraps to the last");
1864        let _ = state.update(Event::Received(vec![entry(Level::Info, "request queued")]));
1865        assert_eq!(
1866            state.match_count(),
1867            3,
1868            "new lines are searched as they arrive"
1869        );
1870        let _ = state.update(Event::ClearSearch);
1871        assert_eq!(state.query(), "");
1872        assert_eq!(state.match_count(), 0);
1873        assert_eq!(state.current_match(), None);
1874    }
1875
1876    #[test]
1877    fn typing_jumps_to_the_nearest_match_at_or_after_the_highlight() {
1878        let mut state = sample();
1879        let _ = state.update(Event::Press(1, Modifiers::empty()));
1880        let _ = state.update(Event::Search("request".into()));
1881        assert_eq!(state.current_match(), Some((3, 1)));
1882        assert_eq!(state.reveal_target().map(|(index, _)| index), Some(3));
1883        let _ = state.update(Event::Search("request s".into()));
1884        assert_eq!(state.current_match(), Some((4, 1)), "narrows onwards");
1885        let _ = state.update(Event::Search("server".into()));
1886        assert_eq!(
1887            state.current_match(),
1888            Some((0, 1)),
1889            "nothing after the highlight takes the last before it"
1890        );
1891
1892        let mut scrolled = sample();
1893        let _ = scrolled.update(Event::Follow(false));
1894        let _ = scrolled.update(Event::Search("request".into()));
1895        assert_eq!(
1896            scrolled.current_match(),
1897            Some((3, 1)),
1898            "the oldest while not following"
1899        );
1900    }
1901
1902    #[test]
1903    fn stepping_without_matches_does_nothing() {
1904        let mut none = sample();
1905        let _ = none.update(Event::Search("nothing like this".into()));
1906        let _ = none.update(Event::NextMatch);
1907        assert_eq!(none.current_match(), None);
1908        assert_eq!(none.highlighted(), None);
1909    }
1910
1911    #[test]
1912    fn matches_follow_the_level_filter() {
1913        let mut state = sample();
1914        let _ = state.update(Event::Search("request".into()));
1915        let _ = state.update(Event::ToggleLevel(Level::Error));
1916        assert_eq!(state.matches().collect::<Vec<_>>(), [4]);
1917    }
1918
1919    #[test]
1920    fn pausing_holds_entries_back_until_resumed() {
1921        let mut state = sample().with_limit(6);
1922        let _ = state.update(Event::TogglePause);
1923        assert!(state.is_paused());
1924        let _ = state.update(Event::Received(
1925            (0..10)
1926                .map(|n| entry(Level::Info, format!("held {n}")))
1927                .collect(),
1928        ));
1929        assert_eq!(state.len(), 5, "nothing shown while paused");
1930        assert_eq!(state.pending(), 6, "held entries are bounded by the limit");
1931        let _ = state.update(Event::TogglePause);
1932        assert!(!state.is_paused());
1933        assert_eq!(state.pending(), 0);
1934        assert_eq!(state.len(), 6);
1935        let last = state.entries().last().map(|entry| entry.message.clone());
1936        assert_eq!(last.as_deref(), Some("held 9"));
1937    }
1938
1939    #[test]
1940    fn clearing_removes_everything_and_follows() {
1941        let mut state = sample();
1942        let _ = state.update(Event::Press(1, Modifiers::empty()));
1943        let _ = state.update(Event::Clear);
1944        assert!(state.is_empty());
1945        assert_eq!(state.visible_len(), 0);
1946        assert_eq!(state.count(Level::Info), 0);
1947        assert!(state.selected().is_empty());
1948        assert!(state.is_following());
1949        let _ = state.update(Event::Received(vec![entry(Level::Info, "fresh")]));
1950        assert_eq!(state.visible().collect::<Vec<_>>(), [5], "ids carry on");
1951    }
1952
1953    #[test]
1954    fn copying_returns_the_selected_lines_in_order() {
1955        let mut state = sample();
1956        assert!(
1957            state.update(Event::CopySelection).is_none(),
1958            "nothing to copy"
1959        );
1960        assert!(!state.can_copy());
1961        let _ = state.update(Event::Press(3, Modifiers::empty()));
1962        assert!(state.can_copy());
1963        let _ = state.update(Event::Press(0, Modifiers::COMMAND));
1964        let Some(Output::Copy(text)) = state.update(Event::CopySelection) else {
1965            panic!("copies the selection");
1966        };
1967        assert_eq!(text, "INFO  server started\nERROR request failed: timeout");
1968        let _ = state.update(Event::Press(0, Modifiers::COMMAND));
1969        let _ = state.update(Event::Press(3, Modifiers::COMMAND));
1970        assert!(state.selected().is_empty());
1971        assert_eq!(
1972            state.copy_text().as_deref(),
1973            Some("ERROR request failed: timeout"),
1974            "falls back to the highlighted line"
1975        );
1976    }
1977
1978    #[test]
1979    fn shift_presses_and_keys_select_ranges_of_shown_lines() {
1980        let mut state = sample();
1981        let _ = state.update(Event::ToggleLevel(Level::Debug));
1982        let _ = state.update(Event::Press(0, Modifiers::empty()));
1983        let _ = state.update(Event::Press(3, Modifiers::SHIFT));
1984        assert_eq!(state.selected(), [0, 2, 3], "the hidden line is skipped");
1985        let _ = state.update(Event::ExtendNext);
1986        assert_eq!(state.selected(), [0, 2, 3, 4]);
1987        let _ = state.update(Event::Press(2, Modifiers::empty()));
1988        let _ = state.update(Event::ExtendPrevious);
1989        assert_eq!(state.selected(), [0, 2]);
1990        let _ = state.update(Event::SelectAll);
1991        assert_eq!(state.selected(), [0, 2, 3, 4]);
1992        let _ = state.update(Event::Press(1, Modifiers::empty()));
1993        assert_eq!(
1994            state.selected(),
1995            [0, 2, 3, 4],
1996            "a hidden line cannot be pressed"
1997        );
1998    }
1999
2000    #[test]
2001    fn navigation_follows_only_at_the_newest_line() {
2002        let mut state = sample();
2003        let _ = state.update(Event::Previous);
2004        assert_eq!(state.highlighted(), Some(4));
2005        assert!(state.is_following());
2006        let _ = state.update(Event::Previous);
2007        assert!(!state.is_following());
2008        let _ = state.update(Event::Received(vec![entry(Level::Info, "new")]));
2009        assert_eq!(state.unseen(), 1);
2010        let _ = state.update(Event::First);
2011        assert_eq!(state.highlighted(), Some(0));
2012        let _ = state.update(Event::Page(2));
2013        let _ = state.update(Event::NextPage);
2014        assert_eq!(state.highlighted(), Some(2));
2015        let _ = state.update(Event::PreviousPage);
2016        assert_eq!(state.highlighted(), Some(0));
2017        let _ = state.update(Event::Next);
2018        assert_eq!(state.highlighted(), Some(1));
2019        let _ = state.update(Event::Last);
2020        assert_eq!(state.highlighted(), Some(5));
2021        assert!(state.is_following());
2022        assert_eq!(state.unseen(), 0);
2023        assert_eq!(state.reveal_target().map(|(index, _)| index), Some(5));
2024    }
2025
2026    #[test]
2027    fn scrolling_away_stops_following_and_counts_new_lines() {
2028        let mut state = sample();
2029        let _ = state.update(Event::Follow(false));
2030        assert!(!state.is_following());
2031        let _ = state.update(Event::Received(vec![
2032            entry(Level::Info, "one"),
2033            entry(Level::Info, "two"),
2034        ]));
2035        assert_eq!(state.unseen(), 2);
2036        let _ = state.update(Event::Follow(true));
2037        assert!(state.is_following());
2038        assert_eq!(state.unseen(), 0);
2039    }
2040
2041    #[test]
2042    fn focus_lands_on_the_newest_line_without_scrolling() {
2043        let mut state = sample();
2044        let _ = state.update(Event::Focus(true));
2045        assert!(state.is_focused());
2046        assert_eq!(state.highlighted(), Some(4));
2047        assert_eq!(state.reveal_target(), None);
2048        let mut paused = sample();
2049        let _ = paused.update(Event::Follow(false));
2050        let _ = paused.update(Event::Focus(true));
2051        assert_eq!(paused.highlighted(), Some(0));
2052        let _ = paused.update(Event::Focus(false));
2053        assert!(!paused.is_focused());
2054    }
2055
2056    #[test]
2057    fn wrap_and_page_events_update_the_state() {
2058        let mut state = sample();
2059        let _ = state.update(Event::ToggleWrap);
2060        assert!(state.is_wrapped());
2061        let _ = state.update(Event::Page(0));
2062        assert_eq!(state.page, 1);
2063        assert!(matches!(
2064            state.update(Event::FocusSearch),
2065            Some(Output::FocusSearch)
2066        ));
2067        let (sender, _receiver) = mpsc::channel(1);
2068        assert!(matches!(
2069            state.update(Event::Ready(sender)),
2070            Some(Output::Ready(_))
2071        ));
2072    }
2073
2074    #[test]
2075    fn the_default_keymap_maps_to_events() {
2076        let mut state = sample();
2077        let keymap = default_keymap();
2078        let resolve = |state: &State, pressed: keys::Event| state.key_event(&keymap, &pressed);
2079        let named = |name: Named, modifiers| key(Key::Named(name), modifiers);
2080        let character = |c: &str, modifiers| key(Key::Character(c.into()), modifiers);
2081
2082        assert!(matches!(
2083            resolve(&state, character("f", Modifiers::COMMAND)),
2084            Some(Event::FocusSearch)
2085        ));
2086        assert!(matches!(
2087            resolve(&state, named(Named::End, Modifiers::empty())),
2088            Some(Event::Last)
2089        ));
2090        assert!(
2091            resolve(&state, named(Named::Space, Modifiers::empty())).is_none(),
2092            "nothing highlighted to select"
2093        );
2094        assert!(
2095            resolve(&state, character("w", Modifiers::empty())).is_none(),
2096            "no bare letters"
2097        );
2098        assert!(
2099            resolve(&state, named(Named::Enter, Modifiers::empty())).is_none(),
2100            "lines have no activation"
2101        );
2102        assert!(matches!(
2103            resolve(&state, character("l", Modifiers::CTRL)),
2104            Some(Event::Clear)
2105        ));
2106        assert!(
2107            resolve(&state, named(Named::F3, Modifiers::empty())).is_none(),
2108            "no search, so F3 is left for others"
2109        );
2110        assert!(resolve(&state, named(Named::Escape, Modifiers::empty())).is_none());
2111        assert!(resolve(&state, character("c", Modifiers::COMMAND)).is_none());
2112
2113        let _ = state.update(Event::Search("request".into()));
2114        assert!(matches!(
2115            resolve(&state, named(Named::F3, Modifiers::empty())),
2116            Some(Event::NextMatch)
2117        ));
2118        assert!(
2119            resolve(&state, named(Named::Enter, Modifiers::SHIFT)).is_none(),
2120            "Enter steps through matches only in the search field"
2121        );
2122        assert!(matches!(
2123            resolve(&state, named(Named::F3, Modifiers::SHIFT)),
2124            Some(Event::PreviousMatch)
2125        ));
2126        assert!(matches!(
2127            resolve(&state, named(Named::Escape, Modifiers::empty())),
2128            Some(Event::ClearSearch)
2129        ));
2130        let _ = state.update(Event::Press(0, Modifiers::empty()));
2131        assert!(matches!(
2132            resolve(&state, character("c", Modifiers::COMMAND)),
2133            Some(Event::CopySelection)
2134        ));
2135        assert!(matches!(
2136            resolve(&state, named(Named::ArrowDown, Modifiers::SHIFT)),
2137            Some(Event::ExtendNext)
2138        ));
2139        assert!(matches!(
2140            resolve(&state, named(Named::Space, Modifiers::empty())),
2141            Some(Event::ToggleHighlighted)
2142        ));
2143
2144        let empty = State::new();
2145        assert!(resolve(&empty, named(Named::ArrowDown, Modifiers::empty())).is_none());
2146        assert!(resolve(&empty, character("l", Modifiers::CTRL)).is_none());
2147        assert!(
2148            matches!(
2149                resolve(&empty, named(Named::End, Modifiers::empty())),
2150                Some(Event::Last)
2151            ),
2152            "End always resumes following"
2153        );
2154    }
2155
2156    #[test]
2157    fn keymaps_can_be_overridden_and_unbound() {
2158        let keymap = default_keymap()
2159            .bind(Chord::character('p'), Action::TogglePause)
2160            .unbind(&Chord::named(Named::Space));
2161        let state = sample();
2162        let p = key(Key::Character("p".into()), Modifiers::empty());
2163        assert!(matches!(
2164            state.key_event(&keymap, &p),
2165            Some(Event::TogglePause)
2166        ));
2167        let space = key(Key::Named(Named::Space), Modifiers::empty());
2168        assert!(state.key_event(&keymap, &space).is_none());
2169    }
2170
2171    #[test]
2172    fn every_action_is_named_described_and_bound_but_the_toolbar_toggles() {
2173        let toolbar_only = [Action::TogglePause, Action::ToggleWrap];
2174        for action in Action::ALL {
2175            assert!(!action.name().is_empty());
2176            assert!(action.description().ends_with('.'));
2177            let bound = !default_keymap().chords(action).is_empty();
2178            assert_eq!(bound, !toolbar_only.contains(action), "{action:?}");
2179        }
2180        let state = sample();
2181        assert!(matches!(
2182            Action::TogglePause.event(&state),
2183            Some(Event::TogglePause)
2184        ));
2185        assert!(matches!(
2186            Action::ToggleWrap.event(&state),
2187            Some(Event::ToggleWrap)
2188        ));
2189    }
2190
2191    #[test]
2192    fn no_default_chord_is_a_bare_letter_or_alt() {
2193        for (chord, _) in default_keymap().bindings() {
2194            let label = chord.to_string();
2195            assert!(!label.contains("Alt"), "{label}");
2196            let bare = label.chars().count() == 1;
2197            assert!(!bare, "{label}");
2198        }
2199    }
2200
2201    #[test]
2202    fn space_selects_the_highlighted_line_and_keeps_the_others() {
2203        let mut state = sample();
2204        let _ = state.update(Event::Press(1, Modifiers::empty()));
2205        let _ = state.update(Event::Next);
2206        let _ = state.update(Event::ToggleHighlighted);
2207        assert_eq!(state.selected(), [1, 2]);
2208        let _ = state.update(Event::ToggleHighlighted);
2209        assert_eq!(state.selected(), [1]);
2210        assert!(State::new().update(Event::ToggleHighlighted).is_none());
2211    }
2212
2213    #[test]
2214    fn the_level_filters_are_a_multiple_choice_group_with_counts() {
2215        let mut state = sample();
2216        let levels = state.levels();
2217        assert_eq!(levels.mode(), toggle_group::Mode::Multiple);
2218        assert_eq!(levels.selected(), Level::ALL);
2219        let labels: Vec<&str> = levels
2220            .items()
2221            .iter()
2222            .map(|item| item.label.as_str())
2223            .collect();
2224        assert_eq!(
2225            labels,
2226            ["Trace 0", "Debug 1", "Info 2", "Warn 1", "Error 1"]
2227        );
2228
2229        let _ = state.update(Event::Levels(toggle_group::Event::Toggle(Level::Info)));
2230        assert!(!state.is_shown(Level::Info));
2231        assert!(!state.levels().is_selected(Level::Info));
2232        assert_eq!(state.visible().collect::<Vec<_>>(), [1, 2, 3]);
2233
2234        let _ = state.update(Event::Received(vec![entry(Level::Info, "more")]));
2235        assert_eq!(state.levels().items()[2].label, "Info 3", "counts follow");
2236        assert!(!state.levels().is_selected(Level::Info), "and stay off");
2237        let _ = state.update(Event::ToggleLevel(Level::Info));
2238        assert!(state.levels().is_selected(Level::Info));
2239        let _ = state.update(Event::Clear);
2240        assert_eq!(state.levels().items()[2].label, "Info 0");
2241    }
2242
2243    #[test]
2244    fn the_menu_copies_and_filters_one_line() {
2245        let mut state = sample();
2246        let Some(Output::Copy(line)) = state.update(MenuItem::CopyLine.event(2)) else {
2247            panic!("copies the line");
2248        };
2249        assert_eq!(line, "WARN  disk almost full");
2250        let Some(Output::Copy(message)) = state.update(MenuItem::CopyMessage.event(3)) else {
2251            panic!("copies the message");
2252        };
2253        assert_eq!(message, "request failed: timeout");
2254        assert!(state.update(Event::CopyLine(99)).is_none());
2255
2256        let _ = state.update(MenuItem::FilterToLevel.event(0));
2257        assert_eq!(state.visible().collect::<Vec<_>>(), [0, 4]);
2258        assert_eq!(state.levels().selected(), [Level::Info]);
2259        let _ = state.update(Event::FilterToLevel(99));
2260        assert_eq!(state.visible_len(), 2, "a missing line changes nothing");
2261
2262        let menu = menu();
2263        assert_eq!(MenuItem::ALL.len(), 3);
2264        for item in MenuItem::ALL {
2265            assert!(menu.menu().item(item).is_some(), "{item:?}");
2266        }
2267    }
2268
2269    #[test]
2270    fn the_match_label_counts_matches() {
2271        let mut state = sample();
2272        assert_eq!(match_label(&state), "");
2273        let _ = state.update(Event::Search("request".into()));
2274        assert_eq!(match_label(&state), "2 of 2");
2275        let _ = state.update(Event::NextMatch);
2276        assert_eq!(match_label(&state), "1 of 2");
2277        let _ = state.update(Event::ToggleLevel(Level::Error));
2278        assert_eq!(
2279            match_label(&state),
2280            "1 found",
2281            "the current match was hidden"
2282        );
2283        let _ = state.update(Event::Search("nothing like this".into()));
2284        assert_eq!(match_label(&state), "None");
2285    }
2286
2287    #[test]
2288    fn level_colours_come_from_the_tokens() {
2289        for theme in [light(), dark()] {
2290            let tokens = Tokens::of(&theme);
2291            assert_eq!(level_colour(&tokens, Level::Debug), tokens.muted_foreground);
2292            let colours: Vec<Color> = Level::ALL
2293                .iter()
2294                .map(|&level| level_colour(&tokens, level))
2295                .collect();
2296            for (index, colour) in colours.iter().enumerate() {
2297                assert!(
2298                    !colours[index + 1..].contains(colour),
2299                    "levels look different: {colours:?}"
2300                );
2301            }
2302        }
2303        let dark = Tokens::of(&dark());
2304        assert_eq!(level_colour(&dark, Level::Error), dark.destructive);
2305    }
2306
2307    #[test]
2308    fn line_styles_cover_levels_matches_and_statuses() {
2309        for theme in [light(), dark()] {
2310            let tokens = Tokens::of(&theme);
2311            let idle = line_style(&tokens, Level::Info, false, Status::default());
2312            assert_eq!(idle.background, None);
2313            assert_eq!(idle.ring, None);
2314            assert_eq!(idle.text, tokens.foreground);
2315            let error = line_style(&tokens, Level::Error, false, Status::default());
2316            assert!(error.background.is_some(), "error lines are tinted");
2317            let selected = line_style(
2318                &tokens,
2319                Level::Error,
2320                false,
2321                Status {
2322                    selected: true,
2323                    ..Status::default()
2324                },
2325            );
2326            assert_eq!(selected.background, Some(tokens.accent), "selection wins");
2327            assert_eq!(selected.text, tokens.accent_foreground);
2328            let hovered = line_style(
2329                &tokens,
2330                Level::Warn,
2331                false,
2332                Status {
2333                    hovered: true,
2334                    ..Status::default()
2335                },
2336            );
2337            assert!(hovered.background.is_some());
2338            let highlighted = line_style(
2339                &tokens,
2340                Level::Info,
2341                false,
2342                Status {
2343                    highlighted: true,
2344                    ..Status::default()
2345                },
2346            );
2347            assert_eq!(highlighted.ring, Some(tokens.ring));
2348            let disabled = line_style(
2349                &tokens,
2350                Level::Info,
2351                false,
2352                Status {
2353                    disabled: true,
2354                    highlighted: true,
2355                    ..Status::default()
2356                },
2357            );
2358            assert_eq!(disabled.ring, None);
2359            let current = line_style(&tokens, Level::Info, true, Status::default());
2360            assert!(current.mark.a > idle.mark.a, "the current match stands out");
2361        }
2362    }
2363
2364    #[test]
2365    fn the_builder_has_sensible_defaults() {
2366        let state = sample();
2367        let viewer: LogViewer<'_, ()> = log_viewer(&state);
2368        assert!(!viewer.is_enabled());
2369        assert!(viewer.toolbar);
2370        assert_eq!(viewer.height, Length::Fill);
2371        assert!(viewer.menu.is_none());
2372        assert_eq!(viewer.menu_keymap, context_menu::default_keymap());
2373        let menu = menu();
2374        let viewer = viewer
2375            .toolbar(false)
2376            .height(300)
2377            .width(400)
2378            .placeholder("Filter")
2379            .empty("Quiet")
2380            .keymap(Keymap::new())
2381            .context_menu(&menu, |_| ())
2382            .context_menu_keymap(Keymap::new())
2383            .on_event(|_| ());
2384        assert!(viewer.menu.is_some());
2385        assert!(viewer.menu_keymap.is_empty());
2386        assert!(viewer.is_enabled());
2387        assert!(!viewer.toolbar);
2388        assert_eq!(viewer.height, Length::Fixed(300.0));
2389        assert_eq!(viewer.placeholder, "Filter");
2390        assert_eq!(viewer.empty, "Quiet");
2391        assert!(viewer.keymap.is_empty());
2392        assert!(format!("{viewer:?}").contains("LogViewer"));
2393    }
2394
2395    #[test]
2396    fn stream_emits_ready_first_then_batches() {
2397        let mut events = Box::pin(stream());
2398        let Some(Event::Ready(mut sender)) = block_on(events.next()) else {
2399            panic!("first event must be Ready");
2400        };
2401        block_on(async {
2402            for n in 0..3 {
2403                sender
2404                    .send(entry(Level::Info, format!("line {n}")))
2405                    .await
2406                    .expect("channel open");
2407            }
2408        });
2409        let Some(Event::Received(batch)) = block_on(events.next()) else {
2410            panic!("then a batch");
2411        };
2412        assert_eq!(batch.len(), 3);
2413        assert_eq!(batch[2].message, "line 2");
2414    }
2415
2416    #[test]
2417    fn bursts_arrive_in_batches_of_the_batch_size() {
2418        let items = stream::iter(0..BATCH_SIZE * 2 + 1);
2419        let sizes: Vec<usize> = block_on(
2420            items
2421                .ready_chunks(BATCH_SIZE)
2422                .map(|batch| batch.len())
2423                .collect(),
2424        );
2425        assert_eq!(sizes, [BATCH_SIZE, BATCH_SIZE, 1]);
2426    }
2427}