/*!
 * KoliBri - The accessible HTML-Standard
 */
import { e as watchBoolean, g as watchString, p as parseJson, o as objectObjectHandler, b as watchValidator, G as isObject$1, i as isString, s as setState, k as a11yHint } from './common-DEEjER7G.js';
import { v as validateAccessKey, a as validateAccessAndShortKey, b as validateShortKey, c as validateTabIndex } from './access-and-short-key-CnWGdP5U.js';
import { v as validateDisabled } from './disabled-CtaJsBT2.js';
import { v as validateHideLabel } from './hide-label-CWFMK5Iz.js';
import { a as validateLabelWithExpertSlot } from './label-Cg7TG_7b.js';
import { v as validateTooltipAlign } from './tooltip-align-DzHPWEpv.js';
import { v as validateVariantClassName } from './variant-class-name-CkfE8oGZ.js';
import { d as dispatchDomEvent, K as KolEvent } from './events-BhfZTW2e.js';
import { A as AssociatedInputController } from './associated.controller-D55JWKjs.js';
import { i as isObject } from './_Uint8Array-kJHDjtoP.js';
import { i as isObjectLike, b as baseGetTag, r as root } from './isArray-CcrBs4JM.js';
import { a as __rest } from './tslib.es6-QNbPBOk5.js';
import { h, F as Fragment } from './index-Brmny3Vg.js';
import { B as BaseWebComponent } from './variant-quote-BMV8GZX8.js';
import { T as TooltipFC } from './component-DTx6ZVqq.js';
import { T as TooltipController } from './controller-oT8Y98Yc.js';
import { S as SpanFC, b as buildBadgeTextString, s as showExpertSlot } from './component-CQaxTS4u.js';
import { c as clsx } from './clsx-COFh-Vc8.js';
import { a as createRelatedUniqueId } from './dev.utils-HhhlYW_9.js';
import { t as translate } from './i18n-CaL2ODdQ.js';
import { K as KolAlertFc } from './Alert-COvq80W3.js';

/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';

/**
 * Checks if `value` is classified as a `Symbol` primitive or object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
 * @example
 *
 * _.isSymbol(Symbol.iterator);
 * // => true
 *
 * _.isSymbol('abc');
 * // => false
 */
function isSymbol(value) {
  return typeof value == 'symbol' ||
    (isObjectLike(value) && baseGetTag(value) == symbolTag);
}

/** Used to match a single whitespace character. */
var reWhitespace = /\s/;

/**
 * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
 * character of `string`.
 *
 * @private
 * @param {string} string The string to inspect.
 * @returns {number} Returns the index of the last non-whitespace character.
 */
function trimmedEndIndex(string) {
  var index = string.length;

  while (index-- && reWhitespace.test(string.charAt(index))) {}
  return index;
}

/** Used to match leading whitespace. */
var reTrimStart = /^\s+/;

/**
 * The base implementation of `_.trim`.
 *
 * @private
 * @param {string} string The string to trim.
 * @returns {string} Returns the trimmed string.
 */
function baseTrim(string) {
  return string
    ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
    : string;
}

/** Used as references for various `Number` constants. */
var NAN = 0 / 0;

/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;

/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;

/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;

/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;

/**
 * Converts `value` to a number.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to process.
 * @returns {number} Returns the number.
 * @example
 *
 * _.toNumber(3.2);
 * // => 3.2
 *
 * _.toNumber(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toNumber(Infinity);
 * // => Infinity
 *
 * _.toNumber('3.2');
 * // => 3.2
 */
function toNumber(value) {
  if (typeof value == 'number') {
    return value;
  }
  if (isSymbol(value)) {
    return NAN;
  }
  if (isObject(value)) {
    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
    value = isObject(other) ? (other + '') : other;
  }
  if (typeof value != 'string') {
    return value === 0 ? value : +value;
  }
  value = baseTrim(value);
  var isBinary = reIsBinary.test(value);
  return (isBinary || reIsOctal.test(value))
    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
    : (reIsBadHex.test(value) ? NAN : +value);
}

