UNPKG

@atlaskit/editor-plugin-table

Version:

Table plugin for the @atlaskit/editor

68 lines 2.61 kB
import { TableSortOrder as SortOrder, TableSortStep } from '@atlaskit/custom-steps'; import { createCompareNodes } from '@atlaskit/editor-common/utils'; import { Selection } from '@atlaskit/editor-prosemirror/state'; import { TableMap } from '@atlaskit/editor-tables/table-map'; import { convertArrayOfRowsToTableNode, convertTableNodeToArrayOfRows, findCellRectClosestToPos, findTable, getSelectionRect, isSelectionType } from '@atlaskit/editor-tables/utils'; import { createCommand, getPluginState } from '../plugin-factory'; const createGetInlineCardTextFromStore = attrs => { const { data } = attrs; // Ignored via go/ees005 // eslint-disable-next-line @typescript-eslint/no-explicit-any if (data && (data.name || data.title)) { // Ignored via go/ees005 // eslint-disable-next-line @typescript-eslint/no-explicit-any return data.name || data.title; } const { url: cardUrl } = attrs; return cardUrl; }; export const sortByColumn = (columnIndex, order = SortOrder.DESC) => createCommand(() => ({ type: 'SORT_TABLE', data: { ordering: { columnIndex, order } } }), (tr, state) => { // Ignored via go/ees005 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const table = findTable(tr.selection); if (!table || !table.node) { return tr; } const selectionRect = isSelectionType(tr.selection, 'cell') ? // Ignored via go/ees005 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion getSelectionRect(tr.selection) : findCellRectClosestToPos(tr.selection.$from); if (!selectionRect) { return tr; } const tablePluginState = getPluginState(state); const tableArray = convertTableNodeToArrayOfRows(table.node); let headerRow; if (tablePluginState.isHeaderRowEnabled) { headerRow = tableArray.shift(); } const compareNodesInOrder = createCompareNodes({ getInlineCardTextFromStore: createGetInlineCardTextFromStore }, order); const sortedTable = tableArray.sort((rowA, rowB) => compareNodesInOrder(rowA[columnIndex], rowB[columnIndex])); if (headerRow) { sortedTable.unshift(headerRow); } const newTableNode = convertArrayOfRowsToTableNode(table.node, sortedTable); tr.replaceWith(table.pos, table.pos + table.node.nodeSize, newTableNode); const pos = TableMap.get(table.node).positionAt(selectionRect.top, columnIndex, table.node); const prev = tablePluginState.ordering; const next = { columnIndex, order }; tr.step(new TableSortStep(table.pos, prev, next)); return tr.setSelection(Selection.near(tr.doc.resolve(table.start + pos))); });