i18n_ui 0.2.126

Terminal UI for translation progress with interactive concurrent panels and line-by-line fallback
Documentation
//! Full-screen board: event application and 4-zone layout orchestration

use std::time::{Duration, Instant};

use lang::by_code;
use ratatui::{buffer::Buffer, layout::Rect};

use super::{
  PoolCache, done::DoneFeed, draw_done, draw_foot, draw_pool, draw_sec_head, draw_task, row_rect,
};
use crate::{
  board::{Act, Board, Ended},
  event::Event,
  i18n::T,
  tty::FOOT_ROW,
};

/// How long a failed card stays in the tree, so its error can be read before it joins the feed
///
/// The render thread is a plain OS thread driven by `recv_timeout`; lingering is a deadline checked
/// each frame, never a blocking sleep, so the board keeps animating meanwhile.
pub(super) const FADE: Duration = Duration::from_secs(3);
/// Separator between source language names when tasks come from several languages
const SRC_SEP: &str = " / ";

/// A failed task kept on screen until `until`
pub(super) struct Fade {
  pub(super) ended: Ended,
  /// Original start time, keeps the card in place among its siblings
  pub(super) begin: Instant,
  until: Instant,
}

/// Render-side state of the board stage
#[derive(Default)]
pub(super) struct Stage {
  pool: PoolCache,
  pub(super) fade_li: Vec<Fade>,
  pub(super) done: DoneFeed,
  /// Distinct source languages seen so far, in first-seen order (usually one)
  src_li: Vec<String>,
  /// Cached section title language names, rebuilt only when `src_li` grows
  src: String,
  src_n: usize,
}

impl Stage {
  /// Apply one event; returns `true` when the UI should close
  pub(super) fn apply(&mut self, board: &mut Board, event: Event) -> bool {
    match board.apply(event) {
      Act::None | Act::Plan { .. } | Act::Retry(_) => {}
      Act::Start(id) => {
        if let Some(run) = board.run(id) {
          let from = run.name.from();
          if !self.src_li.iter().any(|s| s == from) {
            self.src_li.push(from.to_owned());
          }
        }
      }
      Act::Text { id, text, reply } => {
        if let Some(run) = board.run(id) {
          run.push_tail(&text, reply);
        }
      }
      Act::End(mut ended) => {
        // Interactive mode never flushes residual thinking on exit; drop buffer before retaining in feeds
        ended.think = String::new();
        if ended.err.is_some() {
          let now = Instant::now();
          // `try_from` instead of `from_secs_f32`, which panics on a negative or non-finite value
          let begin = Duration::try_from_secs_f32(ended.sec)
            .ok()
            .and_then(|d| now.checked_sub(d))
            .unwrap_or(now);
          self.fade_li.push(Fade {
            begin,
            until: now + FADE,
            ended,
          });
        } else {
          self.done.push_ended(ended);
        }
      }
      Act::Log(text) => self.done.push(super::done::DoneItem::Log(text)),
      Act::Close => return true,
    }
    false
  }

  /// Move expired failed cards into the completed feed, then retire expired feed rows
  pub(super) fn reap(&mut self, now: Instant) {
    // `extract_if` keeps the remaining order and moves each expired card out without cloning
    for fade in self.fade_li.extract_if(.., |f| f.until <= now) {
      self.done.push_ended(fade.ended);
    }
    self.done.reap_expired(now);
  }

  /// Move every failed card into the feed (and the exit report), expired or not
  pub(super) fn flush(&mut self) {
    for fade in self.fade_li.drain(..) {
      self.done.push_ended(fade.ended);
    }
  }

  /// Endonyms of every source language seen so far; `src_li` only grows, so its length is the key
  fn src_title(&mut self) -> &str {
    if self.src_n != self.src_li.len() {
      self.src_n = self.src_li.len();
      self.src.clear();
      for (i, code) in self.src_li.iter().enumerate() {
        if i > 0 {
          self.src.push_str(SRC_SEP);
        }
        self.src.push_str(src_name(code));
      }
    }
    &self.src
  }
}

/// Source language display name: the endonym from `lang`, else the raw code
fn src_name(code: &str) -> &str {
  by_code(code).map_or(code, |c| c.name())
}

pub(super) fn draw(area: Rect, buf: &mut Buffer, board: &Board, stage: &mut Stage, frame: usize) {
  if area.width == 0 || area.height == 0 {
    return;
  }
  let w = usize::from(area.width);
  let avail = area.height.saturating_sub(FOOT_ROW);
  let mut y = area.y;

  // 1. Fixed top API pool section (height depends strictly on slot count and terminal height)
  let slot_cnt = board.slot_li.len();
  let pool_row = if slot_cnt == 0 || avail == 0 {
    0
  } else {
    let max_pool = ((u32::from(avail) * 2) / 5)
      .clamp(1, 12)
      .min(u32::from(avail.saturating_sub(4).max(1))) as u16;
    (slot_cnt.min(usize::from(u16::MAX)) as u16).min(max_pool)
  };
  if pool_row > 0 {
    draw_pool(
      Rect::new(area.x, y, area.width, pool_row),
      buf,
      board,
      &mut stage.pool,
    );
    y += pool_row;
  }

  // 2. Fixed middle-to-bottom partition so section headers never bounce as tasks start/finish
  let rem = avail.saturating_sub(pool_row);
  if rem >= 1 {
    let name = stage.src_title();
    let run_title = if board.pool_stat.queued > 0 {
      T.ui
        .sec_run_q(board.active_conc(), name, board.pool_stat.queued)
    } else {
      T.ui.sec_run(board.active_conc(), name)
    };
    draw_sec_head(row_rect(area, y), buf, &run_title, w);
    y += 1;

    let body_rem = rem.saturating_sub(1);
    let rain_zone = Rect::new(area.x, y, area.width, body_rem);
    let done_sec = if body_rem >= 3 {
      ((u32::from(body_rem) * 2) / 5)
        .max(2)
        .min(u32::from(body_rem.saturating_sub(1))) as u16
    } else {
      0
    };
    let task_row = body_rem.saturating_sub(done_sec);
    if task_row > 0 {
      draw_task(
        Rect::new(area.x, y, area.width, task_row),
        rain_zone,
        buf,
        board,
        &stage.fade_li,
        frame,
      );
      y += task_row;
    }

    // 3. Completed feed directly below active tasks (newest first); empty rows show rain
    if done_sec > 0 {
      let done_title = if board.fail > 0 {
        T.ui.sec_done_fail(board.ok, board.fail)
      } else {
        T.ui.sec_done(board.ok)
      };
      draw_sec_head(row_rect(area, y), buf, &done_title, w);
      y += 1;
      let done_row = done_sec.saturating_sub(1);
      draw_done(
        Rect::new(area.x, y, area.width, done_row),
        rain_zone,
        buf,
        &stage.done,
        frame,
      );
    }
  }

  // 4. Fixed single-row global footer at the very bottom
  draw_foot(
    board,
    row_rect(area, area.bottom().saturating_sub(1)),
    buf,
    w,
  );
}