'use client';
'use strict';

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

var date = require('@internationalized/date');
var datepicker = require('@react-aria/datepicker');
var i18n = require('@react-aria/i18n');
var datepicker$1 = require('@react-stately/datepicker');
var React = require('react');
var core = require('@keystar/ui/core');
var field = require('@keystar/ui/field');
var utils = require('@react-aria/utils');
var focus = require('@react-aria/focus');
var style = require('@keystar/ui/style');
var utils$1 = require('@keystar/ui/utils');
var jsxRuntime = require('react/jsx-runtime');
var typography = require('@keystar/ui/typography');

function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefault(React);

const Input = /*#__PURE__*/React.forwardRef(function Input(props, ref) {
  let inputRef = React.useRef(null);
  let {
    children,
    className,
    disableFocusRing,
    fieldProps,
    inputClassName,
    isDisabled,
    style: style$1,
    validationState
  } = props;
  let {
    focusProps,
    isFocusVisible,
    isFocused
  } = focus.useFocusRing({
    isTextInput: true,
    within: true
  });
  let isInvalid = validationState === 'invalid' && !isDisabled;
  let inputStyles = useInputStyles(inputClassName, {
    isDisabled,
    isInvalid,
    isFocused,
    isFocusVisible: isFocusVisible && !disableFocusRing
  });
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    role: "presentation",
    ...utils.mergeProps(fieldProps, focusProps),
    className: className,
    style: style$1,
    children: /*#__PURE__*/jsxRuntime.jsx("div", {
      role: "presentation",
      ...inputStyles,
      children: /*#__PURE__*/jsxRuntime.jsx("div", {
        role: "presentation",
        className: style.css({
          alignItems: 'center',
          display: 'flex',
          height: '100%',
          overflowX: 'auto',
          scrollbarWidth: 'none',
          msOverflowStyle: 'none'
        }),
        ref: utils.mergeRefs(ref, inputRef),
        children: children
      })
    })
  });
});
function useInputStyles(inputClassName, state) {
  let {
    isDisabled,
    isInvalid,
    isFocused,
    isFocusVisible
  } = state;
  let className = style.classNames(inputClassName, style.css({
    backgroundColor: style.tokenSchema.color.background.canvas,
    border: `${style.tokenSchema.size.border.regular} solid ${style.tokenSchema.color.alias.borderIdle}`,
    borderRadius: style.tokenSchema.size.radius.regular,
    height: style.tokenSchema.size.element.regular,
    lineHeight: style.tokenSchema.typography.lineheight.small,
    outline: 0,
    overflow: 'visible',
    paddingBlock: style.tokenSchema.size.space.small,
    paddingInline: style.tokenSchema.size.space.medium,
    position: 'relative',
    textIndent: 0,
    verticalAlign: 'top',
    minWidth: style.tokenSchema.size.scale[2000],
    width: '100%',
    '&[data-invalid=true]': {
      borderColor: style.tokenSchema.color.alias.borderInvalid
    },
    '&[data-focus]': {
      borderColor: style.tokenSchema.color.alias.borderFocused,
      boxShadow: `0 0 0 1px ${style.tokenSchema.color.alias.borderFocused}`
    },
    '&[data-disabled=true]': {
      backgroundColor: style.tokenSchema.color.background.surfaceSecondary,
      borderColor: 'transparent'
    }
  }));
  return {
    ...utils$1.toDataAttributes({
      disabled: isDisabled || undefined,
      invalid: isInvalid || undefined,
      focus: isFocusVisible ? 'visible' : isFocused || undefined
    }),
    className
  };
}

function InputSegment(_ref) {
  let {
    segment,
    state,
    ...otherProps
  } = _ref;
  if (segment.type === 'literal') {
    return /*#__PURE__*/jsxRuntime.jsx(LiteralSegment, {
      segment: segment
    });
  }
  return /*#__PURE__*/jsxRuntime.jsx(EditableSegment, {
    segment: segment,
    state: state,
    ...otherProps
  });
}

