"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _slugid = _interopRequireDefault(require("slugid"));
var _constants = require("../constants");
var _core = require("../../../extension/core");
const PARAGRAPH_TAGS = ['DIV', 'P'];
const listRule = (element, parseChild) => {
  const {
    nodeName,
    childNodes,
    firstChild,
    parentElement
  } = element;
  if (nodeName === 'UL') {
    return {
      id: _slugid.default.nice(),
      type: _constants.UNORDERED_LIST,
      children: parseChild(childNodes)
    };
  }
  if (nodeName === 'OL') {
    return {
      id: _slugid.default.nice(),
      type: _constants.ORDERED_LIST,
      children: parseChild(childNodes)
    };
  }
  if (nodeName === 'LI') {
    const parsedChildren = parseChild(childNodes);
    const normalizedChildren = Array.isArray(parsedChildren) ? parsedChildren : parsedChildren ? [parsedChildren] : [];
    const listItemChildren = [];
    let inlineChildren = [];
    const appendInlineParagraph = () => {
      if (inlineChildren.length === 0) return;
      listItemChildren.push({
        id: _slugid.default.nice(),
        type: _constants.PARAGRAPH,
        children: inlineChildren
      });
      inlineChildren = [];
    };
    normalizedChildren.forEach(child => {
      if (!child) return;
      const isInlineNode = !child.type || _constants.INLINE_LEVEL_TYPES.includes(child.type);
      if (isInlineNode) {
        inlineChildren.push(child);
        return;
      }
      appendInlineParagraph();
      listItemChildren.push(child);
    });
    appendInlineParagraph();
    if (listItemChildren.length === 0) {
      listItemChildren.push({
        id: _slugid.default.nice(),
        type: _constants.PARAGRAPH,
        children: [(0, _core.generateDefaultText)()]
      });
    } else if ([_constants.UNORDERED_LIST, _constants.ORDERED_LIST].includes(listItemChildren[0].type)) {
      // Ensure nested list item content starts with a paragraph.
      listItemChildren.unshift({
        id: _slugid.default.nice(),
        type: _constants.PARAGRAPH,
        children: [(0, _core.generateDefaultText)()]
      });
    }
    return {
      id: _slugid.default.nice(),
      type: _constants.LIST_ITEM,
      children: listItemChildren
    };
  }
  if (PARAGRAPH_TAGS.includes(nodeName) && parentElement && parentElement.nodeName === 'LI') {
    if (Array.from(childNodes).length === 0) {
      return {
        id: _slugid.default.nice(),
        type: _constants.PARAGRAPH,
        children: [(0, _core.generateDefaultText)()]
      };
    }
    return {
      id: _slugid.default.nice(),
      type: _constants.PARAGRAPH,
      children: parseChild(childNodes)
    };
  }
  return;
};
var _default = exports.default = listRule;