UNPKG

@atlaskit/editor-plugin-list

Version:

List plugin for @atlaskit/editor-core

376 lines (365 loc) 19.6 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.toggleOrderedList = exports.toggleList = exports.toggleBulletList = exports.rootListDepth = exports.enterKeyCommand = exports.deleteKeyCommand = exports.backspaceKeyCommand = void 0; var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _analytics = require("@atlaskit/editor-common/analytics"); var _commands = require("@atlaskit/editor-common/commands"); var _lists = require("@atlaskit/editor-common/lists"); var _preset = require("@atlaskit/editor-common/preset"); var _selection = require("@atlaskit/editor-common/selection"); var _utils = require("@atlaskit/editor-common/utils"); var _commands2 = require("@atlaskit/editor-prosemirror/commands"); var _model = require("@atlaskit/editor-prosemirror/model"); var _state = require("@atlaskit/editor-prosemirror/state"); var _utils2 = require("@atlaskit/editor-prosemirror/utils"); var _expValEquals = require("@atlaskit/tmp-editor-statsig/exp-val-equals"); var _conversions = require("../actions/conversions"); var _wrapAndJoinLists = require("../actions/wrap-and-join-lists"); var _transforms = require("../transforms"); var _mark = require("../utils/mark"); var _selection2 = require("../utils/selection"); var _isFirstChildOfParent = require("./isFirstChildOfParent"); var _joinListItemForward = require("./join-list-item-forward"); var _listBackspace = require("./listBackspace"); var _outdentList = require("./outdent-list"); 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 enterKeyCommand = exports.enterKeyCommand = function enterKeyCommand(editorAnalyticsAPI) { return function () { return function (state, dispatch) { var selection = state.selection; if (selection.empty) { var $from = selection.$from; var _state$schema$nodes = state.schema.nodes, listItem = _state$schema$nodes.listItem, codeBlock = _state$schema$nodes.codeBlock; // the list item is the parent of the gap cursor // while for text, list item is the grandparent of the text node var isGapCursorSelection = selection instanceof _selection.GapCursorSelection; var wrapper = isGapCursorSelection ? $from.parent : $from.node($from.depth - 1); if (wrapper && wrapper.type === listItem) { /** Check if the wrapper has any visible content */ var wrapperHasContent = (0, _utils.hasVisibleContent)(wrapper); if (!wrapperHasContent) { return (0, _preset.editorCommandToPMCommand)((0, _outdentList.outdentList)(editorAnalyticsAPI)(_analytics.INPUT_METHOD.KEYBOARD))(state, dispatch); } else if (!(0, _utils2.hasParentNodeOfType)(codeBlock)(selection)) { return splitListItem(listItem)(state, dispatch); } } } return false; }; }; }; var backspaceKeyCommand = exports.backspaceKeyCommand = function backspaceKeyCommand(editorAnalyticsAPI) { return function () { return function (state, dispatch) { return (0, _commands2.chainCommands)((0, _listBackspace.listBackspace)(editorAnalyticsAPI), // if we're at the start of a list item, we need to either backspace // directly to an empty list item above, or outdent this node (0, _utils.filterCommand)([_utils.isEmptySelectionAtStart, // list items might have multiple paragraphs; only do this at the first one _isFirstChildOfParent.isFirstChildOfParent, function (state) { return (0, _selection2.isInsideListItem)(state.tr); }], (0, _commands2.chainCommands)(deletePreviousEmptyListItem, (0, _preset.editorCommandToPMCommand)((0, _outdentList.outdentList)(editorAnalyticsAPI)(_analytics.INPUT_METHOD.KEYBOARD)))), // if we're just inside a paragraph node (or gapcursor is shown) and backspace, then try to join // the text to the previous list item, if one exists (0, _utils.filterCommand)([_utils.isEmptySelectionAtStart, function (state) { return (0, _selection2.canJoinToPreviousListItem)(state.tr); }], joinToPreviousListItem))(state, dispatch); }; }; }; var deleteKeyCommand = exports.deleteKeyCommand = function deleteKeyCommand(editorAnalyticsAPI) { return (0, _joinListItemForward.joinListItemForward)(editorAnalyticsAPI); }; // Get the depth of the nearest ancestor list var rootListDepth = exports.rootListDepth = function rootListDepth(pos, nodes) { var bulletList = nodes.bulletList, orderedList = nodes.orderedList, listItem = nodes.listItem; var depth; for (var i = pos.depth - 1; i > 0; i--) { var node = pos.node(i); if (node.type === bulletList || node.type === orderedList) { depth = i; } if (node.type !== bulletList && node.type !== orderedList && node.type !== listItem) { break; } } return depth; }; function untoggleSelectedList(tr) { var _tr = tr, selection = _tr.selection; var depth = rootListDepth(selection.$to, tr.doc.type.schema.nodes); tr = (0, _transforms.liftFollowingList)(selection.$to.pos, selection.$to.end(depth), depth || 0, tr); if (selection instanceof _state.NodeSelection || selection instanceof _selection.GapCursorSelection) { return (0, _transforms.liftNodeSelectionList)(selection, tr); } return (0, _transforms.liftTextSelectionList)(selection, tr); } var toggleList = exports.toggleList = function toggleList(editorAnalyticsAPI) { return function (inputMethod, listType) { return function (_ref) { var tr = _ref.tr; var taskList = tr.doc.type.schema.nodes.taskList; if ((0, _utils2.hasParentNodeOfType)(taskList)(tr.selection)) { return tr; } var listInsideSelection = (0, _selection2.selectionContainsList)(tr); var listNodeType = tr.doc.type.schema.nodes[listType]; var actionSubjectId = listType === 'bulletList' ? _analytics.ACTION_SUBJECT_ID.FORMAT_LIST_BULLET : _analytics.ACTION_SUBJECT_ID.FORMAT_LIST_NUMBER; if (listInsideSelection) { var selection = tr.selection; // for gap cursor or node selection - list is expected 1 level up (listItem -> list) // for text selection - list is expected 2 levels up (paragraph -> listItem -> list) var positionDiff = selection instanceof _selection.GapCursorSelection || selection instanceof _state.NodeSelection ? 1 : 2; var fromNode = selection.$from.node(selection.$from.depth - positionDiff); var toNode = selection.$to.node(selection.$to.depth - positionDiff); var transformedFrom = listInsideSelection.type.name === 'bulletList' ? _analytics.ACTION_SUBJECT_ID.FORMAT_LIST_BULLET : _analytics.ACTION_SUBJECT_ID.FORMAT_LIST_NUMBER; if ((fromNode === null || fromNode === void 0 ? void 0 : fromNode.type.name) === listType && (toNode === null || toNode === void 0 ? void 0 : toNode.type.name) === listType) { var commonAttributes = (0, _lists.getCommonListAnalyticsAttributes)(tr); untoggleSelectedList(tr); editorAnalyticsAPI === null || editorAnalyticsAPI === void 0 || editorAnalyticsAPI.attachAnalyticsEvent({ action: _analytics.ACTION.CONVERTED, actionSubject: _analytics.ACTION_SUBJECT.LIST, actionSubjectId: _analytics.ACTION_SUBJECT_ID.TEXT, eventType: _analytics.EVENT_TYPE.TRACK, attributes: _objectSpread(_objectSpread({}, commonAttributes), {}, { transformedFrom: transformedFrom, inputMethod: inputMethod }) })(tr); return tr; } (0, _conversions.convertListType)({ tr: tr, nextListNodeType: listNodeType }); editorAnalyticsAPI === null || editorAnalyticsAPI === void 0 || editorAnalyticsAPI.attachAnalyticsEvent({ action: _analytics.ACTION.CONVERTED, actionSubject: _analytics.ACTION_SUBJECT.LIST, actionSubjectId: actionSubjectId, eventType: _analytics.EVENT_TYPE.TRACK, attributes: _objectSpread(_objectSpread({}, (0, _lists.getCommonListAnalyticsAttributes)(tr)), {}, { transformedFrom: transformedFrom, inputMethod: inputMethod }) })(tr); } else { // Need to have this before wrapInList so the wrapping is done with valid content // For example, if trying to convert centre or right aligned paragraphs to lists (0, _mark.sanitiseMarksInSelection)(tr, listNodeType); (0, _wrapAndJoinLists.wrapInListAndJoin)(listNodeType, tr); editorAnalyticsAPI === null || editorAnalyticsAPI === void 0 || editorAnalyticsAPI.attachAnalyticsEvent({ action: _analytics.ACTION.INSERTED, actionSubject: _analytics.ACTION_SUBJECT.LIST, actionSubjectId: actionSubjectId, eventType: _analytics.EVENT_TYPE.TRACK, attributes: { inputMethod: inputMethod } })(tr); } // If document wasn't changed, return false from the command to indicate that the // editing action failed if (!tr.docChanged) { return null; } return tr; }; }; }; var toggleBulletList = exports.toggleBulletList = function toggleBulletList(editorAnalyticsAPI) { return function () { var inputMethod = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _analytics.INPUT_METHOD.TOOLBAR; return toggleList(editorAnalyticsAPI)(inputMethod, 'bulletList'); }; }; var toggleOrderedList = exports.toggleOrderedList = function toggleOrderedList(editorAnalyticsAPI) { return function () { var inputMethod = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _analytics.INPUT_METHOD.TOOLBAR; return toggleList(editorAnalyticsAPI)(inputMethod, 'orderedList'); }; }; /** * Implementation taken and modified for our needs from PM * @param itemType Node * Splits the list items, specific implementation take from PM */ function splitListItem(itemType) { return function (state, dispatch) { var ref = state.selection; var $from = ref.$from; var $to = ref.$to; var node = ref.node; if (node && node.isBlock || $from.depth < 2 || !$from.sameParent($to)) { return false; } // list item is the parent of the gap cursor instead of grandparent var isGapCursorSelection = ref instanceof _selection.GapCursorSelection; var wrapperListItem = isGapCursorSelection ? $from.parent : $from.node(-1); if (wrapperListItem.type !== itemType) { return false; } /** --> The following line changed from the original PM implementation to allow list additions with multiple paragraphs */ if ( // eslint-disable-next-line @typescript-eslint/no-explicit-any wrapperListItem.content.content.length <= 1 && $from.parent.content.size === 0 && !(wrapperListItem.content.size === 0)) { // In an empty block. If this is a nested list, the wrapping // list item should be split. Otherwise, bail out and let next // command handle lifting. if ($from.depth === 2 || $from.node(-3).type !== itemType || $from.index(-2) !== $from.node(-2).childCount - 1) { return false; } if (dispatch) { var wrap = _model.Fragment.empty; var keepItem = $from.index(-1) > 0; // Build a fragment containing empty versions of the structure // from the outer list item to the parent node of the cursor for (var d = $from.depth - (keepItem ? 1 : 2); d >= $from.depth - 3; d--) { wrap = _model.Fragment.from($from.node(d).copy(wrap)); } // Add a second list item with an empty default start node // Ignored via go/ees005 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion wrap = wrap.append(_model.Fragment.from(itemType.createAndFill())); var tr$1 = state.tr.replace($from.before(keepItem ? undefined : -1), $from.after(-3), new _model.Slice(wrap, keepItem ? 3 : 2, 2)); tr$1.setSelection( // eslint-disable-next-line @typescript-eslint/no-explicit-any state.selection.constructor.near(tr$1.doc.resolve($from.pos + (keepItem ? 3 : 2)))); dispatch(tr$1.scrollIntoView()); } return true; } var nextType = $to.pos === $from.end() ? wrapperListItem.contentMatchAt(0).defaultType : null; var tr = state.tr.delete($from.pos, $to.pos); var types = nextType && [null, { type: nextType }]; var fontSize = state.schema.marks.fontSize; var isFontSizeSupported = fontSize && (0, _expValEquals.expValEquals)('platform_editor_small_font_size', 'isEnabled', true); var currentFontSizeAttrs = isFontSizeSupported ? (0, _lists.getBlockMarkAttrs)($from.parent, fontSize) : false; if (dispatch) { var _$from$nodeBefore; if (ref instanceof _state.TextSelection) { var splitTr = tr.split($from.pos, 2, types !== null && types !== void 0 ? types : undefined); if (isFontSizeSupported) { (0, _lists.reconcileBlockMarkForParagraphAtPos)(splitTr, splitTr.selection.from, fontSize, currentFontSizeAttrs); } dispatch(splitTr.scrollIntoView()); return true; } // create new list item with empty paragraph when user clicks enter on gap cursor if (isGapCursorSelection && (_$from$nodeBefore = $from.nodeBefore) !== null && _$from$nodeBefore !== void 0 && _$from$nodeBefore.isBlock) { // For gap cursor selection, we cannot split the list item directly // We need to insert a new list item after the current list item to simulate the split behaviour var _state$schema$nodes2 = state.schema.nodes, listItem = _state$schema$nodes2.listItem, paragraph = _state$schema$nodes2.paragraph; var newListItem = listItem.createChecked({}, paragraph.createChecked({}, undefined, currentFontSizeAttrs && isFontSizeSupported ? [fontSize.create(currentFontSizeAttrs)] : undefined)); dispatch(tr.insert($from.pos, newListItem).setSelection(_state.Selection.near(tr.doc.resolve($to.pos + 1))).scrollIntoView()); return true; } } return false; }; } var deletePreviousEmptyListItem = function deletePreviousEmptyListItem(state, dispatch) { var $from = state.selection.$from; var listItem = state.schema.nodes.listItem; var $cut = (0, _commands.findCutBefore)($from); if (!$cut || !$cut.nodeBefore || !($cut.nodeBefore.type === listItem)) { return false; } var nodeBeforeIsExtension = $cut.nodeBefore.firstChild && $cut.nodeBefore.firstChild.type.name === 'extension'; var previousListItemEmpty = // Ignored via go/ees005 $cut.nodeBefore.childCount === 1 && $cut.nodeBefore.firstChild && $cut.nodeBefore.firstChild.nodeSize <= 2 && !nodeBeforeIsExtension; if (previousListItemEmpty) { var tr = state.tr; if (dispatch) { dispatch(tr.delete($cut.pos - $cut.nodeBefore.nodeSize, $from.pos).scrollIntoView()); } return true; } return false; }; var joinToPreviousListItem = function joinToPreviousListItem(state, dispatch) { var $from = state.selection.$from; var _state$schema$nodes3 = state.schema.nodes, paragraph = _state$schema$nodes3.paragraph, listItem = _state$schema$nodes3.listItem, codeBlock = _state$schema$nodes3.codeBlock, bulletList = _state$schema$nodes3.bulletList, orderedList = _state$schema$nodes3.orderedList; var fontSize = state.schema.marks.fontSize; var isGapCursorShown = state.selection instanceof _selection.GapCursorSelection; var $cutPos = isGapCursorShown ? state.doc.resolve($from.pos + 1) : $from; var $cut = (0, _commands.findCutBefore)($cutPos); if (!$cut) { return false; } // see if the containing node is a list if ($cut.nodeBefore && [bulletList, orderedList].indexOf($cut.nodeBefore.type) > -1) { // and the node after this is a paragraph or a codeBlock if ($cut.nodeAfter && ($cut.nodeAfter.type === paragraph || $cut.nodeAfter.type === codeBlock)) { // find the nearest paragraph that precedes this node var $lastNode = $cut.doc.resolve($cut.pos - 1); while ($lastNode.parent.type !== paragraph && $lastNode.pos > 1) { $lastNode = state.doc.resolve($lastNode.pos - 1); } var tr = state.tr; if (isGapCursorShown) { var nodeBeforePos = (0, _utils2.findPositionOfNodeBefore)(tr.selection); if (typeof nodeBeforePos !== 'number') { return false; } // append the codeblock to the list node var list = $cut.nodeBefore.copy($cut.nodeBefore.content.append(_model.Fragment.from(listItem.createChecked({}, $cut.nodeAfter)))); tr.replaceWith(nodeBeforePos, $from.pos + $cut.nodeAfter.nodeSize, list); } else { var step = (0, _lists.moveTargetIntoList)({ insertPosition: $lastNode.pos, $target: $cut }); // ED-13966: check if the step will cause an ProseMirror error // if there's an error don't apply the step as it will might lead into a data loss. // It doesn't play well with media being a leaf node. var stepResult = state.tr.maybeStep(step); if (stepResult.failed) { return false; } else { tr = state.tr.step(step); } } // find out if there's now another list following and join them // as in, [list, p, list] => [list with p, list], and we want [joined list] var $postCut = tr.doc.resolve(tr.mapping.map($cut.pos + $cut.nodeAfter.nodeSize)); if ($postCut.nodeBefore && $postCut.nodeAfter && $postCut.nodeBefore.type === $postCut.nodeAfter.type && [bulletList, orderedList].indexOf($postCut.nodeBefore.type) > -1) { tr = tr.join($postCut.pos); } if (fontSize && (0, _expValEquals.expValEquals)('platform_editor_small_font_size', 'isEnabled', true)) { var prevListFontSizeAttrs = (0, _lists.getFirstParagraphBlockMarkAttrs)($cut.nodeBefore, fontSize); var containingList = (0, _utils2.findParentNodeOfTypeClosestToPos)(tr.doc.resolve(tr.mapping.map($cut.pos)), [bulletList, orderedList]); if (containingList) { (0, _lists.reconcileBlockMarkForContainerAtPos)(tr, containingList.pos, fontSize, prevListFontSizeAttrs); } } if (dispatch) { var _tr$doc$resolve$nodeB; if (!((_tr$doc$resolve$nodeB = tr.doc.resolve($lastNode.pos).nodeBefore) !== null && _tr$doc$resolve$nodeB !== void 0 && _tr$doc$resolve$nodeB.isBlock) || tr.doc.resolve($lastNode.pos).nodeBefore === null) { tr = tr.setSelection(_state.TextSelection.near(tr.doc.resolve(tr.mapping.map($cut.pos)), -1)); } dispatch(tr.scrollIntoView()); } return true; } } return false; };