UNPKG

@atlaskit/editor-plugin-layout

Version:

Layout plugin for @atlaskit/editor-core

406 lines (400 loc) 21 kB
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray"; 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 { SafePlugin } from '@atlaskit/editor-common/safe-plugin'; import { createSelectionClickHandler, GapCursorSelection, Side } from '@atlaskit/editor-common/selection'; import { filterCommand as filter } from '@atlaskit/editor-common/utils'; import { keydownHandler } from '@atlaskit/editor-prosemirror/keymap'; import { Fragment } from '@atlaskit/editor-prosemirror/model'; import { NodeSelection, Selection, TextSelection } from '@atlaskit/editor-prosemirror/state'; import { findParentNodeClosestToPos, findParentNodeOfType } from '@atlaskit/editor-prosemirror/utils'; import { Decoration, DecorationSet } from '@atlaskit/editor-prosemirror/view'; import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals'; import { editorExperiment } from '@atlaskit/tmp-editor-statsig/experiments'; import { fixColumnSizes, fixColumnStructure, getSelectedLayout, LAYOUT_COLUMN_INSERT_META } from './actions'; import { getColumnDividerDecorations } from './column-resize-divider'; import { EVEN_DISTRIBUTED_COL_WIDTHS } from './consts'; import { pluginKey } from './plugin-key'; import { pluginKey as layoutResizingPluginKey } from './resizing'; import { getGapCursorTargetForBlankSpaceClick, getMaybeLayoutSection, isParagraphBlankSpaceTarget } from './utils'; import { getSelectedLayoutColumnsFromSelection } from './utils/layout-column-selection'; export var DEFAULT_LAYOUT = 'two_equal'; /** * Shared blank-space gap cursor placement, used by both `handleClick` and `handleClickOn` * (the latter catches clicks on atomic node views that stop propagation before `handleClick`). * Returns `true` when it placed a selection and consumed the click, else `false`. */ var applyBlankSpaceGapCursor = function applyBlankSpaceGapCursor(view, event) { if (!expValEquals('platform_editor_layout_column_menu', 'isEnabled', true) || !editorExperiment('advanced_layouts', true)) { return false; } var gapTarget = getGapCursorTargetForBlankSpaceClick(view, event); if (gapTarget === undefined) { return false; } var $pos = view.state.doc.resolve(gapTarget.pos); // A paragraph child takes a TextSelection (caret at the edge) rather than a gap cursor. var isParagraphTarget = isParagraphBlankSpaceTarget(view, gapTarget); var nextSelection = isParagraphTarget ? TextSelection.near($pos, gapTarget.side === 'left' ? 1 : -1) : new GapCursorSelection($pos, gapTarget.side === 'left' ? Side.LEFT : Side.RIGHT); // Idempotency guard: `mousedown` already placed this selection, but the browser still // fires `mouseup`, so `handleClick`/`handleClickOn` re-run for the same click. Consume it // without re-dispatching (which would add a redundant undo entry). if (view.state.selection.eq(nextSelection)) { return true; } view.dispatch(view.state.tr.setSelection(nextSelection).scrollIntoView()); return true; }; var isWholeSelectionInsideLayoutColumn = function isWholeSelectionInsideLayoutColumn(state) { // Since findParentNodeOfType doesn't check if selection.to shares the parent, we do this check ourselves var fromParent = findParentNodeOfType(state.schema.nodes.layoutColumn)(state.selection); if (fromParent) { var isToPosInsideSameLayoutColumn = state.selection.from < fromParent.pos + fromParent.node.nodeSize; return isToPosInsideSameLayoutColumn; } return false; }; var moveCursorToNextColumn = function moveCursorToNextColumn(state, dispatch) { var selection = state.selection; var _state$schema$nodes = state.schema.nodes, layoutColumn = _state$schema$nodes.layoutColumn, layoutSection = _state$schema$nodes.layoutSection; // Ignored via go/ees005 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion var section = findParentNodeOfType(layoutSection)(selection); // Ignored via go/ees005 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion var column = findParentNodeOfType(layoutColumn)(selection); if (column.node !== section.node.lastChild) { var $nextColumn = state.doc.resolve(column.pos + column.node.nodeSize); var shiftedSelection = TextSelection.findFrom($nextColumn, 1); if (dispatch) { dispatch(state.tr.setSelection(shiftedSelection)); } } return true; }; var getNodeDecoration = function getNodeDecoration(pos, node) { return [Decoration.node(pos, pos + node.nodeSize, { class: 'selected' })]; }; var getDangerPreviewDecorations = function getDangerPreviewDecorations(state, positions) { var _positions$flatMap; return (_positions$flatMap = positions === null || positions === void 0 ? void 0 : positions.flatMap(function (pos) { var node = state.doc.nodeAt(pos); if (!node) { return []; } return [Decoration.node(pos, pos + node.nodeSize, { class: 'layout-column-danger-preview' })]; })) !== null && _positions$flatMap !== void 0 ? _positions$flatMap : []; }; var getInitialPluginState = function getInitialPluginState(options, state) { var maybeLayoutSection = getMaybeLayoutSection(state); var allowBreakout = options.allowBreakout || false; var addSidebarLayouts = options.UNSAFE_addSidebarLayouts || false; var allowSingleColumnLayout = options.UNSAFE_allowSingleColumnLayout || false; var pos = maybeLayoutSection ? maybeLayoutSection.pos : null; var selectedLayout = getSelectedLayout(maybeLayoutSection && maybeLayoutSection.node, DEFAULT_LAYOUT); return { pos: pos, allowBreakout: allowBreakout, addSidebarLayouts: addSidebarLayouts, selectedLayout: selectedLayout, allowSingleColumnLayout: allowSingleColumnLayout, isResizing: false, isLayoutColumnMenuOpen: false, layoutColumnMenuOpenedViaKeyboard: false, layoutColumnMenuAnchorPos: undefined, dangerPreviewLayoutColumnPositions: undefined }; }; var fireLayoutColumnMenuOpenedAnalytics = function fireLayoutColumnMenuOpenedAnalytics(editorAnalyticsAPI, state, openedViaKeyboard) { var selectedLayoutColumnsResult = getSelectedLayoutColumnsFromSelection(state.selection); if (!selectedLayoutColumnsResult) { return; } var layoutSectionNode = selectedLayoutColumnsResult.layoutSectionNode, selectedLayoutColumns = selectedLayoutColumnsResult.selectedLayoutColumns, startIndex = selectedLayoutColumnsResult.startIndex, endIndex = selectedLayoutColumnsResult.endIndex; editorAnalyticsAPI === null || editorAnalyticsAPI === void 0 || editorAnalyticsAPI.fireAnalyticsEvent({ action: ACTION.OPENED, actionSubject: ACTION_SUBJECT.LAYOUT_COLUMN_MENU, attributes: { columnCount: layoutSectionNode.childCount, endIndex: endIndex, inputMethod: openedViaKeyboard ? INPUT_METHOD.KEYBOARD : INPUT_METHOD.MOUSE, selectedCount: selectedLayoutColumns.length, startIndex: startIndex }, eventType: EVENT_TYPE.UI }); }; var reduceLayoutColumnMenuState = function reduceLayoutColumnMenuState(pluginState, action) { switch (action.type) { case 'toggleLayoutColumnMenu': { var _action$meta = action.meta, anchorPos = _action$meta.anchorPos, isOpen = _action$meta.isOpen, openedViaKeyboard = _action$meta.openedViaKeyboard; // `isOpen` provided: use directly (legacy). Omitted: toggle off only when re-clicking // the already-open column; otherwise open for the clicked column. var isSameColumnAsOpenMenu = pluginState.isLayoutColumnMenuOpen && anchorPos !== undefined && anchorPos === pluginState.layoutColumnMenuAnchorPos; var nextIsOpen = isOpen !== null && isOpen !== void 0 ? isOpen : !isSameColumnAsOpenMenu; return _objectSpread(_objectSpread({}, pluginState), {}, { isLayoutColumnMenuOpen: nextIsOpen, layoutColumnMenuOpenedViaKeyboard: nextIsOpen ? openedViaKeyboard !== null && openedViaKeyboard !== void 0 ? openedViaKeyboard : false : false, layoutColumnMenuAnchorPos: nextIsOpen ? anchorPos : undefined, dangerPreviewLayoutColumnPositions: nextIsOpen ? pluginState.dangerPreviewLayoutColumnPositions : undefined }); } case 'setDangerPreview': return _objectSpread(_objectSpread({}, pluginState), {}, { dangerPreviewLayoutColumnPositions: action.positions }); case 'clearDangerPreview': return _objectSpread(_objectSpread({}, pluginState), {}, { dangerPreviewLayoutColumnPositions: undefined }); case 'setResizeState': return _objectSpread(_objectSpread({}, pluginState), {}, { isResizing: action.isResizing }); case 'syncSelectionState': { var maybeLayoutSection = getMaybeLayoutSection(action.state); return _objectSpread(_objectSpread({}, pluginState), {}, { pos: maybeLayoutSection ? maybeLayoutSection.pos : null, selectedLayout: getSelectedLayout(maybeLayoutSection && maybeLayoutSection.node, // Ignored via go/ees005 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion pluginState.selectedLayout) }); } } }; // To prevent a single-column layout, // if a user attempts to delete a layout column and // we will force remove the content instead. // There are some edge cases where user can delete a layout column // see packages/editor/editor-plugin-layout-tests/src/__tests__/unit/delete.ts var handleDeleteLayoutColumn = function handleDeleteLayoutColumn(state, dispatch) { var sel = state.selection; if (sel instanceof NodeSelection && sel.node.type.name === 'layoutColumn' && sel.$from.parent.type.name === 'layoutSection' && sel.$from.parent.childCount === 2 && dispatch && editorExperiment('advanced_layouts', true) && !editorExperiment('single_column_layouts', true)) { var _sel$$from$parent$las, _sel$$from$parent$fir; var tr = state.tr; var layoutContentFragment = sel.$from.parentOffset === 0 ? Fragment.from((_sel$$from$parent$las = sel.$from.parent.lastChild) === null || _sel$$from$parent$las === void 0 ? void 0 : _sel$$from$parent$las.content) : Fragment.from((_sel$$from$parent$fir = sel.$from.parent.firstChild) === null || _sel$$from$parent$fir === void 0 ? void 0 : _sel$$from$parent$fir.content); var parent = findParentNodeClosestToPos(sel.$from, function (node) { return node.type.name === 'layoutSection'; }); if (parent) { var layoutSectionPos = tr.mapping.map(parent.pos); var layoutSectionNodeSize = parent.node.nodeSize; dispatch(state.tr.replaceWith(layoutSectionPos, layoutSectionPos + layoutSectionNodeSize, layoutContentFragment)); return true; } return false; } return false; }; export default (function (options, editorAnalyticsAPI) { // Store a reference to the EditorView so widget decorations can dispatch transactions var editorViewRef; return new SafePlugin({ key: pluginKey, view: function view(_view) { editorViewRef = _view; return { update: function update(updatedView) { editorViewRef = updatedView; }, destroy: function destroy() { editorViewRef = undefined; } }; }, state: { init: function init(_, state) { return getInitialPluginState(options, state); }, apply: function apply(tr, pluginState, oldState, newState) { var _tr$getMeta, _pluginKey$getState; var nextPluginState = pluginState; var columnMenuMeta = tr.getMeta('toggleLayoutColumnMenu'); var dangerPreviewMeta = tr.getMeta('layoutColumnDangerPreview'); if (columnMenuMeta) { var wasLayoutColumnMenuOpen = nextPluginState.isLayoutColumnMenuOpen; nextPluginState = reduceLayoutColumnMenuState(nextPluginState, { meta: columnMenuMeta, type: 'toggleLayoutColumnMenu' }); if (!wasLayoutColumnMenuOpen && nextPluginState.isLayoutColumnMenuOpen) { fireLayoutColumnMenuOpenedAnalytics(editorAnalyticsAPI, newState, columnMenuMeta.openedViaKeyboard); } } if (tr.getMeta('layoutColumnDangerPreview') !== undefined) { nextPluginState = reduceLayoutColumnMenuState(nextPluginState, { positions: dangerPreviewMeta !== null && dangerPreviewMeta !== void 0 ? dangerPreviewMeta : undefined, type: 'setDangerPreview' }); } if (tr.docChanged) { nextPluginState = reduceLayoutColumnMenuState(nextPluginState, { type: 'clearDangerPreview' }); } var isResizing = editorExperiment('single_column_layouts', true) ? (_tr$getMeta = tr.getMeta('is-resizer-resizing')) !== null && _tr$getMeta !== void 0 ? _tr$getMeta : (_pluginKey$getState = pluginKey.getState(oldState)) === null || _pluginKey$getState === void 0 ? void 0 : _pluginKey$getState.isResizing : false; nextPluginState = reduceLayoutColumnMenuState(nextPluginState, { isResizing: isResizing, type: 'setResizeState' }); if (tr.docChanged || tr.selectionSet) { return reduceLayoutColumnMenuState(nextPluginState, { state: newState, type: 'syncSelectionState' }); } return nextPluginState; } }, props: { decorations: function decorations(state) { var layoutState = pluginKey.getState(state); var isLayoutResizingPluginAvailable = layoutResizingPluginKey.get(state) !== undefined; if (editorExperiment('advanced_layouts', true) && editorExperiment('platform_editor_layout_column_resize_handle', true) && isLayoutResizingPluginAvailable) { var dividerDecorations = getColumnDividerDecorations(state, editorViewRef, editorAnalyticsAPI); var selectedDecorations = layoutState.pos !== null ? getNodeDecoration(layoutState.pos, state.doc.nodeAt(layoutState.pos)) : []; var _dangerPreviewDecorations = getDangerPreviewDecorations(state, layoutState.dangerPreviewLayoutColumnPositions); var allDecorations = [].concat(_toConsumableArray(selectedDecorations), _toConsumableArray(dividerDecorations), _toConsumableArray(_dangerPreviewDecorations)); if (allDecorations.length > 0) { return DecorationSet.create(state.doc, allDecorations); } return undefined; } var dangerPreviewDecorations = getDangerPreviewDecorations(state, layoutState.dangerPreviewLayoutColumnPositions); if (layoutState.pos !== null || dangerPreviewDecorations.length > 0) { var _selectedDecorations = layoutState.pos !== null ? getNodeDecoration(layoutState.pos, state.doc.nodeAt(layoutState.pos)) : []; return DecorationSet.create(state.doc, [].concat(_toConsumableArray(_selectedDecorations), _toConsumableArray(dangerPreviewDecorations))); } return undefined; }, handleKeyDown: keydownHandler({ Tab: filter(isWholeSelectionInsideLayoutColumn, moveCursorToNextColumn), 'Mod-Backspace': handleDeleteLayoutColumn, 'Mod-Delete': handleDeleteLayoutColumn, Backspace: handleDeleteLayoutColumn, Delete: handleDeleteLayoutColumn }), handleDOMEvents: { // Place the gap cursor on `mousedown` (not `mouseup`) so the caret never flashes // inside a nested editable child first. mousedown: function mousedown(view, event) { var target = event.target; if (target !== null && target !== void 0 && target.hasAttribute('data-layout-section')) { return false; } if (applyBlankSpaceGapCursor(view, event)) { event.preventDefault(); // `preventDefault()` blocks the editor focus that makes the gap cursor blink, // so restore it here. The `handleClick`/`handleClickOn` paths don't need this. if (!view.hasFocus()) { view.focus(); } return true; } return false; } }, handleClickOn: function () { var selectionClickHandler = createSelectionClickHandler(['layoutColumn'], function (target) { return target.hasAttribute('data-layout-section') || target.hasAttribute('data-layout-column'); }, { useLongPressSelection: options.useLongPressSelection || false, getNodeSelectionPos: function getNodeSelectionPos(state, nodePos) { return state.doc.resolve(nodePos).before(); } }); return function (view, pos, node, nodePos, event, direct) { // Fallback for clicks on an atomic node view that the mousedown hook missed. var target = event.target; if (!(target !== null && target !== void 0 && target.hasAttribute('data-layout-section')) && applyBlankSpaceGapCursor(view, event)) { return true; } return selectionClickHandler(view, pos, node, nodePos, event, direct); }; }(), handleClick: function handleClick(view, _pos, event) { // Fallback for clicks the mousedown interceptor missed. var target = event.target; if (target !== null && target !== void 0 && target.hasAttribute('data-layout-section')) { return false; } return applyBlankSpaceGapCursor(view, event); } }, appendTransaction: function appendTransaction(transactions, _oldState, newState) { var changes = []; transactions.forEach(function (prevTr) { // remap change segments across the transaction set changes.forEach(function (change) { return { from: prevTr.mapping.map(change.from), to: prevTr.mapping.map(change.to), slice: change.slice }; }); // don't consider transactions that don't mutate if (!prevTr.docChanged) { return; } // Skip fixing column sizes for column resize drag transactions if (editorExperiment('platform_editor_layout_column_resize_handle', true) && prevTr.getMeta('layoutColumnResize')) { return; } // Layout column insert actions already recalculate column widths and need their own // selection mapping; avoid a follow-up normalisation transaction that can remap it. if (prevTr.getMeta(LAYOUT_COLUMN_INSERT_META)) { return; } var change = fixColumnSizes(prevTr, newState); if (change) { changes.push(change); } }); if (editorExperiment('advanced_layouts', true) && changes.length === 1) { var _change$slice$content, _change$slice$content2; var change = changes[0]; // When editorExperiment('single_column_layouts', true) is on // delete can create a single column layout // otherwise we replace the single column layout with its content if (!editorExperiment('single_column_layouts', true) && change.slice.content.childCount === 1 && ((_change$slice$content = change.slice.content.firstChild) === null || _change$slice$content === void 0 ? void 0 : _change$slice$content.type.name) === 'layoutColumn' && ((_change$slice$content2 = change.slice.content.firstChild) === null || _change$slice$content2 === void 0 ? void 0 : _change$slice$content2.attrs.width) === EVEN_DISTRIBUTED_COL_WIDTHS[1]) { var tr = newState.tr; var content = change.slice.content.firstChild.content; tr.replaceWith(change.from - 1, change.to, content); return tr; } } if (changes.length) { var _tr = newState.tr; var selection = newState.selection.toJSON(); changes.forEach(function (change) { _tr.replaceRange(change.from, change.to, change.slice); }); // selecting and deleting across columns in 3 col layouts can remove // a layoutColumn so we fix the structure here _tr = fixColumnStructure(newState) || _tr; if (_tr.docChanged) { _tr.setSelection(Selection.fromJSON(_tr.doc, selection)); return _tr; } } return; } }); });