Liferay.Loader.define("commerce-organization-web@4.0.23/js/components/OrgChart", ['module', 'exports', 'require', 'frontend-js-react-web$classnames', 'commerce-organization-web$d3', 'frontend-js-react-web$prop-types', 'frontend-js-react-web$react', '../utils/utils'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;

    var _classnames = _interopRequireDefault(require("frontend-js-react-web$classnames"));

    var _d = require("commerce-organization-web$d3");

    var _propTypes = _interopRequireDefault(require("frontend-js-react-web$prop-types"));

    var _react = _interopRequireWildcard(require("frontend-js-react-web$react"));

    var _utils = require("../utils/utils");

    function _getRequireWildcardCache() {
      if (typeof WeakMap !== "function") return null;var cache = new WeakMap();_getRequireWildcardCache = function _getRequireWildcardCache() {
        return cache;
      };return cache;
    }

    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      }if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
        return { default: obj };
      }var cache = _getRequireWildcardCache();if (cache && cache.has(obj)) {
        return cache.get(obj);
      }var newObj = {};var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;if (desc && (desc.get || desc.set)) {
            Object.defineProperty(newObj, key, desc);
          } else {
            newObj[key] = obj[key];
          }
        }
      }newObj.default = obj;if (cache) {
        cache.set(obj, newObj);
      }return newObj;
    }

    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { default: obj };
    }

    function _typeof(obj) {
      "@babel/helpers - typeof";
      if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function _typeof(obj) {
          return typeof obj;
        };
      } else {
        _typeof = function _typeof(obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
      }return _typeof(obj);
    }

    function _toConsumableArray(arr) {
      return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
    }

    function _nonIterableSpread() {
      throw new TypeError("Invalid attempt to spread non-iterable instance");
    }

    function _iterableToArray(iter) {
      if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
    }

    function _arrayWithoutHoles(arr) {
      if (Array.isArray(arr)) {
        for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
          arr2[i] = arr[i];
        }return arr2;
      }
    }

    function ownKeys(object, enumerableOnly) {
      var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);if (enumerableOnly) symbols = symbols.filter(function (sym) {
          return Object.getOwnPropertyDescriptor(object, sym).enumerable;
        });keys.push.apply(keys, symbols);
      }return keys;
    }

    function _objectSpread(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i] != null ? arguments[i] : {};if (i % 2) {
          ownKeys(Object(source), true).forEach(function (key) {
            _defineProperty(target, key, source[key]);
          });
        } else if (Object.getOwnPropertyDescriptors) {
          Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
        } else {
          ownKeys(Object(source)).forEach(function (key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
          });
        }
      }return target;
    }

    function _defineProperty(obj, key, value) {
      if (key in obj) {
        Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });
      } else {
        obj[key] = value;
      }return obj;
    }

    function _classCallCheck(instance, Constructor) {
      if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
      }
    }

    function _defineProperties(target, props) {
      for (var i = 0; i < props.length; i++) {
        var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
      }
    }

    function _createClass(Constructor, protoProps, staticProps) {
      if (protoProps) _defineProperties(Constructor.prototype, protoProps);if (staticProps) _defineProperties(Constructor, staticProps);return Constructor;
    }

    function _possibleConstructorReturn(self, call) {
      if (call && (_typeof(call) === "object" || typeof call === "function")) {
        return call;
      }return _assertThisInitialized(self);
    }

    function _getPrototypeOf(o) {
      _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
        return o.__proto__ || Object.getPrototypeOf(o);
      };return _getPrototypeOf(o);
    }

    function _assertThisInitialized(self) {
      if (self === void 0) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
      }return self;
    }

    function _inherits(subClass, superClass) {
      if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function");
      }subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });if (superClass) _setPrototypeOf(subClass, superClass);
    }

    function _setPrototypeOf(o, p) {
      _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
        o.__proto__ = p;return o;
      };return _setPrototypeOf(o, p);
    }

    var OrgChart = /*#__PURE__*/function (_Component) {
      _inherits(OrgChart, _Component);

      function OrgChart(props) {
        var _this;

        _classCallCheck(this, OrgChart);

        _this = _possibleConstructorReturn(this, _getPrototypeOf(OrgChart).call(this, props));
        (0, _utils.bindAll)(_assertThisInitialized(_this), 'collapse', 'handleNodeClick', 'updateZoomValue', 'zoomIn', 'zoomOut');
        _this._nodeLabelWidth = 5;
        _this._currentScale = 0.88;
        _this._duration = 400;
        _this._idCount = 0;
        _this._margin = 24;
        _this._nodeCenterOffset = 200;
        _this._nodeDepth = 400;
        _this._nodeHeight = 72;
        _this._nodePadding = 10;
        _this._nodeWidth = 310;
        _this._selectedIdPath = [props];
        _this._svgHeight = '100%';
        _this._svgWidth = '100%';
        return _this;
      }

      _createClass(OrgChart, [{
        key: "shouldComponentUpdate",
        value: function shouldComponentUpdate() {
          return false;
        }
      }, {
        key: "componentDidMount",
        value: function componentDidMount() {
          var _this$props = this.props,
              data = _this$props.data,
              namespace = _this$props.namespace,
              selectedId = _this$props.selectedId;
          this._namespace = namespace.toString();

          if (data) {
            this._svg = this.createSVG();
            this._tree = this.setUpTree();
            this._root = this.setUpRoot(data);
            this.updateChart(this._root);

            var nodes = this._tree(this._root).descendants(),
                selectedNode = nodes.find(function (d) {
              return d.data.organizationId === selectedId;
            });

            this.updateChart(selectedNode);
            setTimeout(function () {
              var orgNodes = document.querySelectorAll('[data-organization-id]'),
                  firstOrgNode = orgNodes[orgNodes.length - 2],
                  mouseEvent = new MouseEvent('click');
              firstOrgNode.dispatchEvent(mouseEvent);
            }, 1000);
          }
        }
      }, {
        key: "render",
        value: function render() {
          var _this2 = this;

          return (/*#__PURE__*/_react.default.createElement("div", {
              className: "org-chart-container"
            }, /*#__PURE__*/_react.default.createElement("div", {
              className: "svg-wrapper"
            }, /*#__PURE__*/_react.default.createElement("svg", {
              ref: function ref(e) {
                _this2.chartSVG = e;
              }
            }, /*#__PURE__*/_react.default.createElement("g", {
              ref: function ref(e) {
                _this2.tree = e;
              }
            }))), /*#__PURE__*/_react.default.createElement("div", {
              className: "controls"
            }, /*#__PURE__*/_react.default.createElement("div", {
              className: "zoom"
            }, /*#__PURE__*/_react.default.createElement("span", {
              className: "zoom-button",
              onClick: this.zoomOut
            }, "\u2013"), /*#__PURE__*/_react.default.createElement("span", {
              className: "zoom-percentage",
              ref: function ref(e) {
                _this2.zoomPercent = e;
              }
            }, '100%'), /*#__PURE__*/_react.default.createElement("span", {
              className: "zoom-button",
              onClick: this.zoomIn
            }, "+"))))
          );
        }
      }, {
        key: "addNewNode",
        value: function addNewNode(newData, parentNode) {
          var newNode = (0, _d.hierarchy)(newData, function (d) {
            return d.children;
          });
          newNode.parent = parentNode;
          newNode.depth = parentNode.depth + 1;

          if (newNode.children) {
            newNode._children = newNode.children.map(function (child) {
              return _objectSpread(_objectSpread({}, child), {}, {
                depth: parentNode.depth + 2
              });
            });
            newNode.children = null;
          }

          if (!(0, _utils.isArray)(parentNode._children)) {
            parentNode._children = [];
          }

          parentNode._children = [].concat(_toConsumableArray(parentNode._children), [newNode]);
        }
      }, {
        key: "collapse",
        value: function collapse(item) {
          if (item.children) {
            item._children = item.children;

            item._children.forEach(this.collapse);

            item.children = null;
          }
        }
      }, {
        key: "createConnectingLine",
        value: function createConnectingLine(s, u, node) {
          var y = u.y + this._nodeWidth,
              isRoot = node.parent && node.parent.data && node.parent.data.name === 'Root';
          return isRoot ? '' : "M ".concat(s.y, " ").concat(s.x, " C ").concat((s.y + y) / 2, " ").concat(s.x, ", ").concat((s.y + y) / 2, " ").concat(u.x, ", ").concat(y, " ").concat(u.x);
        }
      }, {
        key: "createNewNodes",
        value: function createNewNodes(nodeEnter, source) {
          var _this3 = this;

          var gNode = nodeEnter.append('g').lower();
          gNode.attr('class', 'node');
          gNode.attr('transform', function () {
            return _this3.getTranslateString(source.y0, source.x0);
          });
          gNode.attr('data-color-identifier', this.getColorIdentifier);
          gNode.attr('data-organization-id', function (_ref) {
            var data = _ref.data;
            var organizationId = data.organizationId;
            return organizationId;
          });
          gNode.on('click', this.handleNodeClick);
          var rectNode = gNode.append('rect');
          var nodeHeightHalf = this._nodeHeight / 2;
          rectNode.attr('height', this._nodeHeight);
          rectNode.attr('width', this._nodeWidth);
          rectNode.attr('y', -nodeHeightHalf);
          var nodeLabel = gNode.append('line');
          nodeLabel.attr('class', 'node-label');
          nodeLabel.attr('height', this._nodeHeight - 10);
          nodeLabel.attr('width', this._nodeLabelWidth);
          nodeLabel.attr('x1', this._nodePadding);
          nodeLabel.attr('y1', this._nodePadding - nodeHeightHalf);
          nodeLabel.attr('x2', this._nodePadding);
          nodeLabel.attr('y2', nodeHeightHalf - this._nodePadding);
          nodeLabel.attr('stroke', this.getColorIdentifier);
          var nameNode = gNode.append('text'),
              textRight = this._nodePadding + this._nodeLabelWidth + 15;
          nameNode.attr('class', 'name');
          nameNode.attr('x', textRight);
          nameNode.attr('y', function (_ref2) {
            var data = _ref2.data;
            var organizationsTotal = data.organizationsTotal;
            return organizationsTotal ? -5 : 5;
          });
          nameNode.text(function (_ref3) {
            var data = _ref3.data;
            var isRoot = data.name === 'Root';

            if (isRoot) {
              nameNode.node().parentNode.classList.add('root-element');
            }

            return data.name;
          });
          nameNode.each(_utils.truncateTextNode);
          var secondaryInfoNode = gNode.append('text');
          secondaryInfoNode.attr('class', 'secondary-info');
          secondaryInfoNode.attr('x', textRight);
          secondaryInfoNode.attr('y', 16);
          secondaryInfoNode.text(function (_ref4) {
            var data = _ref4.data;
            var organizationsTotal = data.organizationsTotal;

            return organizationsTotal ? "".concat(organizationsTotal, " ").concat((0, _utils.getLocalizedText)('suborganizations')) : '';
          });
          var addButtonNodeGroup = gNode.append('g');
          addButtonNodeGroup.attr('class', 'add-button-node').on('click', function (d) {
            var _ref5 = d.data || {},
                organizationId = _ref5.organizationId,
                addOrganizationButton = document.querySelector("#".concat(_this3._namespace, "addOrganizationButton")),
                mouseEvent = new CustomEvent('click', {
              detail: {
                cmd: 'add',
                organizationId: organizationId
              }
            });

            addOrganizationButton.dispatchEvent(mouseEvent);
          });
          addButtonNodeGroup.append('circle').attr('class', 'add-button-node-circle').attr('r', 15).attr('cx', this._nodeWidth - 10 - 30);
          addButtonNodeGroup.append('text').attr('class', 'add-button-node-plus').attr('x', this._nodeWidth - this._nodePadding - 35).attr('y', nodeHeightHalf * 0.18).text('+');
          return gNode;
        }
      }, {
        key: "createSVG",
        value: function createSVG() {
          var _this4 = this;

          var chartSVG = this.chartSVG;
          var tree = this.tree;
          var height = this._svgHeight;
          var width = this._svgWidth;
          var svg = (0, _d.select)(chartSVG);
          svg.attr('class', 'org-chart');
          svg.attr('height', height);
          svg.attr('viewBox', null);
          svg.attr('width', width);
          var treeNode = (0, _d.select)(tree);
          treeNode.attr('transform', this.getTranslateString(this._margin, this._nodeHeight * 2));
          this._zoom = (0, _d.zoom)().scaleExtent([0.25, 2]).on('zoom', function () {
            return _this4.handleZoom(svg, treeNode);
          });
          this._zoomInterface = (0, _d.select)(chartSVG);

          this._zoomInterface.call(this._zoom);

          return treeNode;
        }
      }, {
        key: "getTranslateString",
        value: function getTranslateString(x, y) {
          return "translate(".concat(x, ", ").concat(y, ")");
        }
      }, {
        key: "handleNodeClick",
        value: function handleNodeClick(d) {
          var _this5 = this;

          var _this$props2 = this.props,
              onNodeClick = _this$props2.onNodeClick,
              requestChildren = _this$props2.requestChildren;
          var _d$data = d.data,
              data = _d$data === void 0 ? {} : _d$data,
              _children = d._children,
              children = d.children;
          var colorIdentifier = data.colorIdentifier,
              lastLevel = data.lastLevel,
              organizationId = data.organizationId;
          var lastActive = this._selectedIdPath[this._selectedIdPath.length - 1] === organizationId;
          this._selectedIdPath = this.setSelectedId(d);
          onNodeClick((0, _utils.isNumber)(organizationId) ? organizationId : undefined, colorIdentifier);

          if (!(children || _children) && !lastLevel) {
            requestChildren(organizationId).then(function (subOrganizations) {
              if ((0, _utils.isArray)(subOrganizations)) {
                subOrganizations.forEach(function (item) {
                  return _this5.addNewNode(item, d);
                });
              }

              _this5.updateChildren(d, lastActive);
            });
          } else {
            this.updateChildren(d, lastActive);
          }
        }
      }, {
        key: "handleNodesEntering",
        value: function handleNodesEntering(node, source) {
          return this.createNewNodes(node.enter(), source);
        }
      }, {
        key: "handleNodesExiting",
        value: function handleNodesExiting(node, source) {
          var _this6 = this;

          var exitNode = node.exit();
          exitNode.transition().duration(this._duration).attr('transform', function () {
            return _this6.getTranslateString(source.y, source.x);
          }).remove();
        }
      }, {
        key: "handleNodesUpdating",
        value: function handleNodesUpdating(nodeEnter, node) {
          var _this7 = this;

          var nodeUpdating = nodeEnter.merge(node);
          var rectNodes = nodeUpdating.selectAll('rect');
          rectNodes.attr('class', function (d) {
            return (0, _classnames.default)('node', {
              highlight: _this7._selectedIdPath[d.depth] === d.data.organizationId,
              selected: _this7._selectedIdPath[_this7._selectedIdPath.length - 1] === d.data.organizationId
            });
          });
          nodeUpdating.transition().duration(this._duration).attr('transform', function (_ref6) {
            var x = _ref6.x,
                y = _ref6.y;
            return _this7.getTranslateString(y, x);
          });
        }
      }, {
        key: "handleZoom",
        value: function handleZoom(svg, g) {
          var k = _d.event.transform.k;
          this._currentScale = k;
          this.updateZoomValue();
          g.attr('transform', _d.event.transform);
        }
      }, {
        key: "setOldPositions",
        value: function setOldPositions(nodes) {
          nodes.forEach(function (d) {
            d.x0 = d.x;
            d.y0 = d.y;
          });
        }
      }, {
        key: "getColorIdentifier",
        value: function getColorIdentifier(d) {
          if (d.data.organizationId) {
            var colorIdentifier = 'colorIdentifier' in d.data ? d.data.colorIdentifier : d.parent.data.colorIdentifier;
            d.data['colorIdentifier'] = colorIdentifier;
            return colorIdentifier;
          }

          return '';
        }
      }, {
        key: "setSelectedId",
        value: function setSelectedId(node) {
          var arr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
          var parent = node.parent;

          if (parent) {
            arr = this.setSelectedId(parent, arr);
          }

          return [].concat(_toConsumableArray(arr), [node.data.organizationId]);
        }
      }, {
        key: "setUpRoot",
        value: function setUpRoot(data) {
          var root = (0, _d.hierarchy)(data, function (d) {
            return d.organizations;
          });
          var _this$chartSVG = this.chartSVG,
              clientHeight = _this$chartSVG.clientHeight,
              clientWidth = _this$chartSVG.clientWidth;
          root.x0 = clientHeight / 2;
          root.y0 = clientWidth / 2 - this._nodeCenterOffset - this._nodeWidth * 3;
          return root;
        }
      }, {
        key: "setUpTree",
        value: function setUpTree() {
          return (0, _d.tree)().nodeSize([this._nodeHeight + this._margin, this._nodeWidth]);
        }
      }, {
        key: "updateChart",
        value: function updateChart(source) {
          var _this8 = this;

          var treeData = this._tree(this._root);

          var nodes = treeData.descendants();
          nodes.forEach(function (d) {
            d.y = d.depth * _this8._nodeDepth;
          });

          var gNodes = this._svg.selectAll('g.node').data(nodes, function (d) {
            if (d.id) {
              d.id = ++_this8._idCount;
              return d.id;
            }
          });

          var nodeEnter = this.handleNodesEntering(gNodes, source);
          this.handleNodesUpdating(nodeEnter, gNodes);
          this.handleNodesExiting(gNodes, source);
          this.updateLinks(source, treeData);
          this.setOldPositions(nodes);
          this.updateTransform(source);
        }
      }, {
        key: "updateChildren",
        value: function updateChildren(d, collapse) {
          if (d.children && collapse) {
            d._children = d.children;
            d.children = null;
          } else if (d._children) {
            d.children = d._children;
            d._children = null;
          }

          this.updateChart(d);
        }
      }, {
        key: "updateLinks",
        value: function updateLinks(source, treeData) {
          var _this9 = this;

          var links = treeData.descendants().slice(1);

          var linkNodes = this._svg.selectAll('path.link').data(links, function (d) {
            return d.id;
          });

          var gNode = linkNodes.enter().insert('path', 'g');
          gNode.attr('d', function (d) {
            var o = {
              x: source.x0,
              y: source.y0
            };
            return _this9.createConnectingLine(o, o, d);
          });
          var linkUpdate = gNode.merge(linkNodes);
          linkUpdate.attr('class', function (d) {
            return (0, _classnames.default)('link', {
              highlight: _this9._selectedIdPath[d.depth] === d.data.organizationId
            });
          });
          linkUpdate.transition().duration(this._duration).attr('d', function (d) {
            return _this9.createConnectingLine(d, d.parent, d);
          });
          var exitNode = linkNodes.exit();
          exitNode.transition().duration(this._duration).attr('d', function (d) {
            var o = {
              x: source.x,
              y: source.y
            };
            return _this9.createConnectingLine(o, o, d);
          });
          exitNode.remove();
        }
      }, {
        key: "updateTransform",
        value: function updateTransform(source) {
          var _this$chartSVG$getBou = this.chartSVG.getBoundingClientRect(),
              height = _this$chartSVG$getBou.height,
              width = _this$chartSVG$getBou.width;

          var k = this._currentScale;
          var offset = this._nodeCenterOffset + this._nodeWidth;
          var y0 = source.y0;

          if (!source.children && source.parent) {
            y0 = source.parent.y0;
          }

          var x = -(y0 + offset) * k + width / 2;
          var y = -source.x0 * k + (height / 2 - 20);

          this._svg.transition().duration(this._duration).attr('transform', "".concat(this.getTranslateString(x, y), " scale(").concat(k, ")"));

          this._zoomInterface.transition().duration(this._duration).call(this._zoom.transform, _d.zoomIdentity.translate(x, y).scale(k));
        }
      }, {
        key: "updateZoomValue",
        value: function updateZoomValue() {
          this.zoomPercent.innerHTML = "".concat(Math.round(this._currentScale * 100), "%");
        }
      }, {
        key: "zoomIn",
        value: function zoomIn() {
          this._zoomInterface.transition().duration(this._duration).call(this._zoom.scaleBy, 2);
        }
      }, {
        key: "zoomOut",
        value: function zoomOut() {
          this._zoomInterface.transition().duration(this._duration).call(this._zoom.scaleBy, 0.5);
        }
      }]);

      return OrgChart;
    }(_react.Component);

    OrgChart.defaultProps = {
      data: {},
      requestChildren: _utils.noop
    };
    var _default = OrgChart;
    exports.default = _default;
    //# sourceMappingURL=OrgChart.js.map
  }
});
//# sourceMappingURL=OrgChart.js.map