curd-editor 0.6.0

A small terminal code editor: projects with a file tree, git status, tabs, quick open and language-server support
//! The file tree shown in the sidebar.
//!
//! Folders are read only when they are opened, so a huge project costs
//! nothing until the user looks inside it.

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use crossterm::style::Color;

use crate::git::{FileStatus, GitInfo};
use crate::screen::{fit, Row, Span, Style};

#[cfg(test)]
mod tests;

/// One visible row of the tree.
#[derive(Clone, Debug, PartialEq)]
pub struct Entry {
    pub path: PathBuf,
    pub name: String,
    /// How many folders deep it is below the project folder.
    pub depth: usize,
    pub is_dir: bool,
    /// For folders: whether its contents are shown.
    pub expanded: bool,
}

pub struct Tree {
    root: PathBuf,
    /// The visible rows, top to bottom.
    entries: Vec<Entry>,
    selected: usize,
    /// The first entry shown, when there are more than fit on screen.
    offset: usize,
}

/// What is directly inside `dir`: folders first, then files, each in
/// alphabetical order. The `.git` folder is left out.
fn children(dir: &Path, depth: usize) -> Vec<Entry> {
    let Ok(listing) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    let mut entries: Vec<Entry> = listing
        .flatten()
        .map(|item| Entry {
            name: item.file_name().to_string_lossy().into_owned(),
            is_dir: item.path().is_dir(),
            path: item.path(),
            depth,
            expanded: false,
        })
        .filter(|entry| entry.name != ".git")
        .collect();
    entries.sort_by_key(|entry| (!entry.is_dir, entry.name.to_lowercase()));
    entries
}

