"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "createBlockTaskItem", {
  enumerable: true,
  get: function get() {
    return _createBlockTaskItem.createBlockTaskItem;
  }
});
Object.defineProperty(exports, "getFormattedNode", {
  enumerable: true,
  get: function get() {
    return _getFormattedNode.getFormattedNode;
  }
});
exports.transformListRecursively = exports.transformBetweenListTypes = void 0;
Object.defineProperty(exports, "transformListStructure", {
  enumerable: true,
  get: function get() {
    return _transformListStructure.transformListStructure;
  }
});
Object.defineProperty(exports, "transformSliceEnsureListItemParagraphFirst", {
  enumerable: true,
  get: function get() {
    return _transformSliceEnsureListItemParagraphFirst.transformSliceEnsureListItemParagraphFirst;
  }
});
Object.defineProperty(exports, "transformTaskListToBlockNodes", {
  enumerable: true,
  get: function get() {
    return _transformTaskListToBlockNodes.transformTaskListToBlockNodes;
  }
});
exports.transformToTaskList = void 0;
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _model = require("@atlaskit/editor-prosemirror/model");
var _expValEquals = require("@atlaskit/tmp-editor-statsig/exp-val-equals");
var _convertBlockToInlineContent = require("./convertBlockToInlineContent");
var _createBlockTaskItem = require("./createBlockTaskItem");
var _isBulletOrOrderedList = require("./isBulletOrOrderedList");
var _isTaskList = require("./isTaskList");
var _listUtils = require("./list-utils");
var _transformListStructure = require("./transformListStructure");
var _transformTaskListToBlockNodes = require("./transformTaskListToBlockNodes");
var _getFormattedNode = require("./getFormattedNode");
var _transformSliceEnsureListItemParagraphFirst = require("./transformSliceEnsureListItemParagraphFirst");
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 getContentSupportChecker = function getContentSupportChecker(targetNodeType) {
  return function (node) {
    try {
      return targetNodeType.validContent(_model.Fragment.from(node));
    } catch (_unused) {
      return false;
    }
  };
};
var _transformListRecursively = exports.transformListRecursively = function transformListRecursively(props, onhandleUnsupportedContent) {
  var transformedItems = [];
  var listNode = props.listNode,
    isSourceBulletOrOrdered = props.isSourceBulletOrOrdered,
    isTargetBulletOrOrdered = props.isTargetBulletOrOrdered,
    isSourceTask = props.isSourceTask,
    isTargetTask = props.isTargetTask,
    supportedListTypes = props.supportedListTypes,
    schema = props.schema,
    targetNodeType = props.targetNodeType;
  var _schema$nodes = schema.nodes,
    taskList = _schema$nodes.taskList,
    listItem = _schema$nodes.listItem,
    taskItem = _schema$nodes.taskItem,
    paragraph = _schema$nodes.paragraph,
    blockTaskItem = _schema$nodes.blockTaskItem;

  // gating behind platform_editor_small_font_size to support task lists with font size applied,
  // but keep this solution general
  var isBlockTaskEnabled = !!blockTaskItem && (0, _expValEquals.expValEquals)('platform_editor_small_font_size', 'isEnabled', true);

  /**
   * Extracts paragraph children from a blockTaskItem, preserving their marks.
   */
  var extractParagraphsFromBlockTaskItem = function extractParagraphsFromBlockTaskItem(node) {
    var paragraphs = [];
    node.forEach(function (child) {
      if (child.type === paragraph) {
        paragraphs.push(child);
      }
    });
    return paragraphs;
  };
  listNode.forEach(function (child) {
    if (isSourceBulletOrOrdered && isTargetTask) {
      // Convert bullet/ordered => task
      if (child.type === listItem) {
        var inlineContent = [];
        var nestedTaskLists = [];
        var blockMarks = [];
        child.forEach(function (grandChild) {
          if (supportedListTypes.has(grandChild.type) && grandChild.type !== taskList) {
            nestedTaskLists.push(_transformListRecursively(_objectSpread(_objectSpread({}, props), {}, {
              listNode: grandChild
            }), onhandleUnsupportedContent));
          } else if (!getContentSupportChecker(taskItem)(grandChild) && !grandChild.isTextblock) {
            onhandleUnsupportedContent === null || onhandleUnsupportedContent === void 0 || onhandleUnsupportedContent(grandChild);
          } else {
            if (isBlockTaskEnabled && grandChild.type === paragraph && grandChild.marks.length > 0) {
              blockMarks = grandChild.marks;
            }
            inlineContent.push.apply(inlineContent, (0, _toConsumableArray2.default)((0, _convertBlockToInlineContent.convertBlockToInlineContent)(grandChild, schema)));
          }
        });
        if (isBlockTaskEnabled && blockMarks.length > 0) {
          transformedItems.push((0, _createBlockTaskItem.createBlockTaskItem)({
            content: inlineContent,
            marks: blockMarks,
            schema: schema
          }));
        } else {
          transformedItems.push(taskItem.create(null, inlineContent.length > 0 ? inlineContent : null));
        }
        transformedItems.push.apply(transformedItems, nestedTaskLists);
      }
    } else if (isSourceTask && isTargetBulletOrOrdered) {
      // Convert task => bullet/ordered
      if (child.type === taskItem) {
        var _inlineContent = (0, _toConsumableArray2.default)(child.content.content);

        // Transfer taskItem's block marks to the paragraph.
        // Use listItem.allowsMarkType since the paragraph will be inside a listItem
        // (which uses ParagraphWithFontSizeStage0 that allows fontSize).
        var paragraphMarks = isBlockTaskEnabled && child.marks.length > 0 ? child.marks.filter(function (mark) {
          return listItem.allowsMarkType(mark.type);
        }) : undefined;
        var paragraphNode = paragraph.create(null, _inlineContent.length > 0 ? _inlineContent : null, paragraphMarks);
        transformedItems.push(listItem.create(null, [paragraphNode]));
      } else if (isBlockTaskEnabled && child.type === blockTaskItem) {
        // blockTaskItem wraps content in paragraphs — extract them directly,
        // preserving their fontSize marks
        var paragraphs = extractParagraphsFromBlockTaskItem(child);
        if (paragraphs.length > 0) {
          transformedItems.push(listItem.create(null, paragraphs));
        }
      } else if (child.type === taskList) {
        var transformedNestedList = _transformListRecursively(_objectSpread(_objectSpread({}, props), {}, {
          listNode: child
        }), onhandleUnsupportedContent);
        var lastItem = transformedItems[transformedItems.length - 1];
        if ((lastItem === null || lastItem === void 0 ? void 0 : lastItem.type) === listItem) {
          // Attach nested list to previous item
          var updatedContent = [].concat((0, _toConsumableArray2.default)(lastItem.content.content), [transformedNestedList]);
          transformedItems[transformedItems.length - 1] = listItem.create(lastItem.attrs, updatedContent);
        } else {
          // No previous item, flatten nested items
          transformedItems.push.apply(transformedItems, (0, _toConsumableArray2.default)(transformedNestedList.content.content));
        }
      }
    } else if (isSourceBulletOrOrdered && isTargetBulletOrOrdered) {
      if (child.type === listItem) {
        var convertedNestedLists = [];
        child.forEach(function (grandChild) {
          if (supportedListTypes.has(grandChild.type) && grandChild.type !== targetNodeType) {
            var convertedNode = _transformListRecursively(_objectSpread(_objectSpread({}, props), {}, {
              listNode: grandChild
            }), onhandleUnsupportedContent);
            convertedNestedLists.push(convertedNode);
          } else {
            convertedNestedLists.push(grandChild);
          }
        });
        transformedItems.push(listItem.create(null, convertedNestedLists));
      }
    }
  });
  return targetNodeType.create(null, transformedItems);
};

