File
Blob: src/client/components/editor/extensions/table/selection.ts
| 1 | import { TextSelection } from "@tiptap/pm/state"; |
| 2 | import type { EditorView } from "@tiptap/pm/view"; |
| 3 | import { CellSelection, TableMap } from "@tiptap/pm/tables"; |
| 4 | import type { Node as PMNode } from "@tiptap/pm/model"; |
| 5 | |
| 6 | export function columnCellSelection( |
| 7 | doc: PMNode, |
| 8 | tablePos: number, |
| 9 | table: PMNode, |
| 10 | colIndex: number, |
| 11 | ): CellSelection | null { |
| 12 | const map = TableMap.get(table); |
| 13 | if (colIndex < 0 || colIndex >= map.width) return null; |
| 14 | |
| 15 | const start = tablePos + 1; |
| 16 | const firstCellPos = map.positionAt(0, colIndex, table); |
| 17 | const lastCellPos = map.positionAt(map.height - 1, colIndex, table); |
| 18 | return CellSelection.colSelection(doc.resolve(start + firstCellPos), doc.resolve(start + lastCellPos)); |
| 19 | } |
| 20 | |
| 21 | export function rowCellSelection(doc: PMNode, tablePos: number, table: PMNode, rowIndex: number): CellSelection | null { |
| 22 | const map = TableMap.get(table); |
| 23 | if (rowIndex < 0 || rowIndex >= map.height) return null; |
| 24 | |
| 25 | const start = tablePos + 1; |
| 26 | const firstCellPos = map.positionAt(rowIndex, 0, table); |
| 27 | const lastCellPos = map.positionAt(rowIndex, map.width - 1, table); |
| 28 | return CellSelection.rowSelection(doc.resolve(start + firstCellPos), doc.resolve(start + lastCellPos)); |
| 29 | } |
| 30 | |
| 31 | export function allCellsSelection(doc: PMNode, tablePos: number, table: PMNode): CellSelection | null { |
| 32 | const map = TableMap.get(table); |
| 33 | if (map.width === 0 || map.height === 0) return null; |
| 34 | |
| 35 | const start = tablePos + 1; |
| 36 | const firstCellPos = map.positionAt(0, 0, table); |
| 37 | const lastCellPos = map.positionAt(map.height - 1, map.width - 1, table); |
| 38 | return CellSelection.create(doc, start + firstCellPos, start + lastCellPos); |
| 39 | } |
| 40 | |
| 41 | export function setCaretInCell(view: EditorView, table: PMNode, tablePos: number, row: number, col: number) { |
| 42 | const map = TableMap.get(table); |
| 43 | if (row < 0 || row >= map.height || col < 0 || col >= map.width) return; |
| 44 | |
| 45 | const start = tablePos + 1; |
| 46 | const cellOffset = map.positionAt(row, col, table); |
| 47 | const inside = start + cellOffset + 1; |
| 48 | view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(inside)))); |
| 49 | } |