Skip to main content

subspace_dashboard/chat_input/
counter.rs

1//! Opt-in draft limits, independent of any protocol or host.
2
3use crate::badge::PillTone;
4
5const BYTES_PER_KB: usize = 1024;
6const BYTE_REVEAL_DIVISOR: usize = 2;
7const WARNING_NUMERATOR: usize = 4;
8const WARNING_DENOMINATOR: usize = 5;
9
10/// Limits supplied by the host. Zero values are clamped to one.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub struct DraftLimits {
13    lines: usize,
14    bytes: usize,
15}
16
17impl DraftLimits {
18    pub fn new(lines: usize, bytes: usize) -> Self {
19        Self {
20            lines: lines.max(1),
21            bytes: bytes.max(1),
22        }
23    }
24
25    pub(super) fn counter(self, text: &str) -> Option<Counter> {
26        let lines = text.lines().count().max(1);
27        let bytes = text.len();
28        Counter::new(lines, bytes, self)
29    }
30}
31
32#[derive(Debug, PartialEq)]
33pub(super) struct Counter {
34    pub text: String,
35    pub label: String,
36    pub tone: PillTone,
37}
38
39impl Counter {
40    fn new(lines: usize, bytes: usize, limits: DraftLimits) -> Option<Self> {
41        let text = counter_text(lines, bytes, limits);
42        let tone = usage_tone(lines, limits.lines).max(usage_tone(bytes, limits.bytes));
43        let label = format!("Draft limits: {text}. {}.", limit_status(tone));
44        (!text.is_empty()).then_some(Self { text, label, tone })
45    }
46}
47
48fn limit_status(tone: PillTone) -> &'static str {
49    match tone {
50        PillTone::Muted => "Within limits",
51        PillTone::Warning => "Near the limit",
52        PillTone::Danger => "Over the limit",
53    }
54}
55
56fn counter_text(lines: usize, bytes: usize, limits: DraftLimits) -> String {
57    let mut parts = Vec::new();
58    if lines > 1 {
59        parts.push(format!("{lines} / {} lines", limits.lines));
60    }
61    if bytes > limits.bytes / BYTE_REVEAL_DIVISOR {
62        parts.push(format!(
63            "{:.1} / {} KB",
64            bytes as f64 / BYTES_PER_KB as f64,
65            limits.bytes / BYTES_PER_KB,
66        ));
67    }
68    parts.join(" ยท ")
69}
70
71fn usage_tone(used: usize, maximum: usize) -> PillTone {
72    if used > maximum {
73        PillTone::Danger
74    } else if used.saturating_mul(WARNING_DENOMINATOR) >= maximum.saturating_mul(WARNING_NUMERATOR)
75    {
76        PillTone::Warning
77    } else {
78        PillTone::Muted
79    }
80}
81
82#[cfg(test)]
83mod tests;