canvist_extension_table 0.2.2

canvist: TipTap's `table`, `tableRow`, `tableCell`, and `tableHeader`, with commands to add, remove, merge, and split cells
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
#![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"
)]
//! # `canvist_extension_table`
//!
//! TipTap's tables for the canvist editor, as in TipTap's
//! `@tiptap/extension-table`: [`Table`] registers `table`, `tableRow`,
//! `tableCell`, and `tableHeader`, with merged cells, header rows and
//! columns, and Tab between cells.
//!
//! Cells hold blocks and carry `colspan`, `rowspan`, and `colwidth`
//! attributes. The `insertTable` command makes a table of empty cells;
//! `addColumnBefore`, `addRowAfter`, and the like grow it, `deleteColumn`,
//! `deleteRow`, and `deleteTable` shrink it, `mergeCells` and `splitCell`
//! merge and split cells, the `toggleHeader…` commands switch cells to
//! header cells and back, and `setCellAttribute` sets any cell attribute.
//! The `tableCell` query, and [`TableHandle::cell`], say where the
//! selection head sits. [`TableHandle`] offers each command typed.
//!
//! After every structural change, the tables it touched are kept well
//! formed, as TipTap's `fixTables` keeps them: every cell holds a block, and
//! every row covers every column. Tab moves to the next cell, adding a row
//! past the last, and Backspace and Delete never join text across a cell's
//! edge.
//!
//! ```
//! use std::time::Duration;
//!
//! use canvist_core::Editor;
//! use canvist_core::Env;
//! use canvist_extension_document::Document;
//! use canvist_extension_paragraph::Paragraph;
//! use canvist_extension_table::Table;
//!
//! let mut builder = Editor::builder().extension(Document).extension(Paragraph);
//! let table = builder.add(Table);
//! let mut editor = builder.build()?;
//! let mut env = Env::headless(Duration::ZERO);
//!
//! editor.run(&table.insert(2, 3, true), &mut env)?;
//! editor.run(&table.add_column_after(), &mut env)?;
//!
//! let cell = table.cell(editor.state()).expect("the caret is in the first cell");
//! assert!(cell.header);
//! assert_eq!((cell.row, cell.column), (0, 0));
//! assert_eq!((cell.rows, cell.columns), (2, 4));
//! # Ok::<(), canvist_core::EditorError>(())
//! ```

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;

/// The most rows or columns `insertTable` makes.
const MAX_SIZE: i64 = 1_000;

/// TipTap's `TableKit`: a `table` of `tableRow`s of `tableCell`s and
/// `tableHeader`s, each cell holding blocks, with `colspan`, `rowspan`, and
/// `colwidth` attributes.
///
/// Layout places the cells on a grid: each column as wide as a cell's
/// `colwidth` says or an even share of what is left, each row as tall as its
/// tallest cell. Commands add and delete rows and columns, merge and split
/// cells, and toggle header rows, columns, and cells; a selection from one
/// cell to another selects the rectangle between them. Tab moves to the
/// next cell, adding a row past the last, and Backspace and Delete never
/// join text across a cell's edge. HTML reads and writes `<table>`; Markdown
/// writes GitHub's pipe tables when the table fits them, and HTML when it
/// does not.
#[derive(Clone, Copy, Debug, Default)]
pub struct Table;

/// Typed access to [`Table`].
#[derive(Clone, Copy, Debug)]
pub struct TableHandle {
	_registration: Registration,
}

/// Where the selection head sits in its table, from [`TableHandle::cell`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TableCell {
	/// The cell's top row and leftmost column, from zero.
	pub row: usize,
	/// The cell's leftmost column.
	pub column: usize,
	/// How many rows and columns it spans.
	pub rowspan: usize,
	/// How many columns it spans.
	pub colspan: usize,
	/// Whether it is a header cell.
	pub header: bool,
	/// The size of its table.
	pub rows: usize,
	/// How many columns its table has.
	pub columns: usize,
}

#[allow(
	clippy::unused_self,
	reason = "handle methods require proof of registration"
)]
impl TableHandle {
	/// Insert a table of `rows` by `cols` empty cells at the selection, the
	/// first row of header cells when `header_row`, with the caret in the
	/// first cell. Does nothing unless both are from 1 to 1000, as
	/// `insertTable` requires.
	#[must_use]
	pub fn insert(self, rows: usize, cols: usize, header_row: bool) -> Command {
		insert_table(rows, cols, header_row)
	}

