multiverse/widgets/
mod.rs

1use itertools::Itertools;
2use ratatui::{prelude::*, widgets::WidgetRef};
3
4pub mod help;
5pub mod recovery;
6pub mod room_list;
7pub mod room_view;
8pub mod settings;
9pub mod status;
10
11/// A hyperlink widget that renders a hyperlink in the terminal using [OSC 8].
12///
13/// [OSC 8]: https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
14struct Hyperlink<'content> {
15    text: Text<'content>,
16    url: String,
17}
18
19impl<'content> Hyperlink<'content> {
20    fn new(text: impl Into<Text<'content>>, url: impl Into<String>) -> Self {
21        Self { text: text.into(), url: url.into() }
22    }
23}
24
25impl WidgetRef for Hyperlink<'_> {
26    fn render_ref(&self, area: Rect, buffer: &mut Buffer) {
27        self.text.render_ref(area, buffer);
28
29        // this is a hacky workaround for https://github.com/ratatui-org/ratatui/issues/902, a bug
30        // in the terminal code that incorrectly calculates the width of ANSI escape
31        // sequences. It works by rendering the hyperlink as a series of
32        // 2-character chunks, which is the calculated width of the hyperlink
33        // text.
34        for (i, two_chars) in self.text.to_string().chars().chunks(2).into_iter().enumerate() {
35            let text = two_chars.collect::<String>();
36            let hyperlink = format!("\x1B]8;;{}\x07{}\x1B]8;;\x07", self.url, text);
37            buffer[(area.x + i as u16 * 2, area.y)].set_symbol(hyperlink.as_str());
38        }
39    }
40}