/** A separator, e.g. punctuation like "/" or "." */
function LiteralSegment(_ref2) {
  let {
    segment
  } = _ref2;
  return /*#__PURE__*/jsxRuntime.jsx(typography.Text, {
    elementType: "span",
    "aria-hidden": "true",
    color: "neutralTertiary",
    trim: false,
    UNSAFE_className: style.css({
      userSelect: 'none',
      whiteSpace: 'pre'
    }),
    "data-testid": segment.type === 'literal' ? undefined : segment.type,
    children: segment.text
  });
}
function EditableSegment(_ref3) {
  let {
    segment,
    state
  } = _ref3;
  let ref = React.useRef(null);
  let {
    segmentProps
  } = datepicker.useDateSegment(segment, state, ref);
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    ...segmentProps,
    ...utils$1.toDataAttributes({
      placeholder: segment.isPlaceholder,
      readonly: !segment.isEditable
    }),
    ref: ref,
    className: style.css({
      borderRadius: style.tokenSchema.size.radius.small,
      color: style.tokenSchema.color.foreground.neutral,
      paddingInline: style.tokenSchema.size.space.xsmall,
      // text styles
      fontFamily: style.tokenSchema.typography.fontFamily.base,
      fontSize: style.tokenSchema.typography.text.regular.size,
      fontVariantNumeric: 'tabular-nums',
      fontWeight: style.tokenSchema.typography.fontWeight.regular,
      lineHeight: style.tokenSchema.typography.lineheight.small,
      whiteSpace: 'nowrap',
      MozOsxFontSmoothing: 'auto',
      WebkitFontSmoothing: 'auto',
      '[dir=ltr] &': {
        textAlign: 'right'
      },
      '[dir=rtl] &': {
        textAlign: 'left'
      },
      '&[data-placeholder=true]': {
        color: style.tokenSchema.color.foreground.neutralTertiary
      },
      '&:focus': {
        backgroundColor: style.tokenSchema.color.background.accentEmphasis,
        color: style.tokenSchema.color.foreground.onEmphasis,
        outline: 'none'
      }
    }),
    style: {
      ...segmentProps.style,
      minWidth: segment.maxValue != null ? String(segment.maxValue).length + 'ch' : undefined
    },
    "data-testid": segment.type,
    children: [/*#__PURE__*/jsxRuntime.jsx("span", {
      "aria-hidden": "true",
      "data-hidden": !segment.isPlaceholder,
      className: style.css({
        display: 'block',
        fontStyle: 'italic',
        height: '0',
        pointerEvents: 'none',
        textAlign: 'center',
        visibility: 'hidden',
        width: '100%',
        '&[data-hidden=false]': {
          height: 'auto',
          visibility: 'visible'
        }
      }),
      children: segment.placeholder
    }), !segment.isPlaceholder && segment.text]
  });
}

function useFormatHelpText(props) {
  let formatter = i18n.useDateFormatter({
    dateStyle: 'short'
  });
  let displayNames = datepicker.useDisplayNames();
  return React.useMemo(() => {
    if (props.description) {
      return props.description;
    }
    if (props.showFormatHelpText) {
      return formatter.formatToParts(new Date()).map(s => {
        if (s.type === 'literal') {
          return s.value;
        }

        // @ts-expect-error - not sure what's going on here
        return displayNames.of(s.type);
      }).join(' ');
    }
    return '';
  }, [props.description, props.showFormatHelpText, formatter, displayNames]);
}
function useFocusManagerRef(ref) {
  let domRef = React.useRef(null);
  // @ts-expect-error - useImperativeHandle wants all properties from `ref`, wtf???
  React.useImperativeHandle(ref, () => ({
    focus() {
      focus.createFocusManager(domRef).focusFirst({
        tabbable: true
      });
    }
  }));
  return domRef;
}