	/// Add a column left of the selected cells.
	#[must_use]
	pub fn add_column_before(self) -> Command {
		command(|state| edit::add_column(state, false))
	}

	/// Add a column right of the selected cells.
	#[must_use]
	pub fn add_column_after(self) -> Command {
		command(|state| edit::add_column(state, true))
	}

	/// Delete the selected columns.
	#[must_use]
	pub fn delete_column(self) -> Command {
		command(edit::delete_column)
	}

	/// Add a row above the selected cells.
	#[must_use]
	pub fn add_row_before(self) -> Command {
		command(|state| edit::add_row(state, false))
	}

	/// Add a row below the selected cells.
	#[must_use]
	pub fn add_row_after(self) -> Command {
		command(|state| edit::add_row(state, true))
	}

	/// Delete the selected rows.
	#[must_use]
	pub fn delete_row(self) -> Command {
		command(edit::delete_row)
	}

	/// Delete the table around the selection.
	#[must_use]
	pub fn delete_table(self) -> Command {
		command(edit::delete_table)
	}

	/// Merge the selected cells into one.
	#[must_use]
	pub fn merge_cells(self) -> Command {
		command(edit::merge_cells)
	}

	/// Split the merged cell holding the selection.
	#[must_use]
	pub fn split_cell(self) -> Command {
		command(edit::split_cell)
	}

	/// Merge the selected cells, or split the merged cell holding the caret.
	#[must_use]
	pub fn merge_or_split(self) -> Command {
		command(edit::merge_or_split)
	}

	/// Toggle header cells for the first row, the first column, or the
	/// selected cells.
	#[must_use]
	pub fn toggle_header(self, part: HeaderPart) -> Command {
		command(move |state| edit::toggle_header(state, part))
	}

	/// Set attribute `name` of the selected cells to `value`, or remove it
	/// for `None`.
	#[must_use]
	pub fn set_cell_attribute(self, name: &str, value: Option<&str>) -> Command {
		cell_attribute(name, value.map_or(Value::Null, Value::from))
	}

	/// Select the next cell's content.
	#[must_use]
	pub fn go_to_next_cell(self) -> Command {
		command(|state| navigate::go_to_cell(state, true))
	}

	/// Select the previous cell's content.
	#[must_use]
	pub fn go_to_previous_cell(self) -> Command {
		command(|state| navigate::go_to_cell(state, false))
	}

	/// Give every short row of every table empty cells up to its width.
	#[must_use]
	pub fn fix_tables(self) -> Command {
		command(fix_all)
	}

	/// Where the selection head sits in its table, or `None` outside one.
	#[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(),
	})
}

/// Insert a table of `rows` by `cols` empty cells at the selection, unless
/// either is outside `1..=MAX_SIZE` or the selection's parent cannot hold a
/// table, then put the caret in its first cell.
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))
	})
}

/// A table of `rows` by `cols` cells, each holding an empty paragraph, of
/// the table, row, and paragraph types given first, with `cells` giving
/// each row's cell type. Its ids are placeholders: pasting gives every
/// block a fresh one.
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)
}

/// Paste `table` over the selection, then put the caret in its first cell.
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,
	}))
}

/// The table an update inserted.
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,
		}
	})
}

/// The tables holding the blocks `update` touched.
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
}

/// Keep `tables` well formed: every cell holds a block, and every row
/// covers every column, as TipTap's `fixTables` keeps them.
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)
	})
}

/// A row short of its table's width: the row, how many cells it has, and
/// how many it lacks.
type ShortRow = (BlockId, usize, usize);

/// The cells of a table that hold no block.
fn empty_cells(doc: &Document, context: &TableContext) -> Vec<BlockId> {
	context
		.cells
		.iter()
		.flatten()
		.copied()
		.filter(|&id| doc.children(Some(id)).is_empty())
		.collect()
}

/// The rows of a table that do not cover every column.
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)
}

/// The `tableCell` query's answer.
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."),
	]))
}

/// A command that takes no arguments: its name, what it does, and how.
type SimpleCommand = (
	&'static str,
	&'static str,
	fn(&mut EditorState) -> CommandResult,
);

/// The commands that change a table's shape or its header cells.
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),
	),
];

/// The commands that move between cells, and `fixTables`, which come after
/// `setCellAttribute`.
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,
	),
];

/// The `insertTable` command, which takes the table's size.
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.",
	))
}

/// The `setCellAttribute` command, which takes an attribute and its value.
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
	}

	/// Below the default, so a list inside a cell sinks on Tab and lists
	/// and code blocks handle their own Backspace first.
	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,
		}
	}
}