'use strict';

exports.__esModule = true;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _events = require('events');

var _events2 = _interopRequireDefault(_events);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _clusterize = require('clusterize.js');

var _clusterize2 = _interopRequireDefault(_clusterize);

var _elementClass = require('element-class');

var _elementClass2 = _interopRequireDefault(_elementClass);

var _isDom = require('is-dom');

var _isDom2 = _interopRequireDefault(_isDom);

var _flattree = require('flattree');

var _lookupTable = require('./lookup-table');

var _lookupTable2 = _interopRequireDefault(_lookupTable);

var _renderer = require('./renderer');

var _domEvents = require('./dom-events');

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

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

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

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

var error = function error() {
    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
    }

    if (console && console.error) {
        var prefix = '[InfiniteTree]';
        console.error.apply(console, [prefix].concat(args));
    }
};

var ensureNodeInstance = function ensureNodeInstance(node) {
    if (!node) {
        // undefined or null
        return false;
    }
    if (!(node instanceof _flattree.Node)) {
        error('The node must be a Node object.');
        return false;
    }
    return true;
};

var createRootNode = function createRootNode(rootNode) {
    return Object.assign(rootNode || new _flattree.Node(), {
        parent: null,
        children: [],
        state: {
            depth: -1,
            open: true, // always open
            path: '',
            prefixMask: '',
            total: 0
        }
    });
};

