import { dynamic } from "@solidjs/web";
import { createMemo, omit } from "solid-js";
import { composeRefs, userRef } from "../../internals/compose-refs.jsx";
import { mergeRootProps } from "../../internals/merge-root-props.jsx";
import { resolveClassStyle } from "../../internals/resolve-class-style.jsx";
import { useSelectRootContext } from "../select-root-context.jsx";
import { hasNullItemLabel, resolveMultipleLabels, resolveSelectedLabel } from "../utils/resolve-value-label.jsx";
export function SelectValue(props) {
  const root = useSelectRootContext();
  const setValueRef = el => {
    root.valueRef.current = el;
  };
  const hasSelectedValue = createMemo(() => {
    const v = root.value();
    if (v == null) return false;
    if (root.multiple() && Array.isArray(v)) return v.length > 0;
    return true;
  });
  const state = createMemo(() => ({
    value: root.value(),
    placeholder: !hasSelectedValue()
  }));
  const hasNullLabel = createMemo(() => {
    const childrenProp = props.children;
    if (hasSelectedValue() || props.placeholder == null || childrenProp != null) {
      return false;
    }
    return hasNullItemLabel(root.items());
  });
  const resolvedChildren = createMemo(() => {
    const childrenProp = props.children;
    const v = root.value();
    if (typeof childrenProp === "function") {
      // `root.value()` is `unknown` at runtime; the `Value` generic is a
      // typed convenience for callers, so cast at this boundary.
      return childrenProp(v);
    }
    if (childrenProp != null) return childrenProp;
    if (!hasSelectedValue() && props.placeholder != null && !hasNullLabel()) {
      return props.placeholder;
    }
    if (Array.isArray(v)) {
      return resolveMultipleLabels(v, root.items(), root.itemToStringLabel());
    }
    return resolveSelectedLabel(v, root.items(), root.itemToStringLabel());
  });
  const internal = {
    get children() {
      return resolvedChildren();
    }
  };
  const userClassStyle = resolveClassStyle(props, () => state());
  // Strip `placeholder` and `children` (children may be a formatter fn).
  const userProps = omit(props, "as", "class", "style", "attrs", "placeholder", "children");
  let merged = mergeRootProps(internal, userClassStyle);
  merged = mergeRootProps(merged, userProps);
  const Tag = dynamic(() => props.as ?? "span");
  return <Tag {...merged} ref={composeRefs(setValueRef, userRef(props))} />;
}
//# sourceMappingURL=select-value.jsx.map
