d25f3187d3
The crate the browser epic hangs off: Command (the wire format), ViewState, RenderCache/CellDisplay/Snapshot, and reduce_view. It depends on improvise-core and serde and nothing else -- no IO, no command layer, no terminal -- and improvise-command now depends on it. ViewState, ViewCursor, ViewFrame, AppMode, Panel, MinibufferConfig, MinibufColor, HELP_PAGE_COUNT and the key types move here. Everything that moved is re-exported from ui::app and command::key, so no existing path changed. The three tickets before this one are what made the move mechanical: h0b evicted the unportable fields, a2x added the derives, 8uz took the cursor out of the shared View. Command's client->server half is not invented. It is exactly the set of EffectKind::ViewOnly effects whose target is the portable slice -- h0b had already sorted the portable state from the host-local, so the enumeration was done. Effects touching the wizard, staged drill edits, storage or the layout cache are absent by construction. The other half carries projections: already-formatted display values and their labels. One thing had to be added rather than moved. reduce_view runs on a client that holds no Workbook, and ViewState::cursors is keyed by view name, so ViewState needs its own active_view. That makes two copies of "which view is active"; App::switch_to_view and App::install_workbook are the only writers, and the_two_active_view_names_never_diverge guards it. The 8uz characterization test caught the desync the moment it appeared, because it was calling workbook.switch_view directly. Whether the two are *allowed* to diverge -- two clients on different views -- is improvise-g0f, deliberately left open. It changes the shape of improvise-cqq, and nothing here forecloses either answer. reduce_view has 12 tests including a determinism check: folding the same stream twice gives the same state, which is what stops the server's mirror drifting from the client it mirrors. Every Command round-trips through JSON. The crate is in the CI wasm job. Closes improvise-cqi Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01V69PGQfMJuGRmtSWpfVAqn
473 lines
17 KiB
Rust
473 lines
17 KiB
Rust
//! Portable session state and the wire vocabulary between a server and a
|
|
//! client (improvise-cqi).
|
|
//!
|
|
//! Everything here crosses a process boundary, so the crate depends only on
|
|
//! `improvise-core` and `serde` — no terminal backend, no command layer, no
|
|
//! IO. `improvise-command` depends on *this*, never the reverse; that
|
|
//! direction is what makes the client able to hold the view half without
|
|
//! pulling in the host.
|
|
//!
|
|
//! Two things live here and it is worth being precise about which travels:
|
|
//!
|
|
//! - [`ViewState`] is a **projection of the command stream**, not a wire
|
|
//! message. The server keeps a mirror of each client's view state by
|
|
//! applying the same commands the client applies, through the shared
|
|
//! [`reduce_view`]. It is serialized at exactly one point — the bootstrap
|
|
//! [`Snapshot`] a newly-connected client folds later commands onto
|
|
//! (improvise-q08). Steady-state traffic is commands only.
|
|
//! - [`Command`] is the wire format, and travels in both directions: user
|
|
//! intent from client to server, projections from server to client.
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
use std::collections::HashMap;
|
|
|
|
pub mod key;
|
|
mod reduce;
|
|
pub mod render;
|
|
|
|
pub use key::{KeyCode, KeyEvent, KeyModifiers};
|
|
pub use reduce::{Command, HelpPage, reduce_view};
|
|
pub use render::{CellDisplay, RenderCache, Snapshot};
|
|
|
|
use improvise_core::model::cell::CellValue;
|
|
|
|
/// Number of pages in the Help screen. Lives here (with the `help_page`
|
|
/// state it bounds) so help-page effects stay terminal-independent; the
|
|
/// help renderer in the root crate imports it.
|
|
pub const HELP_PAGE_COUNT: usize = 5;
|
|
|
|
/// Where one client is looking within one view: the selected cell and the
|
|
/// scroll offsets that keep it on screen.
|
|
///
|
|
/// This is per-client state (improvise-8uz). It used to live on `View`,
|
|
/// inside the shared workbook, which meant one client scrolling moved
|
|
/// everyone's viewport. `View` no longer carries it at all — nothing
|
|
/// persisted it, so there was no saved-position behaviour to preserve.
|
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct ViewCursor {
|
|
/// Selected cell, as (row index, column index).
|
|
pub selected: (usize, usize),
|
|
pub row_offset: usize,
|
|
pub col_offset: usize,
|
|
}
|
|
|
|
/// A saved view+mode pair for the navigation stack.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct ViewFrame {
|
|
pub view_name: String,
|
|
pub mode: AppMode,
|
|
}
|
|
|
|
/// Accent color for a minibuffer prompt. Semantic palette only — the
|
|
/// rendering layer maps each variant to a concrete terminal color, so
|
|
/// this type carries no rendering-framework dependency.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub enum MinibufColor {
|
|
Green,
|
|
Cyan,
|
|
Yellow,
|
|
}
|
|
|
|
/// Display configuration for the bottom-bar minibuffer.
|
|
/// Carried structurally by text-entry `AppMode` variants.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct MinibufferConfig {
|
|
pub buffer_key: String,
|
|
pub prompt: String,
|
|
pub color: MinibufColor,
|
|
}
|
|
|
|
/// One of the three side panels. Paired with [`AppMode::panel`], which names
|
|
/// the panel a mode is focused in.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub enum Panel {
|
|
Formula,
|
|
Category,
|
|
View,
|
|
}
|
|
|
|
impl Panel {
|
|
/// Every panel, in the order their toggle keys are bound.
|
|
pub const ALL: [Panel; 3] = [Panel::Formula, Panel::Category, Panel::View];
|
|
|
|
/// The name commands use for this panel — the spelling `parse_panel`
|
|
/// accepts, so `toggle-panel-and-focus` and `move-panel-cursor` args can
|
|
/// be generated rather than spelled out per panel.
|
|
pub fn name(self) -> &'static str {
|
|
match self {
|
|
Panel::Formula => "formula",
|
|
Panel::Category => "category",
|
|
Panel::View => "view",
|
|
}
|
|
}
|
|
|
|
/// The key that toggles focus to this panel, bound in Normal mode and in
|
|
/// every panel's own keymap.
|
|
pub fn key(self) -> char {
|
|
match self {
|
|
Panel::Formula => 'F',
|
|
Panel::Category => 'C',
|
|
Panel::View => 'V',
|
|
}
|
|
}
|
|
|
|
/// The mode that focuses this panel. Inverse of [`AppMode::panel`] for the
|
|
/// three top-level panel modes (the sub-modes — `FormulaEdit`,
|
|
/// `CategoryAdd`, `ItemAdd` — map back to their panel but not forwards).
|
|
pub fn mode(self) -> AppMode {
|
|
match self {
|
|
Panel::Formula => AppMode::FormulaPanel,
|
|
Panel::Category => AppMode::CategoryPanel,
|
|
Panel::View => AppMode::ViewPanel,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub enum AppMode {
|
|
Normal,
|
|
Editing {
|
|
minibuf: MinibufferConfig,
|
|
},
|
|
FormulaEdit {
|
|
minibuf: MinibufferConfig,
|
|
},
|
|
FormulaPanel,
|
|
CategoryPanel,
|
|
/// Quick-add a new category: Enter adds and stays open, Esc closes.
|
|
CategoryAdd {
|
|
minibuf: MinibufferConfig,
|
|
},
|
|
/// Quick-add items to `category`: Enter adds and stays open, Esc closes.
|
|
ItemAdd {
|
|
category: String,
|
|
minibuf: MinibufferConfig,
|
|
},
|
|
ViewPanel,
|
|
TileSelect,
|
|
ImportWizard,
|
|
ExportPrompt {
|
|
minibuf: MinibufferConfig,
|
|
},
|
|
/// Vim-style `:` command line
|
|
CommandMode {
|
|
minibuf: MinibufferConfig,
|
|
},
|
|
Help,
|
|
Quit,
|
|
/// Records-mode normal: inherits from Normal with records-specific bindings.
|
|
RecordsNormal,
|
|
/// Records-mode editing: inherits from Editing with boundary-aware Tab/Enter.
|
|
RecordsEditing {
|
|
minibuf: MinibufferConfig,
|
|
},
|
|
}
|
|
|
|
impl AppMode {
|
|
/// Short uppercase name shown in the title bar.
|
|
pub fn label(&self) -> &'static str {
|
|
match self {
|
|
Self::Normal => "NORMAL",
|
|
Self::Editing { .. } => "INSERT",
|
|
Self::FormulaEdit { .. } => "FORMULA",
|
|
Self::FormulaPanel => "FORMULAS",
|
|
Self::CategoryPanel => "CATEGORIES",
|
|
Self::CategoryAdd { .. } => "NEW CATEGORY",
|
|
Self::ItemAdd { .. } => "ADD ITEMS",
|
|
Self::ViewPanel => "VIEWS",
|
|
Self::TileSelect => "TILES",
|
|
Self::ImportWizard => "IMPORT",
|
|
Self::ExportPrompt { .. } => "EXPORT",
|
|
Self::CommandMode { .. } => "COMMAND",
|
|
Self::Help => "HELP",
|
|
Self::Quit => "QUIT",
|
|
Self::RecordsNormal => "RECORDS",
|
|
Self::RecordsEditing { .. } => "RECORDS INSERT",
|
|
}
|
|
}
|
|
|
|
/// Context-sensitive keybinding hint for the status bar.
|
|
///
|
|
/// `ExportPrompt` and `Quit` deliberately show nothing: `Quit` is never
|
|
/// rendered, and `ExportPrompt` has no hint text yet (improvise-1c9).
|
|
pub fn hint_text(&self) -> &'static str {
|
|
match self {
|
|
Self::Normal => {
|
|
"hjkl:nav i:edit R:records P:prune F/C/V:panels T:tiles [:]:page >:drill ::cmd"
|
|
}
|
|
Self::Editing { .. } | Self::RecordsEditing { .. } => {
|
|
"Enter:commit Tab:commit+right Esc:cancel"
|
|
}
|
|
Self::RecordsNormal => "hjkl:nav i:edit o:add-row R:pivot P:prune <:back ::cmd",
|
|
Self::FormulaPanel => "n:new d:delete jk:nav Esc:back",
|
|
Self::FormulaEdit { .. } => "Enter:save Esc:cancel — type: Name = expression",
|
|
Self::CategoryPanel => {
|
|
"jk:nav Space:cycle-axis n:new-cat a:add-items d:delete Esc:back"
|
|
}
|
|
Self::CategoryAdd { .. } => {
|
|
"Enter:add & continue Tab:same Esc:done — type a category name"
|
|
}
|
|
Self::ItemAdd { .. } => "Enter:add & continue Tab:same Esc:done — type an item name",
|
|
Self::ViewPanel => "jk:nav Enter:switch n:new d:delete Esc:back",
|
|
Self::TileSelect => "hl:select Enter:cycle r/c/p/n:set-axis Esc:back",
|
|
Self::CommandMode { .. } => {
|
|
":q quit :w save :import :add-cat :formula :show-item :help"
|
|
}
|
|
Self::ImportWizard => "Space:toggle c:cycle Enter:next Esc:cancel",
|
|
Self::Help => "h/l:pages q/Esc:close",
|
|
Self::ExportPrompt { .. } | Self::Quit => "",
|
|
}
|
|
}
|
|
|
|
/// The side panel this mode is focused in, if any. A panel's sub-modes
|
|
/// count as that panel, so the panel keeps its active styling while the
|
|
/// user types into its minibuffer.
|
|
pub fn panel(&self) -> Option<Panel> {
|
|
match self {
|
|
Self::FormulaPanel | Self::FormulaEdit { .. } => Some(Panel::Formula),
|
|
Self::CategoryPanel | Self::CategoryAdd { .. } | Self::ItemAdd { .. } => {
|
|
Some(Panel::Category)
|
|
}
|
|
Self::ViewPanel => Some(Panel::View),
|
|
Self::Normal
|
|
| Self::Editing { .. }
|
|
| Self::TileSelect
|
|
| Self::ImportWizard
|
|
| Self::ExportPrompt { .. }
|
|
| Self::CommandMode { .. }
|
|
| Self::Help
|
|
| Self::Quit
|
|
| Self::RecordsNormal
|
|
| Self::RecordsEditing { .. } => None,
|
|
}
|
|
}
|
|
|
|
/// Extract the minibuffer config from text-entry modes, if present.
|
|
pub fn minibuffer(&self) -> Option<&MinibufferConfig> {
|
|
match self {
|
|
Self::Editing { minibuf, .. }
|
|
| Self::RecordsEditing { minibuf, .. }
|
|
| Self::FormulaEdit { minibuf, .. }
|
|
| Self::CommandMode { minibuf, .. }
|
|
| Self::CategoryAdd { minibuf, .. }
|
|
| Self::ItemAdd { minibuf, .. }
|
|
| Self::ExportPrompt { minibuf, .. } => Some(minibuf),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// True for any cell-editing mode (normal or records).
|
|
pub fn is_editing(&self) -> bool {
|
|
matches!(self, Self::Editing { .. } | Self::RecordsEditing { .. })
|
|
}
|
|
|
|
pub fn editing() -> Self {
|
|
Self::Editing {
|
|
minibuf: MinibufferConfig {
|
|
buffer_key: "edit".into(),
|
|
prompt: "edit: ".into(),
|
|
color: MinibufColor::Green,
|
|
},
|
|
}
|
|
}
|
|
|
|
pub fn records_editing() -> Self {
|
|
Self::RecordsEditing {
|
|
minibuf: MinibufferConfig {
|
|
buffer_key: "edit".into(),
|
|
prompt: "edit: ".into(),
|
|
color: MinibufColor::Green,
|
|
},
|
|
}
|
|
}
|
|
|
|
/// True when this mode is a records-mode variant.
|
|
pub fn is_records(&self) -> bool {
|
|
matches!(self, Self::RecordsNormal | Self::RecordsEditing { .. })
|
|
}
|
|
|
|
pub fn formula_edit() -> Self {
|
|
Self::FormulaEdit {
|
|
minibuf: MinibufferConfig {
|
|
buffer_key: "formula".into(),
|
|
prompt: "formula: ".into(),
|
|
color: MinibufColor::Cyan,
|
|
},
|
|
}
|
|
}
|
|
|
|
pub fn command_mode() -> Self {
|
|
Self::CommandMode {
|
|
minibuf: MinibufferConfig {
|
|
buffer_key: "command".into(),
|
|
prompt: ":".into(),
|
|
color: MinibufColor::Yellow,
|
|
},
|
|
}
|
|
}
|
|
|
|
pub fn category_add() -> Self {
|
|
Self::CategoryAdd {
|
|
minibuf: MinibufferConfig {
|
|
buffer_key: "category".into(),
|
|
prompt: "new category: ".into(),
|
|
color: MinibufColor::Yellow,
|
|
},
|
|
}
|
|
}
|
|
|
|
pub fn item_add(category: String) -> Self {
|
|
let prompt = format!("add item to {category}: ");
|
|
Self::ItemAdd {
|
|
category,
|
|
minibuf: MinibufferConfig {
|
|
buffer_key: "item".into(),
|
|
prompt,
|
|
color: MinibufColor::Green,
|
|
},
|
|
}
|
|
}
|
|
|
|
pub fn export_prompt() -> Self {
|
|
Self::ExportPrompt {
|
|
minibuf: MinibufferConfig {
|
|
buffer_key: "export".into(),
|
|
prompt: "export path: ".into(),
|
|
color: MinibufColor::Yellow,
|
|
},
|
|
}
|
|
}
|
|
}
|
|
|
|
/// UI session-state slice: mode, cursors, panels, buffers, navigation stacks,
|
|
/// and other per-session state that does not persist to disk.
|
|
///
|
|
/// This is the **portable** half of the session: the one thing serialized
|
|
/// into the Snapshot a newly-connected client receives (improvise-q08). Two
|
|
/// properties gate membership, and both are load-bearing (improvise-h0b):
|
|
///
|
|
/// - **portable** — the type is plain data from the allowlisted crates, with
|
|
/// no shared-ownership containers. The `ViewState: Send` assertion in the
|
|
/// tests is the compile-time proxy.
|
|
/// - **snapshot-safe** — a fresh client inheriting the value is *correct*.
|
|
/// Staged uncommitted writes and half-open dialogs are not.
|
|
///
|
|
/// State failing either test lives on `App` instead, under the
|
|
/// **session-local** residue tag.
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
pub struct ViewState {
|
|
pub mode: AppMode,
|
|
pub status_msg: String,
|
|
/// Which view this client is looking at. Duplicated from
|
|
/// `Workbook::active_view` on purpose: `reduce_view` runs on a client
|
|
/// that holds no `Workbook`, and `cursors` is keyed by view name, so
|
|
/// the portable half has to carry its own key (improvise-cqi). The
|
|
/// host keeps the two in step; whether they are *allowed* to diverge —
|
|
/// two clients on different views — is improvise-g0f.
|
|
pub active_view: String,
|
|
/// Cursor and scroll position per view name. Keyed rather than single
|
|
/// so that switching views still restores where you were in each one —
|
|
/// the behaviour `View`-owned cursors gave, now per-client
|
|
/// (improvise-8uz). Absent key means "at the origin".
|
|
pub cursors: HashMap<String, ViewCursor>,
|
|
pub search_query: String,
|
|
pub search_mode: bool,
|
|
pub formula_panel_open: bool,
|
|
pub category_panel_open: bool,
|
|
pub view_panel_open: bool,
|
|
pub cat_panel_cursor: usize,
|
|
pub view_panel_cursor: usize,
|
|
pub formula_cursor: usize,
|
|
/// Yanked cell value for `p` paste
|
|
pub yanked: Option<CellValue>,
|
|
/// Tile select cursor (which category index is highlighted)
|
|
pub tile_cat_idx: usize,
|
|
/// View navigation history: views visited before the current one.
|
|
/// Pushed on SwitchView, popped by `<` (back).
|
|
pub view_back_stack: Vec<ViewFrame>,
|
|
/// Views that were "back-ed" from, available for forward navigation (`>`).
|
|
pub view_forward_stack: Vec<ViewFrame>,
|
|
/// Current page index in the Help screen (0-based).
|
|
pub help_page: usize,
|
|
/// Categories expanded in the category panel tree view.
|
|
pub expanded_cats: std::collections::HashSet<String>,
|
|
/// Named text buffers for text-entry modes
|
|
pub buffers: HashMap<String, String>,
|
|
/// The prefix key currently armed, for Emacs-style sequences (g→gg,
|
|
/// y→yy, Z→ZZ). Holds the key that opened the prefix, not the sub-keymap
|
|
/// it maps to: `KeymapSet` owns the keymaps, and `ViewState` is meant to
|
|
/// be portable, serializable state (improvise-jc8).
|
|
pub transient_prefix: Option<(KeyCode, KeyModifiers)>,
|
|
}
|
|
|
|
impl Default for ViewState {
|
|
fn default() -> Self {
|
|
Self {
|
|
mode: AppMode::Normal,
|
|
status_msg: String::new(),
|
|
active_view: "Default".to_string(),
|
|
cursors: HashMap::new(),
|
|
search_query: String::new(),
|
|
search_mode: false,
|
|
formula_panel_open: false,
|
|
category_panel_open: false,
|
|
view_panel_open: false,
|
|
cat_panel_cursor: 0,
|
|
view_panel_cursor: 0,
|
|
formula_cursor: 0,
|
|
yanked: None,
|
|
tile_cat_idx: 0,
|
|
view_back_stack: Vec::new(),
|
|
view_forward_stack: Vec::new(),
|
|
help_page: 0,
|
|
expanded_cats: std::collections::HashSet::new(),
|
|
buffers: HashMap::new(),
|
|
transient_prefix: None,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl ViewState {
|
|
/// This client's cursor in the active view. Absent means the origin, so
|
|
/// a view visited for the first time opens at (0, 0).
|
|
pub fn cursor(&self) -> ViewCursor {
|
|
self.cursors
|
|
.get(&self.active_view)
|
|
.copied()
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
/// Mutable cursor for the active view, created at the origin if absent.
|
|
pub fn cursor_mut(&mut self) -> &mut ViewCursor {
|
|
self.cursors.entry(self.active_view.clone()).or_default()
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod boundary_tests {
|
|
/// improvise-cqi AC 2: this crate crosses a process boundary, so it must
|
|
/// not drag a terminal backend with it. A `cargo tree` check would be
|
|
/// external; this is the part the compiler can hold — the types here
|
|
/// resolve with only `improvise-core` and `serde` in scope, and adding
|
|
/// a `ratatui` or `crossterm` dependency would have to be written into
|
|
/// Cargo.toml deliberately rather than arriving through a `use`.
|
|
///
|
|
/// The CI `wasm` job is the other half: a crate that pulled in
|
|
/// crossterm would stop building for wasm32.
|
|
#[test]
|
|
fn the_wire_types_need_nothing_but_core_and_serde() {
|
|
fn portable<T: serde::Serialize + serde::de::DeserializeOwned>() {}
|
|
portable::<super::ViewState>();
|
|
portable::<super::AppMode>();
|
|
portable::<super::ViewCursor>();
|
|
portable::<super::ViewFrame>();
|
|
portable::<super::Panel>();
|
|
portable::<super::Command>();
|
|
portable::<super::RenderCache>();
|
|
portable::<super::CellDisplay>();
|
|
portable::<super::Snapshot>();
|
|
portable::<super::KeyCode>();
|
|
portable::<super::KeyModifiers>();
|
|
}
|
|
}
|