Files
Tom Moor 49aee74190 feat: Add filtering to tables in the editor (#14625)
* feat: Add filtering to tables in the editor

* Show the column filter button on header hover in edit mode

* Keep the filter button shown while its menu is open

* Move focusEditor to its own module

* Anchor the filter menu to the filter button

* Address review feedback on table filtering

* Show the filter button background while its menu is open

* Always show the filter button background with its icon

* Remove value counts and hide Clear when there is no filter

* Translations

* placeholder
2026-11-18 22:37:15 -05:00

755 lines
21 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { EditorState, Transaction } from "prosemirror-state";
import type { TableRect } from "prosemirror-tables";
import {
CellSelection,
isInTable,
mergeCells,
selectedRect,
} from "prosemirror-tables";
import { getCellSpan } from "../lib/table";
import { findParentNodeClosestToPos } from "./findParentNode";
import { ColumnSelection } from "../selection/ColumnSelection";
import { RowSelection } from "../selection/RowSelection";
import type { EditorView } from "prosemirror-view";
import type { NodeAttrMark, NodeAttrMarkName } from "../types";
import type { Node } from "prosemirror-model";
import type { Selection } from "prosemirror-state";
/**
* Whether a node is part of a table: the table, a row or a cell.
*
* @param node the node.
* @returns true if the node has a table role.
*/
export function hasTableRole(node: Node): boolean {
return !!node.type.spec.tableRole;
}
/**
* Checks if the current selection is a column selection.
* @param state The editor state.
* @returns True if the selection is a column selection, false otherwise.
*/
export function isColSelection(state: EditorState): boolean {
if (state.selection instanceof ColumnSelection) {
return state.selection.isColSelection();
}
return false;
}
/**
* Checks if the current selection is a row selection.
* @param state The editor state.
* @returns True if the selection is a row selection, false otherwise.
*/
export function isRowSelection(state: EditorState): boolean {
if (state.selection instanceof RowSelection) {
return state.selection.isRowSelection();
}
return false;
}
/**
* Get the index of the first selected column. A cell that spans several
* columns widens the selection rectangle, so the index comes from the
* selection itself.
*
* @param state The editor state.
* @returns The column index, or undefined if no column is selected.
*/
export function getColumnIndex(state: EditorState): number | undefined {
const { selection } = state;
if (selection instanceof ColumnSelection && selection.isColSelection()) {
return Math.min(selection.anchorIndex, selection.headIndex);
}
return undefined;
}
/**
* Get the index of the first selected row. A cell that spans several rows
* widens the selection rectangle, so the index comes from the selection
* itself.
*
* @param state The editor state.
* @returns The row index, or undefined if no row is selected.
*/
export function getRowIndex(state: EditorState): number | undefined {
const { selection } = state;
if (selection instanceof RowSelection && selection.isRowSelection()) {
return Math.min(selection.anchorIndex, selection.headIndex);
}
return undefined;
}
/**
* Get the actual row positions in the table map, accounting for merged cells.
*
* Iterates through each visual row and returns the position of the first unique cell in that row.
* This ensures correct row identification even when cells span multiple rows (rowspan > 1).
*
* @param state The editor state
* @returns Array of cell positions representing the first unique cell in each row
*/
export function getRowsInTable(state: EditorState): number[] {
if (!isInTable(state)) {
return [];
}
const rect = selectedRect(state);
const rows: number[] = [];
const seenCells = new Set<number>();
for (let row = 0; row < rect.map.height; row++) {
// Find the leftmost cell in this row
for (let col = 0; col < rect.map.width; col++) {
const cellPos =
rect.tableStart + rect.map.map[row * rect.map.width + col];
if (!seenCells.has(cellPos)) {
rows.push(cellPos);
seenCells.add(cellPos);
break; // Only add the first unique cell per row
}
}
}
return rows;
}
export function getCellsInColumn(index: number) {
return (state: EditorState): number[] => {
if (!isInTable(state)) {
return [];
}
const rect = selectedRect(state);
const cells = [];
let previous;
for (let i = index; i < rect.map.map.length; i += rect.map.width) {
const cell = rect.tableStart + rect.map.map[i];
// Ensure we don't add the same cell multiple times, this can happen
// if the column is selected and the table row has merged cells.
if (previous === cell) {
continue;
}
previous = cell;
cells.push(cell);
}
return cells;
};
}
export function getCellsInRow(index: number) {
return (state: EditorState): number[] => {
if (!isInTable(state)) {
return [];
}
const rect = selectedRect(state);
const cells = [];
let previous;
for (let i = 0; i < rect.map.width; i += 1) {
const cell = rect.tableStart + rect.map.map[index * rect.map.width + i];
cells.push(cell);
// Ensure we don't add the same cell multiple times, this can happen
// if the row is selected and the table column has merged cells.
if (previous === cell) {
continue;
}
previous = cell;
}
return cells;
};
}
/**
* Check if a specific column is selected in the editor.
*
* @param state The editor state
* @param index The index of the column to check
* @returns Boolean indicating if the column is selected
*/
export function isColumnSelected(index: number) {
return (state: EditorState): boolean =>
state.selection instanceof ColumnSelection &&
state.selection.isColSelection()
? state.selection.containsColumn(index)
: false;
}
/**
* Check if the header is enabled for the given type and table rect
*
* @param state The editor state
* @param type The type of header to check
* @param rect The table rect
* @returns Boolean indicating if the header is enabled
*/
export function isHeaderEnabled(
state: EditorState,
type: "row" | "column",
rect: TableRect
): boolean {
// Get cell positions for first row or first column
const cellPositions = rect.map.cellsInRect({
left: 0,
top: 0,
right: type === "row" ? rect.map.width : 1,
bottom: type === "column" ? rect.map.height : 1,
});
for (let i = 0; i < cellPositions.length; i++) {
const cell = rect.table.nodeAt(cellPositions[i]);
if (cell && cell.type !== state.schema.nodes.th) {
return false;
}
}
return true;
}
/**
* Check if a specific row is selected in the editor.
*
* @param state The editor state
* @param index The index of the row to check
* @returns Boolean indicating if the row is selected
*/
export function isRowSelected(index: number) {
return (state: EditorState): boolean =>
state.selection instanceof RowSelection && state.selection.isRowSelection()
? state.selection.containsRow(index)
: false;
}
/**
* Check if an entire table is selected in the editor.
*
* @param state The editor state
* @returns Boolean indicating if the table is selected
*/
export function isTableSelected(state: EditorState): boolean {
if (state.selection instanceof CellSelection) {
const rect = selectedRect(state);
return (
rect.top === 0 &&
rect.left === 0 &&
rect.bottom === rect.map.height &&
rect.right === rect.map.width &&
!state.selection.empty
);
}
return false;
}
/**
* Check if multiple cells are selected in the editor.
*
* @param state The editor state
* @returns Boolean indicating if multiple cells are selected
*/
export function isMultipleCellSelection(state: EditorState): boolean {
const { selection } = state;
return (
selection instanceof CellSelection &&
(selection.isColSelection() ||
selection.isRowSelection() ||
selection.$anchorCell.pos !== selection.$headCell.pos)
);
}
/**
* Check if the selected cells can be merged into a single cell. A row or
* column selection can only be merged when it covers every cell in the
* selected rows or columns, and no cell spans beyond them.
*
* @param state The editor state
* @returns Boolean indicating if the selected cells can be merged
*/
export function canMergeCells(state: EditorState): boolean {
if (!isMultipleCellSelection(state) || !mergeCells(state)) {
return false;
}
const { selection } = state;
if (selection instanceof RowSelection) {
const { top, bottom, left, right, map } = selectedRect(state);
return (
top === Math.min(selection.anchorIndex, selection.headIndex) &&
bottom === Math.max(selection.anchorIndex, selection.headIndex) + 1 &&
left === 0 &&
right === map.width
);
}
if (selection instanceof ColumnSelection) {
const { top, bottom, left, right, map } = selectedRect(state);
return (
left === Math.min(selection.anchorIndex, selection.headIndex) &&
right === Math.max(selection.anchorIndex, selection.headIndex) + 1 &&
top === 0 &&
bottom === map.height
);
}
return true;
}
/**
* Check if the selection spans multiple merged cells.
*
* @param state The editor state
* @returns Boolean indicating if a merged cell is selected
*/
export function isMergedCellSelection(state: EditorState): boolean {
const { selection } = state;
if (
selection instanceof CellSelection ||
selection instanceof RowSelection ||
selection instanceof ColumnSelection
) {
// Check if any cell in the selection has a colspan or rowspan > 1
let hasMergedCells = false;
selection.forEachCell((cell) => {
if (cell.attrs.colspan > 1 || cell.attrs.rowspan > 1) {
hasMergedCells = true;
return false;
}
return true;
});
return hasMergedCells;
}
return false;
}
/**
* Check if the table contains any cells with rowspan > 1.
* Cells with rowspan span multiple rows and would break table sorting.
*
* @param state The editor state.
* @returns true if the table has any cells with rowspan > 1, false otherwise.
*/
export function tableHasRowspan(state: EditorState): boolean {
if (!isInTable(state)) {
return false;
}
const rect = selectedRect(state);
const seen = new Set<number>();
for (let i = 0; i < rect.map.map.length; i++) {
const pos = rect.map.map[i];
// Skip already checked cells
if (seen.has(pos)) {
continue;
}
seen.add(pos);
const cell = rect.table.nodeAt(pos);
if (cell && cell.attrs.rowspan > 1) {
return true;
}
}
return false;
}
/**
* Get the indices between two bounds, in ascending order and inclusive of both.
*/
function indexRange(from: number, to: number): number[] {
const indices: number[] = [];
for (let index = Math.min(from, to); index <= Math.max(from, to); index++) {
indices.push(index);
}
return indices;
}
/**
* Get the indices of all currently selected columns.
*
* @param state The editor state
* @returns Array of selected column indices
*/
export function getAllSelectedColumns(state: EditorState): number[] {
const { selection } = state;
// A cell that spans columns widens the rect beyond the selected columns, so
// take the range from the selection itself where it is known.
if (selection instanceof ColumnSelection && selection.isColSelection()) {
return indexRange(selection.anchorIndex, selection.headIndex);
}
const rect = selectedRect(state);
const selectedColumns: number[] = [];
for (let col = rect.left; col < rect.right; col++) {
selectedColumns.push(col);
}
return selectedColumns;
}
/**
* Get the indices of all currently selected rows.
*
* @param state The editor state
* @returns Array of selected row indices
*/
export function getAllSelectedRows(state: EditorState): number[] {
const { selection } = state;
// A cell that spans rows deepens the rect beyond the selected rows, so take
// the range from the selection itself where it is known.
if (selection instanceof RowSelection && selection.isRowSelection()) {
return indexRange(selection.anchorIndex, selection.headIndex);
}
const rect = selectedRect(state);
const selectedRows: number[] = [];
for (let row = rect.top; row < rect.bottom; row++) {
selectedRows.push(row);
}
return selectedRows;
}
/**
* Get the positions of every unique cell across all selected columns, falling
* back to a single column when it is not part of the selection.
*
* Operating on the full selection ensures column operations affect all selected
* columns – including columns spanned by a merged (colspan) header cell, which a
* single-column lookup would miss.
*
* @param state The editor state
* @param fallbackIndex The column index to use when nothing is selected
* @returns Array of unique cell positions
*/
export function getCellsInSelectedColumns(
state: EditorState,
fallbackIndex: number
): number[] {
const selectedColumns = getAllSelectedColumns(state);
const columns = selectedColumns.includes(fallbackIndex)
? selectedColumns
: [fallbackIndex];
const seen = new Set<number>();
const cells: number[] = [];
columns.forEach((index) => {
getCellsInColumn(index)(state).forEach((pos) => {
if (!seen.has(pos)) {
seen.add(pos);
cells.push(pos);
}
});
});
return cells;
}
/**
* Get the positions of every unique cell across all selected rows, falling back
* to a single row when it is not part of the selection.
*
* Operating on the full selection ensures row operations affect all selected
* rows – including rows spanned by a merged (rowspan) cell, which a single-row
* lookup would miss.
*
* @param state The editor state
* @param fallbackIndex The row index to use when nothing is selected
* @returns Array of unique cell positions
*/
export function getCellsInSelectedRows(
state: EditorState,
fallbackIndex: number
): number[] {
const selectedRows = getAllSelectedRows(state);
const rows = selectedRows.includes(fallbackIndex)
? selectedRows
: [fallbackIndex];
const seen = new Set<number>();
const cells: number[] = [];
rows.forEach((index) => {
getCellsInRow(index)(state).forEach((pos) => {
if (!seen.has(pos)) {
seen.add(pos);
cells.push(pos);
}
});
});
return cells;
}
/**
* Get the viewport bounds of a row in the table that contains the selection.
*
* @param view The editor view.
* @param index The index of the row.
* @returns The bounds of the row, or undefined if it is not rendered.
*/
export function getRowBounds(
view: EditorView,
index: number
): DOMRect | undefined {
const { tableStart } = selectedRect(view.state);
const tableDOM = view.domAtPos(tableStart).node;
if (!(tableDOM instanceof HTMLElement)) {
return undefined;
}
const rows = tableDOM
.closest("table")
?.querySelectorAll(":scope > tbody > tr, :scope > tr");
return rows?.[index]?.getBoundingClientRect();
}
/**
* Get the viewport bounds of a column in the table that contains the
* selection. The width is measured from a cell that only spans this column
* where there is one.
*
* @param view The editor view.
* @param index The index of the column.
* @returns The bounds of the column, or undefined if it is not rendered.
*/
export function getColumnBounds(
view: EditorView,
index: number
): DOMRect | undefined {
const { map, tableStart } = selectedRect(view.state);
const measure = (row: number) => {
const dom = view.nodeDOM(tableStart + map.map[row * map.width + index]);
return dom instanceof HTMLElement ? dom.getBoundingClientRect() : undefined;
};
const first = measure(0);
if (!first) {
return undefined;
}
for (let row = 0; row < map.height; row++) {
const { start, end } = getCellSpan(map, row, index, "column");
if (end - start === 1) {
const bounds = measure(row);
if (bounds) {
return new DOMRect(bounds.left, first.top, bounds.width, first.height);
}
}
}
return first;
}
/**
* Get the total width of selected columns by measuring DOM elements.
* Uses getBoundingClientRect to get precise rendered widths including decimals.
*
* @param view The editor view
* @param rect The table rect
* @param selectedColumns Array of column indices to measure
* @returns The total width in px, or 0 if measurement fails
*/
export function getWidthFromDom({
view,
rect,
selectedColumns,
}: {
view?: EditorView;
rect: TableRect;
selectedColumns: number[];
}): number {
if (!view) {
return 0;
}
const tableDOM = view.domAtPos(rect.tableStart).node as HTMLElement;
const firstRow = tableDOM.closest("table")?.querySelector("tr");
if (!firstRow) {
return 0;
}
const cells = firstRow.querySelectorAll("td, th");
return selectedColumns.reduce((total, colIndex) => {
const cell = cells[colIndex] as HTMLElement | undefined;
return total + (cell?.getBoundingClientRect().width ?? 0);
}, 0);
}
/**
* Get the total width of selected columns from node attributes.
* Sums the colwidth values stored in the document state.
*
* @param state The editor state
* @param selectedColumns Array of column indices to measure
* @returns The total width in px from colwidth attributes
*/
export function getWidthFromNodes({
state,
selectedColumns,
}: {
state: EditorState;
selectedColumns: number[];
}): number {
const firstRowCells = getCellsInRow(0)(state);
if (!firstRowCells) {
return 0;
}
return selectedColumns.reduce((total, colIndex) => {
const cell =
firstRowCells[colIndex] !== undefined
? state.doc.nodeAt(firstRowCells[colIndex])
: null;
const colwidth = cell?.attrs.colwidth;
return total + (colwidth?.[0] ?? 0);
}, 0);
}
const getCellAttrMark = (cell: Node, type: NodeAttrMarkName) => {
const mark = (cell.attrs.marks ?? []).find(
(mark: NodeAttrMark) => mark.type === type
);
return mark;
};
export const hasNodeAttrMarkCellSelection = (
selection: CellSelection,
type: NodeAttrMarkName
) => {
let hasMark = false;
selection.forEachCell((cell) => {
if (!hasMark) {
hasMark = !!getCellAttrMark(cell, type);
}
});
return hasMark;
};
/**
* Returns the set of background colors applied to selected cells.
*
* @param selection - The current selection.
* @returns A set of color strings from background marks on selected cells.
*/
export function getColorSetForSelectedCells(selection: Selection): Set<string> {
const colors = new Set<string>();
if (!(selection instanceof CellSelection)) {
// If not a CellSelection, return empty set
return colors;
}
selection.forEachCell((cell) => {
const backgroundMark = (cell.attrs.marks ?? []).find(
(mark: NodeAttrMark) => mark.type === "background"
);
if (backgroundMark && backgroundMark.attrs.color) {
colors.add(backgroundMark.attrs.color);
}
});
return colors;
}
/**
* Get all unique background colors used in table cells across the entire document.
*
* @param state The editor state.
* @returns An array of unique hex color strings used for table cell backgrounds in the document.
*/
export function getDocumentTableBackgroundColors(state: EditorState): string[] {
const colors = new Set<string>();
state.doc.descendants((node) => {
if (node.type.name === "td" || node.type.name === "th") {
const backgroundMark = (node.attrs.marks ?? []).find(
(mark: NodeAttrMark) => mark.type === "background"
);
if (backgroundMark && backgroundMark.attrs.color) {
colors.add(backgroundMark.attrs.color);
}
}
});
return Array.from(colors);
}
/**
* Returns true if any cell in the selection has a mark of the given type
* with matching attributes.
*
* @param selection The CellSelection to check.
* @param type The mark type to look for.
* @param attrs The attributes to match against.
* @returns True if any cell has the mark with matching attributes.
*/
export const hasNodeAttrMarkWithAttrsCellSelection = (
selection: CellSelection,
type: NodeAttrMarkName,
attrs: Record<string, unknown>
) => {
let attrsMatch = true;
selection.forEachCell((cell) => {
const cellMark = getCellAttrMark(cell, type);
attrsMatch &&=
!!cellMark &&
Object.entries(attrs).every(
([key, value]) => (cellMark.attrs ?? {})[key] === value
);
});
return attrsMatch;
};
/**
* Checks whether the selection change in a transaction can alter table
* decorations that depend on the selection: a cell selection on either side,
* or the selection moving into, out of, or between tables. Moving the cursor
* within one table does not.
*
* @param tr The transaction.
* @param oldState The editor state before the transaction.
* @param newState The editor state after the transaction.
* @returns true if the selected table or the cell selection changed.
*/
export function hasTableSelectionChanged(
tr: Transaction,
oldState: EditorState,
newState: EditorState
): boolean {
if (!tr.selectionSet) {
return false;
}
if (
oldState.selection instanceof CellSelection ||
newState.selection instanceof CellSelection
) {
return true;
}
const isTable = (node: Node) => node.type.spec.tableRole === "table";
const before = findParentNodeClosestToPos(oldState.selection.$head, isTable);
const after = findParentNodeClosestToPos(newState.selection.$head, isTable);
if (!before || !after) {
return !!before !== !!after;
}
return tr.mapping.map(before.pos) !== after.pos;
}