'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var React = require('react');
var theme = require('@helpdice/theme');

function _arrayLikeToArray(r, a) {
  (null == a || a > r.length) && (a = r.length);
  for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  return n;
}
function _arrayWithHoles(r) {
  if (Array.isArray(r)) return r;
}
function _arrayWithoutHoles(r) {
  if (Array.isArray(r)) return _arrayLikeToArray(r);
}
function _extends() {
  return _extends = Object.assign ? Object.assign.bind() : function (n) {
    for (var e = 1; e < arguments.length; e++) {
      var t = arguments[e];
      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
    }
    return n;
  }, _extends.apply(null, arguments);
}
function _iterableToArray(r) {
  if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
}
function _iterableToArrayLimit(r, l) {
  var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  if (null != t) {
    var e,
      n,
      i,
      u,
      a = [],
      f = true,
      o = false;
    try {
      if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
    } catch (r) {
      o = true, n = r;
    } finally {
      try {
        if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a;
  }
}
function _nonIterableRest() {
  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 _nonIterableSpread() {
  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 _objectWithoutProperties(e, t) {
  if (null == e) return {};
  var o,
    r,
    i = _objectWithoutPropertiesLoose(e, t);
  if (Object.getOwnPropertySymbols) {
    var n = Object.getOwnPropertySymbols(e);
    for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
  }
  return i;
}
function _objectWithoutPropertiesLoose(r, e) {
  if (null == r) return {};
  var t = {};
  for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
    if (-1 !== e.indexOf(n)) continue;
    t[n] = r[n];
  }
  return t;
}
function _slicedToArray(r, e) {
  return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function _toConsumableArray(r) {
  return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
}
function _unsupportedIterableToArray(r, a) {
  if (r) {
    if ("string" == typeof r) return _arrayLikeToArray(r, a);
    var t = {}.toString.call(r).slice(8, -1);
    return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
  }
}

function getDefaultExportFromCjs (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}

var index = {};

var hasRequiredIndex;

function requireIndex () {
	if (hasRequiredIndex) return index;
	hasRequiredIndex = 1;
	var React$1 = React;

	function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

	var React__default = /*#__PURE__*/_interopDefaultLegacy(React$1);

	/*
	Based on Glamor's sheet
	https://github.com/threepointone/glamor/blob/667b480d31b3721a905021b26e1290ce92ca2879/src/sheet.js
	*/ 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);
	    return Constructor;
	}
	var isProd = typeof process !== "undefined" && process.env && process.env.NODE_ENV === "production";
	var isString = function(o) {
	    return Object.prototype.toString.call(o) === "[object String]";
	};
	var StyleSheet = /*#__PURE__*/ function() {
	    function StyleSheet(param) {
	        var ref = param === void 0 ? {} : param, _name = ref.name, name = _name === void 0 ? "stylesheet" : _name, _optimizeForSpeed = ref.optimizeForSpeed, optimizeForSpeed = _optimizeForSpeed === void 0 ? isProd : _optimizeForSpeed;
	        invariant$1(isString(name), "`name` must be a string");
	        this._name = name;
	        this._deletedRulePlaceholder = "#" + name + "-deleted-rule____{}";
	        invariant$1(typeof optimizeForSpeed === "boolean", "`optimizeForSpeed` must be a boolean");
	        this._optimizeForSpeed = optimizeForSpeed;
	        this._serverSheet = undefined;
	        this._tags = [];
	        this._injected = false;
	        this._rulesCount = 0;
	        var node = typeof window !== "undefined" && document.querySelector('meta[property="csp-nonce"]');
	        this._nonce = node ? node.getAttribute("content") : null;
	    }
	    var _proto = StyleSheet.prototype;
	    _proto.setOptimizeForSpeed = function setOptimizeForSpeed(bool) {
	        invariant$1(typeof bool === "boolean", "`setOptimizeForSpeed` accepts a boolean");
	        invariant$1(this._rulesCount === 0, "optimizeForSpeed cannot be when rules have already been inserted");
	        this.flush();
	        this._optimizeForSpeed = bool;
	        this.inject();
	    };
	    _proto.isOptimizeForSpeed = function isOptimizeForSpeed() {
	        return this._optimizeForSpeed;
	    };
	    _proto.inject = function inject() {
	        var _this = this;
	        invariant$1(!this._injected, "sheet already injected");
	        this._injected = true;
	        if (typeof window !== "undefined" && this._optimizeForSpeed) {
	            this._tags[0] = this.makeStyleTag(this._name);
	            this._optimizeForSpeed = "insertRule" in this.getSheet();
	            if (!this._optimizeForSpeed) {
	                if (!isProd) {
	                    console.warn("StyleSheet: optimizeForSpeed mode not supported falling back to standard mode.");
	                }
	                this.flush();
	                this._injected = true;
	            }
	            return;
	        }
	        this._serverSheet = {
	            cssRules: [],
	            insertRule: function(rule, index) {
	                if (typeof index === "number") {
	                    _this._serverSheet.cssRules[index] = {
	                        cssText: rule
	                    };
	                } else {
	                    _this._serverSheet.cssRules.push({
	                        cssText: rule
	                    });
	                }
	                return index;
	            },
	            deleteRule: function(index) {
	                _this._serverSheet.cssRules[index] = null;
	            }
	        };
	    };
	    _proto.getSheetForTag = function getSheetForTag(tag) {
	        if (tag.sheet) {
	            return tag.sheet;
	        }
	        // this weirdness brought to you by firefox
	        for(var i = 0; i < document.styleSheets.length; i++){
	            if (document.styleSheets[i].ownerNode === tag) {
	                return document.styleSheets[i];
	            }
	        }
	    };
	    _proto.getSheet = function getSheet() {
	        return this.getSheetForTag(this._tags[this._tags.length - 1]);
	    };
	    _proto.insertRule = function insertRule(rule, index) {
	        invariant$1(isString(rule), "`insertRule` accepts only strings");
	        if (typeof window === "undefined") {
	            if (typeof index !== "number") {
	                index = this._serverSheet.cssRules.length;
	            }
	            this._serverSheet.insertRule(rule, index);
	            return this._rulesCount++;
	        }
	        if (this._optimizeForSpeed) {
	            var sheet = this.getSheet();
	            if (typeof index !== "number") {
	                index = sheet.cssRules.length;
	            }
	            // this weirdness for perf, and chrome's weird bug
	            // https://stackoverflow.com/questions/20007992/chrome-suddenly-stopped-accepting-insertrule
	            try {
	                sheet.insertRule(rule, index);
	            } catch (error) {
	                if (!isProd) {
	                    console.warn("StyleSheet: illegal rule: \n\n" + rule + "\n\nSee https://stackoverflow.com/q/20007992 for more info");
	                }
	                return -1;
	            }
	        } else {
	            var insertionPoint = this._tags[index];
	            this._tags.push(this.makeStyleTag(this._name, rule, insertionPoint));
	        }
	        return this._rulesCount++;
	    };
	    _proto.replaceRule = function replaceRule(index, rule) {
	        if (this._optimizeForSpeed || typeof window === "undefined") {
	            var sheet = typeof window !== "undefined" ? this.getSheet() : this._serverSheet;
	            if (!rule.trim()) {
	                rule = this._deletedRulePlaceholder;
	            }
	            if (!sheet.cssRules[index]) {
	                // @TBD Should we throw an error?
	                return index;
	            }
	            sheet.deleteRule(index);
	            try {
	                sheet.insertRule(rule, index);
	            } catch (error) {
	                if (!isProd) {
	                    console.warn("StyleSheet: illegal rule: \n\n" + rule + "\n\nSee https://stackoverflow.com/q/20007992 for more info");
	                }
	                // In order to preserve the indices we insert a deleteRulePlaceholder
	                sheet.insertRule(this._deletedRulePlaceholder, index);
	            }
	        } else {
	            var tag = this._tags[index];
	            invariant$1(tag, "old rule at index `" + index + "` not found");
	            tag.textContent = rule;
	        }
	        return index;
	    };
	    _proto.deleteRule = function deleteRule(index) {
	        if (typeof window === "undefined") {
	            this._serverSheet.deleteRule(index);
	            return;
	        }
	        if (this._optimizeForSpeed) {
	            this.replaceRule(index, "");
	        } else {
	            var tag = this._tags[index];
	            invariant$1(tag, "rule at index `" + index + "` not found");
	            tag.parentNode.removeChild(tag);
	            this._tags[index] = null;
	        }
	    };
	    _proto.flush = function flush() {
	        this._injected = false;
	        this._rulesCount = 0;
	        if (typeof window !== "undefined") {
	            this._tags.forEach(function(tag) {
	                return tag && tag.parentNode.removeChild(tag);
	            });
	            this._tags = [];
	        } else {
	            // simpler on server
	            this._serverSheet.cssRules = [];
	        }
	    };
	    _proto.cssRules = function cssRules() {
	        var _this = this;
	        if (typeof window === "undefined") {
	            return this._serverSheet.cssRules;
	        }
	        return this._tags.reduce(function(rules, tag) {
	            if (tag) {
	                rules = rules.concat(Array.prototype.map.call(_this.getSheetForTag(tag).cssRules, function(rule) {
	                    return rule.cssText === _this._deletedRulePlaceholder ? null : rule;
	                }));
	            } else {
	                rules.push(null);
	            }
	            return rules;
	        }, []);
	    };
	    _proto.makeStyleTag = function makeStyleTag(name, cssString, relativeToTag) {
	        if (cssString) {
	            invariant$1(isString(cssString), "makeStyleTag accepts only strings as second parameter");
	        }
	        var tag = document.createElement("style");
	        if (this._nonce) tag.setAttribute("nonce", this._nonce);
	        tag.type = "text/css";
	        tag.setAttribute("data-" + name, "");
	        if (cssString) {
	            tag.appendChild(document.createTextNode(cssString));
	        }
	        var head = document.head || document.getElementsByTagName("head")[0];
	        if (relativeToTag) {
	            head.insertBefore(tag, relativeToTag);
	        } else {
	            head.appendChild(tag);
	        }
	        return tag;
	    };
	    _createClass(StyleSheet, [
	        {
	            key: "length",
	            get: function get() {
	                return this._rulesCount;
	            }
	        }
	    ]);
	    return StyleSheet;
	}();
	function invariant$1(condition, message) {
	    if (!condition) {
	        throw new Error("StyleSheet: " + message + ".");
	    }
	}

	function hash(str) {
	    var _$hash = 5381, i = str.length;
	    while(i){
	        _$hash = _$hash * 33 ^ str.charCodeAt(--i);
	    }
	    /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
	   * integers. Since we want the results to be always positive, convert the
	   * signed int to an unsigned by doing an unsigned bitshift. */ return _$hash >>> 0;
	}
	var stringHash = hash;

	var sanitize = function(rule) {
	    return rule.replace(/\/style/gi, "\\/style");
	};
	var cache = {};
	/**
	 * computeId
	 *
	 * Compute and memoize a jsx id from a basedId and optionally props.
	 */ function computeId(baseId, props) {
	    if (!props) {
	        return "jsx-" + baseId;
	    }
	    var propsToString = String(props);
	    var key = baseId + propsToString;
	    if (!cache[key]) {
	        cache[key] = "jsx-" + stringHash(baseId + "-" + propsToString);
	    }
	    return cache[key];
	}
	/**
	 * computeSelector
	 *
	 * Compute and memoize dynamic selectors.
	 */ function computeSelector(id, css) {
	    var selectoPlaceholderRegexp = /__jsx-style-dynamic-selector/g;
	    // Sanitize SSR-ed CSS.
	    // Client side code doesn't need to be sanitized since we use
	    // document.createTextNode (dev) and the CSSOM api sheet.insertRule (prod).
	    if (typeof window === "undefined") {
	        css = sanitize(css);
	    }
	    var idcss = id + css;
	    if (!cache[idcss]) {
	        cache[idcss] = css.replace(selectoPlaceholderRegexp, id);
	    }
	    return cache[idcss];
	}

	function mapRulesToStyle(cssRules, options) {
	    if (options === void 0) options = {};
	    return cssRules.map(function(args) {
	        var id = args[0];
	        var css = args[1];
	        return /*#__PURE__*/ React__default["default"].createElement("style", {
	            id: "__" + id,
	            // Avoid warnings upon render with a key
	            key: "__" + id,
	            nonce: options.nonce ? options.nonce : undefined,
	            dangerouslySetInnerHTML: {
	                __html: css
	            }
	        });
	    });
	}
	var StyleSheetRegistry = /*#__PURE__*/ function() {
	    function StyleSheetRegistry(param) {
	        var ref = param === void 0 ? {} : param, _styleSheet = ref.styleSheet, styleSheet = _styleSheet === void 0 ? null : _styleSheet, _optimizeForSpeed = ref.optimizeForSpeed, optimizeForSpeed = _optimizeForSpeed === void 0 ? false : _optimizeForSpeed;
	        this._sheet = styleSheet || new StyleSheet({
	            name: "styled-jsx",
	            optimizeForSpeed: optimizeForSpeed
	        });
	        this._sheet.inject();
	        if (styleSheet && typeof optimizeForSpeed === "boolean") {
	            this._sheet.setOptimizeForSpeed(optimizeForSpeed);
	            this._optimizeForSpeed = this._sheet.isOptimizeForSpeed();
	        }
	        this._fromServer = undefined;
	        this._indices = {};
	        this._instancesCounts = {};
	    }
	    var _proto = StyleSheetRegistry.prototype;
	    _proto.add = function add(props) {
	        var _this = this;
	        if (undefined === this._optimizeForSpeed) {
	            this._optimizeForSpeed = Array.isArray(props.children);
	            this._sheet.setOptimizeForSpeed(this._optimizeForSpeed);
	            this._optimizeForSpeed = this._sheet.isOptimizeForSpeed();
	        }
	        if (typeof window !== "undefined" && !this._fromServer) {
	            this._fromServer = this.selectFromServer();
	            this._instancesCounts = Object.keys(this._fromServer).reduce(function(acc, tagName) {
	                acc[tagName] = 0;
	                return acc;
	            }, {});
	        }
	        var ref = this.getIdAndRules(props), styleId = ref.styleId, rules = ref.rules;
	        // Deduping: just increase the instances count.
	        if (styleId in this._instancesCounts) {
	            this._instancesCounts[styleId] += 1;
	            return;
	        }
	        var indices = rules.map(function(rule) {
	            return _this._sheet.insertRule(rule);
	        })// Filter out invalid rules
	        .filter(function(index) {
	            return index !== -1;
	        });
	        this._indices[styleId] = indices;
	        this._instancesCounts[styleId] = 1;
	    };
	    _proto.remove = function remove(props) {
	        var _this = this;
	        var styleId = this.getIdAndRules(props).styleId;
	        invariant(styleId in this._instancesCounts, "styleId: `" + styleId + "` not found");
	        this._instancesCounts[styleId] -= 1;
	        if (this._instancesCounts[styleId] < 1) {
	            var tagFromServer = this._fromServer && this._fromServer[styleId];
	            if (tagFromServer) {
	                tagFromServer.parentNode.removeChild(tagFromServer);
	                delete this._fromServer[styleId];
	            } else {
	                this._indices[styleId].forEach(function(index) {
	                    return _this._sheet.deleteRule(index);
	                });
	                delete this._indices[styleId];
	            }
	            delete this._instancesCounts[styleId];
	        }
	    };
	    _proto.update = function update(props, nextProps) {
	        this.add(nextProps);
	        this.remove(props);
	    };
	    _proto.flush = function flush() {
	        this._sheet.flush();
	        this._sheet.inject();
	        this._fromServer = undefined;
	        this._indices = {};
	        this._instancesCounts = {};
	    };
	    _proto.cssRules = function cssRules() {
	        var _this = this;
	        var fromServer = this._fromServer ? Object.keys(this._fromServer).map(function(styleId) {
	            return [
	                styleId,
	                _this._fromServer[styleId]
	            ];
	        }) : [];
	        var cssRules = this._sheet.cssRules();
	        return fromServer.concat(Object.keys(this._indices).map(function(styleId) {
	            return [
	                styleId,
	                _this._indices[styleId].map(function(index) {
	                    return cssRules[index].cssText;
	                }).join(_this._optimizeForSpeed ? "" : "\n")
	            ];
	        })// filter out empty rules
	        .filter(function(rule) {
	            return Boolean(rule[1]);
	        }));
	    };
	    _proto.styles = function styles(options) {
	        return mapRulesToStyle(this.cssRules(), options);
	    };
	    _proto.getIdAndRules = function getIdAndRules(props) {
	        var css = props.children, dynamic = props.dynamic, id = props.id;
	        if (dynamic) {
	            var styleId = computeId(id, dynamic);
	            return {
	                styleId: styleId,
	                rules: Array.isArray(css) ? css.map(function(rule) {
	                    return computeSelector(styleId, rule);
	                }) : [
	                    computeSelector(styleId, css)
	                ]
	            };
	        }
	        return {
	            styleId: computeId(id),
	            rules: Array.isArray(css) ? css : [
	                css
	            ]
	        };
	    };
	    /**
	   * selectFromServer
	   *
	   * Collects style tags from the document with id __jsx-XXX
	   */ _proto.selectFromServer = function selectFromServer() {
	        var elements = Array.prototype.slice.call(document.querySelectorAll('[id^="__jsx-"]'));
	        return elements.reduce(function(acc, element) {
	            var id = element.id.slice(2);
	            acc[id] = element;
	            return acc;
	        }, {});
	    };
	    return StyleSheetRegistry;
	}();
	function invariant(condition, message) {
	    if (!condition) {
	        throw new Error("StyleSheetRegistry: " + message + ".");
	    }
	}
	var StyleSheetContext = /*#__PURE__*/ React$1.createContext(null);
	StyleSheetContext.displayName = "StyleSheetContext";
	function createStyleRegistry() {
	    return new StyleSheetRegistry();
	}
	function StyleRegistry(param) {
	    var configuredRegistry = param.registry, children = param.children;
	    var rootRegistry = React$1.useContext(StyleSheetContext);
	    var ref = React$1.useState(function() {
	        return rootRegistry || configuredRegistry || createStyleRegistry();
	    }), registry = ref[0];
	    return /*#__PURE__*/ React__default["default"].createElement(StyleSheetContext.Provider, {
	        value: registry
	    }, children);
	}
	function useStyleRegistry() {
	    return React$1.useContext(StyleSheetContext);
	}

	// Opt-into the new `useInsertionEffect` API in React 18, fallback to `useLayoutEffect`.
	// https://github.com/reactwg/react-18/discussions/110
	var useInsertionEffect = React__default["default"].useInsertionEffect || React$1.useLayoutEffect;
	var defaultRegistry = typeof window !== "undefined" ? createStyleRegistry() : undefined;
	function JSXStyle(props) {
	    var registry = defaultRegistry ? defaultRegistry : useStyleRegistry();
	    var insertionEffectCalled = React$1.useRef(false);
	    // `registry` might not exist while server-side rendering
	    if (!registry) {
	        return null;
	    }
	    if (typeof window === "undefined") {
	        registry.add(props);
	        return null;
	    }
	    useInsertionEffect(function() {
	        // ReactDOM removes all DOM during hydration in certain cases
	        if (!document.head) {
	            return;
	        }
	        registry.add(props);
	        insertionEffectCalled.current = true;
	        return function() {
	            insertionEffectCalled.current = false;
	            registry.remove(props);
	        };
	    }, [
	        props.id,
	        String(props.dynamic)
	    ]);
	    React$1.useLayoutEffect(function() {
	        if (!document.head || insertionEffectCalled.current) {
	            return;
	        }
	        registry.add(props);
	        return function() {
	            registry.remove(props);
	        };
	    // props.children can be string[], will be striped since id is identical
	    }, [
	        props.id,
	        String(props.dynamic)
	    ]);
	    return null;
	}
	JSXStyle.dynamic = function(info) {
	    return info.map(function(tagInfo) {
	        var baseId = tagInfo[0];
	        var props = tagInfo[1];
	        return computeId(baseId, props);
	    }).join(" ");
	};

	index.StyleRegistry = StyleRegistry;
	index.createStyleRegistry = createStyleRegistry;
	index.style = JSXStyle;
	index.useStyleRegistry = useStyleRegistry;
	return index;
}

var style;
var hasRequiredStyle;

function requireStyle () {
	if (hasRequiredStyle) return style;
	hasRequiredStyle = 1;
	style = requireIndex().style;
	return style;
}

var styleExports = requireStyle();
var _JSXStyle = /*@__PURE__*/getDefaultExportFromCjs(styleExports);

var TreeFileIcon = function TreeFileIcon(_ref) {
  var color = _ref.color,
    _ref$width = _ref.width,
    width = _ref$width === void 0 ? 22 : _ref$width,
    _ref$height = _ref.height,
    height = _ref$height === void 0 ? 22 : _ref$height;
  var theme$1 = theme.useTheme();
  return /*#__PURE__*/React.createElement("svg", {
    viewBox: "0 0 24 24",
    width: width,
    height: height,
    stroke: "currentColor",
    strokeWidth: "1",
    strokeLinecap: "round",
    strokeLinejoin: "round",
    fill: "none",
    shapeRendering: "geometricPrecision",
    className: _JSXStyle.dynamic([["4043754792", [color || theme$1.palette.accents_8]]])
  }, /*#__PURE__*/React.createElement("path", {
    d: "M13 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V9z",
    className: _JSXStyle.dynamic([["4043754792", [color || theme$1.palette.accents_8]]])
  }), /*#__PURE__*/React.createElement("path", {
    d: "M13 2v7h7",
    className: _JSXStyle.dynamic([["4043754792", [color || theme$1.palette.accents_8]]])
  }), /*#__PURE__*/React.createElement(_JSXStyle, {
    id: "4043754792",
    dynamic: [color || theme$1.palette.accents_8]
  }, "svg.__jsx-style-dynamic-selector{color:".concat(color || theme$1.palette.accents_8, ";}")));
};
TreeFileIcon.displayName = 'TreeFileIcon';

/* "use client" */

var defaultContext = {
  initialExpand: false,
  isImperative: false
};
var TreeContext = /*#__PURE__*/React.createContext(defaultContext);
var useTreeContext = function useTreeContext() {
  return React.useContext(TreeContext);
};

var TreeIndents = function TreeIndents(_ref) {
  var count = _ref.count;
  if (count === 0) return null;
  return /*#__PURE__*/ /* eslint-disable react/jsx-no-useless-fragment */React.createElement(React.Fragment, null, _toConsumableArray(new Array(count)).map(function (_, index) {
    return /*#__PURE__*/React.createElement("span", {
      key: "indent-".concat(index),
      className: _JSXStyle.dynamic([["2622387629", [index + 1]]]) + " " + "indent"
    }, /*#__PURE__*/React.createElement(_JSXStyle, {
      id: "2622387629",
      dynamic: [index + 1]
    }, "span.indent.__jsx-style-dynamic-selector{left:calc(-1.875rem * ".concat(index + 1, " + 0.75rem);}")));
  }))
  /* eslint-enable */;
};

var sortChildren = function sortChildren(children, folderComponentType) {
  return React.Children.toArray(children).sort(function (_a, _b) {
    var a = _a;
    var b = _b;
    if (! /*#__PURE__*/React.isValidElement(a) || ! /*#__PURE__*/React.isValidElement(b)) return 0;
    if (a.type !== b.type) return a.type !== folderComponentType ? 1 : -1;
    return "".concat(a.props.name).charCodeAt(0) - "".concat(b.props.name).charCodeAt(0);
  });
};
var makeChildPath = function makeChildPath(name, parentPath) {
  if (!parentPath) return name;
  return "".concat(parentPath, "/").concat(name);
};
var stopPropagation = function stopPropagation(event) {
  event.stopPropagation();
  event.nativeEvent.stopImmediatePropagation();
};

var _excluded$2 = ["name", "parentPath", "level", "extra", "className"];
var TreeFile = function TreeFile(_ref) {
  var name = _ref.name,
    _ref$parentPath = _ref.parentPath,
    parentPath = _ref$parentPath === void 0 ? '' : _ref$parentPath,
    _ref$level = _ref.level,
    level = _ref$level === void 0 ? 0 : _ref$level,
    extra = _ref.extra,
    _ref$className = _ref.className,
    className = _ref$className === void 0 ? '' : _ref$className,
    props = _objectWithoutProperties(_ref, _excluded$2);
  var theme$1 = theme.useTheme();
  var _useTreeContext = useTreeContext(),
    onFileClick = _useTreeContext.onFileClick;
  var currentPath = React.useMemo(function () {
    return makeChildPath(name, parentPath);
  }, []);
  var clickHandler = function clickHandler(event) {
    stopPropagation(event);
    onFileClick && onFileClick(currentPath);
  };
  return /*#__PURE__*/React.createElement("div", _extends({
    onClick: clickHandler
  }, props, {
    className: _JSXStyle.dynamic([["4220802947", [level, theme$1.palette.accents_2, theme$1.palette.accents_8, theme$1.palette.accents_5]]]) + " " + (props && props.className != null && props.className || theme.useClasses('file', className) || "")
  }), /*#__PURE__*/React.createElement("div", {
    className: _JSXStyle.dynamic([["4220802947", [level, theme$1.palette.accents_2, theme$1.palette.accents_8, theme$1.palette.accents_5]]]) + " " + "names"
  }, /*#__PURE__*/React.createElement(TreeIndents, {
    count: level
  }), /*#__PURE__*/React.createElement("span", {
    className: _JSXStyle.dynamic([["4220802947", [level, theme$1.palette.accents_2, theme$1.palette.accents_8, theme$1.palette.accents_5]]]) + " " + "icon"
  }, /*#__PURE__*/React.createElement(TreeFileIcon, null)), /*#__PURE__*/React.createElement("span", {
    className: _JSXStyle.dynamic([["4220802947", [level, theme$1.palette.accents_2, theme$1.palette.accents_8, theme$1.palette.accents_5]]]) + " " + "name"
  }, name, extra && /*#__PURE__*/React.createElement("span", {
    className: _JSXStyle.dynamic([["4220802947", [level, theme$1.palette.accents_2, theme$1.palette.accents_8, theme$1.palette.accents_5]]]) + " " + "extra"
  }, extra))), /*#__PURE__*/React.createElement(_JSXStyle, {
    id: "4220802947",
    dynamic: [level, theme$1.palette.accents_2, theme$1.palette.accents_8, theme$1.palette.accents_5]
  }, ".file.__jsx-style-dynamic-selector{cursor:pointer;line-height:1;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;margin-left:calc(1.875rem * ".concat(level, ");}.names.__jsx-style-dynamic-selector{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;height:1.75rem;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;position:relative;}.names.__jsx-style-dynamic-selector>.indent{position:absolute;top:50%;-webkit-transform:translateY(-50%);-ms-transform:translateY(-50%);transform:translateY(-50%);width:1px;height:100%;background-color:").concat(theme$1.palette.accents_2, ";margin-left:-1px;}.icon.__jsx-style-dynamic-selector{width:1.5rem;height:100%;display:-webkit-inline-box;display:-webkit-inline-flex;display:-ms-inline-flexbox;display:inline-flex;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;margin-right:0.5rem;}.name.__jsx-style-dynamic-selector{-webkit-transition:opacity 100ms ease 0ms;transition:opacity 100ms ease 0ms;color:").concat(theme$1.palette.accents_8, ";white-space:nowrap;font-size:0.875rem;}.extra.__jsx-style-dynamic-selector{font-size:0.75rem;-webkit-align-self:baseline;-ms-flex-item-align:baseline;align-self:baseline;padding-left:4px;color:").concat(theme$1.palette.accents_5, ";}.name.__jsx-style-dynamic-selector:hover{opacity:0.7;}")));
};
TreeFile.displayName = 'TreeFile';

/* "use client" */

var setChildrenProps = function setChildrenProps(children, props) {
  var targetComponents = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  if (React.Children.count(children) === 0) return [];
  var allowAll = targetComponents.length === 0;
  var clone = function clone(child) {
    var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    return /*#__PURE__*/React.cloneElement(child, props);
  };
  return React.Children.map(children, function (item) {
    if (! /*#__PURE__*/React.isValidElement(item)) return item;
    if (allowAll) return clone(item, props);
    var isAllowed = targetComponents.find(function (child) {
      return child === item.type;
    });
    if (isAllowed) return clone(item, props);
    return item;
  });
};

var TreeFolderIcon = function TreeFolderIcon(_ref) {
  var color = _ref.color,
    _ref$width = _ref.width,
    width = _ref$width === void 0 ? 22 : _ref$width,
    _ref$height = _ref.height,
    height = _ref$height === void 0 ? 22 : _ref$height;
  var theme$1 = theme.useTheme();
  return /*#__PURE__*/React.createElement("svg", {
    viewBox: "0 0 24 24",
    width: width,
    height: height,
    stroke: "currentColor",
    strokeWidth: "1",
    strokeLinecap: "round",
    strokeLinejoin: "round",
    fill: "none",
    shapeRendering: "geometricPrecision",
    className: _JSXStyle.dynamic([["4043754792", [color || theme$1.palette.accents_8]]])
  }, /*#__PURE__*/React.createElement("path", {
    d: "M2.707 7.454V5.62C2.707 4.725 3.469 4 4.409 4h4.843c.451 0 .884.17 1.204.474l.49.467c.126.12.296.186.473.186h8.399c.94 0 1.55.695 1.55 1.59v.737m-18.661 0h-.354a.344.344 0 00-.353.35l.508 11.587c.015.34.31.609.668.609h17.283c.358 0 .652-.269.667-.61L22 7.805a.344.344 0 00-.353-.35h-.278m-18.662 0h18.662",
    className: _JSXStyle.dynamic([["4043754792", [color || theme$1.palette.accents_8]]])
  }), /*#__PURE__*/React.createElement(_JSXStyle, {
    id: "4043754792",
    dynamic: [color || theme$1.palette.accents_8]
  }, "svg.__jsx-style-dynamic-selector{color:".concat(color || theme$1.palette.accents_8, ";}")));
};
TreeFolderIcon.displayName = 'TreeFolderIcon';

var TreeStatusIcon = function TreeStatusIcon(_ref) {
  var color = _ref.color,
    _ref$width = _ref.width,
    width = _ref$width === void 0 ? 12 : _ref$width,
    _ref$height = _ref.height,
    height = _ref$height === void 0 ? 12 : _ref$height,
    _ref$active = _ref.active,
    active = _ref$active === void 0 ? false : _ref$active;
  var theme$1 = theme.useTheme();
  return /*#__PURE__*/React.createElement("svg", {
    viewBox: "0 0 24 24",
    width: width,
    height: height,
    stroke: "currentColor",
    strokeWidth: "1.5",
    strokeLinecap: "round",
    strokeLinejoin: "round",
    fill: "none",
    shapeRendering: "geometricPrecision",
    className: _JSXStyle.dynamic([["4043754792", [color || theme$1.palette.accents_8]]])
  }, /*#__PURE__*/React.createElement("rect", {
    x: "3",
    y: "3",
    width: "18",
    height: "18",
    rx: "2",
    ry: "2",
    className: _JSXStyle.dynamic([["4043754792", [color || theme$1.palette.accents_8]]])
  }), !active && /*#__PURE__*/React.createElement("path", {
    d: "M12 8v8",
    className: _JSXStyle.dynamic([["4043754792", [color || theme$1.palette.accents_8]]])
  }), /*#__PURE__*/React.createElement("path", {
    d: "M8 12h8",
    className: _JSXStyle.dynamic([["4043754792", [color || theme$1.palette.accents_8]]])
  }), /*#__PURE__*/React.createElement(_JSXStyle, {
    id: "4043754792",
    dynamic: [color || theme$1.palette.accents_8]
  }, "svg.__jsx-style-dynamic-selector{color:".concat(color || theme$1.palette.accents_8, ";}")));
};
TreeStatusIcon.displayName = 'TreeStatusIcon';

var _excluded$1 = ["name", "children", "parentPath", "level", "extra", "className"];
var _TreeFolder = function TreeFolder(_ref) {
  var name = _ref.name,
    _ref$children = _ref.children,
    children = _ref$children === void 0 ? '' : _ref$children,
    _ref$parentPath = _ref.parentPath,
    parentPath = _ref$parentPath === void 0 ? '' : _ref$parentPath,
    _ref$level = _ref.level,
    parentLevel = _ref$level === void 0 ? 0 : _ref$level,
    extra = _ref.extra,
    className = _ref.className,
    props = _objectWithoutProperties(_ref, _excluded$1);
  var theme$1 = theme.useTheme();
  var _useTreeContext = useTreeContext(),
    initialExpand = _useTreeContext.initialExpand,
    isImperative = _useTreeContext.isImperative;
  var _useState = React.useState(initialExpand),
    _useState2 = _slicedToArray(_useState, 2),
    expanded = _useState2[0],
    setExpanded = _useState2[1];
  React.useEffect(function () {
    return setExpanded(initialExpand);
  }, []);
  var currentPath = React.useMemo(function () {
    return makeChildPath(name, parentPath);
  }, []);
  var clickHandler = function clickHandler() {
    return setExpanded(!expanded);
  };
  var nextChildren = setChildrenProps(children, {
    parentPath: currentPath,
    level: parentLevel + 1
  }, [_TreeFolder, TreeFile]);
  var sortedChildren = isImperative ? nextChildren : sortChildren(nextChildren, _TreeFolder);
  return /*#__PURE__*/React.createElement("div", _extends({
    onClick: clickHandler
  }, props, {
    className: _JSXStyle.dynamic([["1983983326", [parentLevel, theme$1.palette.accents_2, theme$1.palette.background, theme$1.palette.accents_8, theme$1.palette.accents_5]]]) + " " + (props && props.className != null && props.className || theme.useClasses('folder', className) || "")
  }), /*#__PURE__*/React.createElement("div", {
    className: _JSXStyle.dynamic([["1983983326", [parentLevel, theme$1.palette.accents_2, theme$1.palette.background, theme$1.palette.accents_8, theme$1.palette.accents_5]]]) + " " + "names"
  }, /*#__PURE__*/React.createElement(TreeIndents, {
    count: parentLevel
  }), /*#__PURE__*/React.createElement("span", {
    className: _JSXStyle.dynamic([["1983983326", [parentLevel, theme$1.palette.accents_2, theme$1.palette.background, theme$1.palette.accents_8, theme$1.palette.accents_5]]]) + " " + "status"
  }, /*#__PURE__*/React.createElement(TreeStatusIcon, {
    active: expanded
  })), /*#__PURE__*/React.createElement("span", {
    className: _JSXStyle.dynamic([["1983983326", [parentLevel, theme$1.palette.accents_2, theme$1.palette.background, theme$1.palette.accents_8, theme$1.palette.accents_5]]]) + " " + "icon"
  }, /*#__PURE__*/React.createElement(TreeFolderIcon, null)), /*#__PURE__*/React.createElement("span", {
    className: _JSXStyle.dynamic([["1983983326", [parentLevel, theme$1.palette.accents_2, theme$1.palette.background, theme$1.palette.accents_8, theme$1.palette.accents_5]]]) + " " + "name"
  }, name, extra && /*#__PURE__*/React.createElement("span", {
    className: _JSXStyle.dynamic([["1983983326", [parentLevel, theme$1.palette.accents_2, theme$1.palette.background, theme$1.palette.accents_8, theme$1.palette.accents_5]]]) + " " + "extra"
  }, extra))), /*#__PURE__*/React.createElement(theme.Expand, {
    isExpanded: expanded
  }, /*#__PURE__*/React.createElement("div", {
    onClick: stopPropagation,
    className: _JSXStyle.dynamic([["1983983326", [parentLevel, theme$1.palette.accents_2, theme$1.palette.background, theme$1.palette.accents_8, theme$1.palette.accents_5]]]) + " " + "content"
  }, sortedChildren)), /*#__PURE__*/React.createElement(_JSXStyle, {
    id: "1983983326",
    dynamic: [parentLevel, theme$1.palette.accents_2, theme$1.palette.background, theme$1.palette.accents_8, theme$1.palette.accents_5]
  }, ".folder.__jsx-style-dynamic-selector{cursor:pointer;line-height:1;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;}.names.__jsx-style-dynamic-selector{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;height:1.75rem;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;margin-left:calc(1.875rem * ".concat(parentLevel, ");position:relative;}.names.__jsx-style-dynamic-selector>.indent{position:absolute;top:50%;-webkit-transform:translateY(-50%);-ms-transform:translateY(-50%);transform:translateY(-50%);width:1px;height:100%;background-color:").concat(theme$1.palette.accents_2, ";margin-left:-1px;}.status.__jsx-style-dynamic-selector{position:absolute;left:calc(-1.125rem);top:50%;-webkit-transform:translate(-50%,-50%);-ms-transform:translate(-50%,-50%);transform:translate(-50%,-50%);width:0.875rem;height:0.875rem;z-index:10;background-color:").concat(theme$1.palette.background, ";}.icon.__jsx-style-dynamic-selector{width:1.5rem;height:100%;margin-right:0.5rem;}.status.__jsx-style-dynamic-selector,.icon.__jsx-style-dynamic-selector{display:-webkit-inline-box;display:-webkit-inline-flex;display:-ms-inline-flexbox;display:inline-flex;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;}.name.__jsx-style-dynamic-selector{-webkit-transition:opacity 100ms ease 0ms;transition:opacity 100ms ease 0ms;color:").concat(theme$1.palette.accents_8, ";white-space:nowrap;font-size:0.875rem;}.extra.__jsx-style-dynamic-selector{font-size:0.75rem;-webkit-align-self:baseline;-ms-flex-item-align:baseline;align-self:baseline;padding-left:4px;color:").concat(theme$1.palette.accents_5, ";}.name.__jsx-style-dynamic-selector:hover{opacity:0.7;}.content.__jsx-style-dynamic-selector{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;height:auto;}")));
};
_TreeFolder.displayName = 'TreeFolder';

var tuple = function tuple() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }
  return args;
};
tuple('default', 'secondary', 'success', 'warning', 'error', 'abort', 'secondary-light', 'success-light', 'warning-light', 'error-light');
tuple('default', 'secondary', 'success', 'warning', 'error');
tuple('default', 'secondary', 'success', 'warning', 'error', 'dark', 'lite');
tuple('default', 'secondary', 'success', 'warning', 'error', 'dark', 'lite', 'alert', 'purple', 'violet', 'cyan');
tuple('default', 'silent', 'prevent');
tuple('hover', 'click');
tuple('top', 'topStart', 'topEnd', 'left', 'leftStart', 'leftEnd', 'bottom', 'bottomStart', 'bottomEnd', 'right', 'rightStart', 'rightEnd');
tuple('start', 'center', 'end', 'left', 'right');

