use super::*;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Who {
You,
Claude,
Note,
Diff,
Output,
}
#[derive(Default)]
pub struct Panel {
pub entries: Vec<(Who, String)>,
pub input: String,
pub(super) cursor: usize,
pub(super) history: Vec<String>,
pub(super) history_at: Option<usize>,
pub session: Option<String>,
pub name: String,
pub fixed_mode: bool,
pub account: Account,
pub brief: bool,
pub model: Option<String>,
pub answered_by: Option<String>,
pub attached: Vec<String>,
pub can_edit: bool,
pub can_run: bool,
pub running: bool,
pub(super) started: Option<Instant>,
pub(super) ran_command: bool,
pub(super) partial: bool,
pub(super) scroll: usize,
}
pub(super) const SPINNER: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
pub(super) const MAX_INPUT_ROWS: usize = 5;
pub(super) const HINTS: [&str; 6] = [
"Ask about this project and press Enter. Alt+Enter starts a new line.",
"Type / for commands (model, new conversation, ...) and @ to attach a file.",
"Text selected in the file is sent along with the question.",
"It may change files. Alt+M: read only, or also run commands. Alt+U undoes.",
"Ctrl+R lists the earlier conversations. Ctrl+N starts a new one.",
"Esc goes back to the text. Alt+Z makes this panel bigger.",
];
impl Panel {
pub fn new() -> Self {
Self {
can_edit: true,
..Self::default()
}
}
pub fn say(&mut self, who: Who, text: impl Into<String>) {
self.entries.push((who, text.into()));
self.partial = false;
self.scroll = 0;
}
pub fn start(&mut self) {
self.running = true;
self.started = Some(Instant::now());
}
pub fn apply(&mut self, update: Update) -> bool {
match update {
Update::Session(session) => self.session = Some(session),
Update::Model(model) => self.answered_by = Some(model),
Update::Partial(words) => match self.entries.last_mut() {
Some((Who::Claude, text)) if self.partial => text.push_str(&words),
_ => {
self.say(Who::Claude, words);
self.partial = true;
}
},
Update::Text(text) => {
if self.partial {
self.entries.pop();
}
self.say(Who::Claude, text);
}
Update::Step(step) => {
self.ran_command = step.starts_with("Bash") || step.starts_with("Shell");
self.say(Who::Note, step);
}
Update::Diff(lines) => self.say(Who::Diff, shortened(lines).join("\n")),
Update::Output(printed) => {
if std::mem::take(&mut self.ran_command) {
let lines = printed.trim_end().lines().map(crate::runner::clean).collect();
self.say(Who::Output, shortened(lines).join("\n"));
}
}
Update::Problem(problem) => self.say(Who::Note, problem),
Update::Done => self.running = false,
Update::Failed(why) => {
self.running = false;
self.say(Who::Note, format!("Stopped: {why}"));
}
}
!self.running
}
pub fn next_mode(&mut self) {
(self.can_edit, self.can_run) = match (self.can_edit, self.can_run) {
(true, false) => (false, false),
(false, _) => (true, true),
(true, true) => (true, false),
};
}
pub fn resume(&mut self, id: String, entries: Vec<(Who, String)>) {
self.entries = entries;
self.session = Some(id);
self.partial = false;
self.scroll = 0;
}
pub fn clear(&mut self) {
self.entries.clear();
self.session = None;
self.scroll = 0;
}
pub fn last_answer(&self) -> Option<&str> {
self.entries
.iter()
.rev()
.find(|(who, _)| *who == Who::Claude)
.map(|(_, text)| text.as_str())
}
pub fn scroll_by(&mut self, rows: isize) {
self.scroll = (self.scroll as isize + rows).max(0) as usize;
}
fn byte(&self, at: usize) -> usize {
self.input.char_indices().nth(at).map_or(self.input.len(), |(byte, _)| byte)
}
pub fn type_char(&mut self, c: char) {
let at = self.byte(self.cursor);
self.input.insert(at, c);
self.cursor += 1;
}
pub fn backspace(&mut self) {
if self.cursor > 0 {
self.cursor -= 1;
self.delete();
} else if self.input.is_empty() {
self.attached.pop();
}
}
pub fn attach(&mut self, file: String) {
if !self.attached.contains(&file) {
self.attached.push(file);
}
}
pub fn set_input(&mut self, text: &str) {
self.input = text.to_string();
self.cursor = self.input.chars().count();
}
fn input_rows(&self, room: usize) -> (Vec<String>, (usize, usize)) {
let mut rows = vec![String::new()];
let mut used = 0;
let mut cursor = (0, 0);
for (index, c) in self.input.chars().chain(std::iter::once('\0')).enumerate() {
use unicode_width::UnicodeWidthChar;
let cells = c.width().unwrap_or(0);
if used + cells.max(1) > room && c != '\n' {
rows.push(String::new());
used = 0;
}
if index == self.cursor {
cursor = (rows.len() - 1, used);
}
match c {
'\n' => {
rows.push(String::new());
used = 0;
}
c if cells > 0 => {
let row = rows.last_mut().unwrap();
row.push(c);
if cells == 2 {
row.push(WIDE_PAD);
}
used += cells;
}
_ => {}
}
}
(rows, cursor)
}
pub fn box_rows(&self, width: usize, height: usize) -> usize {
let room = width.saturating_sub(3).max(1);
let most = MAX_INPUT_ROWS.min(height.saturating_sub(3)).max(1);
self.input_rows(room).0.len().min(most) + (height >= 5) as usize
}
fn status(&self) -> String {
let model = match (&self.model, &self.answered_by) {
(Some(model), _) => model.clone(),
(None, Some(answered)) => answered.clone(),
(None, None) => "default model".into(),
};
let files: String = self.attached.iter().map(|file| format!(" @{file}")).collect();
format!(" {model}{files}")
}
pub fn delete(&mut self) {
let at = self.byte(self.cursor);
if at < self.input.len() {
self.input.remove(at);
}
}
pub fn move_cursor(&mut self, step: isize) {
let end = self.input.chars().count() as isize;
self.cursor = (self.cursor as isize).saturating_add(step).clamp(0, end) as usize;
}
pub fn recall(&mut self, step: isize) {
let count = self.history.len() as isize;
let at = self.history_at.map_or(count, |at| at as isize) + step;
if at < 0 || count == 0 {
return;
}
self.history_at = (at < count).then_some(at as usize);
self.input = self.history_at.map(|at| self.history[at].clone()).unwrap_or_default();
self.cursor = self.input.chars().count();
}
pub fn take_input(&mut self) -> Option<String> {
let question = self.input.trim().to_string();
if question.is_empty() {
return None;
}
self.input.clear();
self.cursor = 0;
self.history_at = None;
if self.history.last() != Some(&question) {
self.history.push(question.clone());
}
Some(question)
}
fn lines(&self, width: usize) -> Vec<Row> {
let mut lines: Vec<Row> = Vec::new();
let plain = |style: Style, text: String| vec![Span::new(style, fit(&text, width))];
for (who, text) in &self.entries {
if *who == Who::You && !lines.is_empty() {
lines.push(plain(Style::Plain, String::new()));
}
let (style, first, rest) = match who {
Who::You => (Style::Accent, "> ", " "),
Who::Note => (Style::Dim, "· ", " "),
Who::Diff | Who::Output => {
for line in text.lines() {
let style = match (who, line.chars().next()) {
(Who::Diff, Some('+')) => Style::Colored(Color::Green),
(Who::Diff, Some('-')) => Style::Colored(Color::Red),
_ => Style::Dim,
};
lines.push(plain(style, format!(" {}", widen(line))));
}
continue;
}
Who::Claude => {
lines.extend(markdown(text.trim_end(), width));
continue;
}
};
for (index, line) in wrap(&widen(text), width.saturating_sub(2)).into_iter().enumerate() {
let prefix = if index == 0 { first } else { rest };
lines.push(plain(style, format!("{prefix}{line}")));
}
}
lines
}
pub fn render(&mut self, width: usize, height: usize, focused: bool) -> (Vec<Row>, (usize, usize)) {
let state = if self.running {
let waited = self.started.map_or(0, |started| started.elapsed().as_millis());
let spinner = SPINNER[(waited / 120) as usize % SPINNER.len()];
format!("{spinner} working {}s (Esc stops it)", waited / 1000)
} else if self.fixed_mode {
"its own settings decide what it may do".into()
} else if self.can_edit && self.can_run {
"may change files and run commands (Alt+M)".into()
} else if self.can_edit {
"may change files (Alt+M: read only)".into()
} else {
"read only (Alt+M: also run commands)".into()
};
let title_style = if focused { Style::Title } else { Style::Menu };
let state = match state.split_once(" (") {
Some((short, _)) if self.brief => short.to_string(),
_ => state,
};
let name = if self.name.is_empty() { "Claude" } else { &self.name };
let mut rows = vec![vec![Span::new(title_style, fit(&widen(&format!(" {name} · {state}")), width))]];
let room = width.saturating_sub(3).max(1);
let (question, (cursor_row, cursor_x)) = self.input_rows(room);
let most = MAX_INPUT_ROWS.min(height.saturating_sub(3)).max(1);
let from = (cursor_row + 1).saturating_sub(most);
let question: Vec<&String> = question.iter().skip(from).take(most).collect();
let status = (height >= 5) as usize;
let body = height.saturating_sub(1 + status + question.len());
let lines = self.lines(width);
self.scroll = self.scroll.min(lines.len().saturating_sub(body));
let first = lines.len().saturating_sub(body + self.scroll);
let mut shown: Vec<Row> = lines.into_iter().skip(first).take(body).collect();
if shown.is_empty() {
let name = if self.name.is_empty() { "Claude" } else { &self.name };
let first: Vec<(Style, String)> = match &self.account {
Account::Missing(install) => vec![
(Style::Bold, format!("{name} is not installed on this machine.")),
(Style::Plain, format!("To install it: {install}")),
(Style::Dim, "Then open this panel again.".into()),
],
Account::SignedOut => vec![
(Style::Bold, format!("You are not signed in to {name}.")),
(Style::Plain, "Press Enter to sign in. Its sign-in page opens in your browser,".into()),
(Style::Plain, "and you come back here when it is done.".into()),
],
Account::SignedIn(who) if !who.is_empty() => vec![(Style::Bold, who.clone())],
_ => Vec::new(),
};
let ready = !matches!(self.account, Account::Missing(_) | Account::SignedOut);
let hints = HINTS.iter().filter(|_| ready).map(|hint| (Style::Dim, hint.to_string()));
let lines = first.into_iter().chain(hints).take(body);
shown.extend(lines.map(|(style, line)| vec![Span::new(style, fit(&widen(&line), width))]));
}
shown.resize(body, vec![Span::new(Style::Plain, fit("", width))]);
rows.extend(shown);
if status > 0 {
rows.push(vec![Span::new(Style::FieldNote, fit(&self.status(), width))]);
}
let first_row = rows.len();
for (index, row) in question.iter().enumerate() {
let mark = if index + from == 0 { "> " } else { " " };
rows.push(vec![Span::new(Style::Field, fit(&format!("{mark}{row}"), width))]);
}
rows.truncate(height);
let cursor = (2 + cursor_x, (first_row + cursor_row - from).min(height.saturating_sub(1)));
(rows, cursor)
}
}