impl Tree {
    pub fn new(root: PathBuf) -> Self {
        Self {
            entries: children(&root, 0),
            root,
            selected: 0,
            offset: 0,
        }
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    /// The entry the selection is on, if the folder is not empty.
    pub fn selected(&self) -> Option<&Entry> {
        self.entries.get(self.selected)
    }

    /// Moves the selection `rows` down (up, when negative).
    pub fn move_by(&mut self, rows: isize) {
        let last = self.entries.len().saturating_sub(1) as isize;
        self.selected = (self.selected as isize + rows).clamp(0, last) as usize;
    }

    fn expand(&mut self, index: usize) {
        let entry = &mut self.entries[index];
        if entry.is_dir && !entry.expanded {
            entry.expanded = true;
            let inside = children(&entry.path.clone(), entry.depth + 1);
            self.entries.splice(index + 1..index + 1, inside);
        }
    }

    fn collapse(&mut self, index: usize) {
        let depth = self.entries[index].depth;
        self.entries[index].expanded = false;
        let inside = self.entries[index + 1..]
            .iter()
            .take_while(|entry| entry.depth > depth)
            .count();
        self.entries.drain(index + 1..index + 1 + inside);
    }

    /// Enter on the selected entry: a folder opens or closes, and a file
    /// is returned for the editor to open.
    pub fn activate(&mut self) -> Option<PathBuf> {
        let entry = self.entries.get(self.selected)?;
        if !entry.is_dir {
            return Some(entry.path.clone());
        }
        if entry.expanded {
            self.collapse(self.selected);
        } else {
            self.expand(self.selected);
        }
        None
    }

    /// Right arrow: opens a folder, or steps into one that is already open.
    pub fn right(&mut self) {
        match self.entries.get(self.selected) {
            Some(entry) if entry.is_dir && !entry.expanded => self.expand(self.selected),
            Some(entry) if entry.is_dir => self.move_by(1),
            _ => {}
        }
    }

    /// Left arrow: closes an open folder, or else jumps to the folder the
    /// selected entry is in.
    pub fn left(&mut self) {
        let Some(entry) = self.entries.get(self.selected) else {
            return;
        };
        if entry.is_dir && entry.expanded {
            self.collapse(self.selected);
        } else if let Some(parent) = self.entries[..self.selected]
            .iter()
            .rposition(|above| above.depth < entry.depth)
        {
            self.selected = parent;
        }
    }

    /// Reads the folders again, keeping open folders open and the selection
    /// on the same entry where it still exists.
    pub fn refresh(&mut self) {
        let open: HashSet<PathBuf> = self
            .entries
            .iter()
            .filter(|entry| entry.expanded)
            .map(|entry| entry.path.clone())
            .collect();
        let selected = self.selected().map(|entry| entry.path.clone());

        self.entries = children(&self.root, 0);
        let mut index = 0;
        while index < self.entries.len() {
            if open.contains(&self.entries[index].path) {
                self.expand(index);
            }
            index += 1;
        }
        self.selected = selected
            .and_then(|path| self.entries.iter().position(|entry| entry.path == path))
            .unwrap_or(self.selected.min(self.entries.len().saturating_sub(1)));
    }

    /// Opens the folders leading to `path` and selects it, so the tree
    /// shows where the open file is. Does nothing for files outside the
    /// project.
    pub fn reveal(&mut self, path: &Path) {
        let Ok(inside) = path.strip_prefix(&self.root) else {
            return;
        };
        let mut current = self.root.clone();
        for part in inside.components() {
            current.push(part);
            let Some(index) = self.entries.iter().position(|entry| entry.path == current) else {
                return;
            };
            if current != path {
                self.expand(index);
            }
            self.selected = index;
        }
    }

    /// A mouse click on row `row` of the list (not counting the title):
    /// selects that entry and acts on it like Enter.
    pub fn click(&mut self, row: usize) -> Option<PathBuf> {
        let index = self.offset + row;
        if index >= self.entries.len() {
            return None;
        }
        self.selected = index;
        self.activate()
    }

    /// The sidebar, exactly `width` x `height` characters: the project
    /// name, the tree, and the git branch on the last row.
    pub fn render(
        &mut self,
        width: usize,
        height: usize,
        focused: bool,
        git: Option<&GitInfo>,
    ) -> Vec<Row> {
        let mut rows = Vec::with_capacity(height);
        if height == 0 {
            return rows;
        }
        let title = self.root.file_name().map_or_else(
            || self.root.to_string_lossy().into_owned(),
            |name| name.to_string_lossy().into_owned(),
        );
        rows.push(vec![Span::new(Style::Bold, fit(&format!(" {title}"), width))]);

        // Keep the selection in view.
        let list_rows = height.saturating_sub(2);
        if self.selected < self.offset {
            self.offset = self.selected;
        }
        if list_rows > 0 && self.selected >= self.offset + list_rows {
            self.offset = self.selected + 1 - list_rows;
        }

        for index in self.offset..self.offset + list_rows {
            let Some(entry) = self.entries.get(index) else {
                rows.push(vec![Span::new(Style::Plain, " ".repeat(width))]);
                continue;
            };
            let status = git.and_then(|git| git.status_of(&entry.path));
            let arrow = match (entry.is_dir, entry.expanded) {
                (true, true) => "▾",
                (true, false) => "▸",
                (false, _) => " ",
            };
            // The status letter sits at the right edge, like in VS Code.
            let letter = match status {
                Some(FileStatus::Modified) => "M",
                Some(FileStatus::Staged) => "S",
                Some(FileStatus::Untracked) => "U",
                Some(FileStatus::Conflict) => "!",
                Some(FileStatus::Ignored) | None => " ",
            };
            let label = format!(" {}{arrow} {}", "  ".repeat(entry.depth), entry.name);
            let text = format!("{}{letter} ", fit(&label, width.saturating_sub(2)));
            let style = if focused && index == self.selected {
                Style::Reverse
            } else {
                match status {
                    Some(FileStatus::Modified) => Style::Colored(Color::Yellow),
                    Some(FileStatus::Staged) => Style::Colored(Color::Cyan),
                    Some(FileStatus::Untracked) => Style::Colored(Color::Green),
                    Some(FileStatus::Conflict) => Style::Colored(Color::Red),
                    Some(FileStatus::Ignored) => Style::Dim,
                    None => Style::Plain,
                }
            };
            rows.push(vec![Span::new(style, fit(&text, width))]);
        }

        if height > 1 {
            let branch = match git {
                Some(git) => format!(" git: {}", git.branch),
                None => " no git".to_string(),
            };
            rows.push(vec![Span::new(Style::Reverse, fit(&branch, width))]);
        }
        rows
    }
}