var InfiniteTree = function (_events$EventEmitter) {
    _inherits(InfiniteTree, _events$EventEmitter);

    // Creates new InfiniteTree object.
    function InfiniteTree(el, options) {
        _classCallCheck(this, InfiniteTree);

        var _this = _possibleConstructorReturn(this, _events$EventEmitter.call(this));

        _this.options = {
            autoOpen: false,
            droppable: false,
            el: null,
            layout: 'div',
            loadNodes: null,
            noDataClass: 'infinite-tree-no-data',
            noDataText: 'No data',
            nodeIdAttr: 'data-id',
            rowRenderer: _renderer.defaultRowRenderer,
            selectable: true,
            shouldSelectNode: null,
            togglerClass: 'infinite-tree-toggler'
        };
        _this.state = {
            openNodes: [],
            rootNode: createRootNode(),
            selectedNode: null
        };
        _this.clusterize = null;
        _this.nodeTable = new _lookupTable2['default']();
        _this.nodes = [];
        _this.rows = [];
        _this.scrollElement = null;
        _this.contentElement = null;
        _this.draggableTarget = null;
        _this.droppableTarget = null;
        _this.contentListener = {
            'click': function click(event) {
                event = event || window.event;

                // Wrap stopPropagation that allows click event handler to stop execution
                // by setting the cancelBubble property
                var stopPropagation = event.stopPropagation;
                event.stopPropagation = function () {
                    // Setting the cancelBubble property in browsers that don't support it doesn't hurt.
                    // Of course it doesn't actually cancel the bubbling, but the assignment itself is safe.
                    event.cancelBubble = true;

                    if (stopPropagation) {
                        stopPropagation.call(event);
                    }
                };

                // Call setTimeout(fn, 0) to re-queues the execution of subsequent calls, it allows the
                // click event to bubble up to higher level event handlers before handling tree events.
                setTimeout(function () {
                    // Stop execution if the cancelBubble property is set to true by higher level event handlers
                    if (event.cancelBubble === true) {
                        return;
                    }

                    // Emit a "click" event
                    _this.emit('click', event);

                    // Stop execution if the cancelBubble property is set to true after emitting the click event
                    if (event.cancelBubble === true) {
                        return;
                    }

                    var itemTarget = null;
                    var clickToggler = false;

                    if (event.target) {
                        itemTarget = event.target !== event.currentTarget ? event.target : null;
                    } else if (event.srcElement) {
                        // IE8
                        itemTarget = event.srcElement;
                    }

                    while (itemTarget && itemTarget.parentElement !== _this.contentElement) {
                        if ((0, _elementClass2['default'])(itemTarget).has(_this.options.togglerClass)) {
                            clickToggler = true;
                        }
                        itemTarget = itemTarget.parentElement;
                    }

                    if (!itemTarget || itemTarget.hasAttribute('disabled')) {
                        return;
                    }

                    var id = itemTarget.getAttribute(_this.options.nodeIdAttr);
                    var node = _this.getNodeById(id);
                    if (!node) {
                        return;
                    }

                    // Click on the toggler to open/close a tree node
                    if (clickToggler) {
                        _this.toggleNode(node);
                        return;
                    }

                    _this.selectNode(node); // selectNode will re-render the tree
                }, 0);
            },
            'dblclick': function dblclick(event) {
                // Emit a "doubleClick" event
                _this.emit('doubleClick', event);
            },
            // https://developer.mozilla.org/en-US/docs/Web/Events/dragstart
            // The dragstart event is fired when the user starts dragging an element or text selection.
            'dragstart': function dragstart(event) {
                event = event || window.event;

                _this.draggableTarget = event.target || event.srcElement;
            },
            // https://developer.mozilla.org/en-US/docs/Web/Events/dragend
            // The dragend event is fired when a drag operation is being ended (by releasing a mouse button or hitting the escape key).
            'dragend': function dragend(event) {
                event = event || window.event;

                var _this$options$droppab = _this.options.droppable.hoverClass;
                var hoverClass = _this$options$droppab === undefined ? '' : _this$options$droppab;

                // Draggable

                _this.draggableTarget = null;

                // Droppable
                if (_this.droppableTarget) {
                    (0, _elementClass2['default'])(_this.droppableTarget).remove(hoverClass);
                    _this.droppableTarget = null;
                }
            },
            // https://developer.mozilla.org/en-US/docs/Web/Events/dragenter
            // The dragenter event is fired when a dragged element or text selection enters a valid drop target.
            'dragenter': function dragenter(event) {
                event = event || window.event;

                var itemTarget = null;

                if (event.target) {
                    itemTarget = event.target !== event.currentTarget ? event.target : null;
                } else if (event.srcElement) {
                    // IE8
                    itemTarget = event.srcElement;
                }

                while (itemTarget && itemTarget.parentElement !== _this.contentElement) {
                    itemTarget = itemTarget.parentElement;
                }

                if (!itemTarget) {
                    return;
                }

                if (_this.droppableTarget === itemTarget) {
                    return;
                }

                var _this$options$droppab2 = _this.options.droppable;
                var accept = _this$options$droppab2.accept;
                var _this$options$droppab3 = _this$options$droppab2.hoverClass;
                var hoverClass = _this$options$droppab3 === undefined ? '' : _this$options$droppab3;


                (0, _elementClass2['default'])(_this.droppableTarget).remove(hoverClass);
                _this.droppableTarget = null;

                var canDrop = true; // Defaults to true

                if (typeof accept === 'function') {
                    var id = itemTarget.getAttribute(_this.options.nodeIdAttr);
                    var node = _this.getNodeById(id);

                    canDrop = !!accept.call(_this, event, {
                        type: 'dragenter',
                        draggableTarget: _this.draggableTarget,
                        droppableTarget: itemTarget,
                        node: node
                    });
                }

                if (canDrop) {
                    (0, _elementClass2['default'])(itemTarget).add(hoverClass);
                    _this.droppableTarget = itemTarget;
                }
            },
            // https://developer.mozilla.org/en-US/docs/Web/Events/dragover
            // The dragover event is fired when an element or text selection is being dragged over a valid drop target (every few hundred milliseconds).
            'dragover': function dragover(event) {
                event = event || window.event;

                (0, _domEvents.preventDefault)(event);
            },
            // https://developer.mozilla.org/en-US/docs/Web/Events/drop
            // The drop event is fired when an element or text selection is dropped on a valid drop target.
            'drop': function drop(event) {
                event = event || window.event;

                // prevent default action (open as link for some elements)
                (0, _domEvents.preventDefault)(event);

                if (!(_this.draggableTarget && _this.droppableTarget)) {
                    return;
                }

                var _this$options$droppab4 = _this.options.droppable;
                var accept = _this$options$droppab4.accept;
                var drop = _this$options$droppab4.drop;
                var _this$options$droppab5 = _this$options$droppab4.hoverClass;
                var hoverClass = _this$options$droppab5 === undefined ? '' : _this$options$droppab5;

                var id = _this.droppableTarget.getAttribute(_this.options.nodeIdAttr);
                var node = _this.getNodeById(id);

                var canDrop = true; // Defaults to true

                if (typeof accept === 'function') {
                    canDrop = !!accept.call(_this, event, {
                        type: 'drop',
                        draggableTarget: _this.draggableTarget,
                        droppableTarget: _this.droppableTarget,
                        node: node
                    });
                }

                if (canDrop && typeof drop === 'function') {
                    drop.call(_this, event, {
                        draggableTarget: _this.draggableTarget,
                        droppableTarget: _this.droppableTarget,
                        node: node
                    });
                }

                (0, _elementClass2['default'])(_this.droppableTarget).remove(hoverClass);
                _this.droppableTarget = null;
            }
        };


        if ((0, _isDom2['default'])(el)) {
            options = _extends({}, options, { el: el });
        } else {
            options = el;
        }

        // Assign options
        _this.options = _extends({}, _this.options, options);

        if (!_this.options.el) {
            console.error('Failed to initialize infinite-tree: el is not specified.', options);
            return _possibleConstructorReturn(_this);
        }

        _this.create();

        // Load tree data if it's provided
        if (options.data) {
            _this.loadData(options.data);
        }
        return _this;
    }

    InfiniteTree.prototype.create = function create() {
        var _this2 = this;

        if (!this.options.el) {
            error('The element option is not specified.');
        }

        var tag = null;

        this.scrollElement = document.createElement('div');

        if (this.options.layout === 'table') {
            var tableElement = document.createElement('table');
            tableElement.className = (0, _classnames2['default'])('infinite-tree', 'infinite-tree-table');
            var contentElement = document.createElement('tbody');
            tableElement.appendChild(contentElement);
            this.scrollElement.appendChild(tableElement);
            this.contentElement = contentElement;

            // The tag name for supporting elements
            tag = 'tr';
        } else {
            var _contentElement = document.createElement('div');
            this.scrollElement.appendChild(_contentElement);
            this.contentElement = _contentElement;

            // The tag name for supporting elements
            tag = 'div';
        }

        this.scrollElement.className = (0, _classnames2['default'])('infinite-tree', 'infinite-tree-scroll');
        this.contentElement.className = (0, _classnames2['default'])('infinite-tree', 'infinite-tree-content');

        this.options.el.appendChild(this.scrollElement);

        this.clusterize = new _clusterize2['default']({
            tag: tag,
            rows: [],
            scrollElem: this.scrollElement,
            contentElem: this.contentElement,
            no_data_text: this.options.noDataText,
            no_data_class: this.options.noDataClass,
            callbacks: {
                clusterWillChange: function clusterWillChange() {
                    _this2.emit('clusterWillChange');
                },
                clusterChanged: function clusterChanged() {
                    _this2.emit('clusterDidChange');
                }
            }
        });

        (0, _domEvents.addEventListener)(this.contentElement, 'click', this.contentListener.click);
        (0, _domEvents.addEventListener)(this.contentElement, 'dblclick', this.contentListener.dblclick);

        if (this.options.droppable) {
            (0, _domEvents.addEventListener)(document, 'dragstart', this.contentListener.dragstart);
            (0, _domEvents.addEventListener)(document, 'dragend', this.contentListener.dragend);
            (0, _domEvents.addEventListener)(this.contentElement, 'dragenter', this.contentListener.dragenter);
            (0, _domEvents.addEventListener)(this.contentElement, 'dragleave', this.contentListener.dragleave);
            (0, _domEvents.addEventListener)(this.contentElement, 'dragover', this.contentListener.dragover);
            (0, _domEvents.addEventListener)(this.contentElement, 'drop', this.contentListener.drop);
        }
    };

    InfiniteTree.prototype.destroy = function destroy() {
        (0, _domEvents.removeEventListener)(this.contentElement, 'click', this.contentListener);
        if (this.options.droppable) {
            (0, _domEvents.removeEventListener)(document, 'dragstart', this.contentListener.dragstart);
            (0, _domEvents.removeEventListener)(document, 'dragend', this.contentListener.dragend);
            (0, _domEvents.removeEventListener)(this.contentElement, 'dragenter', this.contentListener.dragenter);
            (0, _domEvents.removeEventListener)(this.contentElement, 'dragleave', this.contentListener.dragleave);
            (0, _domEvents.removeEventListener)(this.contentElement, 'dragover', this.contentListener.dragover);
            (0, _domEvents.removeEventListener)(this.contentElement, 'drop', this.contentListener.drop);
        }

        this.clear();

        if (this.clusterize) {
            this.clusterize.destroy(true); // True to remove all data from the list
            this.clusterize = null;
        }

        // Remove all child nodes
        while (this.contentElement.firstChild) {
            this.contentElement.removeChild(this.contentElement.firstChild);
        }
        while (this.scrollElement.firstChild) {
            this.scrollElement.removeChild(this.scrollElement.firstChild);
        }
        if (this.options.el) {
            var containerElement = this.options.el;
            while (containerElement.firstChild) {
                containerElement.removeChild(containerElement.firstChild);
            }
        }
        this.contentElement = null;
        this.scrollElement = null;
    };
    // Adds an array of new child nodes to a parent node at the specified index.
    // * If the parent is null or undefined, inserts new childs at the specified index in the top-level.
    // * If the parent has children, the method adds the new child to it at the specified index.
    // * If the parent does not have children, the method adds the new child to the parent.
    // * If the index value is greater than or equal to the number of children in the parent, the method adds the child at the end of the children.
    // @param {Array} newNodes An array of new child nodes.
    // @param {number} [index] The 0-based index of where to insert the child node.
    // @param {Node} parentNode The Node object that defines the parent node.
    // @return {boolean} Returns true on success, false otherwise.


    InfiniteTree.prototype.addChildNodes = function addChildNodes(newNodes, index, parentNode) {
        var _this3 = this;

        newNodes = [].concat(newNodes || []); // Ensure array
        if (newNodes.length === 0) {
            return false;
        }

        if ((typeof index === 'undefined' ? 'undefined' : _typeof(index)) === 'object') {
            // The 'object' type might be Node or null
            parentNode = index || this.state.rootNode; // Defaults to rootNode if not specified
            index = parentNode.children.length;
        } else {
            parentNode = parentNode || this.state.rootNode; // Defaults to rootNode if not specified
        }

        if (!ensureNodeInstance(parentNode)) {
            return false;
        }

        if (typeof index !== 'number') {
            index = parentNode.children.length;
        }

        // Assign parent
        newNodes.forEach(function (newNode) {
            newNode.parent = parentNode;
        });

        // Insert new child node at the specified index
        parentNode.children.splice.apply(parentNode.children, [index, 0].concat(newNodes));

        // Get the index of the first new node within the array of child nodes
        index = parentNode.children.indexOf(newNodes[0]);

        var deleteCount = parentNode.state.total;
        var nodes = (0, _flattree.flatten)(parentNode.children, { openNodes: this.state.openNodes });
        var rows = nodes.map(function (node) {
            return _this3.options.rowRenderer(node, _this3.options);
        });

        if (parentNode === this.state.rootNode) {
            this.nodes = nodes;
            this.rows = rows;
        } else {
            var parentOffset = this.nodes.indexOf(parentNode);
            if (parentOffset >= 0) {
                // Update nodes & rows
                this.nodes.splice.apply(this.nodes, [parentOffset + 1, deleteCount].concat(nodes));
                this.rows.splice.apply(this.rows, [parentOffset + 1, deleteCount].concat(rows));

                // Update the row corresponding to the parent node
                this.rows[parentOffset] = this.options.rowRenderer(parentNode, this.options);
            }
        }

        // Update the lookup table with newly added nodes
        parentNode.children.slice(index).forEach(function (childNode) {
            _this3.flattenNode(childNode).forEach(function (node) {
                if (node.id !== undefined) {
                    _this3.nodeTable.set(node.id, node);
                }
            });
        });

        // Updates list with new data
        this.update();

        return true;
    };
    // Adds a new child node to the end of the list of children of a specified parent node.
    // * If the parent is null or undefined, inserts the child at the specified index in the top-level.
    // * If the parent has children, the method adds the child as the last child.
    // * If the parent does not have children, the method adds the child to the parent.
    // @param {object} newNode The new child node.
    // @param {Node} parentNode The Node object that defines the parent node.
    // @return {boolean} Returns true on success, false otherwise.


    InfiniteTree.prototype.appendChildNode = function appendChildNode(newNode, parentNode) {
        // Defaults to rootNode if the parentNode is not specified
        parentNode = parentNode || this.state.rootNode;

        if (!ensureNodeInstance(parentNode)) {
            return false;
        }

        var index = parentNode.children.length;
        var newNodes = [].concat(newNode || []); // Ensure array
        return this.addChildNodes(newNodes, index, parentNode);
    };
    // Clears the tree.


    InfiniteTree.prototype.clear = function clear() {
        this.clusterize.clear();
        this.nodeTable.clear();
        this.nodes = [];
        this.rows = [];
        this.state.openNodes = [];
        this.state.rootNode = createRootNode(this.state.rootNode);
        this.state.selectedNode = null;
    };
    // Closes a node to hide its children.
    // @param {Node} node The Node object.
    // @param {object} [options] The options object.
    // @param {boolean} [options.silent] Pass true to prevent "closeNode" and "selectNode" events from being triggered.
    // @return {boolean} Returns true on success, false otherwise.


    InfiniteTree.prototype.closeNode = function closeNode(node, options) {
        var _options = _extends({}, options);

        var _options$silent = _options.silent;
        var silent = _options$silent === undefined ? false : _options$silent;


        if (!ensureNodeInstance(node)) {
            return false;
        }

        // Retrieve node index
        var nodeIndex = this.nodes.indexOf(node);
        if (nodeIndex < 0) {
            error('Invalid node index');
            return false;
        }

        // Check if the closeNode action can be performed
        if (this.state.openNodes.indexOf(node) < 0) {
            return false;
        }

        // Keep selected node unchanged if "node" is equal to "this.state.selectedNode"
        if (this.state.selectedNode && this.state.selectedNode !== node) {
            // row #0 - node.0         => parent node (total=4)
            // row #1   - node.0.0     => close this node; next selected node (total=2)
            // row #2       node.0.0.0 => selected node (total=0)
            // row #3       node.0.0.1
            // row #4     node.0.1
            var selectedIndex = this.nodes.indexOf(this.state.selectedNode);
            var rangeFrom = nodeIndex + 1;
            var rangeTo = nodeIndex + node.state.total;

            if (rangeFrom <= selectedIndex && selectedIndex <= rangeTo) {
                this.selectNode(node, options);
            }
        }

        node.state.open = false; // Set the open state to false
        var openNodes = this.state.openNodes.filter(function (node) {
            return node.hasChildren() && node.state.open;
        });
        this.state.openNodes = openNodes;

        var deleteCount = node.state.total;

        // Subtract the deleteCount for all ancestors (parent, grandparent, etc.) of the current node
        for (var p = node; p !== null; p = p.parent) {
            p.state.total = p.state.total - deleteCount;
        }

        // Update nodes & rows
        this.nodes.splice(nodeIndex + 1, deleteCount);
        this.rows.splice(nodeIndex + 1, deleteCount);

        // Update the row corresponding to the node
        this.rows[nodeIndex] = this.options.rowRenderer(node, this.options);

        if (!silent) {
            // Emit a "closeNode" event
            this.emit('closeNode', node);
        }

        // Updates list with new data
        this.update();

        return true;
    };
    // Flattens all child nodes of a parent node by performing full tree traversal using child-parent link.
    // No recursion or stack is involved.
    // @param {Node} parentNode The Node object that defines the parent node.
    // @return {array} Returns an array of Node objects containing all the child nodes of the parent node.


    InfiniteTree.prototype.flattenChildNodes = function flattenChildNodes(parentNode) {
        // Defaults to rootNode if the parentNode is not specified
        parentNode = parentNode || this.state.rootNode;

        if (!ensureNodeInstance(parentNode)) {
            return [];
        }

        var list = [];
        var node = parentNode.getFirstChild(); // Ignore parent node
        while (node) {
            list.push(node);
            if (node.hasChildren()) {
                node = node.getFirstChild();
            } else {
                // Find the parent level
                while (node.getNextSibling() === null && node.parent !== parentNode) {
                    // Use child-parent link to get to the parent level
                    node = node.getParent();
                }

                // Get next sibling
                node = node.getNextSibling();
            }
        }

        return list;
    };
    // Flattens a node by performing full tree traversal using child-parent link.
    // No recursion or stack is involved.
    // @param {Node} node The Node object.
    // @return {array} Returns a flattened list of Node objects.


    InfiniteTree.prototype.flattenNode = function flattenNode(node) {
        if (!ensureNodeInstance(node)) {
            return [];
        }

        return [node].concat(this.flattenChildNodes(node));
    };
    // Gets a list of child nodes.
    // @param {Node} [parentNode] The Node object that defines the parent node. If null or undefined, returns a list of top level nodes.
    // @return {array} Returns an array of Node objects containing all the child nodes of the parent node.


    InfiniteTree.prototype.getChildNodes = function getChildNodes(parentNode) {
        // Defaults to rootNode if the parentNode is not specified
        parentNode = parentNode || this.state.rootNode;

        if (!ensureNodeInstance(parentNode)) {
            return [];
        }

        return parentNode.children;
    };
    // Gets a node by its unique id. This assumes that you have given the nodes in the data a unique id.
    // @param {string|number} id An unique node id. A null value will be returned if the id doesn't match.
    // @return {Node} Returns a node the matches the id, null otherwise.


    InfiniteTree.prototype.getNodeById = function getNodeById(id) {
        var node = this.nodeTable.get(id);
        if (!node) {
            // Find the first node that matches the id
            node = this.nodes.filter(function (node) {
                return node.id === id;
            })[0];
            if (!node) {
                return null;
            }
            this.nodeTable.set(node.id, node);
        }
        return node;
    };
    // Gets an array of open nodes.
    // @return {array} Returns an array of Node objects containing open nodes.


    InfiniteTree.prototype.getOpenNodes = function getOpenNodes() {
        // returns a shallow copy of an array into a new array object.
        return this.state.openNodes.slice();
    };
    // Gets the root node.
    // @return {Node} Returns the root node, or null if empty.


    InfiniteTree.prototype.getRootNode = function getRootNode() {
        return this.state.rootNode;
    };
    // Gets the selected node.
    // @return {Node} Returns the selected node, or null if not selected.


    InfiniteTree.prototype.getSelectedNode = function getSelectedNode() {
        return this.state.selectedNode;
    };
    // Inserts the specified node after the reference node.
    // @param {object} newNode The new sibling node.
    // @param {Node} referenceNode The Node object that defines the reference node.
    // @return {boolean} Returns true on success, false otherwise.


    InfiniteTree.prototype.insertNodeAfter = function insertNodeAfter(newNode, referenceNode) {
        if (!ensureNodeInstance(referenceNode)) {
            return false;
        }

        var parentNode = referenceNode.getParent();
        var index = parentNode.children.indexOf(referenceNode) + 1;
        var newNodes = [].concat(newNode || []); // Ensure array

        return this.addChildNodes(newNodes, index, parentNode);
    };
    // Inserts the specified node before the reference node.
    // @param {object} newNode The new sibling node.
    // @param {Node} referenceNode The Node object that defines the reference node.
    // @return {boolean} Returns true on success, false otherwise.


    InfiniteTree.prototype.insertNodeBefore = function insertNodeBefore(newNode, referenceNode) {
        if (!ensureNodeInstance(referenceNode)) {
            return false;
        }

        var parentNode = referenceNode.getParent();
        var index = parentNode.children.indexOf(referenceNode);
        var newNodes = [].concat(newNode || []); // Ensure array

        return this.addChildNodes(newNodes, index, parentNode);
    };
    // Loads data in the tree.
    // @param {object|array} data The data is an object or array of objects that defines the node.


    InfiniteTree.prototype.loadData = function loadData() {
        var _this4 = this;

        var data = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0];

        this.nodes = (0, _flattree.flatten)(data, { openAllNodes: this.options.autoOpen });

        // Clear lookup table
        this.nodeTable.clear();

        this.state.openNodes = this.nodes.filter(function (node) {
            return node.hasChildren() && node.state.open;
        });
        this.state.selectedNode = null;

        var rootNode = function () {
            var node = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0];

            // Finding the root node
            while (node && node.parent !== null) {
                node = node.parent;
            }
            return node;
        }(this.nodes.length > 0 ? this.nodes[0] : null);

        this.state.rootNode = rootNode || createRootNode(this.state.rootNode); // Create a new root node if rootNode is null

        // Update the lookup table with newly added nodes
        this.flattenChildNodes(this.state.rootNode).forEach(function (node) {
            if (node.id !== undefined) {
                _this4.nodeTable.set(node.id, node);
            }
        });

        // Update rows
        this.rows = this.nodes.map(function (node) {
            return _this4.options.rowRenderer(node, _this4.options);
        });

        // Updates list with new data
        this.update();
    };
    // Opens a node to display its children.
    // @param {Node} node The Node object.
    // @param {object} [options] The options object.
    // @param {boolean} [options.silent] Pass true to prevent "openNode" event from being triggered.
    // @return {boolean} Returns true on success, false otherwise.


    InfiniteTree.prototype.openNode = function openNode(node, options) {
        var _this5 = this;

        var _options2 = _extends({}, options);

        var _options2$silent = _options2.silent;
        var silent = _options2$silent === undefined ? false : _options2$silent;


        if (!ensureNodeInstance(node)) {
            return false;
        }

        // Retrieve node index
        var nodeIndex = this.nodes.indexOf(node);
        if (nodeIndex < 0) {
            error('Invalid node index');
            return false;
        }

        // Check if the openNode action can be performed
        if (this.state.openNodes.indexOf(node) >= 0) {
            return false;
        }

        if (!node.hasChildren() && node.loadOnDemand) {
            if (typeof this.options.loadNodes !== 'function') {
                return false;
            }

            // Reentrancy not allowed
            if (node.state.loading === true) {
                return false;
            }

            // Set loading state to true
            node.state.loading = true;
            this.rows[nodeIndex] = this.options.rowRenderer(node, this.options);

            // Updates list with new data
            this.update();

            this.options.loadNodes(node, function (err, nodes) {
                // Set loading state to false
                node.state.loading = false;
                _this5.rows[nodeIndex] = _this5.options.rowRenderer(node, _this5.options);

                // Updates list with new data
                _this5.update();

                if (err) {
                    return;
                }
                if (!nodes) {
                    return;
                }

                nodes = [].concat(nodes || []); // Ensure array
                if (nodes.length === 0) {
                    return;
                }

                // Append child nodes
                nodes.forEach(function (childNode) {
                    _this5.appendChildNode(childNode, node);
                });

                // Ensure the node has children to prevent from infinite loop
                if (node.hasChildren()) {
                    // Call openNode again
                    _this5.openNode(node, options);
                }
            });

            return true;
        }

        node.state.open = true; // Set node.state.open to true
        var openNodes = [node].concat(this.state.openNodes); // the most recently used items first
        this.state.openNodes = openNodes;

        var nodes = (0, _flattree.flatten)(node.children, { openNodes: this.state.openNodes });
        var rows = nodes.map(function (node) {
            return _this5.options.rowRenderer(node, _this5.options);
        });

        // Update nodes & rows
        this.nodes.splice.apply(this.nodes, [nodeIndex + 1, 0].concat(nodes));
        this.rows.splice.apply(this.rows, [nodeIndex + 1, 0].concat(rows));

        // Update the row corresponding to the node
        this.rows[nodeIndex] = this.options.rowRenderer(node, this.options);

        // Add all child nodes to the lookup table if the first child does not exist in the lookup table
        if (nodes.length > 0 && !this.nodeTable.get(nodes[0])) {
            nodes.forEach(function (node) {
                if (node.id !== undefined) {
                    _this5.nodeTable.set(node.id, node);
                }
            });
        }

        if (!silent) {
            // Emit a "openNode" event
            this.emit('openNode', node);
        }

        // Updates list with new data
        this.update();

        return true;
    };
    // Removes all child nodes from a parent node.
    // @param {Node} parentNode The Node object that defines the parent node.
    // @param {object} [options] The options object.
    // @param {boolean} [options.silent] Pass true to prevent "selectNode" event from being triggered.
    // @return {boolean} Returns true on success, false otherwise.


    InfiniteTree.prototype.removeChildNodes = function removeChildNodes(parentNode, options) {
        var _this6 = this;

        if (!ensureNodeInstance(parentNode)) {
            return false;
        }

        if (parentNode.children.length === 0) {
            return false;
        }
        if (parentNode === this.state.rootNode) {
            this.clear();
            return true;
        }

        var parentNodeIndex = this.nodes.indexOf(parentNode);

        // Update selected node
        if (parentNodeIndex >= 0 && this.state.selectedNode) {
            // row #0 - node.0         => parent node (total=4)
            // row #1   - node.0.0
            // row #2       node.0.0.0 => current selected node
            // row #3       node.0.0.1
            // row #4     node.0.1
            var selectedIndex = this.nodes.indexOf(this.state.selectedNode);
            var rangeFrom = parentNodeIndex + 1;
            var rangeTo = parentNodeIndex + parentNode.state.total;

            if (rangeFrom <= selectedIndex && selectedIndex <= rangeTo) {
                if (parentNode === this.state.rootNode) {
                    this.selectNode(null, options);
                } else {
                    this.selectNode(parentNode, options);
                }
            }
        }

        // Get the nodes being removed
        var removedNodes = this.flattenChildNodes(parentNode);

        // Get the number of nodes to be removed
        var deleteCount = parentNode.state.total;

        // Subtract the deleteCount for all ancestors (parent, grandparent, etc.) of the current node
        for (var p = parentNode; p !== null; p = p.parent) {
            p.state.total = p.state.total - deleteCount;
        }

        // Update parent node
        parentNode.children = [];
        parentNode.state.open = parentNode.state.open && parentNode.children.length > 0;

        if (parentNodeIndex >= 0) {
            // Update nodes & rows
            this.nodes.splice(parentNodeIndex + 1, deleteCount);
            this.rows.splice(parentNodeIndex + 1, deleteCount);

            // Update the row corresponding to the parent node
            this.rows[parentNodeIndex] = this.options.rowRenderer(parentNode, this.options);
        }

        {
            // Update open nodes and lookup table
            this.state.openNodes = this.state.openNodes.filter(function (node) {
                return removedNodes.indexOf(node) < 0 && node.hasChildren() && node.state.open;
            });

            removedNodes.forEach(function (node) {
                _this6.nodeTable.unset(node.id);
            });
        }

        // Updates list with new data
        this.update();

        return true;
    };
    // Removes a node and all of its child nodes.
    // @param {Node} node The Node object.
    // @param {object} [options] The options object.
    // @param {boolean} [options.silent] Pass true to prevent "selectNode" event from being triggered.
    // @return {boolean} Returns true on success, false otherwise.


    InfiniteTree.prototype.removeNode = function removeNode(node, options) {
        var _this7 = this;

        if (!ensureNodeInstance(node)) {
            return false;
        }

        var parentNode = node.parent;
        if (!parentNode) {
            return false;
        }

        // Retrieve node index
        var nodeIndex = this.nodes.indexOf(node);
        var parentNodeIndex = this.nodes.indexOf(parentNode);

        // Update selected node
        if (nodeIndex >= 0 && this.state.selectedNode) {
            // row #0 - node.0         => parent node (total=4)
            // row #1   - node.0.0     => remove this node (total=2)
            // row #2       node.0.0.0 => current selected node (total=0)
            // row #3       node.0.0.1
            // row #4     node.0.1     => next selected node (total=0)
            var selectedIndex = this.nodes.indexOf(this.state.selectedNode);
            var rangeFrom = nodeIndex;
            var rangeTo = nodeIndex + node.state.total + 1;

            if (rangeFrom <= selectedIndex && selectedIndex <= rangeTo) {
                // Change the selected node in the following order:
                // 1. next sibling node
                // 2. previous sibling node
                // 3. parent node
                var selectedNode = node.getNextSibling() || node.getPreviousSibling() || node.getParent();

                if (selectedNode === this.state.rootNode) {
                    this.selectNode(null, options);
                } else {
                    this.selectNode(selectedNode, options);
                }
            }
        }

        // Get the nodes being removed
        var removedNodes = this.flattenNode(node);

        // Get the number of nodes to be removed
        var deleteCount = node.state.total + 1;

        // Subtract the deleteCount for all ancestors (parent, grandparent, etc.) of the current node
        for (var p = parentNode; p !== null; p = p.parent) {
            p.state.total = p.state.total - deleteCount;
        }

        // Update parent node
        parentNode.children.splice(parentNode.children.indexOf(node), 1);
        parentNode.state.open = parentNode.state.open && parentNode.children.length > 0;

        if (nodeIndex >= 0) {
            // Update nodes & rows
            this.nodes.splice(nodeIndex, deleteCount);
            this.rows.splice(nodeIndex, deleteCount);
        }

        // Update the row corresponding to the parent node
        if (parentNodeIndex >= 0) {
            this.rows[parentNodeIndex] = this.options.rowRenderer(parentNode, this.options);
        }

        {
            // Update open nodes and lookup table
            this.state.openNodes = this.state.openNodes.filter(function (node) {
                return removedNodes.indexOf(node) < 0 && node.hasChildren() && node.state.open;
            });

            removedNodes.forEach(function (node) {
                _this7.nodeTable.unset(node.id);
            });
        }

        // Updates list with new data
        this.update();

        return true;
    };
    // Sets the current scroll position to this node.
    // @param {Node} node The Node object.
    // @return {boolean} Returns true on success, false otherwise.


    InfiniteTree.prototype.scrollToNode = function scrollToNode(node) {
        if (!ensureNodeInstance(node)) {
            return false;
        }

        // Retrieve node index
        var nodeIndex = this.nodes.indexOf(node);
        if (nodeIndex < 0) {
            return false;
        }
        if (!this.contentElement) {
            return false;
        }
        // Get the offset height of the first child
        var firstChild = this.contentElement.firstChild;
        var rowHeight = firstChild && firstChild.offsetHeight || 0;
        this.scrollTop(nodeIndex * rowHeight);

        return true;
    };
    // Gets (or sets) the current vertical position of the scroll bar.
    // @param {number} [value] If the value is specified, indicates the new position to set the scroll bar to.
    // @return {number} Returns the vertical scroll position.


    InfiniteTree.prototype.scrollTop = function scrollTop(value) {
        if (!this.scrollElement) {
            return 0;
        }
        if (value !== undefined) {
            this.scrollElement.scrollTop = Number(value);
        }
        return this.scrollElement.scrollTop;
    };
    // Selects a node.
    // @param {Node} node The Node object. If null or undefined, deselects the current node.
    // @param {object} [options] The options object.
    // @param {boolean} [options.silent] Pass true to prevent "selectNode" event from being triggered.
    // @return {boolean} Returns true on success, false otherwise.


    InfiniteTree.prototype.selectNode = function selectNode() {
        var node = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0];
        var options = arguments[1];
        var _options3 = this.options;
        var selectable = _options3.selectable;
        var shouldSelectNode = _options3.shouldSelectNode;

        var _options4 = _extends({}, options);

        var _options4$silent = _options4.silent;
        var silent = _options4$silent === undefined ? false : _options4$silent;


        if (!selectable) {
            return false;
        }
        if (typeof shouldSelectNode === 'function' && !shouldSelectNode(node)) {
            return false;
        }
        if (node === this.state.rootNode) {
            return false;
        }

        if (node === null) {
            // Deselect the current node
            if (this.state.selectedNode) {
                var selectedNode = this.state.selectedNode;
                var selectedIndex = this.nodes.indexOf(selectedNode);

                selectedNode.state.selected = false;
                this.rows[selectedIndex] = this.options.rowRenderer(selectedNode, this.options);
                this.state.selectedNode = null;

                if (!silent) {
                    // Emit a "selectNode" event
                    this.emit('selectNode', null);
                }

                // Updates list with new data
                this.update();

                return true;
            }

            return false;
        }

        if (!ensureNodeInstance(node)) {
            return false;
        }

        // Retrieve node index
        var nodeIndex = this.nodes.indexOf(node);
        if (nodeIndex < 0) {
            error('Invalid node index');
            return false;
        }

        // Select this node
        if (this.state.selectedNode !== node) {
            node.state.selected = true;

            // Update the row corresponding to the node
            this.rows[nodeIndex] = this.options.rowRenderer(node, this.options);
        }

        // Deselect the current node
        if (this.state.selectedNode) {
            var _selectedNode = this.state.selectedNode;
            var _selectedIndex = this.nodes.indexOf(_selectedNode);
            _selectedNode.state.selected = false;
            this.rows[_selectedIndex] = this.options.rowRenderer(_selectedNode, this.options);
        }

        if (this.state.selectedNode !== node) {
            this.state.selectedNode = node;

            if (!silent) {
                // Emit a "selectNode" event
                this.emit('selectNode', node);
            }
        } else {
            this.state.selectedNode = null;

            if (!silent) {
                // Emit a "selectNode" event
                this.emit('selectNode', null);
            }
        }

        // Updates list with new data
        this.update();

        return true;
    };
    // Toggles a node to display or hide its children.
    // @param {Node} node The Node object.
    // @param {object} [options] The options object.
    // @param {boolean} [options.silent] Pass true to prevent "closeNode", "openNode", and "selectNode" events from being triggered.
    // @return {boolean} Returns true on success, false otherwise.


    InfiniteTree.prototype.toggleNode = function toggleNode(node, options) {
        if (!ensureNodeInstance(node)) {
            return false;
        }

        if (this.state.openNodes.indexOf(node) >= 0) {
            // close node
            return this.closeNode(node, options);
        } else {
            // open node
            return this.openNode(node, options);
        }
    };
    // Serializes the current state of a node to a JSON string.
    // @param {Node} node The Node object. If null, returns the whole tree.
    // @return {string} Returns a JSON string represented the tree.


    InfiniteTree.prototype.toString = function toString() {
        var node = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0];

        var traverse = function traverse(node) {
            var s = '[';
            if (node && node.children) {
                var _loop = function _loop(i) {
                    var list = [];
                    s = s + '{';
                    Object.keys(node).forEach(function (key) {
                        var value = node[key];
                        if (key === 'parent') {
                            // ignore parent
                            return;
                        }
                        if (key === 'children') {
                            // traverse child nodes
                            list.push('"' + key + '":' + traverse(node.children[i]));
                            return;
                        }
                        if (typeof value === 'string' || (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
                            list.push('"' + key + '":' + JSON.stringify(value));
                        } else {
                            // primitive types
                            list.push('"' + key + '":' + value);
                        }
                    });
                    s = s + list.join(',');
                    s = s + '}' + (i === node.children.length - 1 ? '' : ',');
                };

                for (var i = 0; i < node.children.length; ++i) {
                    _loop(i);
                }
            }
            s = s + ']';
            return s;
        };

        if (!node) {
            node = this.state.rootNode;
        }

        return traverse(node);
    };
    // Updates the tree.


    InfiniteTree.prototype.update = function update() {
        // Emit a "contentWillUpdate" event
        this.emit('contentWillUpdate');

        // Update the list with new data
        this.clusterize.update(this.rows);

        // Emit a "contentWillUpdate" event
        this.emit('contentDidUpdate');
    };
    // Updates the data of a node.
    // @param {Node} node The Node object.
    // @param {object} data The data object.
    // @param {object} [options] The options object.
    // @param {boolean} [options.shallowRendering] True to render only the parent node, false to render the parent node and all expanded child nodes. Defaults to false.


    InfiniteTree.prototype.updateNode = function updateNode(node, data, options) {
        if (!ensureNodeInstance(node)) {
            return;
        }

        // Clone a new one
        data = _extends({}, data);

        // Ignore keys: children, parent, and state
        delete data.children;
        delete data.parent;
        delete data.state;

        node = Object.assign(node, data);

        // Retrieve node index
        var nodeIndex = this.nodes.indexOf(node);
        if (nodeIndex >= 0) {
            var _options5 = _extends({}, options);

            var _options5$shallowRend = _options5.shallowRendering;
            var shallowRendering = _options5$shallowRend === undefined ? false : _options5$shallowRend;

            // Update the row corresponding to the node

            this.rows[nodeIndex] = this.options.rowRenderer(node, this.options);

            if (!shallowRendering) {
                var rangeFrom = nodeIndex + 1;
                var rangeTo = nodeIndex + node.state.total;
                for (var index = rangeFrom; index <= rangeTo; ++index) {
                    this.rows[index] = this.options.rowRenderer(this.nodes[index], this.options);
                }
            }

            // Updates list with new data
            this.update();
        }
    };

    return InfiniteTree;
}(_events2['default'].EventEmitter);

exports['default'] = InfiniteTree;