/**
 * Gets the timestamp of the number of milliseconds that have elapsed since
 * the Unix epoch (1 January 1970 00:00:00 UTC).
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Date
 * @returns {number} Returns the timestamp.
 * @example
 *
 * _.defer(function(stamp) {
 *   console.log(_.now() - stamp);
 * }, _.now());
 * // => Logs the number of milliseconds it took for the deferred invocation.
 */
var now = function() {
  return root.Date.now();
};

/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
    nativeMin = Math.min;

/**
 * Creates a debounced function that delays invoking `func` until after `wait`
 * milliseconds have elapsed since the last time the debounced function was
 * invoked. The debounced function comes with a `cancel` method to cancel
 * delayed `func` invocations and a `flush` method to immediately invoke them.
 * Provide `options` to indicate whether `func` should be invoked on the
 * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
 * with the last arguments provided to the debounced function. Subsequent
 * calls to the debounced function return the result of the last `func`
 * invocation.
 *
 * **Note:** If `leading` and `trailing` options are `true`, `func` is
 * invoked on the trailing edge of the timeout only if the debounced function
 * is invoked more than once during the `wait` timeout.
 *
 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
 *
 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
 * for details over the differences between `_.debounce` and `_.throttle`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to debounce.
 * @param {number} [wait=0] The number of milliseconds to delay.
 * @param {Object} [options={}] The options object.
 * @param {boolean} [options.leading=false]
 *  Specify invoking on the leading edge of the timeout.
 * @param {number} [options.maxWait]
 *  The maximum time `func` is allowed to be delayed before it's invoked.
 * @param {boolean} [options.trailing=true]
 *  Specify invoking on the trailing edge of the timeout.
 * @returns {Function} Returns the new debounced function.
 * @example
 *
 * // Avoid costly calculations while the window size is in flux.
 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
 *
 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
 * jQuery(element).on('click', _.debounce(sendMail, 300, {
 *   'leading': true,
 *   'trailing': false
 * }));
 *
 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
 * var source = new EventSource('/stream');
 * jQuery(source).on('message', debounced);
 *
 * // Cancel the trailing debounced invocation.
 * jQuery(window).on('popstate', debounced.cancel);
 */
