UNPKG

@atlaskit/editor-plugin-layout

Version:

Layout plugin for @atlaskit/editor-core

541 lines (528 loc) 20.8 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, ACTION_SUBJECT_ID, EVENT_TYPE, LAYOUT_TYPE, INPUT_METHOD } from '@atlaskit/editor-common/analytics'; import { withAnalytics } from '@atlaskit/editor-common/editor-analytics'; import { flatmap, getStepRange, isEmptyDocument, mapChildren } from '@atlaskit/editor-common/utils'; import { Fragment, Slice } from '@atlaskit/editor-prosemirror/model'; import { NodeSelection, TextSelection } from '@atlaskit/editor-prosemirror/state'; import { safeInsert } from '@atlaskit/editor-prosemirror/utils'; import { fg } from '@atlaskit/platform-feature-flags'; import { editorExperiment } from '@atlaskit/tmp-editor-statsig/experiments'; import { EVEN_DISTRIBUTED_COL_WIDTHS } from './consts'; import { pluginKey } from './plugin-key'; export var ONE_COL_LAYOUTS = ['single']; export var TWO_COL_LAYOUTS = ['two_equal', 'two_left_sidebar', 'two_right_sidebar']; export var THREE_COL_LAYOUTS = ['three_equal', 'three_with_sidebars']; var getWidthsForPreset = function getWidthsForPreset(presetLayout) { if (editorExperiment('advanced_layouts', true)) { switch (presetLayout) { case 'single': return [100]; case 'two_equal': return [50, 50]; case 'three_equal': return [33.33, 33.33, 33.33]; case 'two_left_sidebar': return [33.33, 66.66]; case 'two_right_sidebar': return [66.66, 33.33]; case 'three_with_sidebars': return [25, 50, 25]; case 'three_left_sidebars': return [25, 25, 50]; case 'three_right_sidebars': return [50, 25, 25]; case 'four_equal': return [25, 25, 25, 25]; case 'five_equal': return [20, 20, 20, 20, 20]; } } switch (presetLayout) { case 'single': return [100]; case 'two_equal': return [50, 50]; case 'three_equal': return [33.33, 33.33, 33.33]; case 'two_left_sidebar': return [33.33, 66.66]; case 'two_right_sidebar': return [66.66, 33.33]; case 'three_with_sidebars': return [25, 50, 25]; } return []; }; var isValidLayoutWidthDistributions = function isValidLayoutWidthDistributions(layoutSection) { var totalWidth = 0; var hasInvalidWidth = false; mapChildren(layoutSection, function (column) { return column.attrs.width; }).forEach(function (width) { if (typeof width === 'number' && isFinite(width) && width > 0 && width <= 100) { totalWidth += width; } else { hasInvalidWidth = true; } }); return !hasInvalidWidth && Math.round(totalWidth) === 100; }; /** * Finds layout preset based on the width attrs of all the layoutColumn nodes * inside the layoutSection node */ export var getPresetLayout = function getPresetLayout(section) { var widths = mapChildren(section, function (column) { return column.attrs.width; }).join(','); if (editorExperiment('advanced_layouts', true)) { switch (widths) { case '100': return 'single'; case '33.33,33.33,33.33': return 'three_equal'; case '25,50,25': return 'three_with_sidebars'; case '50,25,25': return 'three_right_sidebars'; case '25,25,50': return 'three_left_sidebars'; case '50,50': return 'two_equal'; case '33.33,66.66': return 'two_left_sidebar'; case '66.66,33.33': return 'two_right_sidebar'; case '25,25,25,25': return 'four_equal'; case '20,20,20,20,20': return 'five_equal'; } return; } switch (widths) { case '100': return 'single'; case '33.33,33.33,33.33': return 'three_equal'; case '25,50,25': return 'three_with_sidebars'; case '50,50': return 'two_equal'; case '33.33,66.66': return 'two_left_sidebar'; case '66.66,33.33': return 'two_right_sidebar'; } return; }; var isLayoutOutOfSync = function isLayoutOutOfSync(node, presetLayout) { return node.childCount !== getWidthsForPreset(presetLayout).length; }; export var getSelectedLayout = function getSelectedLayout(maybeLayoutSection, current) { if (maybeLayoutSection && isLayoutOutOfSync(maybeLayoutSection, current) && editorExperiment('advanced_layouts', true)) { return getDefaultPresetLayout(maybeLayoutSection); } if (maybeLayoutSection && getPresetLayout(maybeLayoutSection)) { return getPresetLayout(maybeLayoutSection) || current; } return current; }; export var createMultiColumnLayoutSection = function createMultiColumnLayoutSection(state) { var numberOfColumns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; var _state$schema$nodes = state.schema.nodes, layoutSection = _state$schema$nodes.layoutSection, layoutColumn = _state$schema$nodes.layoutColumn; var columns = Fragment.fromArray(Array.from({ length: numberOfColumns }, function () { return layoutColumn.createAndFill({ width: EVEN_DISTRIBUTED_COL_WIDTHS[numberOfColumns] }); })); return layoutSection.createAndFill(undefined, columns); }; export var createDefaultLayoutSection = function createDefaultLayoutSection(state) { var _state$schema$nodes2 = state.schema.nodes, layoutSection = _state$schema$nodes2.layoutSection, layoutColumn = _state$schema$nodes2.layoutColumn; // create a 50-50 layout by default var columns = Fragment.fromArray([layoutColumn.createAndFill({ width: 50 }), layoutColumn.createAndFill({ width: 50 })]); return layoutSection.createAndFill(undefined, columns); }; export var insertLayoutColumns = function insertLayoutColumns(state, dispatch) { if (dispatch) { dispatch(safeInsert(createDefaultLayoutSection(state))(state.tr)); } return true; }; export var insertLayoutColumnsWithAnalytics = function insertLayoutColumnsWithAnalytics(editorAnalyticsAPI) { return function (inputMethod) { return withAnalytics(editorAnalyticsAPI, { action: ACTION.INSERTED, actionSubject: ACTION_SUBJECT.DOCUMENT, actionSubjectId: ACTION_SUBJECT_ID.LAYOUT, attributes: { inputMethod: fg('platform_editor_element_browser_analytic') ? inputMethod : INPUT_METHOD.QUICK_INSERT, columnCount: fg('platform_editor_column_count_analytics') ? 2 : undefined }, eventType: EVENT_TYPE.TRACK })(function (state, dispatch) { if (dispatch) { dispatch(safeInsert(createDefaultLayoutSection(state))(state.tr)); } return true; }); }; }; /** * Add a column to the right of existing layout */ function addColumn(schema, pos) { if (editorExperiment('advanced_layouts', false)) { return function (tr) { tr.replaceWith(tr.mapping.map(pos), tr.mapping.map(pos), schema.nodes.layoutColumn.createAndFill()); }; } return function (tr) { tr.replaceWith(tr.mapping.map(pos), tr.mapping.map(pos), schema.nodes.layoutColumn.createAndFill(undefined)); }; } function removeLastColumnInLayout(column, columnPos, insideRightEdgePos) { return function (tr) { // check if the column only contains a paragraph with a placeholder text // if so, remove the whole column, otherwise just remove the paragraph if (isEmptyDocument(column)) { var fromPos = editorExperiment('single_column_layouts', true) ? columnPos : columnPos - 1; tr.replaceRange(tr.mapping.map(fromPos), tr.mapping.map(insideRightEdgePos), Slice.empty); } else { tr.replaceRange(tr.mapping.map(columnPos - 1), tr.mapping.map(columnPos + 1), Slice.empty); } }; } var fromTwoColsToThree = addColumn; var fromOneColToTwo = addColumn; var fromTwoColsToOne = removeLastColumnInLayout; var fromThreeColsToTwo = removeLastColumnInLayout; var fromOneColToThree = function fromOneColToThree(schema, pos) { return function (tr) { addColumn(schema, pos)(tr); addColumn(schema, pos)(tr); }; }; var fromThreeColstoOne = function fromThreeColstoOne(node, tr, insideRightEdgePos) { var thirdColumn = node.content.child(2); fromThreeColsToTwo(thirdColumn, insideRightEdgePos - thirdColumn.nodeSize, insideRightEdgePos)(tr); var secondColumn = node.content.child(1); fromTwoColsToOne(secondColumn, insideRightEdgePos - thirdColumn.nodeSize - secondColumn.nodeSize, insideRightEdgePos)(tr); }; var increaseColumns = function increaseColumns(schema, pos) { var newColumnsNumber = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; return function (tr) { for (var i = 0; i < newColumnsNumber; i++) { addColumn(schema, pos)(tr); } }; }; var decreaseColumns = function decreaseColumns(node, insideRightEdgePos) { var columnsNumberToRemove = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; return function (tr) { var endPos = insideRightEdgePos; var lastColumn = node.content.lastChild; for (var i = 0; i < columnsNumberToRemove; i++) { var _lastColumn; lastColumn && removeLastColumnInLayout(lastColumn, endPos - lastColumn.nodeSize, endPos)(tr); endPos -= ((_lastColumn = lastColumn) === null || _lastColumn === void 0 ? void 0 : _lastColumn.nodeSize) || 0; lastColumn = node.content.child(node.childCount - i - 2); } }; }; /** * Handles switching from 2 -> 3 cols, or 3 -> 2 cols * Switching from 2 -> 3 just adds a new one at the end * Switching from 3 -> 2 moves all the content of the third col inside the second before * removing it */ function forceColumnStructure(state, node, pos, presetLayout) { var tr = state.tr; var insideRightEdgeOfLayoutSection = pos + node.nodeSize - 1; var numCols = node.childCount; // 3 columns -> 2 columns if (TWO_COL_LAYOUTS.indexOf(presetLayout) >= 0 && numCols === 3) { var thirdColumn = node.content.child(2); var columnPos = insideRightEdgeOfLayoutSection - thirdColumn.nodeSize; fromThreeColsToTwo(thirdColumn, columnPos, insideRightEdgeOfLayoutSection)(tr); // 2 columns -> 3 columns } else if (THREE_COL_LAYOUTS.indexOf(presetLayout) >= 0 && numCols === 2) { fromTwoColsToThree(state.schema, insideRightEdgeOfLayoutSection)(tr); // 2 columns -> 1 column } else if (ONE_COL_LAYOUTS.indexOf(presetLayout) >= 0 && numCols === 2) { var secondColumn = node.content.child(1); var _columnPos = insideRightEdgeOfLayoutSection - secondColumn.nodeSize; fromTwoColsToOne(secondColumn, _columnPos, insideRightEdgeOfLayoutSection)(tr); // 3 columns -> 1 column } else if (ONE_COL_LAYOUTS.indexOf(presetLayout) >= 0 && numCols === 3) { fromThreeColstoOne(node, tr, insideRightEdgeOfLayoutSection); // 1 column -> 2 columns } else if (TWO_COL_LAYOUTS.indexOf(presetLayout) >= 0 && numCols === 1) { fromOneColToTwo(state.schema, insideRightEdgeOfLayoutSection)(tr); // 1 column -> 3 columns } else if (THREE_COL_LAYOUTS.indexOf(presetLayout) >= 0 && numCols === 1) { fromOneColToThree(state.schema, insideRightEdgeOfLayoutSection)(tr); } return tr; } function forceColumnStructureNew(state, node, pos, presetLayout) { var tr = state.tr; var insideRightEdgeOfLayoutSection = pos + node.nodeSize - 1; var numCols = node.childCount; var columnChange = getWidthsForPreset(presetLayout).length - numCols; if (columnChange > 0) { increaseColumns(state.schema, insideRightEdgeOfLayoutSection, columnChange)(tr); } else if (columnChange < 0) { decreaseColumns(node, insideRightEdgeOfLayoutSection, -columnChange)(tr); } return tr; } function columnWidth(node, schema, widths) { var layoutColumn = schema.nodes.layoutColumn; var truncatedWidths = widths.map(function (w) { return Number(w.toFixed(2)); }); return flatmap(node.content, function (column, idx) { if (column.type === layoutColumn) { return layoutColumn.create(_objectSpread(_objectSpread({}, column.attrs), {}, { width: truncatedWidths[idx] }), column.content, column.marks); } else { return column; } }); } function forceColumnWidths(state, tr, pos, presetLayout) { var node = tr.doc.nodeAt(pos); if (!node) { return tr; } return tr.replaceWith(pos + 1, pos + node.nodeSize - 1, columnWidth(node, state.schema, getWidthsForPreset(presetLayout))); } /** * Forces a layout section node to match the given preset layout by adjusting * its column structure and widths, then restoring the original selection. */ export function forceSectionToPresetLayout(state, node, pos, presetLayout) { var forceColumnStructureFn = editorExperiment('advanced_layouts', true) ? forceColumnStructureNew : forceColumnStructure; var tr = forceColumnStructureFn(state, node, pos, presetLayout); // save the selection here, since forcing column widths causes a change over the // entire layoutSection, which remaps selection to the end. not remapping here // is safe because the structure is no longer changing. var selection = tr.selection; tr = forceColumnWidths(state, tr, pos, presetLayout); var selectionPos$ = tr.doc.resolve(selection.$from.pos); return tr.setSelection(state.selection instanceof NodeSelection ? new NodeSelection(selectionPos$) : new TextSelection(selectionPos$)); } export var setPresetLayout = function setPresetLayout(editorAnalyticsAPI) { return function (layout) { return function (state, dispatch) { var _ref = pluginKey.getState(state), pos = _ref.pos, selectedLayout = _ref.selectedLayout; if (pos === null) { return false; } var node = state.doc.nodeAt(pos); if (!node) { return false; } if (selectedLayout === layout && node.childCount > 1) { return false; } var tr = forceSectionToPresetLayout(state, node, pos, layout); if (tr) { editorAnalyticsAPI === null || editorAnalyticsAPI === void 0 || editorAnalyticsAPI.attachAnalyticsEvent({ action: ACTION.CHANGED_LAYOUT, actionSubject: ACTION_SUBJECT.LAYOUT, attributes: { previousLayout: formatLayoutName(selectedLayout), newLayout: formatLayoutName(layout) }, eventType: EVENT_TYPE.TRACK })(tr); tr.setMeta('scrollIntoView', false); if (dispatch) { dispatch(tr); } return true; } return false; }; }; }; function layoutNeedChanges(node) { if (editorExperiment('advanced_layouts', true)) { if (editorExperiment('platform_editor_layout_column_resize_handle', true)) { // Custom widths that sum to 100% are valid and should not be forced back to presets if (isValidLayoutWidthDistributions(node)) { return false; } return true; } return !getPresetLayout(node) || !isValidLayoutWidthDistributions(node); } return !getPresetLayout(node); } var getDefaultPresetLayout = function getDefaultPresetLayout(layoutNode) { var layoutColumnCount = layoutNode.childCount; if (layoutColumnCount <= 1) { return 'single'; } switch (layoutColumnCount) { case 1: return 'single'; case 2: return 'two_equal'; case 3: return 'three_equal'; case 4: return 'four_equal'; case 5: return 'five_equal'; default: return 'five_equal'; } }; function getLayoutChange(node, pos, schema) { if (node.type === schema.nodes.layoutSection) { if (!layoutNeedChanges(node)) { return; } var presetLayout = editorExperiment('advanced_layouts', true) ? getDefaultPresetLayout(node) : node.childCount === 2 ? 'two_equal' : node.childCount === 3 ? 'three_equal' : 'single'; var fixedColumns = columnWidth(node, schema, getWidthsForPreset(presetLayout)); return { from: pos + 1, to: pos + node.nodeSize - 1, slice: new Slice(fixedColumns, 0, 0) }; } } export var fixColumnSizes = function fixColumnSizes(changedTr, state) { var layoutSection = state.schema.nodes.layoutSection; var change; var range = getStepRange(changedTr); if (!range) { return undefined; } changedTr.doc.nodesBetween(range.from, range.to, function (node, pos) { if (node.type !== layoutSection) { return true; // Check all internal nodes expect for layout section } // Node is a section if (layoutNeedChanges(node)) { change = getLayoutChange(node, pos, state.schema); } return false; // We dont go deep, We dont accept nested layouts }); // Hack to prevent: https://product-fabric.atlassian.net/browse/ED-7523 // By default prosemirror try to recreate the node with the default attributes // The default attribute is invalid adf though. when this happen the node after // current position is a layout section var $pos = changedTr.doc.resolve(range.to); if ($pos.depth > 0) { // 'range.to' position could resolve to doc, in this ResolvedPos.after will throws var pos = $pos.after(); var node = changedTr.doc.nodeAt(pos); if (node && node.type === layoutSection && layoutNeedChanges(node)) { change = getLayoutChange(node, pos, state.schema); } } return change; }; export var fixColumnStructure = function fixColumnStructure(state) { var _ref2 = pluginKey.getState(state), pos = _ref2.pos, selectedLayout = _ref2.selectedLayout; if (pos !== null && selectedLayout) { var node = state.doc.nodeAt(pos); if (node) { if (node.childCount !== getWidthsForPreset(selectedLayout).length) { // If the resize handle experiment is on and widths are valid, don't force preset // (column count mismatch might be from a different preset being selected) if (editorExperiment('advanced_layouts', true) && editorExperiment('platform_editor_layout_column_resize_handle', true) && isValidLayoutWidthDistributions(node)) { return; } return forceSectionToPresetLayout(state, node, pos, selectedLayout); } if (!isValidLayoutWidthDistributions(node) && editorExperiment('advanced_layouts', true)) { return forceSectionToPresetLayout(state, node, pos, selectedLayout); } } } return; }; export var deleteActiveLayoutNode = function deleteActiveLayoutNode(editorAnalyticsAPI, inputMethod) { return function (state, dispatch) { var _ref3 = pluginKey.getState(state), pos = _ref3.pos, selectedLayout = _ref3.selectedLayout; if (pos !== null) { var node = state.doc.nodeAt(pos); if (dispatch) { var tr = state.tr.delete(pos, pos + node.nodeSize); editorAnalyticsAPI === null || editorAnalyticsAPI === void 0 || editorAnalyticsAPI.attachAnalyticsEvent({ action: ACTION.DELETED, actionSubject: ACTION_SUBJECT.LAYOUT, attributes: { layout: formatLayoutName(selectedLayout), inputMethod: inputMethod }, eventType: EVENT_TYPE.TRACK })(tr); dispatch(tr); } return true; } return false; }; }; var formatLayoutName = function formatLayoutName(layout) { if (editorExperiment('advanced_layouts', true)) { switch (layout) { case 'single': return LAYOUT_TYPE.SINGLE_COL; case 'two_equal': return LAYOUT_TYPE.TWO_COLS_EQUAL; case 'three_equal': return LAYOUT_TYPE.THREE_COLS_EQUAL; case 'two_left_sidebar': return LAYOUT_TYPE.LEFT_SIDEBAR; case 'two_right_sidebar': return LAYOUT_TYPE.RIGHT_SIDEBAR; case 'three_with_sidebars': return LAYOUT_TYPE.THREE_WITH_SIDEBARS; case 'four_equal': return LAYOUT_TYPE.FOUR_COLS_EQUAL; case 'five_equal': return LAYOUT_TYPE.FIVE_COLS_EQUAL; } } switch (layout) { case 'single': return LAYOUT_TYPE.SINGLE_COL; case 'two_equal': return LAYOUT_TYPE.TWO_COLS_EQUAL; case 'three_equal': return LAYOUT_TYPE.THREE_COLS_EQUAL; case 'two_left_sidebar': return LAYOUT_TYPE.LEFT_SIDEBAR; case 'two_right_sidebar': return LAYOUT_TYPE.RIGHT_SIDEBAR; case 'three_with_sidebars': return LAYOUT_TYPE.THREE_WITH_SIDEBARS; } };