var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
  var target = {};
  for (var prop in source)
    if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
      target[prop] = source[prop];
  if (source != null && __getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(source)) {
      if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
        target[prop] = source[prop];
    }
  return target;
};
import React, { useRef, useEffect, useState, useCallback, cloneElement, useMemo, useLayoutEffect, useContext } from "react";
var Box$1 = "";
function css(base, modifiers) {
  const classNames = Array.isArray(base) ? base.filter((v) => !!v) : [base || ""];
  const element = classNames[0] || "";
  if (modifiers) {
    for (const modifier in modifiers) {
      if (!modifiers[modifier])
        continue;
      classNames.push(`${element}--${modifier}`);
    }
  }
  return classNames.join(" ");
}
function splitByBreaks(name, value) {
  const isNone2 = value === void 0 || value === null || value === "";
  if (isNone2)
    return {};
  const string = "" + value;
  return Object.fromEntries(string.split(" ").map((s) => [`${name}-${s}`, true]));
}
function splitBySides(name, values) {
  if (!values || values === "0")
    return {};
  const sides = values.split(" ");
  return {
    [`${name}-${sides[0]}`]: sides.length === 1,
    [`${name}-v-${sides[0]}`]: sides.length === 2 && sides[0] !== "0",
    [`${name}-h-${sides[1]}`]: sides.length === 2 && sides[1] !== "0",
    [`${name}-t-${sides[0]}`]: sides.length === 4 && sides[0] !== "0",
    [`${name}-r-${sides[1]}`]: sides.length === 4 && sides[1] !== "0",
    [`${name}-b-${sides[2]}`]: sides.length === 4 && sides[2] !== "0",
    [`${name}-l-${sides[3]}`]: sides.length === 4 && sides[3] !== "0"
  };
}
function useCombinedRefs(...refs) {
  const combinedRef = useRef(null);
  useEffect(() => {
    for (let ref of refs) {
      if (!ref)
        return;
      if (typeof ref === "function") {
        ref(combinedRef.current);
      } else {
        ref.current = combinedRef.current;
      }
    }
  }, [refs]);
  return combinedRef;
}
function getRandomId() {
  return (Math.random() * 1048575).toString(16).slice(0, 5);
}
var BoxItem = "";
function useBoxItem(_a, itemClassNames) {
  var _b = _a, {
    flex,
    aspect,
    shrink,
    align,
    inline,
    visible,
    color,
    background,
    opacity,
    width,
    height,
    maxWidth,
    maxHeight,
    margin,
    padding,
    cursor,
    hoverable
  } = _b, props = __objRest(_b, [
    "flex",
    "aspect",
    "shrink",
    "align",
    "inline",
    "visible",
    "color",
    "background",
    "opacity",
    "width",
    "height",
    "maxWidth",
    "maxHeight",
    "margin",
    "padding",
    "cursor",
    "hoverable"
  ]);
  return [
    css([
      css("jui-box__item", __spreadProps(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
        inline,
        hoverable
      }, splitByBreaks("width", width)), splitByBreaks("max-width", maxWidth)), splitByBreaks("max-height", maxHeight)), splitByBreaks("visible", visible)), splitBySides("padding", padding)), splitBySides("margin", margin)), splitByBreaks("color", color)), splitByBreaks("bg", background)), splitByBreaks("opacity", opacity)), {
        [`height-${height}`]: !!height,
        [`aspect-${aspect}`]: !!aspect,
        [`flex-${flex}`]: !!flex,
        [`shrink-${shrink}`]: !!shrink,
        [`align-${align}`]: !!align,
        [`cursor-${cursor}`]: !!cursor
      })),
      itemClassNames
    ]),
    props
  ];
}
const Box = React.forwardRef((_c, forwardedRef) => {
  var _d = _c, {
    as: Tag = "div",
    className,
    zIndex,
    fixed,
    stretch,
    overflow,
    fullScreen,
    columns,
    position,
    vertical,
    horizontal,
    wrap,
    spacing,
    justify,
    alignItems,
    shadow,
    radius,
    overlay,
    border,
    borderColor,
    borderCollapse,
    separatorSymbol,
    separator: separatorProp,
    children,
    style: propsStyle
  } = _d, props = __objRest(_d, [
    "as",
    "className",
    "zIndex",
    "fixed",
    "stretch",
    "overflow",
    "fullScreen",
    "columns",
    "position",
    "vertical",
    "horizontal",
    "wrap",
    "spacing",
    "justify",
    "alignItems",
    "shadow",
    "radius",
    "overlay",
    "border",
    "borderColor",
    "borderCollapse",
    "separatorSymbol",
    "separator",
    "children",
    "style"
  ]);
  const splitBorderColor = (borderColor == null ? void 0 : borderColor.includes("@")) ? splitByBreaks : splitBySides;
  const shadowType = typeof shadow === "string" ? shadow : shadow && "1";
  const radiusType = typeof radius === "string" ? radius : radius && "1";
  const separator = separatorSymbol ? "symbol" : separatorProp;
  const [styles, attrs] = useBoxItem(props, css(["jui-box", className], __spreadProps(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
    vertical,
    horizontal,
    stretch,
    overlay: !!overlay,
    "overlay-clickthrough": overlay === "clickthrough"
  }, splitByBreaks("wrap", wrap)), splitByBreaks("fixed", fixed)), splitByBreaks("columns", columns)), splitBySides("border", border)), splitBySides("spacing", spacing)), splitBySides("border-radius", radiusType)), splitBorderColor("border-color", borderColor)), {
    grid: !!columns,
    "border-collapse": borderCollapse,
    "full-screen": fullScreen,
    [`separator-${separator}`]: !!separator,
    [`shadow-${shadowType}`]: !!shadow,
    [`overflow-${overflow}`]: !!overflow,
    [`z-index-${zIndex}`]: !!zIndex,
    [`align-items-${alignItems}`]: !!alignItems,
    [`justify-${justify}`]: !!justify,
    [`position-${position}`]: !!position
  })));
  const style = __spreadValues(__spreadValues({}, propsStyle), separatorSymbol ? { "--l-separator-symbol": `"${separatorSymbol}"` } : null);
  return /* @__PURE__ */ React.createElement(Tag, __spreadProps(__spreadValues({}, attrs), {
    className: styles,
    style,
    ref: forwardedRef
  }), children);
});
var Icon$1 = "";
const Icon = React.forwardRef((_e, forwardedRef) => {
  var _f = _e, { href, size, className, children: icon } = _f, props = __objRest(_f, ["href", "size", "className", "children"]);
  const [styles, attrs] = useBoxItem(props, css(["jui-icon", className], {
    [`size-${size}`]: !!size
  }));
  const Tag = href ? "a" : "i";
  return /* @__PURE__ */ React.createElement(Tag, __spreadProps(__spreadValues({}, attrs), {
    href,
    ref: forwardedRef,
    className: styles
  }), icon);
});
var Button$1 = "";
const Button = React.forwardRef((_g, forwardedRef) => {
  var _h = _g, {
    size,
    href,
    icon,
    link = !!href,
    label,
    light,
    primary,
    submit,
    disabled,
    onClick,
    onMouseDown,
    children
  } = _h, props = __objRest(_h, [
    "size",
    "href",
    "icon",
    "link",
    "label",
    "light",
    "primary",
    "submit",
    "disabled",
    "onClick",
    "onMouseDown",
    "children"
  ]);
  const Tag = link ? "a" : "button";
  const [styles, attrs] = useBoxItem(props, css("jui-button", {
    link,
    light,
    primary,
    disabled,
    [`size-${size}`]: !!size
  }));
  const content = children || label;
  return /* @__PURE__ */ React.createElement(Tag, __spreadProps(__spreadValues({}, attrs), {
    className: styles,
    type: link ? void 0 : submit ? "submit" : "button",
    href: disabled ? void 0 : href,
    onClick: disabled ? void 0 : onClick,
    onMouseDown: disabled ? void 0 : onMouseDown,
    ref: forwardedRef
  }), icon && /* @__PURE__ */ React.createElement(Icon, {
    className: "jui-button__icon"
  }, icon), icon && link ? /* @__PURE__ */ React.createElement("span", {
    className: "jui-button__label"
  }, content) : content);
});
var Checkbox$1 = "";
const Checkbox = React.forwardRef((_i, forwardedRef) => {
  var _j = _i, {
    size,
    label,
    truncate,
    id,
    value,
    onChange
  } = _j, props = __objRest(_j, [
    "size",
    "label",
    "truncate",
    "id",
    "value",
    "onChange"
  ]);
  const [styles, attrs] = useBoxItem(props, css("jui-checkbox", {
    [`size-${size}`]: !!size
  }));
  const labelStyles = css("jui-checkbox__label", {
    truncate,
    empty: !label,
    colored: !!props.color
  });
  return /* @__PURE__ */ React.createElement("label", {
    className: styles,
    ref: forwardedRef
  }, /* @__PURE__ */ React.createElement("input", {
    className: "jui-checkbox__input",
    type: "checkbox",
    id,
    checked: !!value,
    onChange: (e) => onChange(e.target.checked)
  }), /* @__PURE__ */ React.createElement("span", {
    className: labelStyles
  }, label));
});
const EMPTY = Object.freeze(["", [-1, -1]]);
const ContentEditable = React.forwardRef((_k, forwaredRef) => {
  var _l = _k, {
    value,
    focus,
    onInput,
    onChange,
    onSelection,
    selection,
    placeholder
  } = _l, props = __objRest(_l, [
    "value",
    "focus",
    "onInput",
    "onChange",
    "onSelection",
    "selection",
    "placeholder"
  ]);
  const inputRef = useCombinedRefs(forwaredRef);
  const selectionRange = useRef([0, 0]);
  const [styles, attrs] = useBoxItem(props);
  const requestedRange = selection ? Array.isArray(selection) ? selection : [selection, selection] : null;
  useEffect(() => {
    if (requestedRange)
      selectionRange.current = requestedRange;
  }, [requestedRange ? requestedRange.join("-") : null]);
  useEffect(() => {
    if (focus)
      window.requestAnimationFrame(() => {
        var _a;
        return (_a = inputRef.current) == null ? void 0 : _a.focus();
      });
  }, [focus]);
  useEffect(() => {
    const input = inputRef.current;
    if (!input)
      return;
    window.requestAnimationFrame(() => {
      input.innerHTML = value;
      if (document.activeElement === input) {
        setSelection(input, requestedRange || selectionRange.current);
      }
    });
  });
  return /* @__PURE__ */ React.createElement("div", __spreadProps(__spreadValues({}, attrs), {
    ref: inputRef,
    className: styles,
    contentEditable: true,
    "data-placeholder": placeholder,
    onKeyUp: onSelection ? trackSelection : void 0,
    onClick: onSelection ? trackSelection : void 0,
    onInput: onInput ? inputDidChange : void 0,
    onChange: onChange ? valueDidChange : void 0
  }));
  function trackSelection(e) {
    const [, range] = getTextAndSelection(inputRef.current);
    onSelection(range);
  }
  function inputDidChange(e) {
    const [text, range] = getTextAndSelection(inputRef.current);
    selectionRange.current = range;
    onInput(text, range);
  }
  function valueDidChange(e) {
    const [text] = getTextAndSelection(inputRef.current);
    onChange(text);
  }
});
function getTextAndSelection(input) {
  if (!input)
    return EMPTY;
  const sel = window.getSelection();
  const segments = getSegments(input);
  const text = segments.map(({ text: text2 }) => text2).join("");
  let anchorIndex = 0;
  let focusIndex = 0;
  let currentIndex = 0;
  segments.forEach(({ text: text2, node }) => {
    if (node === sel.anchorNode) {
      anchorIndex = currentIndex + sel.anchorOffset;
    }
    if (node === sel.focusNode) {
      focusIndex = currentIndex + sel.focusOffset;
    }
    currentIndex += text2.length;
  });
  return [text, [anchorIndex, focusIndex]];
}
function getSegments(element) {
  return Array.from(element.childNodes).reduce((segments, node) => {
    switch (node.nodeType) {
      case Node.TEXT_NODE:
        segments.push({ text: node.nodeValue || "", node });
        break;
      case Node.ELEMENT_NODE:
        segments.splice(segments.length, 0, ...getSegments(node));
        break;
    }
    return segments;
  }, []);
}
function setSelection(input, [absoluteAnchorIndex, absoluteFocusIndex]) {
  const sel = window.getSelection();
  const segments = getSegments(input);
  let anchorNode = input;
  let anchorIndex = 0;
  let focusNode = input;
  let focusIndex = 0;
  let currentIndex = 0;
  segments.forEach(({ text, node }) => {
    const startIndexOfNode = currentIndex;
    const endIndexOfNode = startIndexOfNode + text.length;
    if (startIndexOfNode <= absoluteAnchorIndex && absoluteAnchorIndex <= endIndexOfNode) {
      anchorNode = node;
      anchorIndex = absoluteAnchorIndex - startIndexOfNode;
    }
    if (startIndexOfNode <= absoluteFocusIndex && absoluteFocusIndex <= endIndexOfNode) {
      focusNode = node;
      focusIndex = absoluteFocusIndex - startIndexOfNode;
    }
    currentIndex += text.length;
  });
  sel.setBaseAndExtent(anchorNode, anchorIndex, focusNode, focusIndex);
}
function Dropdown({
  delay = 100,
  onBlur,
  visible,
  children: element
}) {
  const ref = useRef(null);
  const [isVisible, setIsVisible] = useState(visible);
  const refState = useRef({ onBlur, isVisible });
  useEffect(() => {
    refState.current = { onBlur, isVisible };
  }, [isVisible, onBlur]);
  const hideTimeout = useRef(null);
  const clearHideTimeout = useCallback(() => {
    var _a;
    const timeout = hideTimeout.current;
    if (timeout)
      clearTimeout(timeout);
    hideTimeout.current = null;
    (_a = ref.current) == null ? void 0 : _a.focus();
  }, []);
  useEffect(() => {
    document.addEventListener("click", blurOnClick);
    return () => document.removeEventListener("click", blurOnClick);
    function blurOnClick(e) {
      const dropdown = ref.current;
      const { onBlur: onBlur2, isVisible: isVisible2 } = refState.current || {};
      if (isVisible2 && dropdown && !dropdown.contains(e.target)) {
        dropdown.blur();
        onBlur2 == null ? void 0 : onBlur2();
        e.stopPropagation();
      }
    }
  }, []);
  useEffect(() => {
    if (visible)
      return setIsVisible(true);
    if (!isVisible && !visible)
      return;
    hideTimeout.current = setTimeout(() => {
      setIsVisible(false);
      hideTimeout.current = null;
    }, delay);
    return clearHideTimeout;
  }, [visible]);
  return isVisible ? cloneElement(element, { ref, onFocus: clearHideTimeout }) : null;
}
var TextInput$1 = "";
const TextInput = React.forwardRef((_m, forwardRef) => {
  var _n = _m, {
    type = "text",
    focus,
    outline,
    multiline = false,
    onChange,
    prefix,
    onPrefixClick,
    suffix,
    onSuffixClick,
    className,
    children
  } = _n, props = __objRest(_n, [
    "type",
    "focus",
    "outline",
    "multiline",
    "onChange",
    "prefix",
    "onPrefixClick",
    "suffix",
    "onSuffixClick",
    "className",
    "children"
  ]);
  const Tag = multiline ? "textarea" : "input";
  const input = useCombinedRefs(forwardRef);
  const [styles, attrs] = useBoxItem(props, css(["jui-input-text", className]));
  useEffect(() => {
    if (focus)
      window.requestAnimationFrame(() => {
        var _a;
        return (_a = input.current) == null ? void 0 : _a.focus();
      });
  }, [focus]);
  return /* @__PURE__ */ React.createElement("div", {
    className: styles
  }, /* @__PURE__ */ React.createElement("div", {
    className: "jui-input-text__frame"
  }, prefix && /* @__PURE__ */ React.createElement("span", {
    className: css("jui-input-text__symbol", {
      prefix: true,
      active: !!onPrefixClick
    }),
    onClick: onPrefixClick
  }, prefix), /* @__PURE__ */ React.createElement(Tag, __spreadProps(__spreadValues({}, attrs), {
    ref: input,
    type: multiline ? void 0 : type,
    onChange: onChange && ((e) => onChange(e.target.value, e)),
    className: css("jui-input-text__input", {
      multiline,
      [`outline-${outline}`]: !!outline
    })
  })), suffix && /* @__PURE__ */ React.createElement("span", {
    className: css("jui-input-text__symbol", {
      suffix: true,
      active: !!onSuffixClick
    }),
    onClick: onSuffixClick
  }, suffix)), children);
});
const ListContext = React.createContext({});
const List = React.forwardRef((_o, forwardedRef) => {
  var _p = _o, {
    item,
    items: givenItems,
    focus,
    onBlur,
    onFocus,
    children,
    onSelect = noop,
    onCommit,
    multiple,
    tabIndex = 0,
    commitOn = "click",
    selection = [],
    onKeyDown,
    keepActive,
    activateOnHover,
    activateOnFocus,
    swapScroll
  } = _p, boxProps = __objRest(_p, [
    "item",
    "items",
    "focus",
    "onBlur",
    "onFocus",
    "children",
    "onSelect",
    "onCommit",
    "multiple",
    "tabIndex",
    "commitOn",
    "selection",
    "onKeyDown",
    "keepActive",
    "activateOnHover",
    "activateOnFocus",
    "swapScroll"
  ]);
  const items = useMemo(() => normalizeItems(givenItems), [
    givenItems
  ]);
  const Item = item;
  const renderItems = children || ((items2, state) => items2.map((item2, index2) => {
    const { id } = item2;
    const selected = selection.includes(id);
    return /* @__PURE__ */ React.createElement(Item, {
      key: `${id}`,
      item: item2,
      index: index2,
      active: active === id,
      dragged: dragging && selected,
      selected
    });
  }));
  const listRef = useCombinedRefs(forwardedRef);
  const horizontal = boxProps.horizontal || !!boxProps.columns;
  const [active, setActive] = useState(null);
  const [dragging, setDragging] = useState(false);
  const activeRef = useRef(null);
  activeRef.current = active;
  const activeItemRef = useRef(null);
  if (active === null)
    activeItemRef.current = null;
  useLayoutEffect(() => {
    const [first] = items;
    if (activateOnFocus && !active && first)
      setActive(first.id);
    if (focus)
      window.requestAnimationFrame(() => {
        var _a;
        return (_a = listRef.current) == null ? void 0 : _a.focus();
      });
  }, [focus]);
  useEffect(syncActive, [items]);
  useEffect(scrollIntoView, [active]);
  const selectItem = useCallback((item2, mods) => {
    if (!item2)
      return;
    const { id } = item2;
    const { metaKey: append, shiftKey: merge } = mods || {};
    const wasSelected = selection.includes(id);
    const active2 = activeRef.current;
    const activeIndex = items.findIndex((i) => i.id === active2);
    if (active2 !== id)
      setActive(id);
    if (wasSelected && append)
      return onSelect(selection.filter((sid) => sid !== id));
    if (multiple && append)
      return onSelect([...selection, id]);
    if (multiple && merge) {
      const clickIndex = items.findIndex((i) => i.id === id);
      const startIndex = Math.min(Math.max(activeIndex, 0), clickIndex);
      const length2 = Math.max(activeIndex, clickIndex) - startIndex + 1;
      return onSelect(Array.from({ length: length2 }, (v, i) => items[i + startIndex].id));
    }
    onSelect([id]);
  }, [items, selection, onSelect, multiple]);
  const context = useMemo(() => ({
    dragBegin,
    dragEnd,
    getItems: () => items,
    getItemProps: (item2) => ({
      ref: item2.id === activeRef.current ? activeItemRef : void 0,
      onClick: (e) => {
        selectItem(item2, e);
        if (commitOn === "click")
          onCommit == null ? void 0 : onCommit(item2);
        e.stopPropagation();
      },
      onMouseEnter: activateOnHover ? () => setActive(item2.id) : void 0,
      onMouseLeave: activateOnHover ? () => setActive(null) : void 0,
      onDoubleClick: onCommit && commitOn === "doubleClick" ? (e) => {
        onCommit(item2);
        e.stopPropagation();
      } : void 0
    })
  }), [items, selectItem, setActive]);
  return /* @__PURE__ */ React.createElement(ListContext.Provider, {
    value: context
  }, /* @__PURE__ */ React.createElement(Box, __spreadProps(__spreadValues({
    as: boxProps.as || "ul",
    ref: listRef,
    justify: "start",
    tabIndex
  }, boxProps), {
    onWheel: swapScroll ? scrollHorizontal : void 0,
    onBlur: handleBlur,
    onFocus,
    onKeyDown: handleKeyDown
  }), renderItems(items, { selection, dragging, active })));
  function syncActive() {
    if (active && !items.find((i) => i.id === active))
      setActive(null);
  }
  function handleBlur(e) {
    if (!keepActive)
      setActive(null);
    onBlur == null ? void 0 : onBlur(e);
  }
  function scrollIntoView() {
    if (!listRef.current)
      return;
    const index2 = items.findIndex((i) => i.id === active);
    const child = listRef.current.children[index2];
    child == null ? void 0 : child.scrollIntoView({ block: "nearest" });
  }
  function scrollHorizontal(e) {
    if (!listRef.current)
      return;
    e.preventDefault();
    const container = listRef.current;
    const initialScroll = container.scrollLeft;
    const delta = Math.abs(e.deltaY) > Math.abs(e.deltaX) ? e.deltaY : e.deltaX;
    container.scrollTo(initialScroll + delta, 0);
  }
  function dragEnd(item2) {
    setDragging(false);
  }
  function dragBegin(item2) {
    const draggedId = item2.id;
    const isSelected = selection.includes(draggedId);
    let draggableItems = [draggedId];
    if (isSelected) {
      draggableItems = [
        ...draggableItems,
        ...selection.filter((id) => id !== draggedId)
      ];
    } else {
      selectItem(item2);
    }
    setDragging(true);
    return draggableItems.map((id) => items.find((i) => i.id === id)).filter((i) => i);
  }
  function handleKeyDown(e) {
    var _a;
    const { key, shiftKey: append } = e;
    const activeItem = items.find((i) => i.id === active) || items[0];
    if (onKeyDown) {
      onKeyDown(e, activeItem);
      if (e.defaultPrevented)
        return;
    }
    if (key.startsWith("Arrow")) {
      e.preventDefault();
      e.stopPropagation();
      (_a = listRef.current) == null ? void 0 : _a.focus();
    }
    switch (true) {
      case key === "Enter":
        if (onCommit && activeItem)
          onCommit(activeItem);
        break;
      case key === "ArrowUp":
        return selectSiblingItem(-1, append);
      case key === "ArrowDown":
        return selectSiblingItem(1, append);
      case (horizontal && key === "ArrowRight"):
        return selectNextColumn(1, append);
      case (horizontal && key === "ArrowLeft"):
        return selectNextColumn(-1, append);
    }
  }
  function selectSiblingItem(modifier = 1, append) {
    if (!items.length)
      return setActive(null);
    const activeIndex = items.findIndex((item2) => item2.id === active);
    const index2 = Math.min(items.length - 1, Math.max(0, activeIndex < 0 ? 0 : activeIndex + modifier));
    selectItem(items[index2], { metaKey: append });
  }
  function selectNextColumn(dir = 1, append) {
    var _a;
    const activeIndex = items.findIndex((i) => i.id === active);
    if (activeIndex < 0 && items[0])
      return selectItem(items[0]);
    if (!activeItemRef.current)
      return;
    const children2 = Array.from(((_a = activeItemRef.current.parentElement) == null ? void 0 : _a.children) || []);
    const startIndex = children2.findIndex((c) => c === activeItemRef.current);
    if (children2.length <= startIndex)
      return;
    const { offsetLeft: left, offsetTop: top } = children2[startIndex];
    for (let i = startIndex; i < children2.length && i >= 0; i += dir) {
      const child = children2[i];
      if ((dir > 0 && child.offsetTop >= top || dir < 0 && child.offsetTop <= top) && (dir > 0 && child.offsetLeft > left || dir < 0 && child.offsetLeft < left)) {
        const selectIndex = activeIndex - startIndex + i;
        return selectItem(items[selectIndex], { metaKey: append });
      }
    }
  }
});
function useListContext() {
  return useContext(ListContext);
}
function normalizeItems(items) {
  if (Array.isArray(items)) {
    if (isStrings(items))
      return items.map((id) => ({ id }));
    else
      return items;
  } else {
    const isNumericKey = Object.keys(items).map((i) => parseInt(i)).findIndex(isNaN) === -1;
    return Object.entries(items).map(([id, name]) => ({
      name,
      id: isNumericKey ? parseInt(id) : id
    }));
  }
}
function noop() {
}
function isStrings(v) {
  if (!Array.isArray(v))
    return false;
  return typeof v[0] === "string";
}
var SelectList$1 = "";
const SelectList = React.forwardRef((_q, forwardRef) => {
  var _r = _q, {
    item,
    itemWidth,
    selection,
    onClose,
    onPrint,
    className = "jui-select-list"
  } = _r, props = __objRest(_r, [
    "item",
    "itemWidth",
    "selection",
    "onClose",
    "onPrint",
    "className"
  ]);
  const ItemContent = item;
  const Item = useCallback(React.memo((props2) => {
    const { item: item2, active, selected } = props2;
    const { getItemProps } = useListContext();
    return /* @__PURE__ */ React.createElement(Box, __spreadValues({
      as: "li",
      width: itemWidth,
      className: css(`${className}__item`, { active, selected }),
      cursor: "pointer"
    }, getItemProps(item2)), ItemContent ? /* @__PURE__ */ React.createElement(ItemContent, __spreadValues({}, props2)) : item2.name || item2.id);
  }), [ItemContent, itemWidth]);
  return /* @__PURE__ */ React.createElement(List, __spreadProps(__spreadValues({
    ref: forwardRef,
    className,
    alignItems: "baseline",
    activateOnHover: true,
    activateOnFocus: true
  }, props), {
    item: Item,
    selection: selection ? [selection] : [],
    onKeyDown,
    onCommit: commitSelection
  }));
  function commitSelection(item2) {
    const { id } = item2;
    onClose == null ? void 0 : onClose(id, item2);
  }
  function onKeyDown(e) {
    const isPrintable = e.key.length === 1 || e.key === "Backspace";
    if (isPrintable && onPrint) {
      e.preventDefault();
      return onPrint(e.key);
    }
    switch (e.key) {
      case "Escape":
        return onClose == null ? void 0 : onClose();
    }
  }
});
const INPUT = "input";
const DROPDOWN = "dropdown";
function Suggest(_s) {
  var _t = _s, {
    id,
    name,
    required,
    placeholder,
    from,
    item,
    value = "",
    onNew,
    onChange,
    onBlur,
    onFocus,
    className
  } = _t, props = __objRest(_t, [
    "id",
    "name",
    "required",
    "placeholder",
    "from",
    "item",
    "value",
    "onNew",
    "onChange",
    "onBlur",
    "onFocus",
    "className"
  ]);
  const [query, setQuery] = useState(value);
  const [focus, setFocus] = useState(null);
  const [dropdownVisible, setDropdownVisible] = useState(false);
  const allItems = useMemo(() => typeof from === "function" ? [] : normalizeItems(from), [from]);
  const [items, setItems] = useState(allItems);
  useEffect(() => setQuery(value), [value]);
  useEffect(() => {
    updateItems();
  }, [dropdownVisible, query, from]);
  const styles = css(["jui-suggest", className], {
    "options-visible": dropdownVisible
  });
  return /* @__PURE__ */ React.createElement(TextInput, __spreadProps(__spreadValues({}, props), {
    id,
    name,
    focus: focus === INPUT,
    value: query,
    placeholder,
    className: styles,
    onFocus: selectText,
    onBlur: onInputBlur,
    onChange: queryDidChange,
    onKeyDown,
    suffix: "\u2193",
    onSuffixClick: showDropdown
  }), dropdownVisible && items.length > 0 && /* @__PURE__ */ React.createElement(SelectList, {
    className: "jui-dropdown-list",
    zIndex: "4",
    width: "100",
    maxHeight: "l",
    padding: "s 0",
    overflow: "auto",
    position: "bottom",
    item,
    items,
    focus: focus === DROPDOWN,
    onMouseDown: focusDropdown,
    onBlur: closeAndReset,
    onClose: closeAndSelect,
    onPrint: closeAndPrint
  }));
  function focusDropdown() {
    setFocus(DROPDOWN);
  }
  function selectText(e) {
    const input = e.target;
    if (input && input.select)
      input.select();
    e.stopPropagation();
    onFocus == null ? void 0 : onFocus();
  }
  function closeAndReset() {
    setQuery(value);
    setDropdownVisible(false);
    setFocus(null);
  }
  function closeAndSelect(id2, newValue) {
    if (id2 !== void 0)
      onChange(id2, newValue);
    setQuery(value);
    setDropdownVisible(false);
    setFocus(INPUT);
  }
  function closeAndPrint(c) {
    setQuery(c === "Backspace" ? query === value ? "" : query.slice(0, -1) : query + c);
    setDropdownVisible(false);
    setFocus(INPUT);
  }
  function queryDidChange(newQuery) {
    if (newQuery !== query)
      setQuery(newQuery);
    setDropdownVisible(true);
  }
  function hideOptions(commit = true) {
    setDropdownVisible(false);
    if (!onNew)
      setQuery(value);
    if (!commit)
      return;
    if (!required && query === "")
      onChange();
    else if (onNew && (!required || query)) {
      if (query !== value)
        onNew(query);
    }
  }
  function showDropdown() {
    setDropdownVisible(true);
    setFocus(DROPDOWN);
  }
  function onInputBlur() {
    if (focus === INPUT)
      setFocus(null);
    if (!dropdownVisible && onBlur)
      onBlur();
    if (focus !== DROPDOWN)
      hideOptions();
  }
  function onKeyDown(e) {
    switch (e.key) {
      case "Backspace":
        if (value === query) {
          e.preventDefault();
          setQuery("");
        }
        break;
      case "Escape":
        if (onNew)
          setQuery(value);
        return hideOptions(false);
      case "Enter":
        return hideOptions();
      case "ArrowDown":
        e.preventDefault();
        e.stopPropagation();
        showDropdown();
        break;
    }
  }
  async function updateItems() {
    if (!dropdownVisible)
      return;
    const term = query.toLowerCase();
    const newItems = typeof from === "function" ? normalizeItems(await from(query === value ? "" : query)) : query === value ? allItems : allItems.filter(({ name: name2, id: id2 }) => `${id2}`.toLowerCase().includes(term) || (name2 == null ? void 0 : name2.toLowerCase().includes(term)));
    setItems(newItems);
    if (!newItems.length) {
      setDropdownVisible(false);
      setFocus(INPUT);
    }
  }
}
const Messages$2 = {
  presence: () => "is required",
  between: (from, to) => `not within ${from} - ${to}`,
  unique: () => "non unique",
  match: () => "not match",
  format: () => "not in format",
  lengthShort: (min) => `too short (min ${min})`,
  lengthLong: (max) => `too long (max ${max})`,
  slug: () => "should start with letter and contain only letters, digits or dashes",
  email: () => "not like email",
  passwordLower: (min) => `min ${min} lower chars`,
  passwordUpper: (min) => `min ${min} upper chars`,
  passwordDigit: (min) => `min ${min} digits`,
  passwordSymbols: (min) => `min ${min} symbols #?!@$%^&*-`
};
const SLUG = /^[a-z]+(?:-[a-z0-9]+)*$/;
const EMAIL = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
const Messages$1 = __spreadValues({}, Messages$2);
function setValidationMessages(messages) {
  for (const key in messages) {
    Messages$1[key] = messages[key];
  }
}
function presence(v) {
  const isEmpty = v === "" || v === null || v === void 0;
  return isEmpty && Messages$1.presence();
}
function between(from, to) {
  return (value) => {
    const result = +value;
    return (result < from || result > to) && Messages$1.between(from.toString(), to.toString());
  };
}
function match(value, message) {
  return (v) => value && value !== v && (message || Messages$1.match());
}
function unique(other) {
  return (value) => other.includes(value) && Messages$1.unique();
}
function format(re, message) {
  return (value) => !re.test("" + value) && (message ? typeof message === "function" ? message() : message : Messages$1.format());
}
function length(min, max = Infinity) {
  return ({ length: length2 }) => length2 < min ? Messages$1.lengthShort(min.toString()) : max < Infinity && length2 > max && Messages$1.lengthLong(max.toString());
}
const slug = format(SLUG, () => Messages$1.slug());
const email = format(EMAIL, () => Messages$1.email());
function password({
  lower = 3,
  upper = 2,
  digits = 2,
  special = 1,
  length: minLength = 8
} = {}) {
  const rule = (re, count) => new RegExp(`(.*${re}){${count},}`);
  return [
    length(minLength),
    format(rule("[a-z]", lower), () => Messages$1.passwordLower(lower.toString())),
    format(rule("[A-Z]", upper), () => Messages$1.passwordUpper(upper.toString())),
    format(rule("[0-9]", digits), () => Messages$1.passwordDigit(digits.toString())),
    format(rule("[#?!@$%^&*-]", special), () => Messages$1.passwordSymbols(special.toString()))
  ];
}
var validators = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  [Symbol.toStringTag]: "Module",
  setValidationMessages,
  presence,
  between,
  match,
  unique,
  format,
  length,
  slug,
  email,
  password
});
var Field$1 = "";
function Field(_u) {
  var _v = _u, {
    className,
    id: givenId,
    name: givenName,
    icon,
    label,
    required,
    validate: validateFns,
    locale,
    masked,
    numeric,
    multiline = false,
    errors: userErrors = [],
    suffix,
    onSuffixClick,
    prefix,
    onPrefixClick,
    from,
    item,
    value: actualValue,
    convert,
    onChange,
    onNewSuggestion,
    validateNewSuggestion: validateNew,
    input: InputComponent,
    inputProps: customInputProps
  } = _v, props = __objRest(_v, [
    "className",
    "id",
    "name",
    "icon",
    "label",
    "required",
    "validate",
    "locale",
    "masked",
    "numeric",
    "multiline",
    "errors",
    "suffix",
    "onSuffixClick",
    "prefix",
    "onPrefixClick",
    "from",
    "item",
    "value",
    "convert",
    "onChange",
    "onNewSuggestion",
    "validateNewSuggestion",
    "input",
    "inputProps"
  ]);
  const validators2 = Array.isArray(validateFns) ? validateFns.flat(2) : validateFns ? [validateFns] : [];
  const newValidators = Array.isArray(validateNew) ? validateNew.flat(2) : validateNew ? [validateNew] : [];
  if (required) {
    validators2.unshift(presence);
    newValidators.unshift(presence);
  }
  const formatter = useMemo(() => getFormatter(locale), [locale]);
  const value = isNone(actualValue) ? "" : typeof actualValue === "number" ? formatter.format(actualValue) : actualValue || "";
  const [proxy, setProxy] = useState(value);
  const [errors, setErrors] = useState([]);
  useEffect(() => {
    setErrors([]);
    setProxy(value);
  }, [value]);
  const converter = useMemo(() => typeof convert === "function" ? convert : convert === "lowercase" ? convertToLowercase : convert === "uppercase" ? convertToUppercase : numeric ? onlyNumbers : null, [convert, formatter]);
  const onInputChange = (value2) => setProxy(converter ? converter(value2) : value2);
  const inputStyles = css("jui-field__input", {
    "with-suffix": !!suffix
  });
  const allErrors = [...new Set(errors.concat(userErrors ? userErrors : []))];
  const id = useMemo(() => givenId || getRandomId(), [givenId]);
  const [styles, attrs] = useBoxItem(props, css(["jui-field", className], {
    "has-errors": allErrors.length > 0
  }));
  const inputProps = __spreadProps(__spreadValues({}, attrs), { id });
  return /* @__PURE__ */ React.createElement("div", {
    className: styles
  }, label && /* @__PURE__ */ React.createElement("label", {
    className: "jui-label jui-field__label",
    htmlFor: id
  }, label), /* @__PURE__ */ React.createElement("div", {
    className: "jui-field__frame"
  }, icon && /* @__PURE__ */ React.createElement(Icon, {
    className: css("jui-field__symbol", {
      prefix: true,
      active: !!onPrefixClick
    })
  }, icon), prefix && /* @__PURE__ */ React.createElement("div", {
    onClick: onPrefixClick,
    className: css("jui-field__symbol", {
      prefix: true,
      active: !!onPrefixClick
    })
  }, prefix), from ? /* @__PURE__ */ React.createElement(Suggest, __spreadProps(__spreadValues({}, inputProps), {
    item,
    from,
    value,
    onNew: onNewSuggestion ? validateNewSuggestion : void 0,
    className: inputStyles,
    onChange: validateSuggestion
  })) : InputComponent ? /* @__PURE__ */ React.createElement(InputComponent, __spreadProps(__spreadValues(__spreadValues({}, inputProps), customInputProps), {
    className: inputStyles,
    onChange: validateAndNotify,
    value
  })) : /* @__PURE__ */ React.createElement(TextInput, __spreadProps(__spreadValues({}, inputProps), {
    type: masked ? "password" : void 0,
    value: proxy,
    multiline,
    onChange: onInputChange,
    className: inputStyles,
    onKeyDown: commitOnEnter,
    onBlur: () => validateAndNotify(proxy)
  })), suffix && /* @__PURE__ */ React.createElement("div", {
    onClick: onSuffixClick,
    className: css("jui-field__symbol", {
      suffix: true,
      active: !!onSuffixClick
    })
  }, suffix)), allErrors.length > 0 && /* @__PURE__ */ React.createElement("ul", {
    className: "jui-field__errors"
  }, allErrors.map((error, i) => /* @__PURE__ */ React.createElement("li", {
    key: error + i,
    className: "jui-field__error"
  }, error))));
  function validateNewSuggestion(id2) {
    const value2 = id2 || "";
    const errors2 = newValidators.map((validate) => validate(value2)).filter(Boolean);
    setErrors(errors2);
    if (!errors2.length && onNewSuggestion)
      onNewSuggestion(value2);
  }
  function validateSuggestion(id2, v) {
    validateAndNotify(v);
  }
  function commitOnEnter(e) {
    const input = e.target;
    switch (e.key) {
      case "Escape":
        e.preventDefault();
        return setProxy(value);
      case "Enter":
        return validateAndNotify(input.value);
    }
  }
  function validateAndNotify(newValue, externalErrors = []) {
    if (!required && "" + newValue === "") {
      setErrors([]);
      if (newValue !== value)
        onChange(newValue);
      return;
    }
    if (numeric && newValue) {
      newValue = convertToNumber(formatter, newValue);
      if (isNaN(newValue)) {
        setProxy(value);
        return;
      }
    }
    const errors2 = [
      ...validators2.map((validate) => validate(newValue)).filter(Boolean),
      ...externalErrors
    ];
    setErrors(errors2);
    if (errors2.length)
      return;
    if (numeric)
      setProxy(formatter.format(newValue));
    const isScalar = ["string", "number"].includes(typeof newValue);
    if (!isScalar || newValue !== value)
      onChange(newValue);
  }
}
const isNone = (v) => v === void 0 || v === null;
const convertToLowercase = (v) => v.toLowerCase();
const convertToUppercase = (v) => v.toUpperCase();
const onlyNumbers = (v) => v.replaceAll(/[^\-\d\., `]/g, "");
function convertToNumber(formatter, value) {
  if (!value || typeof value === "number")
    return value;
  const thousands = formatter.format(1e3)[1];
  const decimal = formatter.format(1.5)[1];
  const parsable = value.replaceAll(thousands, "").replace(decimal, ".").replaceAll(/[^\-\d\.]/g, "");
  return Number(parsable);
}
const formatters = {};
const getFormatter = (locale = "") => {
  let formatter = formatters[locale];
  if (!formatter) {
    try {
      formatter = formatters[locale] = new Intl.NumberFormat(locale ? locale : void 0);
    } catch (e) {
      return new Intl.NumberFormat();
    }
  }
  return formatter;
};
const Messages = {
  presence: () => "\u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u043F\u0443\u0441\u0442\u044B\u043C",
  between: (from, to) => `\u043D\u0435 \u0432 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D\u0435 \u043E\u0442 ${from} \u0434\u043E ${to}`,
  unique: () => "\u0443\u0436\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442",
  match: () => "\u043D\u0435 \u0441\u043E\u0432\u043F\u0430\u0434\u0430\u0435\u0442",
  format: () => "\u043D\u0435 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u0435\u0442 \u0444\u043E\u0440\u043C\u0430\u0442\u0443",
  lengthShort: (min) => `\u0441\u043B\u0438\u0448\u043A\u043E\u043C \u043A\u043E\u0440\u043E\u0442\u043A\u043E\u0435 (\u043C\u0438\u043D. ${min})`,
  lengthLong: (max) => `\u0441\u043B\u0438\u0448\u043A\u043E\u043C \u0434\u043B\u0438\u043D\u043D\u043E\u0435 (\u043C\u0438\u043D. ${max})`,
  slug: () => "\u0434\u043E\u043B\u0436\u0435\u043D \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 \u0431\u0443\u043A\u0432\u044B \u0438 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C \u0442\u043E\u043B\u044C\u043A\u043E \u0431\u0443\u043A\u0432\u044B, \u0446\u0438\u0444\u0440\u044B \u0438\u043B\u0438 \u0442\u0438\u0440\u0435",
  email: () => "\u043D\u0435 \u044F\u0432\u043B\u044F\u0435\u0442\u0441\u044F \u043F\u043E\u0447\u0442\u043E\u0439",
  passwordLower: (min) => `\u043C\u0438\u043D\u0438\u043C\u0443\u043C ${min} \u043F\u0440\u043E\u043F\u0438\u0441\u043D\u044B\u0445 \u0431\u0443\u043A\u0432`,
  passwordUpper: (min) => `\u043C\u0438\u043D\u0438\u043C\u0443\u043C ${min} \u0437\u0430\u0433\u043B\u0430\u0432\u043D\u044B\u0445 \u0431\u0443\u043A\u0432`,
  passwordDigit: (min) => `\u043C\u0438\u043D\u0438\u043C\u0443\u043C ${min} \u0446\u0438\u0444\u0440`,
  passwordSymbols: (min) => `\u043C\u0438\u043D\u0438\u043C\u0443\u043C ${min} \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432 #?!@$%^&*-`
};
var index = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  [Symbol.toStringTag]: "Module",
  ru: Messages,
  en: Messages$2
});
var Radio$1 = "";
function Radio(_w) {
  var _x = _w, {
    name,
    label,
    value,
    onChange,
    children
  } = _x, props = __objRest(_x, [
    "name",
    "label",
    "value",
    "onChange",
    "children"
  ]);
  const nameRef = useRef(name || getRandomId());
  return /* @__PURE__ */ React.createElement(Box, __spreadValues({
    className: "jui-choice",
    spacing: "s"
  }, props), Object.entries(children).map(([itemValue, label2]) => /* @__PURE__ */ React.createElement("label", {
    key: itemValue,
    className: "jui-box__item jui-choice__item"
  }, /* @__PURE__ */ React.createElement("input", {
    className: "jui-choice__input",
    type: "radio",
    name: nameRef.current,
    value: itemValue,
    checked: value === itemValue,
    onChange: (e) => onChange(e.target.value)
  }), /* @__PURE__ */ React.createElement("span", {
    className: "jui-choice__label"
  }, label2))));
}
var Text$1 = "";
const Text = React.forwardRef((_y, forwardedRef) => {
  var _z = _y, {
    h1,
    h2,
    h3,
    h4,
    h5,
    block,
    sup,
    sub,
    caps,
    monospace,
    underline,
    link,
    href,
    right,
    center,
    line,
    icon,
    iconPosition = "before",
    truncate,
    lineClamp,
    small,
    large,
    size = small ? "s" : large ? "l" : void 0,
    strong,
    weight = strong ? "medium" : void 0,
    leading,
    spacing,
    className,
    children,
    as = block ? "div" : sup ? "sup" : sub ? "sub" : "span"
  } = _z, props = __objRest(_z, [
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "block",
    "sup",
    "sub",
    "caps",
    "monospace",
    "underline",
    "link",
    "href",
    "right",
    "center",
    "line",
    "icon",
    "iconPosition",
    "truncate",
    "lineClamp",
    "small",
    "large",
    "size",
    "strong",
    "weight",
    "leading",
    "spacing",
    "className",
    "children",
    "as"
  ]);
  const header = h1 && "h1" || h2 && "h2" || h3 && "h3" || h4 && "h4" || h5 && "h5";
  const Tag = href ? "a" : header || as;
  const iconType = !!icon && children ? iconPosition : null;
  const align = center ? "center" : right ? "right" : null;
  const [styles, attrs] = useBoxItem(props, css(["jui-text", className], {
    block,
    [`header-${header}`]: !!header,
    link,
    line,
    caps,
    small,
    large,
    truncate,
    monospace,
    underline,
    "line-clamp": !!lineClamp,
    [`line-clamp-${lineClamp}`]: typeof lineClamp === "string",
    "with-icon": !!icon,
    [`with-${iconType}-icon`]: !!iconType,
    [`size-${size}`]: !!size,
    [`align-${align}`]: !!align,
    [`weight-${weight}`]: !!weight,
    [`leading-${leading}`]: !!leading,
    [`block-spacing-${spacing}`]: block && !!spacing,
    [`${sub ? "sub" : "super"}script`]: sub || sup
  }));
  return /* @__PURE__ */ React.createElement(Tag, __spreadProps(__spreadValues({}, attrs), {
    ref: forwardedRef,
    href: Tag === "a" ? href : void 0,
    className: styles
  }), icon && iconPosition === "before" && /* @__PURE__ */ React.createElement(Icon, null, icon), children, icon && iconPosition === "after" && /* @__PURE__ */ React.createElement(Icon, null, icon));
});
var Theme$1 = "";
function Theme({ className, stylesheet, children }) {
  const [currentStylesheet, setCurrentStylesheet] = useState("");
  useEffect(() => {
    if (currentStylesheet)
      removeStylesheet(currentStylesheet);
    if (stylesheet) {
      addStylesheet(stylesheet);
      setCurrentStylesheet(stylesheet);
      return () => removeStylesheet(stylesheet);
    }
  }, [stylesheet]);
  return /* @__PURE__ */ React.createElement("div", {
    className: css(["jui-theme", className])
  }, /* @__PURE__ */ React.createElement("div", {
    className: "jui-theme__computed"
  }, children));
}
function addStylesheet(href) {
  const link = document.createElement("link");
  link.rel = "stylesheet";
  link.href = href;
  document.head.append(link);
}
function removeStylesheet(href) {
  var _a;
  const stylesheet = Array.from(document.styleSheets).find((s) => s.href === href);
  if (stylesheet)
    stylesheet.disabled = true;
  (_a = document.querySelector(`link[href="${href}"]`)) == null ? void 0 : _a.remove();
}
export { Box, Button, Checkbox, ContentEditable, Dropdown, Field, Icon, List, Radio, SelectList, Suggest, Text, TextInput, Theme, css, useBoxItem, useListContext, index as validationMessages, validators };
