Skip to main content

supercode_frontend_tui/foundation/
width.rs

1// Derived from OpenAI Codex: codex-rs/tui/src/width.rs
2// Pinned source: 8604689ec5e3437eb79802d8d72249b7722fbf5b
3// Copyright 2025 OpenAI
4// Licensed under the Apache License, Version 2.0.
5// Modified by the Supercode contributors; see docs/legal/codex-frontend-extraction.toml.
6
7//! Width guards for transcript rendering with fixed prefix columns.
8//!
9//! Several rendering paths reserve a fixed number of columns for bullets,
10//! gutters, or labels before laying out content.  When the terminal is very
11//! narrow, those reserved columns can consume the entire width, leaving zero
12//! or negative space for content.
13//!
14//! These helpers centralise the subtraction and enforce a strict-positive
15//! contract: they return `Some(n)` where `n > 0`, or `None` when no usable
16//! content width remains.  Callers treat `None` as "render prefix-only
17//! fallback" rather than attempting wrapped rendering at zero width, which
18//! would produce empty or unstable output.
19
20/// Returns usable content width after reserving fixed columns.
21///
22/// Guarantees a strict positive width (`Some(n)` where `n > 0`) or `None` when
23/// the reserved columns consume the full width.
24///
25/// Treat `None` as "render prefix-only fallback". Coercing it to `0` and still
26/// attempting wrapped rendering often produces empty or unstable output at very
27/// narrow terminal widths.
28pub fn usable_content_width(total_width: usize, reserved_cols: usize) -> Option<usize> {
29    total_width
30        .checked_sub(reserved_cols)
31        .filter(|remaining| *remaining > 0)
32}
33
34/// `u16` convenience wrapper around [`usable_content_width`].
35///
36/// This keeps width math at callsites that receive terminal dimensions as
37/// `u16` while preserving the same `None` contract for exhausted width.
38pub fn usable_content_width_u16(total_width: u16, reserved_cols: u16) -> Option<usize> {
39    usable_content_width(usize::from(total_width), usize::from(reserved_cols))
40}