UNPKG

@atlaskit/editor-plugin-table

Version:

Table plugin for the @atlaskit/editor

309 lines (299 loc) 16.7 kB
import _defineProperty from "@babel/runtime/helpers/defineProperty"; function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } import { ACTION, ACTION_SUBJECT, EVENT_TYPE, INPUT_METHOD } from '@atlaskit/editor-common/analytics'; import { browser as browserLegacy, getBrowserInfo } from '@atlaskit/editor-common/browser'; import { insideTable } from '@atlaskit/editor-common/core-utils'; import { SafePlugin } from '@atlaskit/editor-common/safe-plugin'; import { transformSliceToRemoveOpenBodiedExtension, transformSliceToRemoveOpenExpand, transformSliceToRemoveOpenLayoutNodes, transformSliceToRemoveOpenMultiBodiedExtension, transformSliceToRemoveOpenNestedExpand } from '@atlaskit/editor-common/transforms'; import { closestElement } from '@atlaskit/editor-common/utils'; import { findParentDomRefOfType, findParentNodeOfType } from '@atlaskit/editor-prosemirror/utils'; import { TableMap } from '@atlaskit/editor-tables'; import { findTable } from '@atlaskit/editor-tables/utils'; import { fg } from '@atlaskit/platform-feature-flags'; import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals'; import { tableCellView, tableHeaderView, tableRowView, tableView } from '../nodeviews/table-node-views'; import { pluginKey as decorationsPluginKey } from '../pm-plugins/decorations/plugin'; import { TableCssClassName as ClassName } from '../types'; import { handleBlur, handleClick, handleCut, handleFocus, handleMouseDown, handleMouseEnter, handleMouseLeave, handleMouseMove, handleMouseUp, handleTripleClick, whenTableInFocus, withCellTracking } from '../ui/event-handlers'; import { addBoldInEmptyHeaderCells, clearHoverSelection, setTableRef } from './commands'; import { stopKeyboardColumnResizing } from './commands/column-resize'; import { removeResizeHandleDecorations, transformSliceRemoveCellBackgroundColor, transformSliceToFixDarkModeDefaultBackgroundColor, transformSliceToAddTableHeaders, transformSliceToRemoveColumnsWidths } from './commands/misc'; import { defaultHoveredCell, defaultTableSelection } from './default-table-selection'; import { createPluginState, getPluginState } from './plugin-factory'; import { pluginKey } from './plugin-key'; import { fixTables } from './transforms/fix-tables'; import { replaceSelectedTable } from './transforms/replace-table'; import { findControlsHoverDecoration } from './utils/decoration'; import { transformSliceToCorrectEmptyTableCells, transformSliceToFixHardBreakProblemOnCopyFromCell, transformSliceToRemoveOpenTable, transformSliceToRemoveNestedTables, isHeaderRowRequired, transformSliceTableLayoutDefaultToCenter } from './utils/paste'; export var createPlugin = function createPlugin(dispatchAnalyticsEvent, dispatch, portalProviderAPI, nodeViewPortalProviderAPI, eventDispatcher, pluginConfig, getEditorContainerWidth, getEditorFeatureFlags, getIntl, fullWidthModeEnabled, previousFullWidthModeEnabled, dragAndDropEnabled, editorAnalyticsAPI, pluginInjectionApi, isTableScalingEnabled, shouldUseIncreasedScalingPercent, isCommentEditor, isChromelessEditor) { var _accessibilityUtils; var state = createPluginState(dispatch, _objectSpread(_objectSpread(_objectSpread({ pluginConfig: pluginConfig, isTableHovered: false, insertColumnButtonIndex: undefined, insertRowButtonIndex: undefined, isFullWidthModeEnabled: fullWidthModeEnabled, wasFullWidthModeEnabled: previousFullWidthModeEnabled, isHeaderRowEnabled: !!pluginConfig.allowHeaderRow, isHeaderColumnEnabled: false, isDragAndDropEnabled: dragAndDropEnabled, isTableScalingEnabled: isTableScalingEnabled }, defaultHoveredCell), defaultTableSelection), {}, { getIntl: getIntl })); // Used to prevent invalid table cell spans being reported more than once per editor/document var invalidTableIds = []; var editorViewRef = null; var ariaNotifyPlugin = pluginInjectionApi === null || pluginInjectionApi === void 0 || (_accessibilityUtils = pluginInjectionApi.accessibilityUtils) === null || _accessibilityUtils === void 0 ? void 0 : _accessibilityUtils.actions.ariaNotify; var getCurrentEditorState = function getCurrentEditorState() { var editorView = editorViewRef; if (!editorView) { return null; } return editorView.state; }; var getNodeView = function getNodeView() { return { table: tableView({ portalProviderAPI: portalProviderAPI, eventDispatcher: eventDispatcher, getEditorContainerWidth: getEditorContainerWidth, getEditorFeatureFlags: getEditorFeatureFlags, dispatchAnalyticsEvent: dispatchAnalyticsEvent, pluginInjectionApi: pluginInjectionApi, isCommentEditor: isCommentEditor, isChromelessEditor: isChromelessEditor }), tableRow: tableRowView({ eventDispatcher: eventDispatcher, pluginInjectionApi: pluginInjectionApi }), tableCell: tableCellView({ eventDispatcher: eventDispatcher, pluginInjectionApi: pluginInjectionApi }), tableHeader: tableHeaderView({ eventDispatcher: eventDispatcher, pluginInjectionApi: pluginInjectionApi }) }; }; var nodeViews = getNodeView(); return new SafePlugin({ state: state, key: pluginKey, appendTransaction: function appendTransaction(transactions, oldState, newState) { var tr = transactions.find(function (tr) { return tr.getMeta('uiEvent') === 'cut'; }); function reportInvalidTableCellSpanAttrs(invalidNodeAttr) { if (invalidTableIds.find(function (id) { return id === invalidNodeAttr.tableLocalId; })) { return; } invalidTableIds.push(invalidNodeAttr.tableLocalId); dispatchAnalyticsEvent({ action: ACTION.INVALID_DOCUMENT_ENCOUNTERED, actionSubject: ACTION_SUBJECT.EDITOR, eventType: EVENT_TYPE.OPERATIONAL, attributes: { nodeType: invalidNodeAttr.nodeType, reason: "".concat(invalidNodeAttr.attribute, ": ").concat(invalidNodeAttr.reason), tableLocalId: invalidNodeAttr.tableLocalId, spanValue: invalidNodeAttr.spanValue } }); } if (tr) { var _getEditorFeatureFlag = getEditorFeatureFlags(), _getEditorFeatureFlag2 = _getEditorFeatureFlag.tableWithFixedColumnWidthsOption, tableWithFixedColumnWidthsOption = _getEditorFeatureFlag2 === void 0 ? false : _getEditorFeatureFlag2; // "fixTables" removes empty rows as we don't allow that in schema var updatedTr = handleCut(tr, oldState, newState, pluginInjectionApi, editorAnalyticsAPI, editorViewRef || undefined, isTableScalingEnabled, tableWithFixedColumnWidthsOption, shouldUseIncreasedScalingPercent); return fixTables(updatedTr) || updatedTr; } if (transactions.find(function (tr) { return tr.docChanged; })) { return fixTables(newState.tr, reportInvalidTableCellSpanAttrs); } }, view: function view(editorView) { var domAtPos = editorView.domAtPos.bind(editorView); editorViewRef = editorView; return { update: function update(view, prevState) { var state = view.state, dispatch = view.dispatch; var selection = state.selection; var pluginState = getPluginState(state); var tableRef; if (pluginState.editorHasFocus) { var parent = findParentDomRefOfType(state.schema.nodes.table, domAtPos)(selection); if (parent) { tableRef = // Ignored via go/ees005 // eslint-disable-next-line @atlaskit/editor/no-as-casting parent.querySelector('table') || undefined; } var tableNode = findTable(state.selection); // when keyboard cursor leaves the table we need to stop column resizing var pluginPrevState = getPluginState(prevState); var isStopKeyboardColumResizing = pluginPrevState.isResizeHandleWidgetAdded && pluginPrevState.isKeyboardResize; if (isStopKeyboardColumResizing) { var isTableNodesDifferent = (pluginPrevState === null || pluginPrevState === void 0 ? void 0 : pluginPrevState.tableNode) !== (tableNode === null || tableNode === void 0 ? void 0 : tableNode.node); if (pluginPrevState !== null && pluginPrevState !== void 0 && pluginPrevState.tableNode && tableNode && isTableNodesDifferent) { var oldRowsNumber = TableMap.get(pluginPrevState.tableNode).height; var newRowsNumber = TableMap.get(tableNode.node).height; if (oldRowsNumber !== newRowsNumber || // Add/delete row tableNode.node.attrs.localId !== pluginPrevState.tableNode.attrs.localId) { // Jump to another table stopKeyboardColumnResizing({ ariaNotify: ariaNotifyPlugin, getIntl: getIntl })(state, dispatch); } } else if (!tableNode) { // selection outside of table stopKeyboardColumnResizing({ ariaNotify: ariaNotifyPlugin, getIntl: getIntl })(state, dispatch); } } } if (pluginState.tableRef !== tableRef) { setTableRef(tableRef)(state, dispatch); } if (pluginState.editorHasFocus && pluginState.tableRef) { var _ref = state.selection, $cursor = _ref.$cursor; if ($cursor) { // Only update bold when it's a cursor var tableCellHeader = findParentNodeOfType(state.schema.nodes.tableHeader)(state.selection); if (tableCellHeader) { addBoldInEmptyHeaderCells(tableCellHeader)(state, dispatch); } } } else if (pluginState.isResizeHandleWidgetAdded) { removeResizeHandleDecorations()(state, dispatch); } } }; }, props: { transformPasted: function transformPasted(slice) { var editorState = getCurrentEditorState(); if (!editorState) { return slice; } var schema = editorState.schema; // if we're pasting to outside a table or outside a table // header, ensure that we apply any table headers to the first // row of content we see, if required if (!insideTable(editorState) && isHeaderRowRequired(editorState)) { slice = transformSliceToAddTableHeaders(slice, schema); } // This fixes pasting a table with default layout into comment editor // table lose width and expand to full width if (!insideTable(editorState) && isCommentEditor && pluginConfig.allowTableAlignment && isTableScalingEnabled) { slice = transformSliceTableLayoutDefaultToCenter(slice, schema); } slice = transformSliceToFixHardBreakProblemOnCopyFromCell(slice, schema); // We do this separately, so it also applies to drag/drop events // This needs to go before `transformSliceToRemoveOpenExpand` slice = transformSliceToRemoveOpenLayoutNodes(slice, schema); // If a partial paste of expand, paste only the content // This needs to go before `transformSliceToRemoveOpenTable` slice = transformSliceToRemoveOpenExpand(slice, schema); // transformSliceToRemoveOpenTable() transforms based on the depth of the root node, assuming that the tables will be at the root // Bodied extensions will contribute to the depth of the table selection so we need to remove them first /** If a partial paste of bodied extension, paste only text */ slice = transformSliceToRemoveOpenBodiedExtension(slice, schema); /** If a partial paste of table, paste only table's content */ slice = transformSliceToRemoveOpenTable(slice, schema); /** If a partial paste of multi bodied extension, paste only children */ slice = transformSliceToRemoveOpenMultiBodiedExtension(slice, schema); slice = transformSliceToCorrectEmptyTableCells(slice, schema); if (!pluginConfig.allowColumnResizing) { slice = transformSliceToRemoveColumnsWidths(slice, schema); } // If we don't allow background on cells, we need to remove it // from the paste slice if (!pluginConfig.allowBackgroundColor) { slice = transformSliceRemoveCellBackgroundColor(slice, schema); } else { slice = transformSliceToFixDarkModeDefaultBackgroundColor(slice, schema); } slice = transformSliceToRemoveOpenNestedExpand(slice, schema); if (fg('platform_editor_use_nested_table_pm_nodes')) { slice = transformSliceToRemoveNestedTables(slice, schema, editorState.selection); } return slice; }, handleClick: function handleClick(_ref2, _pos, event) { var state = _ref2.state, dispatch = _ref2.dispatch; var decorationSet = decorationsPluginKey.getState(state); var browser = expValEquals('platform_editor_hydratable_ui', 'isEnabled', true) ? getBrowserInfo() : browserLegacy; if (findControlsHoverDecoration(decorationSet).length) { clearHoverSelection()(state, dispatch); } // ED-6069: workaround for Chrome given a regression introduced in prosemirror-view@1.6.8 // Returning true prevents that updateSelection() is getting called in the commit below: // @see https://github.com/ProseMirror/prosemirror-view/commit/33fe4a8b01584f6b4103c279033dcd33e8047b95 if (browser.chrome && event.target) { // Ignored via go/ees005 // eslint-disable-next-line @atlaskit/editor/no-as-casting var targetClassList = event.target.classList; if (targetClassList.contains(ClassName.CONTROLS_BUTTON) || targetClassList.contains(ClassName.CONTEXTUAL_MENU_BUTTON) || targetClassList.contains(ClassName.DRAG_HANDLE_BUTTON_CLICKABLE_ZONE) || targetClassList.contains(ClassName.DRAG_HANDLE_BUTTON_CONTAINER)) { return true; } } return false; }, handleScrollToSelection: function handleScrollToSelection(view) { // when typing into a sticky header cell, we don't want to scroll // back to the top of the table if the user has already scrolled down var tableHeader = view.state.schema.nodes.tableHeader; var domRef = findParentDomRefOfType(tableHeader, view.domAtPos.bind(view))(view.state.selection); var maybeTr = closestElement(domRef, 'tr'); return maybeTr ? maybeTr.classList.contains('sticky') : false; }, handleTextInput: function handleTextInput(view, _from, _to, text) { var state = view.state, dispatch = view.dispatch; var _getPluginState = getPluginState(state), isKeyboardResize = _getPluginState.isKeyboardResize; if (isKeyboardResize) { stopKeyboardColumnResizing({ ariaNotify: ariaNotifyPlugin, getIntl: getIntl })(state, dispatch); return false; } var tr = replaceSelectedTable(state, text, INPUT_METHOD.KEYBOARD, editorAnalyticsAPI); if (tr.selectionSet) { dispatch(tr); return true; } return false; }, nodeViews: nodeViews, handleDOMEvents: { focus: handleFocus, blur: handleBlur, mousedown: withCellTracking(handleMouseDown), mouseleave: handleMouseLeave, mousemove: whenTableInFocus(handleMouseMove(nodeViewPortalProviderAPI), pluginInjectionApi), mouseenter: handleMouseEnter, mouseup: whenTableInFocus(handleMouseUp), click: withCellTracking(whenTableInFocus(handleClick)) }, handleTripleClick: handleTripleClick } }); };