i18n_ui 0.2.126

Terminal UI for translation progress with interactive concurrent panels and line-by-line fallback
Documentation
//! Direct-to-buffer card body rendering for streaming output, retry details, and fading errors

use std::{borrow::Cow, time::Duration};

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

use super::{
  BAD, Ctx, GLOW, MARK_REPLY, MARK_THINK, PREFIX_W, REPLY, THINK, WARN, body_col,
  retry::{retry_badge, retry_line, same_host},
  trunk,
};
use crate::{
  board::Run,
  text::{fit, fit_owned, split_w, tail},
  tty::{draw_waiting, row_rect, view::Fade},
};

/// Stream output newer than this keeps a glowing head on its last glyph
const GLOW_FOR: Duration = Duration::from_millis(320);

pub(super) fn draw_body(
  area: Rect,
  y: &mut u16,
  buf: &mut Buffer,
  card: super::Card<'_>,
  host: Option<&str>,
  ctx: &Ctx<'_>,
  last: bool,
) {
  match card {
    super::Card::Run(r) => draw_run_body(area, y, buf, r, host, ctx, last),
    super::Card::Fade(f) => draw_fade_body(area, y, buf, f, ctx, last),
  }
}

fn push_row(area: Rect, y: &mut u16, buf: &mut Buffer, line: Line<'_>) {
  line.render(row_rect(area, *y), buf);
  *y += 1;
}

/// Failed card: wrap the error directly onto `buf` rows with zero `Vec<Line>` allocation
fn draw_fade_body(area: Rect, y: &mut u16, buf: &mut Buffer, f: &Fade, ctx: &Ctx<'_>, last: bool) {
  let col = body_col(ctx.w);
  let mut rest = f.ended.err.as_deref().unwrap_or_default();
  for k in 0..ctx.body {
    let text: Cow<'_, str> = if k + 1 == ctx.body {
      fit(rest, col)
    } else {
      let (head, tail) = split_w(rest, col);
      rest = tail;
      Cow::Borrowed(head)
    };
    if text.is_empty() {
      break;
    }
    push_row(
      area,
      y,
      buf,
      Line::from(vec![
        trunk(last),
        Span::raw(MARK_THINK),
        Span::styled(text, BAD),
      ]),
    );
  }
}

fn stream_line<'a>(
  last: bool,
  mark: &'static str,
  text: &'a str,
  style: Style,
  glow: bool,
) -> Line<'a> {
  let mut span_li = Vec::with_capacity(4);
  span_li.push(trunk(last));
  span_li.push(Span::styled(mark, style));
  match text.char_indices().next_back() {
    Some((i, _)) if glow => {
      span_li.push(Span::styled(&text[..i], style));
      span_li.push(Span::styled(&text[i..], GLOW));
    }
    _ => span_li.push(Span::styled(text, style)),
  }
  Line::from(span_li)
}

fn draw_run_body(
  area: Rect,
  y: &mut u16,
  buf: &mut Buffer,
  run: &Run,
  host: Option<&str>,
  ctx: &Ctx<'_>,
  last: bool,
) {
  let col = body_col(ctx.w);

  if let Some(r) = &run.retry {
    let badge = retry_badge(r);
    // The tree root already names this host: do not repeat the endpoint URL
    let base = if host.is_some_and(|h| same_host(&r.base, h)) {
      ""
    } else {
      r.base.as_str()
    };
    if ctx.body > 1 {
      if let Some(text) = tail(&run.reply, col, 1).pop() {
        push_row(
          area,
          y,
          buf,
          stream_line(last, MARK_REPLY, &text, REPLY, false),
        );
      } else if let Some(text) = tail(&run.think, col, 1).pop() {
        push_row(
          area,
          y,
          buf,
          stream_line(last, MARK_THINK, &text, THINK, false),
        );
      } else {
        // Nothing streamed yet: badge + endpoint on the first row, the error below
        let (head, base_shown) = retry_line(last, badge, base, r, ctx.now, col, ctx.w);
        push_row(area, y, buf, head);
        let sub = if base_shown || base.is_empty() {
          fit(&r.err, col)
        } else {
          Cow::Owned(fit_owned(format!("{base} · {}", r.err), col))
        };
        push_row(
          area,
          y,
          buf,
          Line::from(vec![
            trunk(last),
            Span::raw(MARK_THINK),
            Span::styled(sub, WARN),
          ]),
        );
        return;
      }
    }
    let detail = if base.is_empty() {
      Cow::Borrowed(r.err.as_str())
    } else {
      Cow::Owned(format!("{base} · {}", r.err))
    };
    push_row(
      area,
      y,
      buf,
      retry_line(last, badge, &detail, r, ctx.now, col, ctx.w).0,
    );
    return;
  }

  let glow = ctx.now.saturating_duration_since(run.at) < GLOW_FOR;
  let reply = tail(&run.reply, col, 1).pop();
  let think_li = tail(&run.think, col, ctx.body - usize::from(reply.is_some()));
  let think_n = think_li.len();
  let has_text = reply.is_some() || think_n > 0;
  for (k, text) in think_li.iter().enumerate() {
    let newest = reply.is_none() && k + 1 == think_n;
    push_row(
      area,
      y,
      buf,
      stream_line(last, MARK_THINK, text, THINK, glow && newest),
    );
  }
  if let Some(text) = reply {
    push_row(
      area,
      y,
      buf,
      stream_line(last, MARK_REPLY, &text, REPLY, glow),
    );
  }
  if !has_text {
    // Waiting for the first token: render trunk prefix + phosphor pulse directly to `buf`
    let row = row_rect(area, *y);
    Line::from(vec![trunk(last), Span::raw(MARK_THINK)]).render(row, buf);
    if col > 0 && row.width as usize > PREFIX_W {
      let pulse_area = Rect::new(
        row.x + PREFIX_W as u16,
        row.y,
        (row.width - PREFIX_W as u16).min(col as u16),
        1,
      );
      draw_waiting(pulse_area, buf, run.id, ctx.frame);
    }
    *y += 1;
  }
}