function DateField(props, ref) {
  props = core.useProviderProps(props);
  let {
    autoFocus,
    isDisabled,
    isReadOnly,
    isRequired
  } = props;
  let domRef = useFocusManagerRef(ref);
  let {
    locale
  } = i18n.useLocale();
  let state = datepicker$1.useDateFieldState({
    ...props,
    locale,
    createCalendar: date.createCalendar
  });
  let inputRef = React.useRef(null);
  let {
    labelProps,
    fieldProps,
    descriptionProps,
    errorMessageProps
  } = datepicker.useDateField(props, state, inputRef);

  // Note: this description is intentionally not passed to useDatePicker.
  // The format help text is unnecessary for screen reader users because each segment already has a label.
  let description = useFormatHelpText(props);
  if (description && !props.description) {
    descriptionProps.id = undefined;
  }
  if (props.errorMessage) {
    state.validationState = 'invalid';
  }
  return /*#__PURE__*/jsxRuntime.jsx(field.FieldPrimitive, {
    ...props,
    ref: domRef,
    description: description,
    labelProps: labelProps,
    descriptionProps: descriptionProps,
    errorMessageProps: errorMessageProps
    // validationState={state.validationState}
    ,
    children: /*#__PURE__*/jsxRuntime.jsx(Input, {
      ref: inputRef,
      fieldProps: fieldProps,
      isDisabled: isDisabled,
      autoFocus: autoFocus,
      validationState: state.validationState,
      children: state.segments.map((segment, i) => /*#__PURE__*/jsxRuntime.jsx(InputSegment, {
        segment: segment,
        state: state,
        isDisabled: isDisabled,
        isReadOnly: isReadOnly,
        isRequired: isRequired
      }, i))
    })
  });
}

// forwardRef doesn't support generic parameters, so cast the result to the correct type
// https://stackoverflow.com/questions/58469229/react-with-typescript-generics-while-using-react-forwardref

/**
 * DateFields allow users to enter and edit date and time values using a keyboard.
 * Each part of a date value is displayed in an individually editable segment.
 */
const _DateField = /*#__PURE__*/React__default["default"].forwardRef(DateField);

function TimeField(props, ref) {
  props = core.useProviderProps(props);
  let {
    autoFocus,
    isDisabled,
    isReadOnly,
    isRequired
  } = props;
  let domRef = useFocusManagerRef(ref);
  let {
    locale
  } = i18n.useLocale();
  let state = datepicker$1.useTimeFieldState({
    ...props,
    locale
  });
  let inputRef = React.useRef(null);
  let {
    labelProps,
    fieldProps,
    descriptionProps,
    errorMessageProps
  } = datepicker.useTimeField(props, state, inputRef);
  if (props.errorMessage) {
    state.validationState = 'invalid';
  }
  return /*#__PURE__*/jsxRuntime.jsx(field.FieldPrimitive, {
    ...props,
    ref: domRef,
    labelProps: labelProps,
    descriptionProps: descriptionProps,
    errorMessageProps: errorMessageProps
    // validationState={state.validationState}
    ,
    children: /*#__PURE__*/jsxRuntime.jsx(Input, {
      ref: inputRef,
      fieldProps: fieldProps,
      isDisabled: isDisabled,
      autoFocus: autoFocus,
      validationState: state.validationState,
      children: state.segments.map((segment, i) => /*#__PURE__*/jsxRuntime.jsx(InputSegment, {
        segment: segment,
        state: state,
        isDisabled: isDisabled,
        isReadOnly: isReadOnly,
        isRequired: isRequired
      }, i))
    })
  });
}

// forwardRef doesn't support generic parameters, so cast the result to the correct type
// https://stackoverflow.com/questions/58469229/react-with-typescript-generics-while-using-react-forwardref

/**
 * TimeFields allow users to enter and edit time values using a keyboard.
 * Each part of the time is displayed in an individually editable segment.
 */
const _TimeField = /*#__PURE__*/React__default["default"].forwardRef(TimeField);

exports.DateField = _DateField;
exports.TimeField = _TimeField;
