"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");
const tableRule = (element, parseChild) => {
  const {
    nodeName,
    childNodes
  } = element;
  if (nodeName === 'TABLE') {
    return {
      id: _slugid.default.nice(),
      type: _constants.TABLE,
      align: [],
      children: parseChild(childNodes)
    };
  }
  if (nodeName === 'THEAD' || nodeName === 'TBODY') {
    return parseChild(childNodes);
  }
  if (nodeName === 'TR' && childNodes.length > 0) {
    // patch
    const children = Array.from(childNodes);
    const hasTdOrTh = children.some(item => item.nodeName === 'TH' || item.nodeName === 'TD');
    if (!hasTdOrTh) return;
    return {
      id: _slugid.default.nice(),
      type: _constants.TABLE_ROW,
      children: parseChild(childNodes)
    };
  }
  if (nodeName === 'TH' || nodeName === 'TD') {
    const children = Array.from(childNodes);
    const cellChildren = children.flatMap(child => {
      // Replace paragraph node with text node
      if (child.nodeName === 'P') {
        const textContent = Array.from(child.childNodes).map(child => child.textContent).join('');
        return {
          id: _slugid.default.nice(),
          type: 'text',
          text: textContent
        };
      }
      return parseChild([child]);
    });
    return {
      id: _slugid.default.nice(),
      type: _constants.TABLE_CELL,
      children: cellChildren
    };
  }
  return;
};
var _default = exports.default = tableRule;