function debounce(func, wait, options) {
  var lastArgs,
      lastThis,
      maxWait,
      result,
      timerId,
      lastCallTime,
      lastInvokeTime = 0,
      leading = false,
      maxing = false,
      trailing = true;

  if (typeof func != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  wait = toNumber(wait) || 0;
  if (isObject(options)) {
    leading = !!options.leading;
    maxing = 'maxWait' in options;
    maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
    trailing = 'trailing' in options ? !!options.trailing : trailing;
  }

  function invokeFunc(time) {
    var args = lastArgs,
        thisArg = lastThis;

    lastArgs = lastThis = undefined;
    lastInvokeTime = time;
    result = func.apply(thisArg, args);
    return result;
  }

  function leadingEdge(time) {
    // Reset any `maxWait` timer.
    lastInvokeTime = time;
    // Start the timer for the trailing edge.
    timerId = setTimeout(timerExpired, wait);
    // Invoke the leading edge.
    return leading ? invokeFunc(time) : result;
  }

  function remainingWait(time) {
    var timeSinceLastCall = time - lastCallTime,
        timeSinceLastInvoke = time - lastInvokeTime,
        timeWaiting = wait - timeSinceLastCall;

    return maxing
      ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
      : timeWaiting;
  }

  function shouldInvoke(time) {
    var timeSinceLastCall = time - lastCallTime,
        timeSinceLastInvoke = time - lastInvokeTime;

    // Either this is the first call, activity has stopped and we're at the
    // trailing edge, the system time has gone backwards and we're treating
    // it as the trailing edge, or we've hit the `maxWait` limit.
    return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
      (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
  }

  function timerExpired() {
    var time = now();
    if (shouldInvoke(time)) {
      return trailingEdge(time);
    }
    // Restart the timer.
    timerId = setTimeout(timerExpired, remainingWait(time));
  }

  function trailingEdge(time) {
    timerId = undefined;

    // Only invoke if we have `lastArgs` which means `func` has been
    // debounced at least once.
    if (trailing && lastArgs) {
      return invokeFunc(time);
    }
    lastArgs = lastThis = undefined;
    return result;
  }

  function cancel() {
    if (timerId !== undefined) {
      clearTimeout(timerId);
    }
    lastInvokeTime = 0;
    lastArgs = lastCallTime = lastThis = timerId = undefined;
  }

  function flush() {
    return timerId === undefined ? result : trailingEdge(now());
  }

  function debounced() {
    var time = now(),
        isInvoking = shouldInvoke(time);

    lastArgs = arguments;
    lastThis = this;
    lastCallTime = time;

    if (isInvoking) {
      if (timerId === undefined) {
        return leadingEdge(lastCallTime);
      }
      if (maxing) {
        // Handle invocations in a tight loop.
        clearTimeout(timerId);
        timerId = setTimeout(timerExpired, wait);
        return invokeFunc(lastCallTime);
      }
    }
    if (timerId === undefined) {
      timerId = setTimeout(timerExpired, wait);
    }
    return result;
  }
  debounced.cancel = cancel;
  debounced.flush = flush;
  return debounced;
}

const validateAdjustHeight = (component, value) => {
    watchBoolean(component, '_adjustHeight', value);
};

const validateHideMsg = (component, value, options) => {
    watchBoolean(component, '_hideMsg', value, options);
};

const validateHint = (component, value) => {
    watchString(component, '_hint', value);
};

const validateMsg = (component, value) => {
    objectObjectHandler(value, () => {
        try {
            value = parseJson(value);
        }
        catch (_a) {
        }
        watchValidator(component, `_msg`, (value) => {
            if (value === undefined) {
                return true;
            }
            if (typeof value === 'string' && value.length > 0) {
                return true;
            }
            if (isObject$1(value) && value !== null) {
                const desc = value._description;
                return isString(desc, 1);
            }
            return false;
        }, new Set(['MsgPropType', 'string']), value);
    });
};
function isMsgDefinedAndInputTouched(msg, touched) {
    return Boolean(msg) && touched === true;
}
function normalizeMsg(msg) {
    if (typeof msg === 'string') {
        try {
            return parseJson(msg);
        }
        catch (_a) {
            return { _description: msg, _type: 'error' };
        }
    }
    if (msg && typeof msg === 'object' && !('_type' in msg)) {
        return Object.assign(Object.assign({}, msg), { _type: 'error' });
    }
    return msg;
}
function getMsgType(msg) {
    var _a;
    if (typeof msg === 'string') {
        return 'error';
    }
    return (_a = msg === null || msg === void 0 ? void 0 : msg._type) !== null && _a !== void 0 ? _a : 'error';
}

const validateTouched = (component, value) => {
    watchBoolean(component, '_touched', value);
};

class ControlledInputController extends AssociatedInputController {
    constructor(component, name, host) {
        super(component, name, host);
        this.component = component;
    }
    validateTouched(value) {
        validateTouched(this.component, value);
    }
    componentWillLoad() {
        super.componentWillLoad();
        this.validateTouched(this.component._touched);
    }
}

class InputController extends ControlledInputController {
    constructor(component, name, host) {
        super(component, name, host);
        this.valueChangeListeners = [];
        this.onFacade = {
            onBlur: this.onBlur.bind(this),
            onChange: this.onChange.bind(this),
            onClick: this.onClick.bind(this),
            onFocus: this.onFocus.bind(this),
            onInput: this.onInput.bind(this),
            onKeyDown: this.onKeyDown.bind(this),
        };
        this.updateCurrentLengthDebounced = debounce((length) => {
            setState(this.component, '_currentLengthDebounced', length);
        }, 500);
        this.component = component;
    }
    validateAccessKey(value) {
        validateAccessKey(this.component, value);
        validateAccessAndShortKey(value, this.component._shortKey);
    }
    validateAdjustHeight(value) {
        validateAdjustHeight(this.component, value);
    }
    validateDisabled(value) {
        validateDisabled(this.component, value);
    }
    validateTooltipAlign(value) {
        validateTooltipAlign(this.component, value);
    }
    validateHideMsg(value) {
        validateHideMsg(this.component, value, {
            hooks: {
                afterPatch: () => {
                    if (this.component.state._hideMsg) {
                        a11yHint('Property _hideMsg for inputs: Only use when the error message is shown outside of the input component.');
                    }
                },
            },
        });
    }
    validateHideLabel(value) {
        validateHideLabel(this.component, value, {
            hooks: {
                afterPatch: () => {
                    if (this.component.state._hideLabel) {
                        a11yHint('Property hide-label for inputs: Only use for exceptions like search inputs that are clearly identifiable by their context.');
                    }
                },
            },
        });
    }
    validateHint(value) {
        validateHint(this.component, value);
    }
    validateLabel(value) {
        validateLabelWithExpertSlot(this.component, value, {
            required: true,
        });
    }
    validateMsg(value) {
        validateMsg(this.component, value);
    }
    validateOn(value) {
        if (typeof value === 'object') {
            setState(this.component, '_on', value);
        }
    }
    validateShortKey(value) {
        validateShortKey(this.component, value);
        validateAccessAndShortKey(this.component._accessKey, value);
    }
    validateSmartButton(value) {
        objectObjectHandler(value, () => {
            try {
                value = parseJson(value);
            }
            catch (_a) {
            }
            setState(this.component, '_smartButton', value);
        });
    }
    validateTabIndex(value) {
        validateTabIndex(this.component, value);
    }
    validateVariant(value) {
        validateVariantClassName(this.component, value);
    }
    componentWillLoad() {
        super.componentWillLoad();
        this.validateAccessKey(this.component._accessKey);
        this.validateAdjustHeight(this.component._adjustHeight);
        this.validateMsg(this.component._msg);
        this.validateDisabled(this.component._disabled);
        this.validateHideMsg(this.component._hideMsg);
        this.validateHideLabel(this.component._hideLabel);
        this.validateHint(this.component._hint);
        this.validateLabel(this.component._label);
        this.validateShortKey(this.component._shortKey);
        this.validateSmartButton(this.component._smartButton);
        this.validateOn(this.component._on);
        this.validateTabIndex(this.component._tabIndex);
        this.validateVariant(this.component._variant);
        validateAccessAndShortKey(this.component._accessKey, this.component._shortKey);
    }
    emitEvent(type, value) {
        if (this.host) {
            dispatchDomEvent(this.host, type, value);
        }
    }
    onBlur(event) {
        var _a;
        if (this.component._disabled) {
            return;
        }
        this.component._touched = true;
        this.emitEvent(KolEvent.blur);
        if (typeof ((_a = this.component._on) === null || _a === void 0 ? void 0 : _a.onBlur) === 'function') {
            this.component._on.onBlur(event);
        }
    }
    onChange(event, value) {
        var _a;
        if (typeof value === 'undefined') {
            value = event.target.value;
        }
        this.emitEvent(KolEvent.change, value);
        if (typeof ((_a = this.component._on) === null || _a === void 0 ? void 0 : _a.onChange) === 'function') {
            this.component._on.onChange(event, value);
        }
        this.valueChangeListeners.forEach((listener) => listener(value));
    }
    onInput(event, shouldSetFormAssociatedValue = true, value) {
        var _a;
        if (typeof value === 'undefined') {
            value = event.target.value;
        }
        this.emitEvent(KolEvent.input, value);
        if (shouldSetFormAssociatedValue) {
            this.setFormAssociatedValue(value);
        }
        if (typeof ((_a = this.component._on) === null || _a === void 0 ? void 0 : _a.onInput) === 'function') {
            this.component._on.onInput(event, value);
        }
    }
    onClick(event) {
        var _a;
        this.emitEvent(KolEvent.click);
        if (typeof ((_a = this.component._on) === null || _a === void 0 ? void 0 : _a.onClick) === 'function') {
            this.component._on.onClick(event);
        }
    }
    onFocus(event) {
        var _a;
        this.emitEvent(KolEvent.focus);
        if (typeof ((_a = this.component._on) === null || _a === void 0 ? void 0 : _a.onFocus) === 'function') {
            this.component._on.onFocus(event);
        }
    }
    onKeyDown(event) {
        var _a;
        this.emitEvent(KolEvent.keydown);
        if (typeof ((_a = this.component._on) === null || _a === void 0 ? void 0 : _a.onKeyDown) === 'function') {
            this.component._on.onKeyDown(event);
        }
    }
    addValueChangeListener(listener) {
        this.valueChangeListeners.push(listener);
    }
    hasSoftCharacterLimit() {
        return typeof this.component.state._maxLength === 'number' && this.component.state._maxLengthBehavior === 'soft';
    }
    hasCounter() {
        return this.component.state._hasCounter === true;
    }
}

function getDefaultProps({ ariaDescribedBy, hideLabel, label }) {
    return {
        title: '',
        autoCapitalize: 'off',
        autoCorrect: 'off',
        'aria-describedby': (ariaDescribedBy === null || ariaDescribedBy === void 0 ? void 0 : ariaDescribedBy.length) ? ariaDescribedBy.join(' ') : undefined,
        'aria-label': hideLabel && label ? label : undefined,
    };
}

const getRenderStates = (state) => {
    const msg = state._msg;
    const description = typeof msg === 'string' ? msg : msg === null || msg === void 0 ? void 0 : msg._description;
    const type = getMsgType(msg);
    const hasMessage = Boolean(description && description.length > 0);
    const isMessageValidError = type === 'error' && hasMessage;
    const hasError = isMessageValidError && state._touched === true;
    const hasHint = typeof state._hint === 'string' && state._hint.length > 0;
    const ariaDescribedBy = [];
    if (hasMessage && !state._hideMsg) {
        ariaDescribedBy.push(createRelatedUniqueId(state._id, 'msg'));
    }
    if (hasHint === true) {
        ariaDescribedBy.push(createRelatedUniqueId(state._id, 'hint'));
    }
    if (state._hasCounter) {
        ariaDescribedBy.push(createRelatedUniqueId(state._id, 'counter'));
    }
    if (hasError === true) {
        ariaDescribedBy.push(createRelatedUniqueId(state._id, 'error'));
    }
    return { hasError, hasHint, ariaDescribedBy };
};

const KolFormFieldHintFc = (_a) => {
    var { id, class: classNames, hint, baseClassName = 'kol-form-field' } = _a, other = __rest(_a, ["id", "class", "hint", "baseClassName"]);
    if (!hint) {
        return null;
    }
    return (h("span", Object.assign({ class: clsx(`${baseClassName}__hint`, classNames), id: createRelatedUniqueId(id || '', 'hint') }, other), hint));
};

const KolFormFieldLabelFc = (_a) => {
    var { component: Component = 'label', id, baseClassName = 'kol-form-field', class: classNames, accessKey, shortKey, label, hideLabel, hasExpertSlot, showBadge = true, readOnly } = _a, other = __rest(_a, ["component", "id", "baseClassName", "class", "accessKey", "shortKey", "label", "hideLabel", "hasExpertSlot", "showBadge", "readOnly"]);
    const useTooltipInsteadOfLabel = !hasExpertSlot && hideLabel;
    const translateReadOnly = translate('kol-readonly');
    const badgeText = showBadge === false ? undefined : buildBadgeTextString(accessKey, shortKey);
    return (h(Component, Object.assign({}, other, { class: clsx(`${baseClassName}__label`, classNames), id: !useTooltipInsteadOfLabel ? createRelatedUniqueId(id, 'label') : undefined, hidden: useTooltipInsteadOfLabel, htmlFor: id }), h(SpanFC, { class: `${baseClassName}__label-text`, label: hasExpertSlot ? '' : (label !== null && label !== void 0 ? label : ''), badgeText: badgeText }, h("slot", { name: "expert" })), !hasExpertSlot && readOnly ? (h("span", { class: `${baseClassName}__label__read-only`, "aria-hidden": "true" }, "(", translateReadOnly, ")")) : null));
};

const KolFormFieldCharacterLimitHintFc = ({ id, maxLength }) => {
    return (h("span", { id: createRelatedUniqueId(id, 'character-limit-hint'), class: "visually-hidden" }, translate('kol-character-limit-hint', { placeholders: { limit: String(maxLength) } })));
};

const KolFormFieldCounterFc = ({ currentLength, currentLengthDebounced, maxLength, maxLengthBehavior, id }) => {
    let visualText;
    let ariaText;
    const counterClasses = ['kol-form-field__counter'];
    if (maxLengthBehavior === 'hard') {
        visualText =
            typeof maxLength === 'number'
                ? translate('kol-character-counter-current-of-max', { placeholders: { current: String(currentLength), max: String(maxLength) } })
                : translate('kol-character-counter-current', { placeholders: { current: String(currentLength) } });
        ariaText =
            typeof maxLength === 'number'
                ? translate('kol-character-counter-current-of-max-aria', { placeholders: { current: String(currentLengthDebounced), max: String(maxLength) } })
                : translate('kol-character-counter-current', { placeholders: { current: String(currentLengthDebounced) } });
    }
    else if (typeof maxLength === 'number') {
        const remainingLive = maxLength - currentLength;
        const exceededLive = remainingLive < 0;
        const remainingDebounced = maxLength - currentLengthDebounced;
        const exceededDebounced = remainingDebounced < 0;
        visualText = exceededLive
            ? translate('kol-character-limit-exceeded', { placeholders: { over: String(Math.abs(remainingLive)) } })
            : translate('kol-character-limit-remaining', { placeholders: { remaining: String(remainingLive) } });
        ariaText = exceededDebounced
            ? translate('kol-character-limit-exceeded', { placeholders: { over: String(Math.abs(remainingDebounced)) } })
            : translate('kol-character-limit-remaining', { placeholders: { remaining: String(remainingDebounced) } });
        if (exceededLive) {
            counterClasses.push('kol-form-field__counter--exceeded');
        }
    }
    else {
        return null;
    }
    return (h(Fragment, null, h("span", { class: clsx(counterClasses), "aria-hidden": "true", "data-testid": "input-counter" }, visualText), h("span", { id: createRelatedUniqueId(id || '', 'counter'), "aria-live": "polite", class: "visually-hidden", "data-testid": "input-counter-aria" }, ariaText)));
};

const FormFieldMsgFc = (_a) => {
    var _b, _c;
    var { alert, msg, id, class: classNames } = _a, other = __rest(_a, ["alert", "msg", "id", "class"]);
    const message = normalizeMsg(msg);
    return (h(KolAlertFc, Object.assign({ id: createRelatedUniqueId(id, 'msg'), alert: (_b = message === null || message === void 0 ? void 0 : message._alert) !== null && _b !== void 0 ? _b : alert, hasCloser: false, level: 0, type: (_c = message === null || message === void 0 ? void 0 : message._type) !== null && _c !== void 0 ? _c : 'error', variant: "msg", class: clsx('kol-form-field__msg', classNames) }, other), (message === null || message === void 0 ? void 0 : message._description) || undefined));
};

const formFieldTooltipControllerById = new Map();
const getFormFieldTooltipController = (id) => {
    const tooltipController = formFieldTooltipControllerById.get(id);
    if (tooltipController) {
        return tooltipController;
    }
    const nextTooltipController = new TooltipController(BaseWebComponent.stateLess);
    nextTooltipController.componentWillLoad({ label: '' });
    formFieldTooltipControllerById.set(id, nextTooltipController);
    return nextTooltipController;
};
const destroyFormFieldTooltipController = (id) => {
    const tooltipController = formFieldTooltipControllerById.get(id);
    if (tooltipController) {
        tooltipController.destroy();
        formFieldTooltipControllerById.delete(id);
    }
};
function getModifierClassNameByMsgType(msg) {
    if (msg === null || msg === void 0 ? void 0 : msg.type) {
        return ({
            default: 'msg-type-default',
            info: 'msg-type-info',
            success: 'msg-type-success',
            warning: 'msg-type-warning',
            error: 'msg-type-error',
        }[msg === null || msg === void 0 ? void 0 : msg.type] || '');
    }
    return '';
}
const InputContainer = (_a, children) => {
    var { class: classNames } = _a, other = __rest(_a, ["class"]);
    return (h("div", Object.assign({ class: clsx('kol-form-field__input', classNames) }, other), children));
};
const KolFormFieldFc = (props, children) => {
    const { component: Component = 'div', renderNoLabel, renderNoTooltip, renderNoHint, anotherChildren, id, required, alert, disabled, class: classNames, msg, hideMsg, hideLabel, label, hint, accessKey, shortKey, counter, readOnly, touched, maxLength, ariaDescribedBy, showBadge, tooltipAlign, tooltipFloatingRef, variant, formFieldLabelProps, formFieldHintProps, formFieldTooltipProps, formFieldMsgProps, formFieldInputProps } = props, other = __rest(props, ["component", "renderNoLabel", "renderNoTooltip", "renderNoHint", "anotherChildren", "id", "required", "alert", "disabled", "class", "msg", "hideMsg", "hideLabel", "label", "hint", "accessKey", "shortKey", "counter", "readOnly", "touched", "maxLength", "ariaDescribedBy", "showBadge", "tooltipAlign", "tooltipFloatingRef", "variant", "formFieldLabelProps", "formFieldHintProps", "formFieldTooltipProps", "formFieldMsgProps", "formFieldInputProps"]);
    const showLabel = !renderNoLabel;
    const showHint = !renderNoHint;
    const showTooltip = !renderNoTooltip;
    const hasExpertSlot = showExpertSlot(label);
    const showMsg = isMsgDefinedAndInputTouched(msg, touched);
    const badgeText = buildBadgeTextString(accessKey, shortKey);
    const useTooltipInsteadOfLabel = showTooltip && !hasExpertSlot && hideLabel;
    const labelId = createRelatedUniqueId(id, 'label');
    const tooltipController = useTooltipInsteadOfLabel ? getFormFieldTooltipController(id) : undefined;
    if (tooltipController) {
        tooltipController.watchAlign(tooltipAlign);
        tooltipController.watchBadgeText(badgeText || '');
        tooltipController.watchId(labelId);
        tooltipController.watchLabel(label);
    }
    else {
        destroyFormFieldTooltipController(id);
    }
    const forwardedInputRef = formFieldInputProps === null || formFieldInputProps === void 0 ? void 0 : formFieldInputProps.ref;
    const setInputContainerRef = (el) => {
        forwardedInputRef === null || forwardedInputRef === void 0 ? void 0 : forwardedInputRef(el);
        if (tooltipController && el) {
            tooltipController.initContext(el);
            tooltipController.syncListeners(undefined, el, true);
        }
    };
    let stateCssClasses = {
        ['kol-form-field--disabled']: Boolean(disabled),
        ['kol-form-field--required']: Boolean(required),
        ['kol-form-field--touched']: Boolean(touched),
        ['kol-form-field--hide-label']: Boolean(hideLabel),
        ['kol-form-field--read-only']: Boolean(readOnly),
        ['kol-form-field--hidden-msg']: Boolean(hideMsg),
    };
    if (variant) {
        stateCssClasses = Object.assign(Object.assign({}, stateCssClasses), { [`kol-form-field--${variant}`]: true });
    }
    if (showMsg) {
        const msgType = getMsgType(msg);
        stateCssClasses = Object.assign(Object.assign({}, stateCssClasses), { [`kol-form-field--${msgType}`]: true, [`kol-form-field--${getModifierClassNameByMsgType({ type: msgType })}`]: true });
    }
    return (h(Component, Object.assign({ class: clsx('kol-form-field', stateCssClasses, classNames), "aria-describedby": ariaDescribedBy }, other), showLabel && (h(KolFormFieldLabelFc, Object.assign({}, (formFieldLabelProps || {}), { id: id, hasExpertSlot: hasExpertSlot, hideLabel: hideLabel, label: label, accessKey: accessKey, shortKey: shortKey, readOnly: readOnly, showBadge: showBadge }))), h(InputContainer, Object.assign({}, formFieldInputProps, { ref: setInputContainerRef }), children, useTooltipInsteadOfLabel && hideLabel === true && (h("div", { class: clsx('kol-form-field__tooltip', formFieldTooltipProps === null || formFieldTooltipProps === void 0 ? void 0 : formFieldTooltipProps.class) }, h(TooltipFC, { badgeText: badgeText || '', label: label, align: tooltipAlign, id: labelId, refFloating: tooltipFloatingRef !== null && tooltipFloatingRef !== void 0 ? tooltipFloatingRef : ((el) => {
            tooltipController === null || tooltipController === void 0 ? void 0 : tooltipController.setTooltipElementRef(el);
        }) })))), counter ? h(KolFormFieldCounterFc, Object.assign({ id: id }, counter)) : null, maxLength ? h(KolFormFieldCharacterLimitHintFc, { id: id, maxLength: maxLength }) : null, showMsg && !hideMsg && h(FormFieldMsgFc, Object.assign({}, (formFieldMsgProps || {}), { id: id, alert: alert, msg: msg })), showHint && h(KolFormFieldHintFc, Object.assign({}, (formFieldHintProps || {}), { id: id, hint: hint })), anotherChildren));
};

function getFormFieldProps(state) {
    const props = {
        id: state._id,
        disabled: state._disabled,
        msg: state._msg,
        hint: state._hint,
        label: state._label,
        hideLabel: state._hideLabel,
        hideMsg: state._hideMsg,
        touched: state._touched,
        showBadge: ('_accessKey' in state && Boolean(state._accessKey)) || ('_shortKey' in state && Boolean(state._shortKey)),
    };
    if ('_required' in state) {
        props.required = state._required;
    }
    if ('_readOnly' in state) {
        props.readOnly = state._readOnly;
    }
    if ('_accessKey' in state) {
        props.accessKey = state._accessKey;
    }
    if ('_shortKey' in state) {
        props.shortKey = state._shortKey;
    }
    if ('_maxLength' in state) {
        props.maxLength = state._maxLength;
    }
    if ('_currentLength' in state &&
        typeof state._currentLength === 'number' &&
        '_currentLengthDebounced' in state &&
        typeof state._currentLengthDebounced === 'number') {
        if ('_hasCounter' in state && state._hasCounter === true) {
            props.counter = {
                currentLength: state._currentLength,
                currentLengthDebounced: state._currentLengthDebounced,
                maxLength: state._maxLength,
                maxLengthBehavior: state._maxLengthBehavior || 'hard',
            };
        }
    }
    if ('_variant' in state) {
        props.variant = state._variant;
    }
    return props;
}
const FormFieldStateWrapper = (_a, children) => {
    var { state } = _a, other = __rest(_a, ["state"]);
    const { ariaDescribedBy: ariaDescribedByArray } = getRenderStates(state);
    const isRadioVariant = other.component === 'fieldset' || ('_options' in state && '_orientation' in state);
    const ariaDescribedBy = isRadioVariant && ariaDescribedByArray.length > 0 ? ariaDescribedByArray.join(' ') : undefined;
    const baseProps = getFormFieldProps(state);
    return (h(KolFormFieldFc, Object.assign({}, baseProps, other, { ariaDescribedBy: ariaDescribedBy }), children));
};

export { FormFieldStateWrapper as F, InputController as I, KolFormFieldLabelFc as K, getRenderStates as a, KolFormFieldHintFc as b, getDefaultProps as c, getMsgType as g, isMsgDefinedAndInputTouched as i };
//# sourceMappingURL=FormFieldStateWrapper-DCXQnRBu.js.map

//# sourceMappingURL=FormFieldStateWrapper-DCXQnRBu.js.map