#![doc(
html_logo_url = "https://raw.githubusercontent.com/canvist/canvist/main/assets/brand/web/icon.svg",
html_favicon_url = "https://raw.githubusercontent.com/canvist/canvist/main/assets/brand/web/favicon.svg"
)]
mod context;
mod edit;
mod navigate;
use canvist_core::Binding;
use canvist_core::Command;
use canvist_core::CommandResult;
use canvist_core::CommandSpec;
use canvist_core::EditKind;
use canvist_core::EditorError;
use canvist_core::EditorState;
use canvist_core::Extension;
use canvist_core::Field;
use canvist_core::NodeKind;
use canvist_core::NodeMeta;
use canvist_core::Platform;
use canvist_core::QuerySpec;
use canvist_core::Registration;
use canvist_core::TypedExtension;
use canvist_core::Update;
use canvist_core::ValueType;
use canvist_core::command;
use canvist_core::commands;
use canvist_core::commands::Slice;
use canvist_core::position;
use canvist_model::Attrs;
use canvist_model::BlockId;
use canvist_model::BlockSpec;
use canvist_model::BlockTree;
use canvist_model::BlockTypeId;
use canvist_model::Document;
use canvist_model::InlineText;
use canvist_model::Point;
use canvist_model::Schema;
use canvist_model::SchemaBuilder;
use canvist_model::Selection;
use canvist_model::Step;
use canvist_model::Value;
use self::context::CELL;
use self::context::HEADER;
use self::context::ROW;
use self::context::TABLE;
use self::context::TableContext;
use self::context::cell_attrs;
use self::context::current;
use self::context::empty_cell;
use self::context::is_named;
pub use self::edit::HeaderPart;
const MAX_SIZE: i64 = 1_000;
#[derive(Clone, Copy, Debug, Default)]
pub struct Table;
#[derive(Clone, Copy, Debug)]
pub struct TableHandle {
_registration: Registration,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TableCell {
pub row: usize,
pub column: usize,
pub rowspan: usize,
pub colspan: usize,
pub header: bool,
pub rows: usize,
pub columns: usize,
}
#[allow(
clippy::unused_self,
reason = "handle methods require proof of registration"
)]
impl TableHandle {
#[must_use]
pub fn insert(self, rows: usize, cols: usize, header_row: bool) -> Command {
insert_table(rows, cols, header_row)
}
#[must_use]
pub fn add_column_before(self) -> Command {
command(|state| edit::add_column(state, false))
}
#[must_use]
pub fn add_column_after(self) -> Command {
command(|state| edit::add_column(state, true))
}
#[must_use]
pub fn delete_column(self) -> Command {
command(edit::delete_column)
}
#[must_use]
pub fn add_row_before(self) -> Command {
command(|state| edit::add_row(state, false))
}
#[must_use]
pub fn add_row_after(self) -> Command {
command(|state| edit::add_row(state, true))
}
#[must_use]
pub fn delete_row(self) -> Command {
command(edit::delete_row)
}
#[must_use]
pub fn delete_table(self) -> Command {
command(edit::delete_table)
}
#[must_use]
pub fn merge_cells(self) -> Command {
command(edit::merge_cells)
}
#[must_use]
pub fn split_cell(self) -> Command {
command(edit::split_cell)
}
#[must_use]
pub fn merge_or_split(self) -> Command {
command(edit::merge_or_split)
}
#[must_use]
pub fn toggle_header(self, part: HeaderPart) -> Command {
command(move |state| edit::toggle_header(state, part))
}
#[must_use]
pub fn set_cell_attribute(self, name: &str, value: Option<&str>) -> Command {
cell_attribute(name, value.map_or(Value::Null, Value::from))
}
#[must_use]
pub fn go_to_next_cell(self) -> Command {
command(|state| navigate::go_to_cell(state, true))
}
#[must_use]
pub fn go_to_previous_cell(self) -> Command {
command(|state| navigate::go_to_cell(state, false))
}
#[must_use]
pub fn fix_tables(self) -> Command {
command(fix_all)
}
#[must_use]
pub fn cell(self, state: &EditorState) -> Option<TableCell> {
cell_info(state)
}
}
fn cell_attribute(name: &str, value: Value) -> Command {
let name = name.to_owned();
command(move |state| edit::set_cell_attribute(state, &name, &value))
}
fn cell_info(state: &EditorState) -> Option<TableCell> {
let (context, index) = current(state)?;
let cell = context.map.cells()[index];
Some(TableCell {
row: cell.row,
column: cell.column,
rowspan: cell.rowspan,
colspan: cell.colspan,
header: is_named(state.doc(), context.block(index), &[HEADER]),
rows: context.map.height(),
columns: context.map.width(),
})
}
fn insert_table(rows: usize, cols: usize, header_row: bool) -> Command {
command(move |state| {
let size = 1..=MAX_SIZE as usize;
if !size.contains(&rows) || !size.contains(&cols) {
return Ok(None);
}
let table_kind = canvist_core::block_type(state.schema(), TABLE, TABLE)?;
let row_kind = canvist_core::block_type(state.schema(), TABLE, ROW)?;
let cell_kinds = edit::CellKinds::read(state)?;
let doc = state.doc();
let Some(range) = position::text_range(doc, state.selection()) else {
return Ok(None);
};
let parent = position::parent_of(doc, range.from.block)
.and_then(|parent| doc.block(parent))
.map(canvist_model::Block::kind);
if !doc.schema().allows_child(parent, table_kind) {
return Ok(None);
}
let paragraph = doc.schema().default_text_block();
let cells = |row: usize| cell_kinds.pick(row == 0 && header_row);
let table = table_tree([table_kind, row_kind, paragraph], (rows, cols), cells);
state.atomic(|state| paste_table(state, table, table_kind))
})
}
fn table_tree(
[table, row_kind, paragraph]: [BlockTypeId; 3],
(rows, cols): (usize, usize),
cells: impl Fn(usize) -> BlockTypeId,
) -> BlockTree {
let mut seq = 0;
let mut next = || {
seq += 1;
BlockId::new(0, seq)
};
let table_rows = (0..rows)
.map(|row| {
let row_cells = (0..cols)
.map(|_| {
let text = BlockTree::text(next(), paragraph, InlineText::new());
BlockTree::container(next(), cells(row), vec![text])
})
.collect();
BlockTree::container(next(), row_kind, row_cells)
})
.collect();
BlockTree::container(next(), table, table_rows)
}
fn paste_table(state: &mut EditorState, table: BlockTree, kind: BlockTypeId) -> CommandResult {
let Some(pasted) = commands::replace_selection(state, Slice::new(vec![table]))? else {
return Ok(None);
};
let Some(inserted) = inserted_table(&pasted, kind) else {
return Ok(Some(pasted));
};
let start = edit::first_text(state.doc(), inserted);
let caret = state.change(EditKind::Selection, |tr| {
tr.set_selection(Selection::caret(Point::new(start, 0)));
Ok(true)
})?;
Ok(Some(match caret {
Some(caret) => pasted.then(caret),
None => pasted,
}))
}
fn inserted_table(update: &Update, table: BlockTypeId) -> Option<BlockId> {
update.commit.steps.iter().find_map(|step| {
match step {
Step::InsertBlocks { blocks, .. } => {
blocks
.iter()
.find(|tree| tree.kind == table)
.map(|tree| tree.id)
}
_ => None,
}
})
}
fn touched_tables(doc: &Document, update: &Update) -> Vec<BlockId> {
let mut tables = Vec::new();
let parents = update.commit.steps.iter().filter_map(|step| {
match step {
Step::InsertBlocks { parent, .. } | Step::RemoveBlocks { parent, .. } => *parent,
Step::MoveBlocks { to_parent, .. } => *to_parent,
_ => None,
}
});
for block in update.commit.touched.iter().copied().chain(parents) {
let table = position::ancestors_or_self(doc, block).find(|&id| is_named(doc, id, &[TABLE]));
if let Some(table) = table.filter(|table| !tables.contains(table)) {
tables.push(table);
}
}
tables
}
fn fix(state: &mut EditorState, tables: &[BlockId]) -> CommandResult {
let doc = state.doc();
let cell = canvist_core::block_type(state.schema(), TABLE, CELL)?;
let paragraph = doc.schema().default_text_block();
let contexts: Vec<TableContext> = tables
.iter()
.map(|&table| TableContext::new(doc, table))
.collect();
let empty_cells: Vec<BlockId> = contexts
.iter()
.flat_map(|context| empty_cells(doc, context))
.collect();
let short_rows: Vec<ShortRow> = contexts
.iter()
.flat_map(|context| short_rows(doc, context))
.collect();
if empty_cells.is_empty() && short_rows.is_empty() {
return Ok(None);
}
let selection = state.selection();
state.change(EditKind::Structure, |tr| {
for &id in &empty_cells {
let text = tr.allocate_id()?;
let paragraph = BlockTree::text(text, paragraph, InlineText::new());
tr.insert_blocks(Some(id), 0, vec![paragraph])?;
}
for &(row, end, missing) in &short_rows {
let cells = (0..missing)
.map(|_| empty_cell(tr, cell, Attrs::new()))
.collect::<Result<Vec<_>, _>>()?;
tr.insert_blocks(Some(row), end, cells)?;
}
tr.set_selection(position::valid_selection(tr.doc(), selection));
Ok(true)
})
}
type ShortRow = (BlockId, usize, usize);
fn empty_cells(doc: &Document, context: &TableContext) -> Vec<BlockId> {
context
.cells
.iter()
.flatten()
.copied()
.filter(|&id| doc.children(Some(id)).is_empty())
.collect()
}
fn short_rows(doc: &Document, context: &TableContext) -> Vec<ShortRow> {
context
.map
.missing()
.into_iter()
.zip(&context.rows)
.filter(|&(missing, _)| missing > 0)
.map(|(missing, &row)| (row, doc.children(Some(row)).len(), missing))
.collect()
}
fn fix_all(state: &mut EditorState) -> CommandResult {
let doc = state.doc();
let tables: Vec<BlockId> = doc
.iter()
.filter(|block| &*doc.schema().block(block.kind()).name == TABLE)
.map(canvist_model::Block::id)
.collect();
fix(state, &tables)
}
fn size_arg(args: &canvist_core::Args<'_>, key: &str) -> Result<usize, EditorError> {
let value = args.int(key)?;
if !(1..=MAX_SIZE).contains(&value) {
return Err(EditorError::InvalidArgs {
name: "insertTable".to_owned(),
reason: format!("`{key}` must be from 1 to {MAX_SIZE}"),
});
}
Ok(value as usize)
}
fn cell_value(state: &EditorState) -> Value {
cell_info(state).map_or(Value::Null, |cell| {
let attrs = Attrs::new()
.with("row", cell.row as i64)
.with("column", cell.column as i64)
.with("rowspan", cell.rowspan as i64)
.with("colspan", cell.colspan as i64)
.with("header", cell.header)
.with("rows", cell.rows as i64)
.with("columns", cell.columns as i64);
Value::from(attrs)
})
}
fn cell_type() -> ValueType {
let int = |name, doc| Field::required(name, ValueType::Int, doc);
ValueType::nullable(ValueType::Record(vec![
int("row", "The cell's top row, from zero."),
int("column", "The cell's leftmost column, from zero."),
int("rowspan", "How many rows it spans."),
int("colspan", "How many columns it spans."),
Field::required("header", ValueType::Bool, "Whether it is a header cell."),
int("rows", "How many rows its table has."),
int("columns", "How many columns its table has."),
]))
}
type SimpleCommand = (
&'static str,
&'static str,
fn(&mut EditorState) -> CommandResult,
);
const SHAPE_COMMANDS: [SimpleCommand; 13] = [
(
"addColumnBefore",
"Add a column left of the selected cells.",
|state| edit::add_column(state, false),
),
(
"addColumnAfter",
"Add a column right of the selected cells.",
|state| edit::add_column(state, true),
),
(
"deleteColumn",
"Delete the selected columns.",
edit::delete_column,
),
(
"addRowBefore",
"Add a row above the selected cells.",
|state| edit::add_row(state, false),
),
(
"addRowAfter",
"Add a row below the selected cells.",
|state| edit::add_row(state, true),
),
("deleteRow", "Delete the selected rows.", edit::delete_row),
(
"deleteTable",
"Delete the table around the selection.",
edit::delete_table,
),
(
"mergeCells",
"Merge the selected cells into one.",
edit::merge_cells,
),
(
"splitCell",
"Split the merged cell holding the selection.",
edit::split_cell,
),
(
"mergeOrSplit",
"Merge the selected cells, or split the merged cell holding the caret.",
edit::merge_or_split,
),
(
"toggleHeaderRow",
"Toggle header cells for the first row.",
|state| edit::toggle_header(state, HeaderPart::Row),
),
(
"toggleHeaderColumn",
"Toggle header cells for the first column.",
|state| edit::toggle_header(state, HeaderPart::Column),
),
(
"toggleHeaderCell",
"Toggle header cells for the selected cells.",
|state| edit::toggle_header(state, HeaderPart::Cells),
),
];
const OTHER_COMMANDS: [SimpleCommand; 3] = [
("goToNextCell", "Select the next cell's content.", |state| {
navigate::go_to_cell(state, true)
}),
(
"goToPreviousCell",
"Select the previous cell's content.",
|state| navigate::go_to_cell(state, false),
),
(
"fixTables",
"Give every short row of every table empty cells up to its width.",
fix_all,
),
];
fn insert_table_spec() -> CommandSpec {
CommandSpec::new(
"insertTable",
"Insert a table of empty cells at the selection, with the caret in the first cell.",
|args| {
Ok(insert_table(
size_arg(args, "rows")?,
size_arg(args, "cols")?,
args.bool("withHeaderRow")?,
))
},
)
.arg(Field::optional(
"rows",
ValueType::Int,
3,
"How many rows, from 1 to 1000.",
))
.arg(Field::optional(
"cols",
ValueType::Int,
3,
"How many columns, from 1 to 1000.",
))
.arg(Field::optional(
"withHeaderRow",
ValueType::Bool,
true,
"Whether the first row is header cells.",
))
}
fn cell_attribute_spec() -> CommandSpec {
CommandSpec::new(
"setCellAttribute",
"Set an attribute of the selected cells, or remove it when the value is null.",
|args| {
let value = args
.optional_string("value")?
.map_or(Value::Null, Value::from);
Ok(cell_attribute(args.string("name")?, value))
},
)
.arg(Field::required(
"name",
ValueType::String,
"The attribute, such as `backgroundColor`.",
))
.arg(Field::required(
"value",
ValueType::nullable(ValueType::String),
"Its value, or null to remove it.",
))
}
impl Extension for Table {
fn name(&self) -> &'static str {
TABLE
}
fn priority(&self) -> i32 {
99
}
fn schema(&self, schema: SchemaBuilder) -> SchemaBuilder {
schema
.block(BlockSpec::container(TABLE, &[ROW]))
.block(BlockSpec::container(ROW, &[CELL, HEADER]).groups(&[]))
.block(
BlockSpec::container(CELL, &["block"])
.attrs(cell_attrs())
.groups(&[]),
)
.block(
BlockSpec::container(HEADER, &["block"])
.attrs(cell_attrs())
.groups(&[]),
)
}
fn nodes(&self) -> Vec<NodeMeta> {
let cell = |name| {
NodeMeta::new(NodeKind::Block, name)
.attr(Field::optional(
"colspan",
ValueType::Int,
1,
"How many columns the cell spans.",
))
.attr(Field::optional(
"rowspan",
ValueType::Int,
1,
"How many rows the cell spans.",
))
.attr(Field::optional(
"colwidth",
ValueType::nullable(ValueType::List(Box::new(ValueType::Int))),
Value::Null,
"The width in pixels the cell gives each column it spans, or 0 for none.",
))
};
vec![
NodeMeta::new(NodeKind::Block, TABLE),
NodeMeta::new(NodeKind::Block, ROW),
cell(CELL),
cell(HEADER),
]
}
fn commands(&self, _schema: &Schema) -> Result<Vec<CommandSpec>, EditorError> {
let simple =
|&(name, doc, run): &SimpleCommand| CommandSpec::simple(name, doc, command(run));
let commands = std::iter::once(insert_table_spec())
.chain(SHAPE_COMMANDS.iter().map(simple))
.chain(std::iter::once(cell_attribute_spec()))
.chain(OTHER_COMMANDS.iter().map(simple));
Ok(commands.collect())
}
fn queries(&self, _schema: &Schema) -> Result<Vec<QuerySpec>, EditorError> {
Ok(vec![QuerySpec::new(
"tableCell",
"Where the selection head sits in its table, or null outside one.",
cell_type(),
|state, _| Ok(cell_value(state)),
)])
}
fn keymap(&self, _schema: &Schema, _platform: Platform) -> Result<Vec<Binding>, EditorError> {
let backward = || command(|state| navigate::guard_edge(state, false));
let forward = || command(|state| navigate::guard_edge(state, true));
Ok(vec![
("Tab", command(navigate::tab)),
(
"Shift-Tab",
command(|state| navigate::go_to_cell(state, false)),
),
("Backspace", backward()),
("Shift-Backspace", backward()),
("Alt-Backspace", backward()),
("Ctrl-Backspace", backward()),
("Mod-Backspace", backward()),
("Delete", forward()),
("Alt-Delete", forward()),
("Ctrl-Delete", forward()),
("Mod-Delete", forward()),
])
}
fn after_update(&self, state: &mut EditorState, update: &Update) -> CommandResult {
if !update.commit.structural {
return Ok(None);
}
let tables = touched_tables(state.doc(), update);
if tables.is_empty() {
return Ok(None);
}
fix(state, &tables)
}
}
impl TypedExtension for Table {
type Handle = TableHandle;
fn handle(&self, registration: Registration) -> TableHandle {
TableHandle {
_registration: registration,
}
}
}