use dugix_core::highlight::Role;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use crate::theme::Theme;
pub mod glyph {
pub const YOU: &str = "❯";
pub const ASSISTANT: &str = "✦";
pub const TOOL: &str = "⚒";
pub const RESEARCH: &str = "◇";
pub const QUESTION: &str = "?";
pub const PLAN: &str = "☰";
pub const DIGEST: &str = "≡";
pub const LINK: &str = "↪";
pub const MEDIA: &str = "▣";
pub const MODEL: &str = "◆";
pub const SPACE: &str = "⌂";
pub const WEB: &str = "◎";
pub const CONNECTOR: &str = "⇄";
pub const INCOGNITO: &str = "◌";
pub const RUNNING: &str = "⟳";
pub const DOT: &str = "●";
pub const RING: &str = "○";
pub const OK: &str = "✓";
pub const FAIL: &str = "✗";
pub const WARN: &str = "⚠";
pub const SELECTED: &str = "▸";
pub const EXPANDED: &str = "▾";
pub const SECTION: &str = "▍";
pub const RAIL: &str = "▎";
pub const TRACK: &str = "░";
pub const BAR_FILL: &str = "━";
pub const BAR_TRACK: &str = "─";
pub const BAR_END: &str = "╸";
pub const LEVELS: [&str; 8] = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];
pub const FAVORITE: &str = "★";
pub const VISION: &str = "⊡";
pub const CAP_LEFT: &str = "\u{e0b6}";
pub const CAP_RIGHT: &str = "\u{e0b4}";
pub const PREV: &str = "‹";
pub const NEXT: &str = "›";
}
const DISPLAY_FONT: [(char, [&str; 3]); 15] = [
('0', ["█▀█", "█ █", "▀▀▀"]),
('1', ["▀█ ", " █ ", "▀▀▀"]),
('2', ["▀▀█", "█▀▀", "▀▀▀"]),
('3', ["▀▀█", " ▀█", "▀▀▀"]),
('4', ["█ █", "▀▀█", " ▀"]),
('5', ["█▀▀", "▀▀█", "▀▀▀"]),
('6', ["█▀▀", "█▀█", "▀▀▀"]),
('7', ["▀▀█", " █", " ▀"]),
('8', ["█▀█", "█▀█", "▀▀▀"]),
('9', ["█▀█", "▀▀█", "▀▀▀"]),
('.', [" ", " ", "▀"]),
(',', [" ", " ", "▀"]),
('-', [" ", "▀▀▀", " "]),
('+', [" ▄ ", "▀█▀", " "]),
(' ', [" ", " ", " "]),
];
#[must_use]
pub fn display_font(text: &str) -> Option<[String; 3]> {
let mut rows = [String::new(), String::new(), String::new()];
for (index, ch) in text.chars().enumerate() {
let glyph = DISPLAY_FONT.iter().find(|(key, _)| *key == ch)?.1;
for (row, part) in rows.iter_mut().zip(glyph) {
if index > 0 {
row.push(' ');
}
row.push_str(part);
}
}
(!text.is_empty()).then_some(rows)
}
#[must_use]
pub fn display_split(text: &str) -> (&str, &str) {
let end = text
.char_indices()
.find(|&(_, ch)| !(ch.is_ascii_digit() || matches!(ch, '.' | ',' | '-' | '+')))
.map_or(text.len(), |(index, _)| index);
let (number, unit) = text.split_at(end);
if number.chars().any(|ch| ch.is_ascii_digit()) {
(number, unit)
} else {
("", text)
}
}
pub const SEP: &str = " · ";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SyntaxColors {
pub accent: Color,
pub accent2: Color,
pub warning: Color,
pub success: Color,
pub error: Color,
pub dim: Color,
pub fg: Color,
}
impl SyntaxColors {
#[must_use]
pub fn from_theme(theme: &Theme) -> Self {
Self {
accent: theme.accent,
accent2: theme.accent2,
warning: theme.warning,
success: theme.success,
error: theme.error,
dim: theme.fg_dim,
fg: theme.fg,
}
}
}
impl Default for SyntaxColors {
fn default() -> Self {
Self {
accent: Color::Cyan,
accent2: Color::Magenta,
warning: Color::Yellow,
success: Color::Green,
error: Color::Red,
dim: Color::DarkGray,
fg: Color::Reset,
}
}
}
#[must_use]
pub fn syntax_style(colors: SyntaxColors, role: Role) -> Style {
let fg = |color: Color| Style::default().fg(color);
match role {
Role::Keyword | Role::Tag => fg(colors.accent),
Role::Function => fg(colors.accent2),
Role::Type | Role::Attribute => fg(colors.warning),
Role::String | Role::Code => fg(colors.success),
Role::Number | Role::Constant | Role::Escape => fg(colors.error),
Role::Comment => fg(colors.dim).add_modifier(Modifier::ITALIC),
Role::Punctuation | Role::Quote | Role::ListMarker => fg(colors.dim),
Role::Operator | Role::Property | Role::Variable => fg(colors.fg),
Role::Heading => fg(colors.accent).add_modifier(Modifier::BOLD),
Role::Emphasis => Style::default().add_modifier(Modifier::ITALIC),
Role::Strong => Style::default().add_modifier(Modifier::BOLD),
Role::Link => fg(colors.accent).add_modifier(Modifier::UNDERLINED),
}
}
#[must_use]
pub fn highlighted_lines(
source: &str,
lang: &str,
colors: SyntaxColors,
base: Style,
) -> Vec<Line<'static>> {
let spans = dugix_core::highlight::highlight(source, lang);
let mut spans = spans.iter().peekable();
let mut lines = Vec::new();
let mut start = 0;
for text in source.split('\n') {
let end = start + text.len();
let mut parts: Vec<Span<'static>> = Vec::new();
let mut at = start;
while let Some(span) = spans.peek() {
if span.range.start >= end {
break;
}
let from = span.range.start.max(at);
let to = span.range.end.min(end);
if from > at {
parts.push(Span::styled(source[at..from].to_string(), base));
}
if to > from {
parts.push(Span::styled(
source[from..to].to_string(),
base.patch(syntax_style(colors, span.role)),
));
at = to;
}
if span.range.end <= end {
spans.next();
} else {
break;
}
}
if end > at || parts.is_empty() {
parts.push(Span::styled(source[at..end].to_string(), base));
}
lines.push(Line::from(parts));
start = end + 1;
}
lines
}
pub fn section(theme: &Theme, name: &str, width: usize) -> Line<'static> {
let head = format!("{} {name} ", glyph::SECTION);
let rule = width.saturating_sub(crate::ui::style::width(&head));
Line::from(vec![
Span::styled(
head,
Style::default()
.fg(theme.accent)
.add_modifier(Modifier::BOLD),
),
Span::styled("─".repeat(rule), Style::default().fg(theme.border_dim)),
])
}
pub fn meta(theme: &Theme, text: impl Into<String>) -> Span<'static> {
Span::styled(text.into(), Style::default().fg(theme.fg_dim))
}
pub fn width(s: &str) -> usize {
unicode_width::UnicodeWidthStr::width(s)
}
pub fn sep(theme: &Theme) -> Span<'static> {
Span::styled(SEP, Style::default().fg(theme.border_dim))
}
pub fn event_head(
glyph: &str,
glyph_style: Style,
title: String,
title_style: Style,
) -> Line<'static> {
Line::from(vec![
Span::styled(format!("{glyph} "), glyph_style),
Span::styled(title, title_style),
])
}
pub fn event_body(text: &str, style: Style) -> Line<'static> {
Line::from(Span::styled(format!(" {text}"), style))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ui_strings_use_the_glyph_vocabulary_not_emoji() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/ui");
let mut stack = vec![root];
let mut offenders = Vec::new();
while let Some(dir) = stack.pop() {
for entry in std::fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
stack.push(path);
continue;
}
if path.file_name().is_some_and(|n| n == "tests.rs") {
continue;
}
let src = std::fs::read_to_string(&path).unwrap();
let code = src.split("#[cfg(test)]").next().unwrap_or("");
for (n, line) in code.lines().enumerate() {
let is_comment = line.trim_start().starts_with("//");
if !is_comment
&& line
.chars()
.any(|c| ('\u{1F000}'..='\u{1FFFF}').contains(&c))
{
offenders.push(format!("{}:{}: {}", path.display(), n + 1, line.trim()));
}
}
}
}
assert!(
offenders.is_empty(),
"emoji in UI strings:\n{}",
offenders.join("\n")
);
}
#[test]
fn display_font_draws_numbers_and_splits_units() {
let [top, middle, bottom] = display_font("2.5").unwrap();
assert_eq!(top, "▀▀█ █▀▀");
assert_eq!(middle, "█▀▀ ▀▀█");
assert_eq!(bottom, "▀▀▀ ▀ ▀▀▀");
assert!(display_font("12%").is_none());
assert_eq!(display_split("2.1 MB"), ("2.1", " MB"));
assert_eq!(display_split("-40%"), ("-40", "%"));
assert_eq!(display_split("n/a"), ("", "n/a"));
}
#[test]
fn highlighted_lines_split_multiline_spans_and_keep_text() {
let colors = SyntaxColors::default();
let source = "/* a\nb */ fn x() {}\n\nlet é = 1;";
let lines = highlighted_lines(source, "rust", colors, Style::default());
let text: Vec<String> = lines
.iter()
.map(|line| line.spans.iter().map(|s| s.content.as_ref()).collect())
.collect();
assert_eq!(text, ["/* a", "b */ fn x() {}", "", "let é = 1;"]);
let comment = syntax_style(colors, Role::Comment);
assert_eq!(lines[0].spans[0].style, comment);
assert_eq!(lines[1].spans[0].content, "b */");
assert_eq!(lines[1].spans[0].style, comment);
let plain = highlighted_lines("a\nb", "nope", colors, Style::default());
assert_eq!(plain.len(), 2);
assert_eq!(plain[1].spans[0].content, "b");
}
}