UNPKG

@atlaskit/editor-plugin-tasks-and-decisions

Version:

Tasks and decisions plugin for @atlaskit/editor-core

61 lines (60 loc) 2.56 kB
import { NodeSelection, Selection, TextSelection } from '@atlaskit/editor-prosemirror/state'; function isTaskListNode(node) { return Boolean(node && node.type && 'taskList' === node.type.name); } var resolvePositionToStartOfTaskItem = function resolvePositionToStartOfTaskItem($pos) { var fromRange = $pos.blockRange($pos, isTaskListNode); var fromPosition = fromRange && $pos.textOffset === 0 && fromRange.end - 1 === $pos.pos ? Selection.near($pos.doc.resolve(fromRange.end + 1), 1).$from : $pos; return fromPosition; }; var resolvePositionToEndOfTaskItem = function resolvePositionToEndOfTaskItem($pos) { var toRange = $pos.blockRange($pos, isTaskListNode); var toPosition = toRange && $pos.textOffset === 0 && toRange.start + 1 === $pos.pos ? Selection.near($pos.doc.resolve(toRange.start - 1), -1).$to : $pos; return toPosition; }; export var normalizeTaskItemsSelection = function normalizeTaskItemsSelection(selection) { if (selection.empty) { return selection; } var $from = selection.$from, $to = selection.$to; if (selection instanceof NodeSelection) { var _head = resolvePositionToStartOfTaskItem($from); return new TextSelection(_head, _head); } var head = resolvePositionToStartOfTaskItem($from); var anchor = resolvePositionToEndOfTaskItem($to); return new TextSelection(anchor, head); }; /** * Gets the blockTaskItem node and whether it has a paragraph child if it exists near the given resolved position. * @param $from resolved position, typically from the selection when the selection is an empty selection at the start of a task item * @returns {{ blockTaskItemNode: PMNode; hasParagraph: boolean } | false} An object with blockTaskItemNode and hasParagraph if found, or false if there is no blockTaskItem node. */ export var findBlockTaskItem = function findBlockTaskItem($from) { var _$from$doc$type$schem = $from.doc.type.schema.nodes, blockTaskItem = _$from$doc$type$schem.blockTaskItem, paragraph = _$from$doc$type$schem.paragraph; var firstParent = $from.parent; if (firstParent.type === blockTaskItem) { return { blockTaskItemNode: firstParent, hasParagraph: false }; } else if (firstParent.type === paragraph) { if ($from.depth >= 1) { var secondParent = $from.node($from.depth - 1); if (secondParent.type === blockTaskItem) { return { blockTaskItemNode: secondParent, hasParagraph: true }; } else { return false; } } else { return false; } } return false; };