var _excluded = ["children", "onClick", "initialExpand", "value", "className"];
var FileTreeValueType = tuple('directory', 'file');
var directoryType = FileTreeValueType[0];
var _makeChildren = function makeChildren() {
  var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  if (!value || !value.length) return null;
  return value.sort(function (a, b) {
    if (a.type !== b.type) return a.type !== directoryType ? 1 : -1;
    return "".concat(a.name).charCodeAt(0) - "".concat(b.name).charCodeAt(0);
  }).map(function (item, index) {
    if (item.type === directoryType) return /*#__PURE__*/React.createElement(_TreeFolder, {
      name: item.name,
      extra: item.extra,
      key: "folder-".concat(item.name, "-").concat(index)
    }, _makeChildren(item.files));
    return /*#__PURE__*/React.createElement(TreeFile, {
      name: item.name,
      extra: item.extra,
      key: "file-".concat(item.name, "-").concat(index)
    });
  });
};
var Tree = function Tree(_ref) {
  var children = _ref.children,
    onClick = _ref.onClick,
    _ref$initialExpand = _ref.initialExpand,
    initialExpand = _ref$initialExpand === void 0 ? false : _ref$initialExpand,
    value = _ref.value,
    className = _ref.className,
    props = _objectWithoutProperties(_ref, _excluded);
  var isImperative = Boolean(value && value.length > 0);
  var onFileClick = function onFileClick(path) {
    onClick && onClick(path);
  };
  var initialValue = React.useMemo(function () {
    return {
      onFileClick: onFileClick,
      initialExpand: initialExpand,
      isImperative: isImperative
    };
  }, [initialExpand]);
  var customChildren = isImperative ? _makeChildren(value) : sortChildren(children, _TreeFolder);
  return /*#__PURE__*/React.createElement(TreeContext.Provider, {
    value: initialValue
  }, /*#__PURE__*/React.createElement("div", _extends({}, props, {
    className: "jsx-2273069862" + " " + (props && props.className != null && props.className || theme.useClasses('tree', className) || "")
  }), customChildren, /*#__PURE__*/React.createElement(_JSXStyle, {
    id: "2273069862"
  }, ".tree.jsx-2273069862{padding-left:1.625rem;}")));
};
Tree.displayName = 'Tree';

Tree.File = TreeFile;
Tree.Folder = _TreeFolder;

exports.default = Tree;
