Skip to main content

iced_cube/data/
log_viewer.rs

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