i18n_ui 0.2.126

Terminal UI for translation progress with interactive concurrent panels and line-by-line fallback
Documentation
//! Zone 3: completed and failed task feed, lingering fade window, and post-exit error summary

use std::{
  collections::VecDeque,
  io::{Write, stderr},
  time::{Duration, Instant},
};

use ratatui::{
  buffer::Buffer,
  layout::Rect,
  text::{Line, Span},
  widgets::Widget,
};

use super::{
  BAD, COL_GAP, COL_GAP_W, DIM, FAINT, NOTE, OK, RIGHT_PAD, paint_rain, row_rect, style_done_line,
};
use crate::{
  board::{Board, Ended},
  event::Name,
  i18n::T,
  text::{dur_col, fit, fit_end, fmt_tok_word, push_meta, width},
};

/// Max completed/log rows kept for the bottom completed panel
const DONE_CAP: usize = 128;
/// Max failed tasks / notes retained for printing after leaving the alternate screen
const EXIT_CAP: usize = 64;
/// Total display time of completed rows before retiring to clear space for rain
pub(super) const DONE_TTL: Duration = Duration::from_secs(4);
/// Trailing dissolve window during which a completed row dims into dark phosphor
const DONE_FADE: Duration = Duration::from_millis(1200);

/// Failed task record kept for persistent stderr output on exit
pub(super) struct FailRec {
  name: Name,
  slot_label: Option<String>,
  tok: u64,
  err: String,
}

/// Entry shown in the completed section below active translations
pub(super) enum DoneItem {
  Task(Ended),
  Log(String),
}

/// Completed entry timestamped so interactive mode can fade and retire it after a short display
pub(super) struct DoneEntry {
  pub(super) item: DoneItem,
  pub(super) at: Instant,
}

#[derive(Default)]
pub(super) struct DoneFeed {
  /// Newest-first feed of completed tasks and logs rendered in the bottom section
  pub(super) done_li: VecDeque<DoneEntry>,
  /// Failed tasks retained for persistent stderr output on exit
  pub(super) fail_li: Vec<FailRec>,
  /// Informational log messages retained for persistent stderr output on exit
  pub(super) note_li: Vec<String>,
}

impl DoneFeed {
  pub(super) fn push(&mut self, item: DoneItem) {
    if let DoneItem::Log(text) = &item {
      if self.note_li.len() < EXIT_CAP {
        self.note_li.push(text.clone());
      }
    } else if let DoneItem::Task(ended) = &item
      && let Some(err) = &ended.err
      && self.fail_li.len() < EXIT_CAP
    {
      self.fail_li.push(FailRec {
        name: ended.name.clone(),
        slot_label: ended.slot_label.clone(),
        tok: ended.tok,
        err: err.clone(),
      });
    }
    if self.done_li.len() >= DONE_CAP {
      self.done_li.pop_back();
    }
    self.done_li.push_front(DoneEntry {
      item,
      at: Instant::now(),
    });
  }

  /// Record a completed task on exit/timeout without keeping its error twice when moving it directly to the feed
  pub(super) fn push_ended(&mut self, ended: Ended) {
    self.push(DoneItem::Task(ended));
  }

  pub(super) fn reap_expired(&mut self, now: Instant) {
    #[cfg(feature = "matrix")]
    while self
      .done_li
      .back()
      .is_some_and(|e| now.saturating_duration_since(e.at) >= DONE_TTL)
    {
      self.done_li.pop_back();
    }
    #[cfg(not(feature = "matrix"))]
    let _ = now;
  }
}