/**
 * Transform between different list types
 */
// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
var transformBetweenListTypes = exports.transformBetweenListTypes = function transformBetweenListTypes(context) {
  var tr = context.tr,
    sourceNode = context.sourceNode,
    sourcePos = context.sourcePos,
    targetNodeType = context.targetNodeType;
  var nodes = tr.doc.type.schema.nodes;
  var sourceListType = sourceNode.type;
  var isSourceBulletOrOrdered = (0, _isBulletOrOrderedList.isBulletOrOrderedList)(sourceListType);
  var isTargetTask = (0, _isTaskList.isTaskList)(targetNodeType);
  var isSourceTask = (0, _isTaskList.isTaskList)(sourceListType);
  var isTargetBulletOrOrdered = (0, _isBulletOrOrderedList.isBulletOrOrderedList)(targetNodeType);

  // Check if we need structure transformation
  var needsStructureTransform = isSourceBulletOrOrdered && isTargetTask || isSourceTask && isTargetBulletOrOrdered;
  try {
    if (!needsStructureTransform) {
      // Simple type change for same structure lists (bullet <-> ordered)
      // Apply to the main list
      tr.setNodeMarkup(sourcePos, targetNodeType);

      // Apply to nested lists
      var listStart = sourcePos;
      var listEnd = sourcePos + sourceNode.nodeSize;
      var supportedListTypesSet = (0, _listUtils.getSupportedListTypesSet)(nodes);
      tr.doc.nodesBetween(listStart, listEnd, function (node, pos, parent) {
        // Only process nested lists (not the root list we already handled)
        if (supportedListTypesSet.has(node.type) && pos !== sourcePos) {
          var isNestedList = parent && (supportedListTypesSet.has(parent.type) || parent.type === nodes.listItem);
          if (isNestedList) {
            var shouldTransformNode = node.type === sourceListType || (0, _isBulletOrOrderedList.isBulletOrOrderedList)(node.type) && isTargetBulletOrOrdered;
            if (shouldTransformNode) {
              tr.setNodeMarkup(pos, targetNodeType);
            }
          }
        }
        return true; // Continue traversing
      });
      return tr;
    } else {
      return (0, _transformListStructure.transformListStructure)(context);
    }
  } catch (_unused2) {
    return null;
  }
};

