i18n_ui 0.2.126

Terminal UI for translation progress with interactive concurrent panels and line-by-line fallback
Documentation
//! Zone 2: running tasks as a tree rooted at each endpoint host
//!
//! ```text
//!  ◆ api.deepseek.com                               并发 2
//!  ├─⠋ en/guide/install.md                      #1   12.3s
//!  │    先通读原文,确定术语与语气。标题保持简洁▌
//!  │  › Read the source first, settle terms and tone.
//!  └─✕ ja/blog/release.md                       #2    8.1s
//!       HTTP 401: invalid api key
//! ```
//!
//! The host is printed once per tree, so cards only carry the token ordinal. Every card keeps its
//! file name on the head row and the model stream on body rows (two when space allows, else one);
//! failed cards linger in red for a moment before they fall into the completed feed.

mod body;
pub(super) mod retry;

use std::time::Instant;

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

use self::body::draw_body;
use super::{
  ACCENT, BAD, BOLD, COL_GAP, COL_GAP_W, DIM, FAINT, GLOW, HOST, REPLY, RIGHT_PAD, THINK, WARN,
  pad, paint_rain, row_rect, spin_at, view::Fade,
};
use crate::{
  board::{Board, Run, SlotEntry, sec},
  i18n::T,
  text::{dur, fit, fit_end, width},
};

/// Body rows per card in roomy and tight layouts
const BODY_RICH: usize = 2;
const BODY_TIGHT: usize = 1;
/// Head prefix ` ├─⠋ ` and body prefix ` │ › ` share this width so text columns line up
const PREFIX_W: usize = 5;
const BRANCH_MID: &str = "├─";
const BRANCH_END: &str = "└─";
const TRUNK_MID: &str = " │ ";
const TRUNK_END: &str = "   ";
const HOST_MARK: &str = " ◆ ";
const HOST_NONE: &str = " ◇ ";
/// Root label of the tree holding tasks not yet bound to a slot
const HOST_UNKNOWN: &str = "…";
pub(super) const FOLD_MARK: &str = " ┆ … ";
const MARK_THINK: &str = "  ";
const MARK_REPLY: &str = "› ";
const MARK_RETRY: &str = "↻ ";
const FAIL_GLYPH: &str = "✕";
const MID_MIN_W: usize = 8;

/// A card in the tree: a live task or a failed one fading out
#[derive(Clone, Copy)]
enum Card<'a> {
  Run(&'a Run),
  Fade(&'a Fade),
}

impl Card<'_> {
  fn slot(self) -> Option<usize> {
    match self {
      Self::Run(r) => r.slot,
      Self::Fade(f) => f.ended.slot,
    }
  }

  fn begin(self) -> Instant {
    match self {
      Self::Run(r) => r.begin,
      Self::Fade(f) => f.begin,
    }
  }
}

/// Tree rank of cards without a bound slot: they gather in a trailing anonymous tree
const RANK_NONE: usize = usize::MAX;

/// A card with its tree rank (first pool index of its host, so trees keep the pool panel order)
#[derive(Clone, Copy)]
struct Item<'a> {
  rank: usize,
  card: Card<'a>,
}

/// Every card sorted into contiguous trees, by start order inside each tree; one allocation per frame
fn item_li<'a>(board: &'a Board, fade_li: &'a [Fade]) -> Vec<Item<'a>> {
  let mut out: Vec<Item<'a>> = board
    .run_li
    .iter()
    .map(Card::Run)
    .chain(fade_li.iter().map(Card::Fade))
    .map(|card| Item {
      rank: board.slot(card.slot()).map_or(RANK_NONE, |s| s.root),
      card,
    })
    .collect();
  // A failed card keeps its place among its siblings while it fades
  out.sort_unstable_by_key(|it| (it.rank, it.card.begin()));
  out
}

/// Per-frame drawing context shared by every card
struct Ctx<'a> {
  board: &'a Board,
  w: usize,
  now: Instant,
  frame: usize,
  body: usize,
}

