function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _array_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function _assert_this_initialized(self) {
    if (self === void 0) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
    }
    return self;
}
function _call_super(_this, derived, args) {
    derived = _get_prototype_of(derived);
    return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
}
function _class_call_check(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 _create_class(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
}
function _get(target, property, receiver) {
    if (typeof Reflect !== "undefined" && Reflect.get) {
        _get = Reflect.get;
    } else {
        _get = function get(target, property, receiver) {
            var base = _super_prop_base(target, property);
            if (!base) return;
            var desc = Object.getOwnPropertyDescriptor(base, property);
            if (desc.get) {
                return desc.get.call(receiver || target);
            }
            return desc.value;
        };
    }
    return _get(target, property, receiver || target);
}
function _get_prototype_of(o) {
    _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
        return o.__proto__ || Object.getPrototypeOf(o);
    };
    return _get_prototype_of(o);
}
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) _set_prototype_of(subClass, superClass);
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _non_iterable_spread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _possible_constructor_return(self, call) {
    if (call && (_type_of(call) === "object" || typeof call === "function")) {
        return call;
    }
    return _assert_this_initialized(self);
}
function _set_prototype_of(o, p) {
    _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
        o.__proto__ = p;
        return o;
    };
    return _set_prototype_of(o, p);
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _super_prop_base(object, property) {
    while(!Object.prototype.hasOwnProperty.call(object, property)){
        object = _get_prototype_of(object);
        if (object === null) break;
    }
    return object;
}
function _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _type_of(obj) {
    "@swc/helpers - typeof";
    return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
function _is_native_reflect_construct() {
    try {
        var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
    } catch (_) {}
    return (_is_native_reflect_construct = function() {
        return !!result;
    })();
}
import { group, sum } from "d3-array";
import { hierarchy, treemap } from "d3-hierarchy";
import { treemapBinary, treemapDice, treemapSlice, treemapSliceDice, treemapSquarify, treemapResquarify } from "d3-hierarchy";
var tileMethods = {
    treemapBinary: treemapBinary,
    treemapDice: treemapDice,
    treemapSlice: treemapSlice,
    treemapSliceDice: treemapSliceDice,
    treemapSquarify: treemapSquarify,
    treemapResquarify: treemapResquarify
};
import { merge, nestGroups } from "@d3plus/data";
import { assign, elem } from "@d3plus/dom";
import { formatAbbreviate } from "@d3plus/format";
import { Rect } from "../shapes/index.js";
import { accessor, configPrep, constant } from "../utils/index.js";
import Viz from "./Viz.js";
var Treemap = /*#__PURE__*/ function(Viz) {
    "use strict";
    _inherits(Treemap, Viz);
    function Treemap() {
        _class_call_check(this, Treemap);
        var _this;
        _this = _call_super(this, Treemap);
        _this._layoutPadding = 1;
        var defaultLegend = _this._legend;
        _this._legend = function(config, arr) {
            if (arr.length === _this._filteredData.length) return false;
            return defaultLegend.bind(_this)(config, arr);
        };
        _this._legendSort = function(a, b) {
            return _this._sum(b) - _this._sum(a);
        };
        _this._legendTooltip = assign({}, _this._legendTooltip, {
            tbody: []
        });
        _this._shapeConfig = assign({}, _this._shapeConfig, {
            ariaLabel: function ariaLabel(d, i) {
                var rank = _this._rankData ? "".concat(_this._rankData.indexOf(d) + 1, ". ") : "";
                return "".concat(rank).concat(_this._drawLabel(d, i), ", ").concat(_this._sum(d, i), ".");
            },
            labelConfig: {
                fontMax: 32,
                fontMin: 8,
                fontResize: true,
                padding: 5
            }
        });
        _this._sort = function(a, b) {
            var aggA = isAggregated(a);
            var aggB = isAggregated(b);
            return aggA && !aggB ? 1 : !aggA && aggB ? -1 : b.value - a.value;
        };
        _this._sum = accessor("value");
        _this._thresholdKey = _this._sum;
        _this._tile = treemapSquarify;
        _this._tooltipConfig = assign({}, _this._tooltipConfig, {
            tbody: [
                [
                    function() {
                        return _this._translate("Share");
                    },
                    function(d, i, x) {
                        return "".concat(formatAbbreviate(x.share * 100, _this._locale), "%");
                    }
                ]
            ]
        });
        _this._treemap = treemap().round(true);
        var isAggregated = function isAggregated(leaf) {
            return leaf.children && leaf.children.length === 1 && leaf.children[0].data._isAggregation;
        };
        return _this;
    }
    _create_class(Treemap, [
        {
            /**
      Extends the draw behavior of the abstract Viz class.
      @private
*/ key: "_draw",
            value: function _draw(callback) {
                var _this = this;
                _get(_get_prototype_of(Treemap.prototype), "_draw", this).call(this, callback);
                var nestedData = nestGroups(this._filteredData, this._groupBy.slice(0, this._drawDepth + 1));
                var tmapData = this._treemap.padding(this._layoutPadding).size([
                    this._width - this._margin.left - this._margin.right,
                    this._height - this._margin.top - this._margin.bottom
                ]).tile(this._tile)(hierarchy({
                    values: nestedData
                }, function(d) {
                    return d.values;
                }).sum(this._sum).sort(this._sort));
                var shapeData = [], that = this;
                /**
        Flattens and merges treemap data.
        @private
*/ function extractLayout(children) {
                    for(var i = 0; i < children.length; i++){
                        var node = children[i];
                        if (node.depth <= that._drawDepth) extractLayout(node.children);
                        else {
                            var index = node.data.values.length === 1 ? that._filteredData.indexOf(node.data.values[0]) : undefined;
                            node.__d3plus__ = true;
                            node.id = node.data.key;
                            node.i = index > -1 ? index : undefined;
                            node.data = merge(node.data.values, that._aggs);
                            node.x = node.x0 + (node.x1 - node.x0) / 2;
                            node.y = node.y0 + (node.y1 - node.y0) / 2;
                            shapeData.push(node);
                        }
                    }
                }
                if (tmapData.children) extractLayout(tmapData.children);
                this._rankData = shapeData.sort(this._sort).map(function(d) {
                    return d.data;
                });
                var total = tmapData.value;
                shapeData.forEach(function(d) {
                    d.share = _this._sum(d.data, d.i) / total;
                });
                var transform = "translate(".concat(this._margin.left, ", ").concat(this._margin.top, ")");
                var rectConfig = configPrep.bind(this)(this._shapeConfig, "shape", "Rect");
                var fontMax = rectConfig.labelConfig.fontMax;
                var fontMin = rectConfig.labelConfig.fontMin;
                var padding = rectConfig.labelConfig.padding;
                this._shapes.push(new Rect().data(shapeData).label(function(d) {
                    return [
                        _this._drawLabel(d.data, d.i),
                        "".concat(formatAbbreviate(d.share * 100, _this._locale), "%")
                    ];
                }).select(elem("g.d3plus-Treemap", {
                    parent: this._select,
                    enter: {
                        transform: transform
                    },
                    update: {
                        transform: transform
                    }
                }).node()).config({
                    height: function height(d) {
                        return d.y1 - d.y0;
                    },
                    labelBounds: function labelBounds(d, i, s) {
                        var h = s.height;
                        var sh = Math.min(fontMax, (h - padding * 2) * 0.5);
                        if (sh < fontMin) sh = 0;
                        return [
                            {
                                width: s.width,
                                height: h - sh,
                                x: -s.width / 2,
                                y: -h / 2
                            },
                            {
                                width: s.width,
                                height: sh + padding * 2,
                                x: -s.width / 2,
                                y: h / 2 - sh - padding * 2
                            }
                        ];
                    },
                    labelConfig: {
                        textAnchor: function textAnchor(d, i, x) {
                            var line, parent = x;
                            while(typeof line === "undefined" && parent){
                                if (typeof parent.l !== "undefined") line = parent.l;
                                parent = parent.__d3plusParent__;
                            }
                            return line ? "middle" : "start";
                        },
                        verticalAlign: function verticalAlign(d, i, x) {
                            var line, parent = x;
                            while(typeof line === "undefined" && parent){
                                if (typeof parent.l !== "undefined") line = parent.l;
                                parent = parent.__d3plusParent__;
                            }
                            return line ? "bottom" : "top";
                        }
                    },
                    width: function width(d) {
                        return d.x1 - d.x0;
                    }
                }).config(rectConfig).render());
                return this;
            }
        },
        {
            /**
   * Applies the threshold algorithm for Treemaps.
   * @param {Array} data The data to process.
   * @private
*/ key: "_thresholdFunction",
            value: function _thresholdFunction(data) {
                var aggs = this._aggs;
                var drawDepth = this._drawDepth;
                var groupBy = this._groupBy;
                var threshold = this._threshold;
                var thresholdKey = this._thresholdKey;
                var totalSum = sum(data, thresholdKey);
                if (threshold && thresholdKey) {
                    return thresholdByDepth(data, 0);
                }
                /**
        Explores the data tree recursively and merges elements under the indicated threshold.
        @param branchData The current subset of the dataset to work on.
        @param depth The depth of the current branch.
        @private
*/ function thresholdByDepth(branchData, depth) {
                    if (depth < drawDepth) {
                        return _to_consumable_array(group(branchData, groupBy[depth])).reduce(function(bulk, param) {
                            var _param = _sliced_to_array(param, 2), values = _param[1];
                            var _thresholdByDepth;
                            var subBranchData = (_thresholdByDepth = thresholdByDepth(values, depth + 1)) !== null && _thresholdByDepth !== void 0 ? _thresholdByDepth : [];
                            return bulk.concat(subBranchData);
                        }, []);
                    }
                    if (depth === drawDepth) {
                        var thresholdPercent = Math.min(1, Math.max(0, threshold(branchData)));
                        if (!isFinite(thresholdPercent) || isNaN(thresholdPercent)) return null;
                        var removedItems = [];
                        var branchDataCopy = branchData.slice();
                        var thresholdValue = thresholdPercent * totalSum;
                        var n = branchDataCopy.length;
                        while(n--){
                            var datum = branchDataCopy[n];
                            if (thresholdKey(datum) < thresholdValue) {
                                var index = branchDataCopy.indexOf(datum);
                                branchDataCopy.splice(index, 1);
                                removedItems.push(datum);
                            }
                        }
                        if (removedItems.length > 0) {
                            var mergedItem = merge(removedItems, aggs);
                            mergedItem._isAggregation = true;
                            mergedItem._threshold = thresholdPercent;
                            branchDataCopy.push(mergedItem);
                        }
                        return branchDataCopy;
                    }
                    throw new Error("Depth is higher than the amount of grouping levels.");
                }
                return data;
            }
        },
        {
            /**
      The inner and outer padding.
*/ key: "layoutPadding",
            value: function layoutPadding(_) {
                return arguments.length ? (this._layoutPadding = typeof _ === "function" ? _ : constant(_), this) : this._layoutPadding;
            }
        },
        {
            /**
      Sort comparator function for the treemap layout. Defaults to descending order by the associated input data's numeric value attribute.

@example
function comparator(a, b) {
  return b.value - a.value;
}
*/ key: "sort",
            value: function sort(_) {
                return arguments.length ? (this._sort = _, this) : this._sort;
            }
        },
        {
            /**
      The sum accessor used for sizing each rectangle in the treemap.

@example
function sum(d) {
  return d.sum;
}
*/ key: "sum",
            value: function sum(_) {
                if (arguments.length) {
                    this._sum = typeof _ === "function" ? _ : accessor(_);
                    this._thresholdKey = this._sum;
                    return this;
                } else return this._sum;
            }
        },
        {
            /**
      The tiling method used when calculating the size and position of the rectangles.

Can either be a string referring to a d3-hierarchy [tiling method](https://github.com/d3/d3-hierarchy#treemap-tiling), or a custom function in the same format.
*/ key: "tile",
            value: function tile(_) {
                return arguments.length ? (this._tile = typeof _ === "string" ? tileMethods["treemap".concat(_.charAt(0).toUpperCase()).concat(_.slice(1))] || treemapSquarify : _, this) : this._tile;
            }
        }
    ]);
    return Treemap;
}(Viz);
/**
    Uses the [d3 treemap layout](https://github.com/mbostock/d3/wiki/Treemap-Layout) to creates SVG rectangles based on an array of data. See [this example](https://d3plus.org/examples/d3plus-hierarchy/getting-started/) for help getting started using the treemap generator.
*/ export { Treemap as default };