/**
 * Transform selection to task list
 * Handles the special structure where taskItem contains text directly (no paragraph wrapper)
 */
// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
var transformToTaskList = exports.transformToTaskList = function transformToTaskList(tr, range, targetNodeType, targetAttrs, nodes) {
  try {
    var taskItem = nodes.taskItem,
      paragraph = nodes.paragraph,
      blockTaskItem = nodes.blockTaskItem;
    // gating behind platform_editor_small_font_size to support task lists with font size applied,
    // but keep this solution general
    var isBlockTaskItemEnabled = !!blockTaskItem && (0, _expValEquals.expValEquals)('platform_editor_small_font_size', 'isEnabled', true);
    var listItems = [];

    // Process each block in the range
    tr.doc.nodesBetween(range.start, range.end, function (node) {
      if (node.isBlock) {
        var inlineContent = (0, _toConsumableArray2.default)(node.content.content);
        if (inlineContent.length > 0) {
          if (isBlockTaskItemEnabled && node.type === paragraph && node.marks.length > 0) {
            listItems.push((0, _createBlockTaskItem.createBlockTaskItem)({
              attrs: targetAttrs,
              content: inlineContent,
              marks: node.marks,
              schema: tr.doc.type.schema
            }));
          } else {
            listItems.push(taskItem.create(targetAttrs, inlineContent));
          }
        }
      }
      return false;
    });
    if (listItems.length === 0) {
      return null;
    }

    // Create the new task list
    var newList = targetNodeType.create(targetAttrs, listItems);

    // Replace the range with the new list
    tr.replaceWith(range.start, range.end, newList);
    return tr;
  } catch (_unused3) {
    return null;
  }
};
// eslint-disable-next-line @atlaskit/editor/no-re-export

// eslint-disable-next-line @atlaskit/editor/no-re-export

// eslint-disable-next-line @atlaskit/editor/no-re-export

// eslint-disable-next-line @atlaskit/editor/no-re-export

// eslint-disable-next-line @atlaskit/editor/no-re-export