clide/src/tui/editor.rs

122 lines
4.1 KiB
Rust
Raw Normal View History

2026-01-19 09:23:12 -05:00
use crate::tui::component::{Action, Component};
use anyhow::{Context, Result, bail};
use edtui::{
EditorEventHandler, EditorState, EditorTheme, EditorView, LineNumbers, Lines, SyntaxHighlighter,
};
2026-01-17 19:21:14 -05:00
use ratatui::buffer::Buffer;
use ratatui::crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::{Alignment, Rect};
use ratatui::prelude::{Color, Style};
use ratatui::widgets::{Block, Borders, Padding, Widget};
use syntect::parsing::SyntaxSet;
// TODO: Consider using editor-command https://docs.rs/editor-command/latest/editor_command/
// TODO: Title should be detected programming language name
// TODO: Content should be file contents
// TODO: Vimrc should be used
pub struct Editor {
pub state: EditorState,
pub event_handler: EditorEventHandler,
pub file_path: Option<std::path::PathBuf>,
2026-01-20 12:05:03 -05:00
syntax_set: SyntaxSet,
2026-01-17 19:21:14 -05:00
}
impl Editor {
pub fn new() -> Self {
Editor {
state: EditorState::default(),
event_handler: EditorEventHandler::default(),
file_path: None,
2026-01-20 12:05:03 -05:00
syntax_set: SyntaxSet::load_defaults_nonewlines(),
}
2026-01-17 19:21:14 -05:00
}
pub fn set_contents(&mut self, path: &std::path::PathBuf) -> Result<()> {
if let Ok(contents) = std::fs::read_to_string(path) {
let lines: Vec<_> = contents
.lines()
.map(|line| line.chars().collect::<Vec<char>>())
.collect();
self.file_path = Some(path.clone());
self.state.lines = Lines::new(lines);
}
Ok(())
}
pub fn save(&self) -> Result<()> {
if let Some(path) = &self.file_path {
return std::fs::write(path, self.state.lines.to_string()).map_err(|e| e.into());
};
2026-01-20 17:37:15 -05:00
bail!("File not saved. No file path set.")
}
2026-01-17 19:21:14 -05:00
}
impl Widget for &mut Editor {
fn render(self, area: Rect, buf: &mut Buffer) {
let lang = self
.file_path
.as_ref()
.and_then(|p| p.extension())
.map(|e| e.to_str().unwrap_or("md"))
.unwrap_or("md");
2026-01-20 12:05:03 -05:00
let lang_name = self
.syntax_set
.find_syntax_by_extension(lang)
.map(|s| s.name.to_string())
2026-01-20 12:05:03 -05:00
.unwrap_or("Unknown".to_string());
EditorView::new(&mut self.state)
.wrap(true)
.theme(
EditorTheme::default().block(
Block::default()
.title(lang_name.to_owned())
.title_style(Style::default().fg(Color::Yellow))
.title_alignment(Alignment::Right)
.borders(Borders::ALL)
.padding(Padding::new(0, 0, 0, 1)),
),
)
.syntax_highlighter(SyntaxHighlighter::new("dracula", lang).ok())
.tab_width(2)
.line_numbers(LineNumbers::Absolute)
.render(area, buf);
2026-01-17 19:21:14 -05:00
}
}
2026-01-19 09:23:12 -05:00
impl Component for Editor {
fn id(&self) -> &str {
"Editor"
}
fn handle_event(&mut self, event: Event) -> Result<Action> {
if let Some(key_event) = event.as_key_event() {
// Handle events here that should not be passed on to the vim emulation handler.
match self.handle_key_events(key_event)? {
Action::Handled => return Ok(Action::Handled),
_ => {}
}
}
self.event_handler.on_event(event, &mut self.state);
Ok(Action::Pass)
2026-01-17 19:21:14 -05:00
}
/// The events for the vim emulation should be handled by EditorEventHandler::on_event.
/// These events are custom to the clide application.
fn handle_key_events(&mut self, key: KeyEvent) -> Result<Action> {
match key {
KeyEvent {
code: KeyCode::Char('s'),
modifiers: KeyModifiers::CONTROL,
..
} => {
self.save().context("Failed to save file.")?;
Ok(Action::Handled)
}
// For other events not handled here, pass to the vim emulation handler.
_ => Ok(Action::Noop),
}
}
2026-01-17 19:21:14 -05:00
}