pub(super) fn draw_task(
  area: Rect,
  rain_zone: Rect,
  buf: &mut Buffer,
  board: &Board,
  fade_li: &[Fade],
  frame: usize,
) {
  let avail = usize::from(area.height);
  if avail == 0 || area.width == 0 {
    return;
  }
  let item_li = item_li(board, fade_li);
  let mut y = area.y;

  if !item_li.is_empty() {
    let card_n = item_li.len();
    let head_n = item_li.chunk_by(|a, b| a.rank == b.rank).count();
    let body = if head_n + card_n * (1 + BODY_RICH) <= avail {
      BODY_RICH
    } else {
      BODY_TIGHT
    };
    let per = 1 + body;
    // Rows reserved per card are an upper bound: a body may print fewer rows than `body`
    let fold = head_n + card_n * per > avail;
    let mut left = avail - usize::from(fold);
    let ctx = Ctx {
      board,
      w: usize::from(area.width),
      now: Instant::now(),
      frame,
      body,
    };
    let mut shown = 0usize;
    for tree_li in item_li.chunk_by(|a, b| a.rank == b.rank) {
      if left < 1 + per {
        break;
      }
      let take = tree_li.len().min((left - 1) / per);
      left -= 1 + take * per;
      shown += take;
      // SAFETY: `chunk_by` never yields an empty chunk
      let first = unsafe { tree_li.get_unchecked(0) };
      let host = board.slot(first.card.slot()).map(SlotEntry::host);
      host_line(host, tree_li, &ctx).render(row_rect(area, y), buf);
      y += 1;
      for (k, it) in tree_li.iter().take(take).enumerate() {
        let last = k + 1 == take;
        let spin = spin_at(frame + usize::from(y));
        card_head(it.card, &ctx, last, spin).render(row_rect(area, y), buf);
        y += 1;
        draw_body(area, &mut y, buf, it.card, host, &ctx, last);
      }
      if take < tree_li.len() {
        break;
      }
    }
    if shown < card_n && y < area.bottom() {
      fold_line(card_n - shown, board.pool_stat.queued, ctx.w).render(row_rect(area, y), buf);
      y += 1;
    }
  }

  // Digital rain falls through the rows the tree leaves empty
  paint_rain(rain_zone, y, area.bottom(), buf, frame);
}

fn fold_line(rem: usize, queued: usize, w: usize) -> Line<'static> {
  let text = if queued > 0 {
    T.ui.task_more_q(rem, queued)
  } else {
    T.ui.task_more(rem)
  };
  Line::from(vec![
    Span::styled(FOLD_MARK, FAINT),
    Span::styled(
      fit(&text, w.saturating_sub(width(FOLD_MARK) + RIGHT_PAD)).into_owned(),
      DIM,
    ),
  ])
}

fn host_line<'a>(host: Option<&'a str>, tree_li: &[Item<'_>], ctx: &Ctx<'_>) -> Line<'a> {
  let run_n = tree_li
    .iter()
    .filter(|it| matches!(it.card, Card::Run(_)))
    .count();
  let conc = T.ui.pool_conc(run_n);
  let (mark, mark_style, host, host_style) = match host {
    Some(h) => (HOST_MARK, ACCENT, h, HOST),
    None => (HOST_NONE, FAINT, HOST_UNKNOWN, DIM),
  };
  let host_max = ctx
    .w
    .saturating_sub(width(mark) + COL_GAP_W + width(&conc) + RIGHT_PAD);
  let host = fit(host, host_max);
  let gap = host_max.saturating_sub(width(&host)) + COL_GAP_W;
  Line::from(vec![
    Span::styled(mark, mark_style),
    Span::styled(host, host_style),
    Span::raw(pad(gap)),
    Span::styled(conc, DIM),
  ])
}

fn card_head<'a>(card: Card<'a>, ctx: &Ctx<'a>, last: bool, spin: &'static str) -> Line<'a> {
  let branch = if last { BRANCH_END } else { BRANCH_MID };
  let (glyph, glyph_style, file_style, card_sec, out) = match card {
    Card::Run(r) => {
      let style = if r.retry.is_some() { WARN } else { ACCENT };
      (spin, style, BOLD, sec(r.begin), r.name.out())
    }
    Card::Fade(f) => (FAIL_GLYPH, BAD, BAD, f.ended.sec, f.ended.name.out()),
  };
  // Borrowed from the slot label: no per-frame formatting of the ordinal
  let tag = ctx.board.slot(card.slot()).map(SlotEntry::tag);
  let time = dur(card_sec);
  let tag_w = tag.map_or(0, |s| width(s) + COL_GAP_W);
  let fixed = PREFIX_W + tag_w + width(&time) + COL_GAP_W + RIGHT_PAD;
  let file = fit_end(out, ctx.w.saturating_sub(fixed));
  let gap = ctx.w.saturating_sub(fixed + width(&file)) + COL_GAP_W;

  let mut span_li = Vec::with_capacity(9);
  span_li.push(Span::raw(" "));
  span_li.push(Span::styled(branch, FAINT));
  span_li.push(Span::styled(glyph, glyph_style));
  span_li.push(Span::raw(" "));
  span_li.push(Span::styled(file, file_style));
  span_li.push(Span::raw(pad(gap)));
  if let Some(tag) = tag {
    span_li.push(Span::styled(tag, FAINT));
    span_li.push(Span::raw(COL_GAP));
  }
  span_li.push(Span::styled(time, DIM));
  Line::from(span_li)
}

fn trunk(last: bool) -> Span<'static> {
  Span::styled(if last { TRUNK_END } else { TRUNK_MID }, FAINT)
}

/// Body text column width
fn body_col(w: usize) -> usize {
  w.saturating_sub(PREFIX_W + RIGHT_PAD)
}