UNPKG

@atlaskit/editor-plugin-table

Version:

Table plugin for the @atlaskit/editor

73 lines 2.95 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'; var createGetInlineCardTextFromStore = function createGetInlineCardTextFromStore(attrs) { var _ref = attrs, data = _ref.data; // 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; } var _ref2 = attrs, cardUrl = _ref2.url; return cardUrl; }; export var sortByColumn = function sortByColumn(columnIndex) { var order = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : SortOrder.DESC; return createCommand(function () { return { type: 'SORT_TABLE', data: { ordering: { columnIndex: columnIndex, order: order } } }; }, function (tr, state) { // Ignored via go/ees005 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion var table = findTable(tr.selection); if (!table || !table.node) { return tr; } var 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; } var tablePluginState = getPluginState(state); var tableArray = convertTableNodeToArrayOfRows(table.node); var headerRow; if (tablePluginState.isHeaderRowEnabled) { headerRow = tableArray.shift(); } var compareNodesInOrder = createCompareNodes({ getInlineCardTextFromStore: createGetInlineCardTextFromStore }, order); var sortedTable = tableArray.sort(function (rowA, rowB) { return compareNodesInOrder(rowA[columnIndex], rowB[columnIndex]); }); if (headerRow) { sortedTable.unshift(headerRow); } var newTableNode = convertArrayOfRowsToTableNode(table.node, sortedTable); tr.replaceWith(table.pos, table.pos + table.node.nodeSize, newTableNode); var pos = TableMap.get(table.node).positionAt(selectionRect.top, columnIndex, table.node); var prev = tablePluginState.ordering; var next = { columnIndex: columnIndex, order: order }; tr.step(new TableSortStep(table.pos, prev, next)); return tr.setSelection(Selection.near(tr.doc.resolve(table.start + pos))); }); };