import { Node_Type } from "./../ricos-schema/legacy/wix/rich_content/v1/index.js";
import { callOrReturn, findParentNodeClosestToPos } from "./../tiptap/index.js";
import { canJoin, findWrapping } from "./../tiptap/pm/transform.js";
const createListInputRuleHandler = ({ type, getAttributes, getItemAttributes, joinPredicate }) => ({ state, range, match }) => {
  const attributes = callOrReturn(getAttributes, void 0, match) || {};
  const itemAttributes = callOrReturn(getItemAttributes, void 0, match) || {};
  const { from, to } = state.selection;
  let shouldApplyRule = true;
  state.doc.nodesBetween(from, to, (node, pos) => {
    const $pos = state.doc.resolve(pos);
    if (node.isTextblock && node.type.name !== Node_Type.PARAGRAPH && node.type.name !== Node_Type.HEADING || $pos.parent.type.name === Node_Type.LIST_ITEM) {
      shouldApplyRule = false;
      return false;
    }
  });
  if (!shouldApplyRule) {
    return null;
  }
  const tr = state.tr.delete(range.from, range.to);
  const $start = tr.doc.resolve(range.from);
  const blockRange = $start.blockRange();
  const wrapping = blockRange && findWrapping(blockRange, type, attributes);
  if (!wrapping) {
    return null;
  }
  tr.wrap(blockRange, wrapping);
  if (Object.keys(itemAttributes).length > 0) {
    const resolvedPos = tr.doc.resolve(Math.min(range.from + 1, tr.doc.content.size));
    const listItem = findParentNodeClosestToPos(
      resolvedPos,
      (node) => node.type.name === Node_Type.LIST_ITEM
    );
    if (listItem) {
      tr.setNodeMarkup(listItem.pos, listItem.node.type, {
        ...listItem.node.attrs,
        ...itemAttributes
      });
    }
  }
  const before = tr.doc.resolve(range.from - 1).nodeBefore;
  if (before && before.type === type && canJoin(tr.doc, range.from - 1) && (!joinPredicate || joinPredicate(match, before))) {
    tr.join(range.from - 1);
  }
};
export {
  createListInputRuleHandler
};
//# sourceMappingURL=list-input-rule-handler.js.map
