Files
kiln/kiln-tui/src/editor.rs
T

397 lines
16 KiB
Rust
Raw Normal View History

2026-06-15 22:02:15 -05:00
//! World editor mode: state, rendering, and the editor pause menu.
//!
//! The editor is a separate top-level [`Mode`](crate::mode::Mode): it holds its
//! own freshly reloaded [`World`] and never ticks the game. The board is shown
2026-06-17 18:25:09 -05:00
//! with a blinking cursor (moved with the arrow keys or a right-click) and a
//! resizable right-hand sidebar that hosts the [menu tree](MenuLevel): a breadcrumb
//! title and letter-keyed choices that open [dialogs](kiln_ui::dialog). `Esc` walks
//! back up the tree, opening the overlay [editor menu](editor_menu_items) at the root.
2026-06-15 22:02:15 -05:00
2026-06-17 18:25:09 -05:00
use kiln_ui::dialog::{Dialog, DialogResult, ListDialogResponse};
use crate::log::{LogWidget, log_preview_line};
use crate::menu::{MenuItem, MenuKey};
use crate::mode::PendingMode;
use crate::render::{BoardWidget, board_to_screen, screen_to_board};
use crate::ui::Ui;
2026-06-15 22:02:15 -05:00
use kiln_core::Board;
use kiln_core::log::LogLine;
use kiln_core::world::World;
use ratatui::Frame;
2026-06-17 18:25:09 -05:00
use ratatui::crossterm::event::Event;
2026-06-15 22:02:15 -05:00
use ratatui::layout::{Constraint, Layout, Rect, Spacing};
use ratatui::style::{Color, Style};
use ratatui::symbols::merge::MergeStrategy;
2026-06-17 18:25:09 -05:00
use ratatui::text::{Line, Span};
2026-06-15 22:02:15 -05:00
use ratatui::widgets::{Block, Paragraph};
2026-06-17 18:25:09 -05:00
use std::cell::Ref;
2026-06-15 22:02:15 -05:00
/// How long each half of the cursor blink lasts, in seconds.
const BLINK_SECS: f32 = 0.5;
/// Default sidebar width in terminal columns (borders included).
const DEFAULT_SIDEBAR_WIDTH: u16 = 24;
/// Smallest width either the sidebar or the board may shrink to when resizing.
const MIN_PANEL_WIDTH: u16 = 8;
/// The cursor glyph: a solid full block (CP437 219) drawn in light gray.
const CURSOR_CHAR: char = '█';
2026-06-17 18:25:09 -05:00
/// One level in the editor's sidebar menu tree.
///
/// The menu is a stack of levels (the current one is the stack's last element); a
/// breadcrumb is built from their [`title`](MenuLevel::title)s. Today only the
/// top-level [`World`](MenuLevel::World) exists — every choice opens a dialog rather
/// than a sub-menu — but the stack keeps room for nested menus later.
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum MenuLevel {
/// The top-level world menu: set name / entry board, browse scripts / boards.
World,
}
impl MenuLevel {
/// The breadcrumb segment shown for this level.
fn title(self) -> &'static str {
match self {
MenuLevel::World => "World",
}
}
/// The static `(key, label)` choices shown for this level. Keep in sync with the
/// key dispatch in [`handle_editor_input`](crate::input::handle_editor_input).
fn choices(self) -> &'static [(char, &'static str)] {
match self {
MenuLevel::World => &[
('n', "Name"),
('e', "Entry board"),
('s', "Scripts"),
('b', "Boards"),
],
}
}
}
2026-06-15 22:02:15 -05:00
/// All state for an active editing session.
///
/// Built by reloading the world file, so the running game has no bearing on what
/// the editor shows. Holds no [`GameState`](kiln_core::game::GameState) — editing
/// never ticks the game.
pub(crate) struct EditorState {
/// The freshly reloaded world being edited.
world: World,
/// Key (in [`World::boards`]) of the board currently being edited.
board_name: String,
2026-06-17 18:25:09 -05:00
/// The sidebar menu navigation stack; the last element is the current level.
/// Starts as `[MenuLevel::World]` and is never emptied below that root.
menu: Vec<MenuLevel>,
/// The currently open dialog overlay, if any. While `Some`, the editor is in
/// [`InputMode::Dialog`](crate::input::InputMode::Dialog).
pub(crate) dialog: Option<Dialog<EditorState>>,
2026-06-15 22:02:15 -05:00
/// Cursor position in board cells, clamped to the board bounds.
cursor: (i32, i32),
/// Width of the right-hand sidebar in terminal columns (mouse-resizable).
sidebar_width: u16,
/// Whether the blinking cursor is currently in its visible phase.
blink_on: bool,
/// Time accumulated toward the next blink toggle.
blink_timer: f32,
/// Inner board rect from the last [`draw_editor`] call, used to convert a
/// right-click's screen position back to a board cell (written during render,
/// read during input — the same pattern as `ScrollOverlayState::max_scroll`).
last_board_area: Rect,
/// Editor-side log lines (the editor has no game log to draw from).
log: Vec<LogLine>,
}
impl EditorState {
/// Builds an editor session for `world`, starting on its designated start board.
pub(crate) fn new(world: World) -> Self {
let board_name = world.start.clone();
Self {
world,
board_name,
2026-06-17 18:25:09 -05:00
menu: vec![MenuLevel::World],
dialog: None,
2026-06-15 22:02:15 -05:00
cursor: (0, 0),
sidebar_width: DEFAULT_SIDEBAR_WIDTH,
blink_on: true,
blink_timer: 0.0,
last_board_area: Rect::default(),
log: vec![LogLine::raw("editing — press [esc] for the menu")],
}
}
2026-06-17 18:25:09 -05:00
/// The breadcrumb for the current menu path, e.g. `"World"` or `"World > Scripts"`.
fn breadcrumb(&self) -> String {
self.menu
.iter()
.map(|l| l.title())
.collect::<Vec<_>>()
.join(" > ")
}
/// The menu level currently shown in the sidebar (top of the stack).
fn current_menu(&self) -> MenuLevel {
*self.menu.last().expect("menu stack is never empty")
}
/// Handles `Esc` in the menu: pops to the parent level, or — at the root world
/// menu — opens the existing overlay editor menu (Play / Quit / Resume).
pub(crate) fn menu_escape(&mut self, ui: &mut Ui) {
if self.menu.len() > 1 {
self.menu.pop();
} else {
ui.open_menu(editor_menu_items());
}
}
/// Dispatches a letter key against the current menu level. Returns `true` if the
/// key matched a choice (and opened a dialog), so the caller can stop handling it.
pub(crate) fn menu_key(&mut self, c: char) -> bool {
match (self.current_menu(), c) {
(MenuLevel::World, 'n') => {
self.open_name_dialog();
true
}
(MenuLevel::World, 'e') => {
self.open_entry_dialog();
true
}
(MenuLevel::World, 's') => {
self.open_scripts_dialog();
true
}
(MenuLevel::World, 'b') => {
self.open_boards_dialog();
true
}
_ => false,
}
}
/// The "current value" shown beneath a menu choice in the sidebar, if any.
/// Used for `[n] Name` (current world name) and `[e] Entry board` (current start).
fn menu_value(&self, key: char) -> Option<String> {
match (self.current_menu(), key) {
(MenuLevel::World, 'n') => Some(self.world.name.clone()),
(MenuLevel::World, 'e') => Some(self.world.start.clone()),
_ => None,
}
}
/// Opens a text dialog to rename the world; OK writes [`World::name`].
fn open_name_dialog(&mut self) {
let current = self.world.name.clone();
self.dialog = Some(Dialog::text("World Name", current, |opt, ed: &mut EditorState| {
if let Some(s) = opt {
ed.world.name = s;
}
}));
}
/// Opens a list dialog to choose the entry board; selecting one writes [`World::start`].
fn open_entry_dialog(&mut self) {
let mut names: Vec<String> = self.world.boards.keys().cloned().collect();
names.sort();
self.dialog = Some(Dialog::list(
"Entry Board",
names,
false,
|resp, ed: &mut EditorState| {
if let ListDialogResponse::Select(s) = resp {
ed.world.start = s;
}
},
));
}
/// Opens a list dialog of the world's scripts. Select-only for now (no side effect).
fn open_scripts_dialog(&mut self) {
let mut names: Vec<String> = self.world.scripts.keys().cloned().collect();
names.sort();
self.dialog = Some(Dialog::list("Scripts", names, false, |resp, ed: &mut EditorState| {
ed.log.push(LogLine::raw(format!("Script dialog: {:?}", resp)))
}));
}
/// Opens a list dialog of the world's boards. Select-only for now (no side effect).
fn open_boards_dialog(&mut self) {
let mut names: Vec<String> = self.world.boards.keys().cloned().collect();
names.sort();
self.dialog = Some(Dialog::list("Boards", names, false, |_resp, _ed: &mut EditorState| {}));
}
2026-06-15 22:02:15 -05:00
/// Borrows the board currently being edited.
pub(crate) fn board(&self) -> Ref<'_, Board> {
self.world.boards[&self.board_name].borrow()
}
/// Advances the cursor blink by `dt` seconds (the editor's only animation).
pub(crate) fn tick(&mut self, dt: f32) {
self.blink_timer += dt;
if self.blink_timer >= BLINK_SECS {
self.blink_timer -= BLINK_SECS;
self.blink_on = !self.blink_on;
}
}
/// Moves the cursor by `(dx, dy)`, clamped to the board bounds.
pub(crate) fn move_cursor(&mut self, dx: i32, dy: i32) {
2026-06-17 18:25:09 -05:00
let (w, h) = {
let b = self.board();
(b.width as i32, b.height as i32)
};
2026-06-15 22:02:15 -05:00
self.cursor.0 = (self.cursor.0 + dx).clamp(0, w - 1);
self.cursor.1 = (self.cursor.1 + dy).clamp(0, h - 1);
}
/// Moves the cursor to the cell under a screen position, if it lands on the
/// board (right-click handling). No-op when the click is off the board.
pub(crate) fn set_cursor_at_screen(&mut self, sx: u16, sy: u16) {
let cell = screen_to_board(self.last_board_area, &self.board(), sx, sy);
if let Some((bx, by)) = cell {
self.cursor = (bx as i32, by as i32);
}
}
/// Resizes the sidebar to `target` columns, clamped so neither the sidebar nor
/// the board can shrink below [`MIN_PANEL_WIDTH`] (mirrors [`LogState::resize`]).
pub(crate) fn resize_sidebar(&mut self, target: u16, total_w: u16) {
let max = total_w.saturating_sub(MIN_PANEL_WIDTH).max(MIN_PANEL_WIDTH);
self.sidebar_width = target.clamp(MIN_PANEL_WIDTH, max);
}
}
/// Returns the items for the editor's pause menu (opened with `Esc` while editing).
///
/// `[p]` reloads the world and returns to play; `[q]` quits; `Esc` resumes editing.
/// Like all menu actions these take only `&mut Ui` — the mode swap is deferred to
/// the run loop via [`Ui::pending_mode`](crate::ui::Ui::pending_mode).
pub(crate) fn editor_menu_items() -> Vec<MenuItem> {
vec![
MenuItem::new(MenuKey::Char('p'), "Play world", |ui| {
ui.pending_mode = Some(PendingMode::PlayWorld);
ui.begin_close_menu();
}),
MenuItem::new(MenuKey::Char('q'), "Quit game", |ui| {
ui.should_quit = true;
ui.begin_close_menu();
}),
MenuItem::new(MenuKey::Esc, "Resume editing", |ui| {
ui.begin_close_menu();
}),
]
}
2026-06-17 18:25:09 -05:00
/// Handles an input event while a dialog is open ([`InputMode::Dialog`](crate::input::InputMode::Dialog)).
///
/// Forwards the event to the dialog; on `Submit`/`Cancel` it takes the dialog out of
/// [`EditorState::dialog`] (so the callback receives an un-borrowed `&mut EditorState`)
/// and fires the callback via [`Dialog::finish`].
pub(crate) fn handle_dialog_input(event: Event, ed: &mut EditorState) {
let Some(dialog) = ed.dialog.as_mut() else {
return;
};
match dialog.handle_event(&event) {
DialogResult::Continue => {}
result => {
let dialog = ed.dialog.take().expect("dialog present");
dialog.finish(result, ed);
}
}
}
2026-06-15 22:02:15 -05:00
/// Renders the editor: the board (with a blinking cursor and coordinate readout),
/// the right-hand sidebar, and — when open — the bottom log panel spanning the
/// full width (board and sidebar sit side-by-side above it).
pub(crate) fn draw_editor(frame: &mut Frame, ed: &mut EditorState, ui: &mut Ui) {
let (board_area, sidebar_area, log_area) = editor_layout(frame.area(), ui, ed.sidebar_width);
// ── Board, cursor, coordinate readout ────────────────────────────────────
let inner = {
let board = ed.board();
// Title carries the board name (top-left) and live cursor coords (top-right).
let mut block = Block::bordered()
.title(format!(" {} ", board.name))
.title_top(Line::from(format!(" ({}, {}) ", ed.cursor.0, ed.cursor.1)).right_aligned())
.merge_borders(MergeStrategy::Exact);
// When the log is closed, preview the latest line in the bottom border.
if log_area.is_none() {
block = block.title_bottom(log_preview_line(&ed.log).left_aligned());
}
let inner = block.inner(board_area);
frame.render_widget(block, board_area);
frame.render_widget(BoardWidget::new(&board), inner);
// Overlay the cursor during its visible phase (a light-gray solid block).
if ed.blink_on {
let (cx, cy) = (ed.cursor.0 as usize, ed.cursor.1 as usize);
if let Some((sx, sy)) = board_to_screen(inner, &board, cx, cy)
&& let Some(cell) = frame.buffer_mut().cell_mut((sx, sy))
{
cell.set_char(CURSOR_CHAR)
.set_fg(Color::Rgb(180, 180, 180))
.set_bg(Color::Black);
}
}
inner
};
// Record the board rect for right-click hit-testing (board borrow now dropped).
ed.last_board_area = inner;
2026-06-17 18:25:09 -05:00
// ── Sidebar: the current menu (breadcrumb title + letter-keyed choices) ───
let sb_block = Block::bordered()
.title(format!(" {} ", ed.breadcrumb()))
.merge_borders(MergeStrategy::Exact);
2026-06-15 22:02:15 -05:00
let sb_inner = sb_block.inner(sidebar_area);
frame.render_widget(sb_block, sidebar_area);
2026-06-17 18:25:09 -05:00
// One line per choice (`[k] Label`); a choice with a current value (e.g. the
// world name) gets a second, indented line beneath it in a distinct color.
let key_style = Style::default().fg(Color::Rgb(150, 200, 255));
let label_style = Style::default().fg(Color::White);
let value_style = Style::default().fg(Color::Rgb(200, 180, 120));
let mut lines: Vec<Line> = Vec::new();
for (k, label) in ed.current_menu().choices() {
lines.push(Line::from(vec![
Span::styled(format!("[{k}] "), key_style),
Span::styled(*label, label_style),
]));
if let Some(val) = ed.menu_value(*k) {
lines.push(Line::from(Span::styled(format!(" {val}"), value_style)));
}
}
lines.push(Line::from(""));
lines.push(Line::from(Span::styled(
"[esc] menu",
Style::default().fg(Color::DarkGray),
)));
frame.render_widget(Paragraph::new(lines), sb_inner);
2026-06-15 22:02:15 -05:00
// ── Log panel (full width, below board + sidebar) ─────────────────────────
if let Some(log_area) = log_area {
frame.render_stateful_widget(LogWidget::new(&ed.log), log_area, &mut ui.log);
}
}
/// Computes the board / sidebar / optional-log rects for the editor.
///
/// When the log is open the screen splits vertically first (so the log spans the
/// full width), then the top region splits horizontally into board + sidebar.
/// When closed, only the horizontal board/sidebar split applies. `Overlap(1)`
/// makes adjacent panels share their dividing border.
fn editor_layout(area: Rect, ui: &Ui, sidebar_width: u16) -> (Rect, Rect, Option<Rect>) {
let split_h = |top: Rect| {
Layout::horizontal([Constraint::Min(3), Constraint::Length(sidebar_width)])
.spacing(Spacing::Overlap(1))
.areas::<2>(top)
};
if ui.log.open {
let [top, log_area] =
Layout::vertical([Constraint::Min(3), Constraint::Length(ui.log.height)])
.spacing(Spacing::Overlap(1))
.areas(area);
let [board_area, sidebar_area] = split_h(top);
(board_area, sidebar_area, Some(log_area))
} else {
let [board_area, sidebar_area] = split_h(area);
(board_area, sidebar_area, None)
}
}