@atlaskit/editor-plugin-layout
Version:
Layout plugin for @atlaskit/editor-core
1,013 lines (985 loc) • 45.2 kB
JavaScript
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fixColumnStructure = exports.fixColumnSizes = exports.distributeLayoutColumns = exports.deleteLayoutColumn = exports.deleteActiveLayoutNode = exports.createMultiColumnLayoutSection = exports.createDefaultLayoutSection = exports.TWO_COL_LAYOUTS = exports.THREE_COL_LAYOUTS = exports.ONE_COL_LAYOUTS = exports.LAYOUT_COLUMN_INSERT_META = void 0;
exports.forceSectionToPresetLayout = forceSectionToPresetLayout;
exports.getEffectiveMaxLayoutColumns = getEffectiveMaxLayoutColumns;
exports.toggleLayoutColumnMenu = exports.setPresetLayout = exports.setLayoutColumnValign = exports.setLayoutColumnDangerPreview = exports.insertLayoutColumnsWithAnalytics = exports.insertLayoutColumns = exports.insertLayoutColumn = exports.getSelectedLayout = exports.getPresetLayout = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _analytics = require("@atlaskit/editor-common/analytics");
var _editorAnalytics = require("@atlaskit/editor-common/editor-analytics");
var _utils = require("@atlaskit/editor-common/utils");
var _model = require("@atlaskit/editor-prosemirror/model");
var _state = require("@atlaskit/editor-prosemirror/state");
var _transform = require("@atlaskit/editor-prosemirror/transform");
var _utils2 = require("@atlaskit/editor-prosemirror/utils");
var _platformFeatureFlags = require("@atlaskit/platform-feature-flags");
var _expValEquals = require("@atlaskit/tmp-editor-statsig/exp-val-equals");
var _experiments = require("@atlaskit/tmp-editor-statsig/experiments");
var _consts = require("./consts");
var _pluginKey = require("./plugin-key");
var _layoutColumnDistribution = require("./utils/layout-column-distribution");
var _layoutColumnSelection = require("./utils/layout-column-selection");
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) { (0, _defineProperty2.default)(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; }
var ONE_COL_LAYOUTS = exports.ONE_COL_LAYOUTS = ['single'];
var TWO_COL_LAYOUTS = exports.TWO_COL_LAYOUTS = ['two_equal', 'two_left_sidebar', 'two_right_sidebar'];
var THREE_COL_LAYOUTS = exports.THREE_COL_LAYOUTS = ['three_equal', 'three_with_sidebars'];
var getWidthsForPreset = function getWidthsForPreset(presetLayout) {
if ((0, _experiments.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;
(0, _utils.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
*/
var getPresetLayout = exports.getPresetLayout = function getPresetLayout(section) {
var widths = (0, _utils.mapChildren)(section, function (column) {
return column.attrs.width;
}).join(',');
if ((0, _experiments.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;
};
var getSelectedLayout = exports.getSelectedLayout = function getSelectedLayout(maybeLayoutSection, current) {
if (maybeLayoutSection && isLayoutOutOfSync(maybeLayoutSection, current) && (0, _experiments.editorExperiment)('advanced_layouts', true)) {
return getDefaultPresetLayout(maybeLayoutSection);
}
if (maybeLayoutSection && getPresetLayout(maybeLayoutSection)) {
return getPresetLayout(maybeLayoutSection) || current;
}
return current;
};
var createMultiColumnLayoutSection = exports.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 = _model.Fragment.fromArray(Array.from({
length: numberOfColumns
}, function () {
return layoutColumn.createAndFill({
width: _consts.EVEN_DISTRIBUTED_COL_WIDTHS[numberOfColumns]
});
}));
return layoutSection.createAndFill(undefined, columns);
};
var createDefaultLayoutSection = exports.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 = _model.Fragment.fromArray([layoutColumn.createAndFill({
width: 50
}), layoutColumn.createAndFill({
width: 50
})]);
return layoutSection.createAndFill(undefined, columns);
};
var insertLayoutColumns = exports.insertLayoutColumns = function insertLayoutColumns(state, dispatch) {
if (dispatch) {
dispatch((0, _utils2.safeInsert)(createDefaultLayoutSection(state))(state.tr));
}
return true;
};
var insertLayoutColumnsWithAnalytics = exports.insertLayoutColumnsWithAnalytics = function insertLayoutColumnsWithAnalytics(editorAnalyticsAPI) {
return function (inputMethod) {
return (0, _editorAnalytics.withAnalytics)(editorAnalyticsAPI, {
action: _analytics.ACTION.INSERTED,
actionSubject: _analytics.ACTION_SUBJECT.DOCUMENT,
actionSubjectId: _analytics.ACTION_SUBJECT_ID.LAYOUT,
attributes: {
inputMethod: (0, _platformFeatureFlags.fg)('platform_editor_element_browser_analytic') ? inputMethod : _analytics.INPUT_METHOD.QUICK_INSERT,
columnCount: (0, _platformFeatureFlags.fg)('platform_editor_column_count_analytics') ? 2 : undefined
},
eventType: _analytics.EVENT_TYPE.TRACK
})(function (state, dispatch) {
if (dispatch) {
dispatch((0, _utils2.safeInsert)(createDefaultLayoutSection(state))(state.tr));
}
return true;
});
};
};
/**
* Add a column to the right of existing layout
*/
function addColumn(schema, pos) {
if ((0, _experiments.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 ((0, _utils.isEmptyDocument)(column)) {
var fromPos = (0, _experiments.editorExperiment)('single_column_layouts', true) ? columnPos : columnPos - 1;
tr.replaceRange(tr.mapping.map(fromPos), tr.mapping.map(insideRightEdgePos), _model.Slice.empty);
} else {
tr.replaceRange(tr.mapping.map(columnPos - 1), tr.mapping.map(columnPos + 1), _model.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 (0, _utils.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.
*/
function forceSectionToPresetLayout(state, node, pos, presetLayout) {
var forceColumnStructureFn = (0, _experiments.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 _state.NodeSelection ? new _state.NodeSelection(selectionPos$) : new _state.TextSelection(selectionPos$));
}
var setPresetLayout = exports.setPresetLayout = function setPresetLayout(editorAnalyticsAPI) {
return function (layout) {
return function (state, dispatch) {
var _ref = _pluginKey.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: _analytics.ACTION.CHANGED_LAYOUT,
actionSubject: _analytics.ACTION_SUBJECT.LAYOUT,
attributes: {
previousLayout: formatLayoutName(selectedLayout),
newLayout: formatLayoutName(layout)
},
eventType: _analytics.EVENT_TYPE.TRACK
})(tr);
tr.setMeta('scrollIntoView', false);
if (dispatch) {
dispatch(tr);
}
return true;
}
return false;
};
};
};
function layoutNeedChanges(node) {
if ((0, _experiments.editorExperiment)('advanced_layouts', true)) {
if ((0, _experiments.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 = (0, _experiments.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 _model.Slice(fixedColumns, 0, 0)
};
}
}
var fixColumnSizes = exports.fixColumnSizes = function fixColumnSizes(changedTr, state) {
var layoutSection = state.schema.nodes.layoutSection;
var change;
var range = (0, _utils.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;
};
var fixColumnStructure = exports.fixColumnStructure = function fixColumnStructure(state) {
var _ref2 = _pluginKey.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 ((0, _experiments.editorExperiment)('advanced_layouts', true) && (0, _experiments.editorExperiment)('platform_editor_layout_column_resize_handle', true) && isValidLayoutWidthDistributions(node)) {
return;
}
return forceSectionToPresetLayout(state, node, pos, selectedLayout);
}
if (!isValidLayoutWidthDistributions(node) && (0, _experiments.editorExperiment)('advanced_layouts', true)) {
return forceSectionToPresetLayout(state, node, pos, selectedLayout);
}
}
}
return;
};
var deleteActiveLayoutNode = exports.deleteActiveLayoutNode = function deleteActiveLayoutNode(editorAnalyticsAPI, inputMethod) {
return function (state, dispatch) {
var _ref3 = _pluginKey.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: _analytics.ACTION.DELETED,
actionSubject: _analytics.ACTION_SUBJECT.LAYOUT,
attributes: {
layout: formatLayoutName(selectedLayout),
inputMethod: inputMethod
},
eventType: _analytics.EVENT_TYPE.TRACK
})(tr);
dispatch(tr);
}
return true;
}
return false;
};
};
var formatLayoutName = function formatLayoutName(layout) {
if ((0, _experiments.editorExperiment)('advanced_layouts', true)) {
switch (layout) {
case 'single':
return _analytics.LAYOUT_TYPE.SINGLE_COL;
case 'two_equal':
return _analytics.LAYOUT_TYPE.TWO_COLS_EQUAL;
case 'three_equal':
return _analytics.LAYOUT_TYPE.THREE_COLS_EQUAL;
case 'two_left_sidebar':
return _analytics.LAYOUT_TYPE.LEFT_SIDEBAR;
case 'two_right_sidebar':
return _analytics.LAYOUT_TYPE.RIGHT_SIDEBAR;
case 'three_with_sidebars':
return _analytics.LAYOUT_TYPE.THREE_WITH_SIDEBARS;
case 'four_equal':
return _analytics.LAYOUT_TYPE.FOUR_COLS_EQUAL;
case 'five_equal':
return _analytics.LAYOUT_TYPE.FIVE_COLS_EQUAL;
}
}
switch (layout) {
case 'single':
return _analytics.LAYOUT_TYPE.SINGLE_COL;
case 'two_equal':
return _analytics.LAYOUT_TYPE.TWO_COLS_EQUAL;
case 'three_equal':
return _analytics.LAYOUT_TYPE.THREE_COLS_EQUAL;
case 'two_left_sidebar':
return _analytics.LAYOUT_TYPE.LEFT_SIDEBAR;
case 'two_right_sidebar':
return _analytics.LAYOUT_TYPE.RIGHT_SIDEBAR;
case 'three_with_sidebars':
return _analytics.LAYOUT_TYPE.THREE_WITH_SIDEBARS;
}
};
var LAYOUT_COLUMN_INSERT_META = exports.LAYOUT_COLUMN_INSERT_META = 'layoutColumnInsert';
var getPreviousLayoutColumnValign = function getPreviousLayoutColumnValign(selectedLayoutColumns) {
var _selectedLayoutColumn;
var firstValign = (0, _layoutColumnSelection.getLayoutColumnValign)((_selectedLayoutColumn = selectedLayoutColumns[0]) === null || _selectedLayoutColumn === void 0 ? void 0 : _selectedLayoutColumn.node);
var hasMixedValign = selectedLayoutColumns.some(function (_ref4) {
var node = _ref4.node;
return (0, _layoutColumnSelection.getLayoutColumnValign)(node) !== firstValign;
});
return hasMixedValign ? 'mixed' : firstValign !== null && firstValign !== void 0 ? firstValign : _consts.DEFAULT_LAYOUT_COLUMN_VALIGN;
};
var hasLayoutColumnContent = function hasLayoutColumnContent(node) {
return !(0, _utils.isEmptyDocument)(node);
};
/**
* Remaps a selection through a position mapping, preserving its type. Used after replacing a
* layout section's contents so the selection stays in its column instead of being mapped out
* of the layout. Returns `undefined` if no valid selection can be derived (NodeSelection
* whose node is no longer selectable falls back to a nearby caret).
*/
var remapSelectionThroughMapping = function remapSelectionThroughMapping(selection, mapping, doc) {
var docSize = doc.content.size;
var clamp = function clamp(pos) {
return Math.min(Math.max(pos, 0), docSize);
};
if (selection instanceof _state.NodeSelection) {
var _TextSelection$findFr;
var mappedPos = clamp(mapping.map(selection.from));
var nodeAtPos = doc.nodeAt(mappedPos);
if (nodeAtPos && _state.NodeSelection.isSelectable(nodeAtPos)) {
return _state.NodeSelection.create(doc, mappedPos);
}
return (_TextSelection$findFr = _state.TextSelection.findFrom(doc.resolve(mappedPos), 1, true)) !== null && _TextSelection$findFr !== void 0 ? _TextSelection$findFr : undefined;
}
if (selection instanceof _state.TextSelection) {
var mappedFrom = clamp(mapping.map(selection.from));
var mappedTo = clamp(mapping.map(selection.to));
try {
return _state.TextSelection.create(doc, mappedFrom, mappedTo);
} catch (_unused) {
return undefined;
}
}
return undefined;
};
var mapLayoutColumnPreservedSelection = function mapLayoutColumnPreservedSelection(tr, api) {
var insertMeta = tr.getMeta(LAYOUT_COLUMN_INSERT_META);
if (insertMeta) {
var _api$blockControls;
var mapping = insertMeta.side === 'left' ? new _transform.Mapping([new _transform.StepMap([insertMeta.insertedColumnPos, 0, insertMeta.insertedColumnNodeSize])]) : new _transform.Mapping();
api === null || api === void 0 || (_api$blockControls = api.blockControls) === null || _api$blockControls === void 0 || _api$blockControls.commands.mapPreservedSelection(mapping)({
tr: tr
});
return;
}
// Width and alignment updates should keep original layout column selection unchanged.
if (tr.getMeta('scrollIntoView') === false && tr.docChanged) {
var _api$blockControls2;
api === null || api === void 0 || (_api$blockControls2 = api.blockControls) === null || _api$blockControls2 === void 0 || _api$blockControls2.commands.mapPreservedSelection(new _transform.Mapping())({
tr: tr
});
}
};
/**
* Returns the active maximum layout column count for the current advanced layouts experiment state.
*/
function getEffectiveMaxLayoutColumns() {
return (0, _experiments.editorExperiment)('advanced_layouts', true) ? _consts.MAX_LAYOUT_COLUMNS : _consts.MAX_STANDARD_LAYOUT_COLUMNS;
}
var insertLayoutColumnAt = function insertLayoutColumnAt(side, editorAnalyticsAPI) {
var inputMethod = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _analytics.INPUT_METHOD.LAYOUT_COLUMN_MENU;
return function (_ref5) {
var tr = _ref5.tr;
if (!(0, _expValEquals.expValEquals)('platform_editor_layout_column_menu', 'isEnabled', true)) {
return null;
}
var selectedLayoutColumnsResult = (0, _layoutColumnSelection.getLayoutColumnsFromContentSelection)(tr.selection);
if (!selectedLayoutColumnsResult || selectedLayoutColumnsResult.selectedLayoutColumns.length === 0) {
return null;
}
var layoutSectionNode = selectedLayoutColumnsResult.layoutSectionNode,
layoutSectionPos = selectedLayoutColumnsResult.layoutSectionPos,
startIndex = selectedLayoutColumnsResult.startIndex,
endIndex = selectedLayoutColumnsResult.endIndex,
selectedLayoutColumns = selectedLayoutColumnsResult.selectedLayoutColumns;
var selectedColumnIndex = side === 'left' ? startIndex : endIndex;
var selectedColumnCount = selectedLayoutColumns.length;
if (layoutSectionNode.childCount >= getEffectiveMaxLayoutColumns()) {
return null;
}
var insertIndex = side === 'left' ? selectedColumnIndex : selectedColumnIndex + 1;
var existingWidths = (0, _utils.mapChildren)(layoutSectionNode, function (column) {
return column.attrs.width;
});
var redistributedWidths = (0, _layoutColumnDistribution.redistributeProportionally)(existingWidths, insertIndex, getEffectiveMaxLayoutColumns(), _consts.MIN_LAYOUT_COLUMN_WIDTH_PERCENT);
if (redistributedWidths === existingWidths) {
return null;
}
var layoutColumn = tr.doc.type.schema.nodes.layoutColumn;
var newColumn = layoutColumn.createAndFill({
width: redistributedWidths[insertIndex]
});
if (!newColumn) {
return null;
}
var updatedColumns = [];
layoutSectionNode.forEach(function (column, _offset, index) {
if (index === insertIndex) {
updatedColumns.push(newColumn);
}
updatedColumns.push(column);
});
if (insertIndex === layoutSectionNode.childCount) {
updatedColumns.push(newColumn);
}
var updatedLayoutSectionNode = layoutSectionNode.copy(_model.Fragment.fromArray(updatedColumns));
var insertedColumnOffset = 0;
layoutSectionNode.forEach(function (column, _offset, index) {
if (index < insertIndex) {
insertedColumnOffset += column.nodeSize;
}
});
var insertedColumnPos = layoutSectionPos + 1 + insertedColumnOffset;
tr.setMeta(LAYOUT_COLUMN_INSERT_META, {
insertedColumnNodeSize: newColumn.nodeSize,
insertedColumnPos: insertedColumnPos,
side: side
});
// Capture the selection before the section content is replaced (the replace below maps
// it out of the layout by default). The menu path restores its own preserved selection
// afterwards, so this restoration only matters for the cursor-in-column case.
var originalSelection = tr.selection;
tr.replaceWith(layoutSectionPos + 1, layoutSectionPos + layoutSectionNode.nodeSize - 1, columnWidth(updatedLayoutSectionNode, tr.doc.type.schema, redistributedWidths));
// Inserting left shifts positions at/after the new column right by its size; inserting
// right leaves them unchanged. Remap the original selection through that mapping.
if (!(0, _platformFeatureFlags.fg)('platform_editor_layout_column_menu_kill_switch_1')) {
var insertMapping = side === 'left' ? new _transform.Mapping([new _transform.StepMap([insertedColumnPos, 0, newColumn.nodeSize])]) : new _transform.Mapping();
var restoredSelection = remapSelectionThroughMapping(originalSelection, insertMapping, tr.doc);
if (restoredSelection) {
tr.setSelection(restoredSelection);
}
}
editorAnalyticsAPI === null || editorAnalyticsAPI === void 0 || editorAnalyticsAPI.attachAnalyticsEvent({
action: _analytics.ACTION.INSERTED,
actionSubject: _analytics.ACTION_SUBJECT.DOCUMENT,
actionSubjectId: _analytics.ACTION_SUBJECT_ID.LAYOUT_COLUMN,
attributes: {
endIndex: endIndex,
inputMethod: inputMethod,
newColumnCount: redistributedWidths.length,
previousColumnCount: layoutSectionNode.childCount,
selectedCount: selectedColumnCount,
side: side,
startIndex: startIndex
},
eventType: _analytics.EVENT_TYPE.TRACK
})(tr);
tr.setMeta('scrollIntoView', false);
return tr;
};
};
var insertLayoutColumn = exports.insertLayoutColumn = function insertLayoutColumn(_ref6, editorAnalyticsAPI, api) {
var side = _ref6.side,
_ref6$inputMethod = _ref6.inputMethod,
inputMethod = _ref6$inputMethod === void 0 ? _analytics.INPUT_METHOD.LAYOUT_COLUMN_MENU : _ref6$inputMethod;
return function (_ref7) {
var tr = _ref7.tr;
var result = insertLayoutColumnAt(side, editorAnalyticsAPI, inputMethod)({
tr: tr
});
if (result) {
mapLayoutColumnPreservedSelection(tr, api);
}
return result;
};
};
var setLayoutColumnValign = exports.setLayoutColumnValign = function setLayoutColumnValign(_ref8, editorAnalyticsAPI, api) {
var valign = _ref8.valign,
_ref8$inputMethod = _ref8.inputMethod,
inputMethod = _ref8$inputMethod === void 0 ? _analytics.INPUT_METHOD.LAYOUT_COLUMN_MENU : _ref8$inputMethod;
return function (_ref9) {
var tr = _ref9.tr;
if (!(0, _expValEquals.expValEquals)('platform_editor_layout_column_menu', 'isEnabled', true)) {
return null;
}
var selectedLayoutColumnsResult = (0, _layoutColumnSelection.getSelectedLayoutColumnsFromSelection)(tr.selection);
if (!selectedLayoutColumnsResult) {
return null;
}
var layoutSectionNode = selectedLayoutColumnsResult.layoutSectionNode,
startIndex = selectedLayoutColumnsResult.startIndex,
endIndex = selectedLayoutColumnsResult.endIndex,
selectedLayoutColumns = selectedLayoutColumnsResult.selectedLayoutColumns;
var previousValign = getPreviousLayoutColumnValign(selectedLayoutColumns);
var columnsToUpdate = selectedLayoutColumns.filter(function (_ref0) {
var node = _ref0.node;
return (0, _layoutColumnSelection.getLayoutColumnValign)(node) !== valign;
});
if (columnsToUpdate.length === 0) {
return null;
}
var updatedColumnCount = columnsToUpdate.length;
columnsToUpdate.forEach(function (_ref1) {
var node = _ref1.node,
pos = _ref1.pos;
tr.setNodeMarkup(pos, node.type, _objectSpread(_objectSpread({}, node.attrs), {}, {
valign: valign
}));
});
editorAnalyticsAPI === null || editorAnalyticsAPI === void 0 || editorAnalyticsAPI.attachAnalyticsEvent({
action: _analytics.ACTION.UPDATED,
actionSubject: _analytics.ACTION_SUBJECT.DOCUMENT,
actionSubjectId: _analytics.ACTION_SUBJECT_ID.LAYOUT_COLUMN,
attributes: {
columnCount: layoutSectionNode.childCount,
endIndex: endIndex,
inputMethod: inputMethod,
previousValign: previousValign,
selectedCount: selectedLayoutColumns.length,
startIndex: startIndex,
updatedCount: updatedColumnCount,
valign: valign
},
eventType: _analytics.EVENT_TYPE.TRACK
})(tr);
tr.setMeta('scrollIntoView', false);
mapLayoutColumnPreservedSelection(tr, api);
return tr;
};
};
var distributeLayoutColumns = exports.distributeLayoutColumns = function distributeLayoutColumns(editorAnalyticsAPI, api) {
return function () {
var _ref10 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref10$inputMethod = _ref10.inputMethod,
inputMethod = _ref10$inputMethod === void 0 ? _analytics.INPUT_METHOD.LAYOUT_COLUMN_MENU : _ref10$inputMethod,
_ref10$target = _ref10.target,
target = _ref10$target === void 0 ? 'selectedColumns' : _ref10$target;
return function (_ref11) {
var tr = _ref11.tr;
if (!(0, _expValEquals.expValEquals)('platform_editor_layout_column_menu', 'isEnabled', true)) {
return null;
}
var selectedLayoutColumnsResult = target === 'allColumns' ? (0, _layoutColumnSelection.getAllLayoutColumnsFromSelection)(tr.selection) : (0, _layoutColumnSelection.getSelectedLayoutColumnsFromSelection)(tr.selection);
if (!selectedLayoutColumnsResult || selectedLayoutColumnsResult.selectedLayoutColumns.length < 2) {
return null;
}
var layoutSectionNode = selectedLayoutColumnsResult.layoutSectionNode,
startIndex = selectedLayoutColumnsResult.startIndex,
endIndex = selectedLayoutColumnsResult.endIndex,
selectedLayoutColumns = selectedLayoutColumnsResult.selectedLayoutColumns;
var existingWidths = (0, _utils.mapChildren)(layoutSectionNode, function (column) {
return column.attrs.width;
});
var selectedWidths = selectedLayoutColumns.map(function (_ref12) {
var node = _ref12.node;
return node.attrs.width;
});
var distribution = (0, _layoutColumnDistribution.calculateDistribution)(selectedWidths);
if (!distribution) {
return null;
}
var selectedTotal = distribution.selectedTotal,
equalWidth = distribution.equalWidth;
if ((0, _layoutColumnDistribution.isDistributedUniformly)(selectedWidths, distribution)) {
return null;
}
// Build new widths array: selected columns get equal share, unselected unchanged.
// Assign rounded (2dp) equal widths to all selected cols except the last, which absorbs
// the rounding remainder so the sum of selected widths equals selectedTotal exactly.
var assignedToSelected = 0;
var selectedAssignedCount = 0;
var newWidths = existingWidths.map(function (w, idx) {
if (idx < startIndex || idx > endIndex) {
return w;
}
selectedAssignedCount += 1;
if (selectedAssignedCount < selectedLayoutColumns.length) {
assignedToSelected += equalWidth;
return equalWidth;
}
// Last selected column: absorb the remainder to avoid drift
return Number((selectedTotal - assignedToSelected).toFixed(2));
});
// Apply widths via setNodeMarkup per selected column — keeps nodes in place (preserves identity, marks, decorations)
selectedLayoutColumns.forEach(function (_ref13, i) {
var node = _ref13.node,
pos = _ref13.pos;
var colIdx = startIndex + i;
tr.setNodeMarkup(pos, node.type, _objectSpread(_objectSpread({}, node.attrs), {}, {
width: newWidths[colIdx]
}));
});
editorAnalyticsAPI === null || editorAnalyticsAPI === void 0 || editorAnalyticsAPI.attachAnalyticsEvent({
action: _analytics.ACTION.UPDATED,
actionSubject: _analytics.ACTION_SUBJECT.DOCUMENT,
actionSubjectId: _analytics.ACTION_SUBJECT_ID.LAYOUT_COLUMN,
attributes: {
columnCount: layoutSectionNode.childCount,
endIndex: endIndex,
inputMethod: inputMethod,
selectedCount: selectedLayoutColumns.length,
startIndex: startIndex,
target: target
},
eventType: _analytics.EVENT_TYPE.TRACK
})(tr);
tr.setMeta('scrollIntoView', false);
mapLayoutColumnPreservedSelection(tr, api);
return tr;
};
};
};
// Omitting `isOpen` (toggle) requires `anchorPos`, so a toggle can never open the menu
// without a valid anchor. Explicit open/close keeps `anchorPos` optional (close needs none).
var toggleLayoutColumnMenu = exports.toggleLayoutColumnMenu = function toggleLayoutColumnMenu(options) {
return function (_ref14) {
var tr = _ref14.tr;
tr.setMeta('toggleLayoutColumnMenu', options);
tr.setMeta('scrollIntoView', false);
return tr;
};
};
var setLayoutColumnDangerPreview = exports.setLayoutColumnDangerPreview = function setLayoutColumnDangerPreview(show) {
return function (_ref15) {
var _selectedLayoutColumn2;
var tr = _ref15.tr;
var selectedLayoutColumnsResult = (0, _layoutColumnSelection.getSelectedLayoutColumnsFromSelection)(tr.selection);
var positions = show ? (_selectedLayoutColumn2 = selectedLayoutColumnsResult === null || selectedLayoutColumnsResult === void 0 ? void 0 : selectedLayoutColumnsResult.selectedLayoutColumns.map(function (_ref16) {
var pos = _ref16.pos;
return pos;
})) !== null && _selectedLayoutColumn2 !== void 0 ? _selectedLayoutColumn2 : [] : null;
tr.setMeta('layoutColumnDangerPreview', positions);
tr.setMeta('addToHistory', false);
tr.setMeta('scrollIntoView', false);
return tr;
};
};
var deleteLayoutColumn = exports.deleteLayoutColumn = function deleteLayoutColumn() {
var _ref17 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref17$inputMethod = _ref17.inputMethod,
inputMethod = _ref17$inputMethod === void 0 ? _analytics.INPUT_METHOD.LAYOUT_COLUMN_MENU : _ref17$inputMethod;
var editorAnalyticsAPI = arguments.length > 1 ? arguments[1] : undefined;
var api = arguments.length > 2 ? arguments[2] : undefined;
return function (_ref18) {
var _api$blockControls4;
var tr = _ref18.tr;
if (!(0, _expValEquals.expValEquals)('platform_editor_layout_column_menu', 'isEnabled', true)) {
return null;
}
var selectedLayoutColumnsResult = (0, _layoutColumnSelection.getLayoutColumnsFromContentSelection)(tr.selection);
if (!selectedLayoutColumnsResult || selectedLayoutColumnsResult.selectedLayoutColumns.length === 0) {
return null;
}
var layoutSectionNode = selectedLayoutColumnsResult.layoutSectionNode,
layoutSectionPos = selectedLayoutColumnsResult.layoutSectionPos,
selectedLayoutColumns = selectedLayoutColumnsResult.selectedLayoutColumns,
startIndex = selectedLayoutColumnsResult.startIndex,
endIndex = selectedLayoutColumnsResult.endIndex;
var hadContent = selectedLayoutColumns.some(function (_ref19) {
var node = _ref19.node;
return hasLayoutColumnContent(node);
});
var emitDeleteColumnAnalytics = function emitDeleteColumnAnalytics(newColumnCount) {
editorAnalyticsAPI === null || editorAnalyticsAPI === void 0 || editorAnalyticsAPI.attachAnalyticsEvent({
action: _analytics.ACTION.DELETED,
actionSubject: _analytics.ACTION_SUBJECT.DOCUMENT,
actionSubjectId: _analytics.ACTION_SUBJECT_ID.LAYOUT_COLUMN,
attributes: {
endIndex: endIndex,
hadContent: hadContent,
inputMethod: inputMethod,
newColumnCount: newColumnCount,
previousColumnCount: layoutSectionNode.childCount,
selectedCount: selectedLayoutColumns.length,
startIndex: startIndex
},
eventType: _analytics.EVENT_TYPE.TRACK
})(tr);
};
// If all columns are selected, remove the entire layoutSection
if (selectedLayoutColumns.length === layoutSectionNode.childCount) {
var _api$blockControls3;
tr.delete(layoutSectionPos, layoutSectionPos + layoutSectionNode.nodeSize);
emitDeleteColumnAnalytics(0);
tr.setMeta('scrollIntoView', false);
api === null || api === void 0 || (_api$blockControls3 = api.blockControls) === null || _api$blockControls3 === void 0 || _api$blockControls3.commands.stopPreservingSelection()({
tr: tr
});
return tr;
}
// Build new column list without the selected columns
var remainingColumns = [];
layoutSectionNode.forEach(function (column, _offset, index) {
if (index < startIndex || index > endIndex) {
remainingColumns.push(column);
}
});
// Redistribute widths proportionally among remaining columns using shared utility
var existingWidths = (0, _utils.mapChildren)(layoutSectionNode, function (column) {
return column.attrs.width;
});
var redistributed = selectedLayoutColumns.map(function (_, i) {
return startIndex + i;
})
// Delete highest indices first so lower original indices still point at the same columns
// as each redistribution step shrinks the widths array.
.reverse().reduce(function (widths, selectedIndex) {
return (0, _layoutColumnDistribution.redistributeAfterDeletion)(widths, selectedIndex, _consts.MIN_LAYOUT_COLUMN_WIDTH_PERCENT);
}, existingWidths);
var updatedLayoutSectionNode = layoutSectionNode.copy(_model.Fragment.fromArray(remainingColumns));
// The cursor-in-column (keyboard) path has a plain text selection; the menu path has a
// column NodeSelection whose post-delete landing is owned by the block-controls
// preserved-selection plugin, so we only restore the caret for the former.
var hadTextSelection = tr.selection instanceof _state.TextSelection;
tr.replaceWith(layoutSectionPos + 1, layoutSectionPos + layoutSectionNode.nodeSize - 1, columnWidth(updatedLayoutSectionNode, tr.doc.type.schema, redistributed));
// Land the caret in a remaining column — the one now occupying the deleted slot, or the
// last column when the deleted slot no longer exists. Otherwise the replace above maps
// the caret out of the layout to the following paragraph.
var remainingColumnCount = remainingColumns.length;
if (hadTextSelection && !(0, _platformFeatureFlags.fg)('platform_editor_layout_column_menu_kill_switch_1') && remainingColumnCount > 0) {
var targetColumnIndex = Math.min(startIndex, remainingColumnCount - 1);
var updatedSectionNode = tr.doc.nodeAt(layoutSectionPos);
if (updatedSectionNode) {
var columnOffset = 1;
for (var columnIndex = 0; columnIndex < targetColumnIndex; columnIndex++) {
columnOffset += updatedSectionNode.child(columnIndex).nodeSize;
}
// +1 to land inside the column's first child rather than on the column boundary.
var caretPos = layoutSectionPos + columnOffset + 1;
if (caretPos >= 0 && caretPos <= tr.doc.content.size) {
var caretSelection = _state.TextSelection.findFrom(tr.doc.resolve(caretPos), 1, true);
if (caretSelection) {
tr.setSelection(caretSelection);
}
}
}
}
emitDeleteColumnAnalytics(redistributed.length);
tr.setMeta('scrollIntoView', false);
api === null || api === void 0 || (_api$blockControls4 = api.blockControls) === null || _api$blockControls4 === void 0 || _api$blockControls4.commands.stopPreservingSelection()({
tr: tr
});
return tr;
};
};