/// Completed or failed task row fitted to terminal width `w`
pub(super) fn ended_line<'a>(ended: &'a Ended, w: usize) -> Line<'a> {
  let (glyph, style) = match ended.err {
    None => (" ✓ ", OK),
    Some(_) => (" ✕ ", BAD),
  };
  let mut span_li = vec![Span::styled(glyph, style)];
  let mut used = width(glyph);
  if ended.err.is_none() {
    let d = dur_col(ended.sec);
    used += width(&d) + COL_GAP_W;
    span_li.push(Span::styled(d, DIM));
    span_li.push(Span::raw(COL_GAP));
  }
  let mut tail_li: Vec<Span<'a>> = Vec::with_capacity(6);
  let mut tail_w = 0usize;
  if let Some(slot_label) = ended.slot_label.as_deref() {
    tail_w += COL_GAP_W + width(slot_label);
    tail_li.push(Span::raw(COL_GAP));
    tail_li.push(Span::styled(slot_label, FAINT));
  }
  if ended.tok > 0 {
    let tok_s = fmt_tok_word(ended.tok);
    tail_w += COL_GAP_W + width(&tok_s);
    tail_li.push(Span::raw(COL_GAP));
    tail_li.push(Span::styled(tok_s, FAINT));
  }
  match &ended.err {
    None => {
      if ended.retry_cnt > 0 {
        let retry_s = T.ui.retry_n(ended.retry_cnt);
        tail_w += COL_GAP_W + width(&retry_s);
        tail_li.push(Span::raw(COL_GAP));
        tail_li.push(Span::styled(retry_s, FAINT));
      }
      let out_budget = w.saturating_sub(used + tail_w + RIGHT_PAD).max(8);
      span_li.push(Span::styled(fit_end(ended.name.out(), out_budget), DIM));
      span_li.extend(tail_li);
    }
    Some(msg) => {
      let max_w = w.saturating_sub(RIGHT_PAD);
      let path_cap = max_w.saturating_sub(used + tail_w);
      let out = fit_end(ended.name.out(), (path_cap / 2).max(10));
      used += width(&out) + tail_w;
      span_li.push(Span::styled(out, DIM));
      span_li.extend(tail_li);
      let err_budget = max_w.saturating_sub(used + COL_GAP_W).max(8);
      span_li.push(Span::raw(COL_GAP));
      span_li.push(Span::styled(fit(msg, err_budget), BAD));
    }
  }
  Line::from(span_li)
}

pub(super) fn draw_done(
  area: Rect,
  rain_zone: Rect,
  buf: &mut Buffer,
  done: &DoneFeed,
  frame: usize,
) {
  let w = usize::from(area.width);
  let now = Instant::now();
  let mut y = area.y;
  for entry in done.done_li.iter().take(usize::from(area.height)) {
    let rem_life = DONE_TTL.saturating_sub(now.saturating_duration_since(entry.at));
    match &entry.item {
      DoneItem::Task(ended) => {
        // Render owned line when matrix fade mutates styles
        let line = ended_line(ended, w);
        #[cfg(feature = "matrix")]
        let line = style_done_line(
          Line::from(
            line
              .spans
              .into_iter()
              .map(|s| Span::styled(s.content.into_owned(), s.style))
              .collect::<Vec<_>>(),
          ),
          rem_life,
          DONE_FADE,
        );
        #[cfg(not(feature = "matrix"))]
        let _ = (rem_life, DONE_FADE, style_done_line);
        line.render(row_rect(area, y), buf);
      }
      DoneItem::Log(text) => {
        let note = T.ui.note();
        let line = Line::from(vec![
          Span::styled(" ", NOTE),
          Span::styled(note, NOTE),
          Span::styled(" ", NOTE),
          Span::styled(
            fit(text, w.saturating_sub(width(note) + 2 + RIGHT_PAD)).into_owned(),
            DIM,
          ),
        ]);
        style_done_line(line, rem_life, DONE_FADE).render(row_rect(area, y), buf);
      }
    }
    y = y.saturating_add(1);
  }
  paint_rain(rain_zone, y, area.bottom(), buf, frame);
}

pub(super) fn print_exit(board: &Board, done: &DoneFeed) {
  let mut err = stderr().lock();
  for text in &done.note_li {
    let _ = writeln!(err, "{} {text}", T.ui.note());
  }
  let mut meta = String::with_capacity(48);
  for rec in &done.fail_li {
    meta.clear();
    push_meta(&mut meta, rec.slot_label.as_deref(), rec.tok);
    let _ = writeln!(err, "✕ {}{meta}  {}", rec.name.tag(), rec.err);
  }
  if let Some(summary) = board.summary() {
    let _ = writeln!(err, "{summary}");
  }
}