### Complete ProseMirror Editor Setup with Table Support Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt This TypeScript code demonstrates a full ProseMirror editor setup with table support. It includes schema creation with table nodes, plugin integration for table editing and column resizing, and exposes table commands for UI interaction. Ensure the ProseMirror libraries and DOM are available. ```typescript import { EditorState } from 'prosemirror-state'; import { EditorView } from 'prosemirror-view'; import { Schema, DOMParser } from 'prosemirror-model'; import { schema as baseSchema } from 'prosemirror-schema-basic'; import { keymap } from 'prosemirror-keymap'; import { baseKeymap } from 'prosemirror-commands'; import { tableNodes, tableEditing, columnResizing, goToNextCell, fixTables, addColumnBefore, addColumnAfter, addRowBefore, addRowAfter, deleteColumn, deleteRow, mergeCells, splitCell, deleteTable, } from 'prosemirror-tables'; // 1. Create schema with table nodes const schema = new Schema({ nodes: baseSchema.spec.nodes.append( tableNodes({ tableGroup: 'block', cellContent: 'block+', cellAttributes: {}, }) ), marks: baseSchema.spec.marks, }); // 2. Parse initial document const doc = DOMParser.fromSchema(schema).parse( document.querySelector('#content') ); // 3. Create editor state with plugins let state = EditorState.create({ doc, plugins: [ columnResizing(), tableEditing(), keymap({ 'Tab': goToNextCell(1), 'Shift-Tab': goToNextCell(-1), }), keymap(baseKeymap), ], }); // 4. Fix any table issues in initial document const fix = fixTables(state); if (fix) { state = state.apply(fix.setMeta('addToHistory', false)); } // 5. Create editor view const view = new EditorView(document.querySelector('#editor'), { state }); // 6. Expose commands for UI buttons window.tableCommands = { addColumnBefore: () => addColumnBefore(view.state, view.dispatch), addColumnAfter: () => addColumnAfter(view.state, view.dispatch), addRowBefore: () => addRowBefore(view.state, view.dispatch), addRowAfter: () => addRowAfter(view.state, view.dispatch), deleteColumn: () => deleteColumn(view.state, view.dispatch), deleteRow: () => deleteRow(view.state, view.dispatch), mergeCells: () => mergeCells(view.state, view.dispatch), splitCell: () => splitCell(view.state, view.dispatch), deleteTable: () => deleteTable(view.state, view.dispatch), }; ``` -------------------------------- ### Table Position Helper Functions Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt A collection of utility functions for checking table context, finding cells, determining column counts, and getting table-related positional information. ```typescript import { isInTable, findCell, cellAround, cellNear, nextCell, colCount, findTable, findCellPos, findCellRange, selectedRect } from 'prosemirror-tables'; // Check if selection is inside a table if (isInTable(view.state)) { console.log('Cursor is in a table'); } // Find cell rectangle at a resolved position const $pos = view.state.selection.$head; const rect = findCell($pos); console.log('Cell spans columns', rect.left, 'to', rect.right); // Find cell around a position const $cell = cellAround($pos); if ($cell) { console.log('Found cell at:', $cell.pos); } // Get column count for a cell const col = colCount($pos); // Find next cell in direction const $next = nextCell($pos, 'horiz', 1); // Find table containing position const tableResult = findTable($pos); if (tableResult) { console.log('Table at:', tableResult.pos, 'depth:', tableResult.depth); } // Get selected rectangle with table info const rect = selectedRect(view.state); console.log('Selection:', rect.left, rect.top, rect.right, rect.bottom); console.log('Table starts at:', rect.tableStart); ``` -------------------------------- ### TableMap - Get Table Structure Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Use TableMap.get to obtain a map of the table's structure. This map provides dimensions and cell positions for efficient lookups. ```typescript import { TableMap } from 'prosemirror-tables'; // Get the map for a table node const map = TableMap.get(tableNode); console.log('Table dimensions:', map.width, 'x', map.height); // Find cell dimensions at a position (relative to table start) const rect = map.findCell(cellPos); console.log('Cell bounds:', rect.left, rect.top, rect.right, rect.bottom); // Get column index for a cell const col = map.colCount(cellPos); // Find next cell in a direction const nextCellPos = map.nextCell(cellPos, 'horiz', 1); // horizontal, forward const prevCellPos = map.nextCell(cellPos, 'vert', -1); // vertical, backward // Get rectangle spanning two cells const rect = map.rectBetween(cellPos1, cellPos2); // Get all cells in a rectangle const cellPositions = map.cellsInRect({ left: 0, top: 0, right: 2, bottom: 2 }); // Get position at specific row/col const pos = map.positionAt(row, col, tableNode); ``` -------------------------------- ### TableMap Class Source: https://github.com/prosemirror/prosemirror-tables/blob/master/README.md The TableMap class is used to describe the structure of a table. It caches these descriptions per table node for efficiency. Positions within the map are relative to the start of the table. ```APIDOC ## TableMap A table map describes the structure of a given table. To avoid recomputing them all the time, they are cached per table node. To be able to do that, positions saved in the map are relative to the start of the table, rather than the start of the document. ### Properties * **`width`** (number) - The width of the table. * **`height`** (number) - The table's height. * **`map`** ([number]) - A width * height array with the start position of the cell covering that part of the table in each slot. ### Methods * **`findCell`**(pos: number) → Rect Find the dimensions of the cell at the given position. * **`colCount`**(pos: number) → number Find the left side of the cell at the given position. * **`nextCell`**(pos: number, axis: string, dir: number) → ?number Find the next cell in the given direction, starting from the cell at `pos`, if any. * **`rectBetween`**(a: number, b: number) → Rect Get the rectangle spanning the two given cells. * **`cellsInRect`**(rect: Rect) → [number] Return the position of all cells that have the top left corner in the given rectangle. * **`positionAt`**(row: number, col: number, table: Node) → number Return the position at which the cell at the given row and column starts, or would start, if a cell started there. ### Static Methods * **`get`**(table: Node) → TableMap Find the table map for the given table node. ``` -------------------------------- ### Table Schema and Editing Source: https://github.com/prosemirror/prosemirror-tables/blob/master/src/README.md Core components for initializing table support in a ProseMirror schema and enabling editing capabilities. ```APIDOC ## Schema and Plugin Setup ### tableNodes - Used to create a table-enabled schema. ### tableEditing - Plugin to manage cell selections and enforce table invariants. ### CellSelection - Custom selection class for selecting cells within a table. ``` -------------------------------- ### columnResizing - Enable Column Resize Plugin Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Adds functionality for users to resize table columns by dragging column borders, with visual feedback. ```APIDOC ## columnResizing - Enable Column Resize Plugin ### Description Creates a plugin that allows users to resize table columns by dragging column borders. It provides visual feedback during resize operations. ### Method `columnResizing(options)` ### Parameters #### Request Body - **options** (object) - Optional - Configuration options for column resizing. - **handleWidth** (number) - Optional - The width of the resize handle. - **cellMinWidth** (number) - Optional - The minimum width for a cell. - **defaultCellMinWidth** (number) - Optional - The default minimum width for cells. - **lastColumnResizable** (boolean) - Optional - Whether the last column can be resized. ### Request Example ```typescript import { EditorState } from 'prosemirror-state'; import { columnResizing, tableEditing } from 'prosemirror-tables'; const state = EditorState.create({ doc: myDoc, plugins: [ columnResizing({ handleWidth: 5, cellMinWidth: 25, defaultCellMinWidth: 100, lastColumnResizable: true, }), tableEditing(), ], }); ``` ### Response #### Success Response (200) - **Plugin** - A ProseMirror plugin object that enables column resizing. ``` -------------------------------- ### Create a CellSelection Instance Source: https://github.com/prosemirror/prosemirror-tables/blob/master/README.md Instantiate `CellSelection` with resolved positions pointing before the anchor and head cells. Use static methods for column or row selections. ```typescript new CellSelection($anchorCell, $headCell) ``` ```typescript CellSelection.colSelection($anchorCell, $headCell) ``` ```typescript CellSelection.rowSelection($anchorCell, $headCell) ``` ```typescript CellSelection.create(doc, anchorCell, headCell) ``` -------------------------------- ### Add Column Commands Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Use addColumnBefore and addColumnAfter to insert new columns into the table. These can be used directly or as menu items. ```typescript import { addColumnBefore, addColumnAfter } from 'prosemirror-tables'; // Use as menu item const menuItem = new MenuItem({ label: 'Insert column before', select: addColumnBefore, run: addColumnBefore, }); // Execute directly if (addColumnBefore(view.state, view.dispatch)) { console.log('Column added before selection'); } if (addColumnAfter(view.state, view.dispatch)) { console.log('Column added after selection'); } ``` -------------------------------- ### Add Row Commands Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Use addRowBefore and addRowAfter to insert new rows into the table. These commands can be bound to keyboard shortcuts or executed directly. ```typescript import { addRowBefore, addRowAfter } from 'prosemirror-tables'; // Bind to keyboard shortcut import { keymap } from 'prosemirror-keymap'; const tableKeymap = keymap({ 'Ctrl-Shift-Enter': addRowAfter, 'Ctrl-Alt-Enter': addRowBefore, }); // Execute directly rowAfter(view.state, view.dispatch); ``` -------------------------------- ### Initialize Table Editing Plugin Source: https://github.com/prosemirror/prosemirror-tables/blob/master/README.md The `tableEditing` plugin enables cell selection, handles copy/paste for cells, and enforces table well-formedness. It's recommended to place this plugin towards the end of the plugin list. ```typescript tableEditing() ``` -------------------------------- ### Enable Column Resize Plugin Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Adds column resizing capabilities to the editor, allowing users to drag borders to adjust column widths. ```typescript import { EditorState } from 'prosemirror-state'; import { columnResizing, tableEditing } from 'prosemirror-tables'; const state = EditorState.create({ doc: myDoc, plugins: [ columnResizing({ handleWidth: 5, cellMinWidth: 25, defaultCellMinWidth: 100, lastColumnResizable: true, }), tableEditing(), ], }); ``` -------------------------------- ### Navigate Between Table Cells with goToNextCell Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Use goToNextCell to create commands for navigating between table cells using Tab and Shift-Tab. This is typically added to the keymap plugin. ```typescript import { goToNextCell } from 'prosemirror-tables'; import { keymap } from 'prosemirror-keymap'; // Create keymap for tab navigation const tableKeymap = keymap({ 'Tab': goToNextCell(1), // Next cell 'Shift-Tab': goToNextCell(-1), // Previous cell }); // Add to plugins const state = EditorState.create({ doc: myDoc, plugins: [ columnResizing(), tableEditing(), tableKeymap, ], }); ``` -------------------------------- ### addColumnBefore / addColumnAfter - Insert Columns Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Commands to insert a new column either before or after the currently selected column in the table. ```APIDOC ## addColumnBefore / addColumnAfter - Insert Columns Commands to add a column before or after the currently selected column. ### Method - **addColumnBefore(state, dispatch)**: Inserts a column before the current selection. - **addColumnAfter(state, dispatch)**: Inserts a column after the current selection. ### Parameters - **state** (EditorState) - The current ProseMirror editor state. - **dispatch** (function) - The dispatch function to apply the transaction. ### Example Usage ```typescript import { addColumnBefore, addColumnAfter } from 'prosemirror-tables'; // Use as menu item const menuItem = new MenuItem({ label: 'Insert column before', select: addColumnBefore, run: addColumnBefore, }); // Execute directly if (addColumnBefore(view.state, view.dispatch)) { console.log('Column added before selection'); } if (addColumnAfter(view.state, view.dispatch)) { console.log('Column added after selection'); } ``` ``` -------------------------------- ### Select Multiple Cells Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Demonstrates programmatic creation of CellSelection instances and methods for inspecting or iterating over selected table cells. ```typescript import { CellSelection } from 'prosemirror-tables'; // Create a cell selection programmatically const $anchorCell = doc.resolve(cellPos1); const $headCell = doc.resolve(cellPos2); const selection = new CellSelection($anchorCell, $headCell); // Create using static methods const colSelection = CellSelection.colSelection($anchorCell, $headCell); const rowSelection = CellSelection.rowSelection($anchorCell, $headCell); const singleCell = CellSelection.create(doc, cellPos); // Check selection type if (selection.isColSelection()) { console.log('Entire columns selected'); } if (selection.isRowSelection()) { console.log('Entire rows selected'); } // Iterate over selected cells selection.forEachCell((node, pos) => { console.log('Cell at position:', pos, 'content:', node.textContent); }); ``` -------------------------------- ### addRowBefore / addRowAfter - Insert Rows Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Commands to insert a new row either before or after the currently selected row in the table. ```APIDOC ## addRowBefore / addRowAfter - Insert Rows Commands to add a row before or after the currently selected row. ### Method - **addRowBefore(state, dispatch)**: Inserts a row before the current selection. - **addRowAfter(state, dispatch)**: Inserts a row after the current selection. ### Parameters - **state** (EditorState) - The current ProseMirror editor state. - **dispatch** (function) - The dispatch function to apply the transaction. ### Example Usage ```typescript import { addRowBefore, addRowAfter } from 'prosemirror-tables'; import { keymap } from 'prosemirror-keymap'; // Bind to keyboard shortcut const tableKeymap = keymap({ 'Ctrl-Shift-Enter': addRowAfter, 'Ctrl-Alt-Enter': addRowBefore, }); // Execute directly addRowAfter(view.state, view.dispatch); ``` ``` -------------------------------- ### Utilities Source: https://github.com/prosemirror/prosemirror-tables/blob/master/src/README.md Utility functions for maintaining table integrity and mapping. ```APIDOC ## Utilities ### fixTables - Function to enforce invariants and fix broken tables. ### TableMap - Utility class for mapping table structure. ``` -------------------------------- ### Table Manipulation Commands Source: https://github.com/prosemirror/prosemirror-tables/blob/master/README.md Commands for adding, deleting, merging, splitting, and moving table elements. ```APIDOC ## addColumnBefore ### Description Adds a column before the column with the selection. ### Parameters - **state** (EditorState) - Required - **dispatch** (fn(tr: Transaction)) - Optional ### Response - **bool** - Returns true if the command was executed. ## addColumnAfter ### Description Adds a column after the column with the selection. ### Parameters - **state** (EditorState) - Required - **dispatch** (fn(tr: Transaction)) - Optional ### Response - **bool** - Returns true if the command was executed. ## deleteColumn ### Description Removes the selected columns from a table. ### Parameters - **state** (EditorState) - Required - **dispatch** (fn(tr: Transaction)) - Optional ### Response - **bool** - Returns true if the command was executed. ## addRowBefore ### Description Adds a table row before the selection. ### Parameters - **state** (EditorState) - Required - **dispatch** (fn(tr: Transaction)) - Optional ### Response - **bool** - Returns true if the command was executed. ## addRowAfter ### Description Adds a table row after the selection. ### Parameters - **state** (EditorState) - Required - **dispatch** (fn(tr: Transaction)) - Optional ### Response - **bool** - Returns true if the command was executed. ## deleteRow ### Description Removes the selected rows from a table. ### Parameters - **state** (EditorState) - Required - **dispatch** (fn(tr: Transaction)) - Optional ### Response - **bool** - Returns true if the command was executed. ## mergeCells ### Description Merges the selected cells into a single cell. Only available when the selected cells' outline forms a rectangle. ### Parameters - **state** (EditorState) - Required - **dispatch** (fn(tr: Transaction)) - Optional ### Response - **bool** - Returns true if the command was executed. ## splitCell ### Description Split a selected cell, whose rowpan or colspan is greater than one, into smaller cells. ### Parameters - **state** (EditorState) - Required - **dispatch** (fn(tr: Transaction)) - Optional ### Response - **bool** - Returns true if the command was executed. ## deleteTable ### Description Deletes the table around the selection, if any. ### Parameters - **state** (EditorState) - Required - **dispatch** (fn(tr: Transaction)) - Optional ### Response - **bool** - Returns true if the command was executed. ``` -------------------------------- ### tableNodes - Create Table Schema Nodes Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Defines the ProseMirror node specifications for tables, rows, and cells, including custom attributes like background color. ```APIDOC ## tableNodes - Create Table Schema Nodes ### Description Creates a set of ProseMirror node specifications for `table`, `table_row`, `table_header`, and `table_cell` node types that can be added to your schema. ### Method `tableNodes(options)` ### Parameters #### Request Body - **options** (object) - Required - Configuration options for table nodes. - **tableGroup** (string) - Optional - The group name for table nodes. - **cellContent** (string) - Optional - The content expression for cells. - **cellAttributes** (object) - Optional - Custom attributes for cells. - **attributeName** (object) - Required - Configuration for a specific cell attribute. - **default** (any) - Optional - Default value for the attribute. - **getFromDOM** (function) - Optional - Function to get the attribute value from DOM. - **setDOMAttr** (function) - Optional - Function to set the attribute value on DOM. ### Request Example ```typescript import { Schema } from 'prosemirror-model'; import { schema as baseSchema } from 'prosemirror-schema-basic'; import { tableNodes } from 'prosemirror-tables'; const schema = new Schema({ nodes: baseSchema.spec.nodes.append( tableNodes({ tableGroup: 'block', cellContent: 'block+', cellAttributes: { background: { default: null, getFromDOM(dom) { return dom.style.backgroundColor || null; }, setDOMAttr(value, attrs) { if (value) { attrs.style = `background-color: ${value}`; } }, }, }, }) ), marks: baseSchema.spec.marks, }); ``` ### Response #### Success Response (200) - **object** - A ProseMirror schema specification object for table nodes. ``` -------------------------------- ### Create Table Schema Nodes Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Defines the necessary node specifications for tables, rows, and cells to be integrated into a ProseMirror schema. ```typescript import { Schema } from 'prosemirror-model'; import { schema as baseSchema } from 'prosemirror-schema-basic'; import { tableNodes } from 'prosemirror-tables'; const schema = new Schema({ nodes: baseSchema.spec.nodes.append( tableNodes({ tableGroup: 'block', cellContent: 'block+', cellAttributes: { background: { default: null, getFromDOM(dom) { return dom.style.backgroundColor || null; }, setDOMAttr(value, attrs) { if (value) { attrs.style = `background-color: ${value}`; } }, }, }, }) ), marks: baseSchema.spec.marks, }); ``` -------------------------------- ### TableMap - Table Structure Information Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt The TableMap class provides methods to efficiently query the structure of a table, including cell positions, dimensions, and relationships. ```APIDOC ## TableMap - Table Structure Information A class that describes the structure of a table, caching cell positions and dimensions for efficient lookups. Positions are table-relative. ### Methods - **get(tableNode)**: Returns a TableMap instance for the given table node. - **findCell(cellPos)**: Finds the rectangle (left, top, right, bottom) of the cell at the given position. - **colCount(cellPos)**: Returns the column index of the cell at the given position. - **nextCell(cellPos, direction, step)**: Finds the next cell in a given direction (horiz/vert) by a specified step. - **rectBetween(cellPos1, cellPos2)**: Gets the rectangle spanning two cells. - **cellsInRect(rect)**: Gets all cell positions within a given rectangle. - **positionAt(row, col, tableNode)**: Gets the position at a specific row and column within a table node. ### Example Usage ```typescript import { TableMap } from 'prosemirror-tables'; // Get the map for a table node const map = TableMap.get(tableNode); console.log('Table dimensions:', map.width, 'x', map.height); // Find cell dimensions at a position (relative to table start) const rect = map.findCell(cellPos); console.log('Cell bounds:', rect.left, rect.top, rect.right, rect.bottom); // Get column index for a cell const col = map.colCount(cellPos); // Find next cell in a direction const nextCellPos = map.nextCell(cellPos, 'horiz', 1); // horizontal, forward const prevCellPos = map.nextCell(cellPos, 'vert', -1); // vertical, backward // Get rectangle spanning two cells const rect = map.rectBetween(cellPos1, cellPos2); // Get all cells in a rectangle const cellPositions = map.cellsInRect({ left: 0, top: 0, right: 2, bottom: 2 }); // Get position at specific row/col const pos = map.positionAt(row, col, tableNode); ``` ``` -------------------------------- ### Navigation Between Cells Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Provides a command to navigate between table cells using Tab and Shift+Tab keys. ```APIDOC ## goToNextCell - Navigate Between Cells Returns a command for selecting the next or previous cell in a table, useful for Tab navigation. ### Method Command (function that returns a command) ### Endpoint N/A (This is a library function, not an API endpoint) ### Parameters - **direction** (number) - Required - The direction to move: 1 for next cell, -1 for previous cell. ### Request Example ```typescript import { goToNextCell } from 'prosemirror-tables'; import { keymap } from 'prosemirror-keymap'; const tableKeymap = keymap({ 'Tab': goToNextCell(1), 'Shift-Tab': goToNextCell(-1) }); ``` ### Response N/A (This function returns a Prosemirror command) ``` -------------------------------- ### Enable Table Editing Plugin Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Initializes the table editing plugin to handle cell-based interactions and maintain table integrity. Place this plugin near the end of the plugins array. ```typescript import { EditorState } from 'prosemirror-state'; import { EditorView } from 'prosemirror-view'; import { tableEditing } from 'prosemirror-tables'; const state = EditorState.create({ doc: myDoc, plugins: [ tableEditing({ allowTableNodeSelection: false }), // ... other plugins ], }); const view = new EditorView(document.querySelector('#editor'), { state }); ``` -------------------------------- ### Table Commands Source: https://github.com/prosemirror/prosemirror-tables/blob/master/src/README.md Commands available for performing table editing operations. ```APIDOC ## Table Commands - **addColumnBefore**: Adds a column before the current selection. - **addColumnAfter**: Adds a column after the current selection. - **deleteColumn**: Deletes the current column. - **addRowBefore**: Adds a row before the current selection. - **addRowAfter**: Adds a row after the current selection. - **deleteRow**: Deletes the current row. - **mergeCells**: Merges selected cells. - **splitCell**: Splits a merged cell. - **splitCellWithType**: Splits a cell with a specific type. - **setCellAttr**: Sets an attribute on a cell. - **toggleHeaderRow**: Toggles the header row status. - **toggleHeaderColumn**: Toggles the header column status. - **toggleHeaderCell**: Toggles the header cell status. - **toggleHeader**: Toggles header status. - **goToNextCell**: Navigates to the next cell. - **deleteTable**: Deletes the entire table. ``` -------------------------------- ### Table Utility Functions Source: https://github.com/prosemirror/prosemirror-tables/blob/master/README.md Utility functions for inspecting and finding table nodes and cell positions. ```APIDOC ## fixTables ### Description Inspect all tables in the given state's document and return a transaction that fixes them, if necessary. ### Parameters - **state** (EditorState) - Required - **oldState** (EditorState) - Optional ### Response - **Transaction** - Returns a transaction if fixes are needed. ## findTable ### Description Find the closest table node that contains the given position. ### Parameters - **$pos** (ResolvedPos) - Required ### Response - **FindNodeResult** - The found table node result. ## findCellPos ### Description Find a resolved pos of a cell by using the given position as a hit point. ### Parameters - **doc** (Node) - Required - **pos** (number) - Required ### Response - **ResolvedPos** - The resolved position of the cell. ``` -------------------------------- ### Reorder Rows and Columns Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Commands to move rows or columns from one position to another within a table. ```APIDOC ## moveTableRow / moveTableColumn - Reorder Rows and Columns Commands to move rows or columns from one position to another. ### Method Command (function that returns a command) ### Endpoint N/A (These are library functions, not API endpoints) ### Parameters - **moveTableRow**: - **from** (number) - Required - The starting index of the row. - **to** (number) - Required - The destination index for the row. - **select** (boolean) - Optional - Whether to select the moved row/column. - **moveTableColumn**: - **from** (number) - Required - The starting index of the column. - **to** (number) - Required - The destination index for the column. - **select** (boolean) - Optional - Whether to select the moved row/column. ### Request Example ```typescript import { moveTableRow, moveTableColumn } from 'prosemirror-tables'; // Move row from index 0 to index 2 const moveFirstRowToThird = moveTableRow({ from: 0, to: 2, select: true }); moveFirstRowToThird(view.state, view.dispatch); // Move column from index 1 to index 0 const moveColumnLeft = moveTableColumn({ from: 1, to: 0, select: true }); moveColumnLeft(view.state, view.dispatch); // Move without selecting the moved row/column const moveRowSilent = moveTableRow({ from: 2, to: 0, select: false }); ``` ### Response N/A (These functions return Prosemirror commands) ``` -------------------------------- ### Table Position Helper Functions Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Utility functions for working with table cells and positions within a Prosemirror document. ```APIDOC ## Utility Functions - Table Position Helpers Helper functions for working with table cells and positions. ### Method Functions ### Endpoint N/A (These are library functions, not API endpoints) ### Functions - **isInTable**(state: EditorState): boolean - Checks if the current selection is inside a table. - **findCell**(pos: ResolvedPos): CellInfo | null - Finds the cell containing the given resolved position. - **cellAround**(pos: ResolvedPos): ResolvedPos | null - Finds the cell nearest to the given resolved position. - **cellNear**(pos: ResolvedPos): ResolvedPos | null - Finds the cell nearest to the given resolved position, potentially in an adjacent cell if the position is between cells. - **nextCell**(pos: ResolvedPos, direction: 'horiz' | 'vert', step: number): ResolvedPos | null - Finds the next cell in a given direction (horizontal or vertical) by a specified step. - **colCount**(pos: ResolvedPos): number - Returns the column index of the cell at the given resolved position. - **findTable**(pos: ResolvedPos): { pos: number, depth: number } | null - Finds the nearest table node containing the given resolved position. - **findCellPos**(state: EditorState, pos: number): number | null - Finds the position of a cell at a given document position. - **findCellRange**(state: EditorState, pos: number): { from: number, to: number } | null - Finds the range of a cell at a given document position. - **selectedRect**(state: EditorState): { left: number, right: number, top: number, bottom: number, tableStart: number } | null - Gets the bounding rectangle of the selected cells within a table. ### Request Example ```typescript import { isInTable, findCell, cellAround, cellNear, nextCell, colCount, findTable, findCellPos, findCellRange, selectedRect } from 'prosemirror-tables'; // Check if selection is inside a table if (isInTable(view.state)) { console.log('Cursor is in a table'); } // Find cell rectangle at a resolved position const $pos = view.state.selection.$head; const rect = findCell($pos); if (rect) { console.log('Cell spans columns', rect.left, 'to', rect.right); } // Find cell around a position const $cell = cellAround($pos); if ($cell) { console.log('Found cell at:', $cell.pos); } // Get column count for a cell const col = colCount($pos); // Find next cell in direction const $next = nextCell($pos, 'horiz', 1); // Find table containing position const tableResult = findTable($pos); if (tableResult) { console.log('Table at:', tableResult.pos, 'depth:', tableResult.depth); } // Get selected rectangle with table info const selRect = selectedRect(view.state); if (selRect) { console.log('Selection:', selRect.left, selRect.top, selRect.right, selRect.bottom); console.log('Table starts at:', selRect.tableStart); } ``` ### Response - **Various types** (boolean, CellInfo, ResolvedPos, number, object, null) - Depending on the function called. ``` -------------------------------- ### Create Table Nodes Schema Extension Source: https://github.com/prosemirror/prosemirror-tables/blob/master/README.md Use `tableNodes` to generate node specifications for table, table_row, and table_cell. Configure table group, cell content, and cell attributes. ```typescript tableNodes({ tableGroup: "block", cellContent: "paragraph block*", cellAttributes: { background: { default: null, getFromDOM: (td: HTMLElement) => td.style.backgroundColor, setDOMAttr: (value: string, attrs: {[key: string]: string}) => { attrs["style"] = (attrs["style"] || "") + `background-color: ${value}` } } } }) ``` -------------------------------- ### toggleHeaderRow / toggleHeaderColumn / toggleHeaderCell - Toggle Headers Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Commands to toggle header status for rows, columns, or individual cells. ```APIDOC ## toggleHeaderRow / toggleHeaderColumn / toggleHeaderCell - Toggle Headers Commands to toggle whether rows, columns, or cells are header cells. ### Method - **toggleHeaderRow(state, dispatch)**: Toggles the header status of the selected row(s). - **toggleHeaderColumn(state, dispatch)**: Toggles the header status of the selected column(s). - **toggleHeaderCell(state, dispatch)**: Toggles the header status of the selected cell(s). - **toggleHeader(type)**: Returns a command to toggle headers of a specific type ('row' or 'column'). ### Parameters - **state** (EditorState) - The current ProseMirror editor state. - **dispatch** (function) - The dispatch function to apply the transaction. - **type** (string): The type of header to toggle ('row' or 'column'). ### Example Usage ```typescript import { toggleHeaderRow, toggleHeaderColumn, toggleHeaderCell, toggleHeader } from 'prosemirror-tables'; // Toggle first row as header toggleHeaderRow(view.state, view.dispatch); // Toggle first column as header toggleHeaderColumn(view.state, view.dispatch); // Toggle selected cells as headers toggleHeaderCell(view.state, view.dispatch); // Generic toggle with type parameter const toggleCol = toggleHeader('column'); const toggleRow = toggleHeader('row'); toggleCol(view.state, view.dispatch); ``` ``` -------------------------------- ### Delete Entire Table Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Provides a command to delete the table containing the current selection. ```APIDOC ## deleteTable - Delete Entire Table Command to delete the table containing the current selection. ### Method Command (function) ### Endpoint N/A (This is a library function, not an API endpoint) ### Parameters None ### Request Example ```typescript import { deleteTable } from 'prosemirror-tables'; // Add to menu const menuItem = new MenuItem({ label: 'Delete table', select: deleteTable, run: deleteTable }); // Execute directly if (deleteTable(view.state, view.dispatch)) { console.log('Table deleted'); } ``` ### Response N/A (This function returns a Prosemirror command or a boolean indicating success) ``` -------------------------------- ### Table Editing Plugin Source: https://github.com/prosemirror/prosemirror-tables/blob/master/README.md A plugin that enables cell-selection, handles cell-based copy/paste, and ensures table well-formedness. ```APIDOC ## tableEditing ### Description Creates a plugin that, when added to an editor, enables cell-selection, handles cell-based copy/paste, and makes sure tables stay well-formed (each row has the same width, and cells don't overlap). ### Usage It is recommended to place this plugin near the end of your array of plugins. ``` -------------------------------- ### tableEditing - Enable Table Editing Plugin Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Provides essential table editing features, including cell selection, copy/paste handling, and table normalization. ```APIDOC ## tableEditing - Enable Table Editing Plugin ### Description Creates a plugin that enables cell-selection, handles cell-based copy/paste, and ensures tables remain well-formed. This plugin should be placed near the end of your ProseMirror plugins array. ### Method `tableEditing(options)` ### Parameters #### Request Body - **options** (object) - Optional - Configuration options for table editing. - **allowTableNodeSelection** (boolean) - Optional - Whether to allow selection of the entire table node. ### Request Example ```typescript import { EditorState } from 'prosemirror-state'; import { EditorView } from 'prosemirror-view'; import { tableEditing } from 'prosemirror-tables'; const state = EditorState.create({ doc: myDoc, plugins: [ tableEditing({ allowTableNodeSelection: false }), // ... other plugins ], }); const view = new EditorView(document.querySelector('#editor'), { state }); ``` ### Response #### Success Response (200) - **Plugin** - A ProseMirror plugin object that enables table editing. ``` -------------------------------- ### Merge and Split Cell Commands Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Commands for merging selected cells into one (mergeCells) or splitting a merged cell back into multiple (splitCell). splitCellWithType allows custom cell type selection during splitting. ```typescript import { mergeCells, splitCell, splitCellWithType } from 'prosemirror-tables'; // Merge selected cells (only works when selection forms a rectangle) if (mergeCells(view.state, view.dispatch)) { console.log('Cells merged'); } // Split a cell with rowspan/colspan > 1 if (splitCell(view.state, view.dispatch)) { console.log('Cell split'); } // Split with custom cell type selection const splitWithType = splitCellWithType(({ node, row, col }) => { // Return header_cell for first row, regular cell otherwise const types = tableNodeTypes(view.state.schema); return row === 0 ? types.header_cell : types.cell; }); splitWithType(view.state, view.dispatch); ``` -------------------------------- ### mergeCells / splitCell - Merge and Split Cells Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Commands to merge selected cells into a single cell or split a merged cell back into its original cells. ```APIDOC ## mergeCells / splitCell - Merge and Split Cells Commands to merge selected cells into one or split a merged cell back into multiple cells. ### Method - **mergeCells(state, dispatch)**: Merges the selected cells if they form a rectangle. - **splitCell(state, dispatch)**: Splits a cell that has rowspan or colspan greater than 1. - **splitCellWithType(cellTypeSelector)**: Splits a cell, allowing custom selection of cell types for the split cells. ### Parameters - **state** (EditorState) - The current ProseMirror editor state. - **dispatch** (function) - The dispatch function to apply the transaction. - **cellTypeSelector** (function): A function that takes `(node, row, col)` and returns the desired cell type for the split cells. ### Example Usage ```typescript import { mergeCells, splitCell, splitCellWithType } from 'prosemirror-tables'; // Merge selected cells (only works when selection forms a rectangle) if (mergeCells(view.state, view.dispatch)) { console.log('Cells merged'); } // Split a cell with rowspan/colspan > 1 if (splitCell(view.state, view.dispatch)) { console.log('Cell split'); } // Split with custom cell type selection const splitWithType = splitCellWithType(({ node, row, col }) => { // Return header_cell for first row, regular cell otherwise const types = tableNodeTypes(view.state.schema); return row === 0 ? types.header_cell : types.cell; }); splitWithType(view.state, view.dispatch); ``` ``` -------------------------------- ### Reorder Table Rows and Columns with moveTableRow/moveTableColumn Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Commands to move rows or columns to different positions within a table. The 'select' option determines if the moved content is selected afterwards. ```typescript import { moveTableRow, moveTableColumn } from 'prosemirror-tables'; // Move row from index 0 to index 2 const moveFirstRowToThird = moveTableRow({ from: 0, to: 2, select: true }); moveFirstRowToThird(view.state, view.dispatch); // Move column from index 1 to index 0 const moveColumnLeft = moveTableColumn({ from: 1, to: 0, select: true }); moveColumnLeft(view.state, view.dispatch); // Move without selecting the moved row/column const moveRowSilent = moveTableRow({ from: 2, to: 0, select: false }); ``` -------------------------------- ### Repair Malformed Tables with fixTables Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt The fixTables command inspects a document for structural table issues and returns a transaction to correct them. It can be used on initial load or incrementally. ```typescript import { fixTables } from 'prosemirror-tables'; // Fix tables on initial load let state = EditorState.create({ doc, plugins }); const fix = fixTables(state); if (fix) { state = state.apply(fix.setMeta('addToHistory', false)); } // Incremental fix (comparing with previous state) const newFix = fixTables(newState, oldState); if (newFix) { view.dispatch(newFix); } ``` -------------------------------- ### Repair Malformed Tables Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Inspects all tables in a document and returns a transaction that fixes structural problems. ```APIDOC ## fixTables - Repair Malformed Tables Inspects all tables in a document and returns a transaction that fixes structural problems like overlapping cells or uneven row widths. ### Method Function ### Endpoint N/A (This is a library function, not an API endpoint) ### Parameters - **state** (EditorState) - Required - The current Prosemirror editor state. - **oldState** (EditorState) - Optional - The previous Prosemirror editor state for incremental fixing. ### Request Example ```typescript import { fixTables } from 'prosemirror-tables'; // Fix tables on initial load let state = EditorState.create({ doc, plugins }); const fix = fixTables(state); if (fix) { state = state.apply(fix.setMeta('addToHistory', false)); } // Incremental fix (comparing with previous state) const newFix = fixTables(newState, oldState); if (newFix) { view.dispatch(newFix); } ``` ### Response - **Transaction** | **null** - A Prosemirror transaction object if fixes were applied, otherwise null. ``` -------------------------------- ### setCellAttr - Set Cell Attributes Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Returns a command that sets a specified attribute to a given value on the selected cells. ```APIDOC ## setCellAttr - Set Cell Attributes Returns a command that sets a given attribute to a value on selected cells. ### Method - **setCellAttr(attribute, value)**: Returns a command to set the specified attribute on selected cells. ### Parameters - **attribute** (string) - The name of the cell attribute to set (e.g., 'background', 'colspan'). - **value** - The value to set for the attribute. Can be null to remove the attribute. ### Example Usage ```typescript import { setCellAttr } from 'prosemirror-tables'; // Create commands for setting cell background colors const makeGreen = setCellAttr('background', '#dfd'); const makeRed = setCellAttr('background', '#fdd'); const clearBackground = setCellAttr('background', null); // Use in menu const colorMenu = [ new MenuItem({ label: 'Green background', run: makeGreen, select: makeGreen }), new MenuItem({ label: 'Red background', run: makeRed, select: makeRed }), new MenuItem({ label: 'Clear background', run: clearBackground, select: clearBackground }), ]; // Execute directly makeGreen(view.state, view.dispatch); ``` ``` -------------------------------- ### Set Cell Attribute Command Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt The setCellAttr command creates a command to set a specific attribute on selected cells. Useful for styling, like setting background colors. ```typescript import { setCellAttr } from 'prosemirror-tables'; // Create commands for setting cell background colors const makeGreen = setCellAttr('background', '#dfd'); const makeRed = setCellAttr('background', '#fdd'); const clearBackground = setCellAttr('background', null); // Use in menu const colorMenu = [ new MenuItem({ label: 'Green background', run: makeGreen, select: makeGreen }), new MenuItem({ label: 'Red background', run: makeRed, select: makeRed }), new MenuItem({ label: 'Clear background', run: clearBackground, select: clearBackground }), ]; // Execute directly makeGreen(view.state, view.dispatch); ``` -------------------------------- ### Toggle Header Commands Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt Commands to toggle header status for rows, columns, or individual cells. toggleHeader provides a generic way to toggle based on type ('row' or 'column'). ```typescript import { toggleHeaderRow, toggleHeaderColumn, toggleHeaderCell, toggleHeader } from 'prosemirror-tables'; // Toggle first row as header toggleHeaderRow(view.state, view.dispatch); // Toggle first column as header toggleHeaderColumn(view.state, view.dispatch); // Toggle selected cells as headers toggleHeaderCell(view.state, view.dispatch); // Generic toggle with type parameter const toggleCol = toggleHeader('column'); const toggleRow = toggleHeader('row'); toggleCol(view.state, view.dispatch); ``` -------------------------------- ### Delete Entire Table with deleteTable Source: https://context7.com/prosemirror/prosemirror-tables/llms.txt The deleteTable command removes the entire table containing the current selection. It can be used directly or added to menu items. ```typescript import { deleteTable } from 'prosemirror-tables'; // Add to menu const menuItem = new MenuItem({ label: 'Delete table', select: deleteTable, run: deleteTable, }); // Execute directly if (deleteTable(view.state, view.dispatch)) { console.log('Table deleted'); } ```