@public-ui/components
Version:
Contains all web components that belong to KoliBri - The accessible HTML-Standard.
848 lines (796 loc) • 34.4 kB
JavaScript
/*!
* KoliBri - The accessible HTML-Standard
*/
'use strict';
var common = require('./common-DPb6NWR4.js');
var accessAndShortKey = require('./access-and-short-key-CspEpGOV.js');
var disabled = require('./disabled-GY6LfYNH.js');
var hideLabel = require('./hide-label-BnMTmbm4.js');
var label = require('./label-8vcJJEVI.js');
var tooltipAlign = require('./tooltip-align-BeYhiCq6.js');
var variantClassName = require('./variant-class-name-BCWuCRd0.js');
var events = require('./events-Jc2wxPjR.js');
var associated_controller = require('./associated.controller-DLy6rpeW.js');
var _Uint8Array = require('./_Uint8Array-BAQUGozM.js');
var isArray = require('./isArray-BOIOdEQh.js');
var tslib_es6 = require('./tslib.es6-Cm0ytgPY.js');
var index = require('./index-BrhW8s5h.js');
var variantQuote = require('./variant-quote-DpNzmCtr.js');
var component$1 = require('./component-kXVnT0Wy.js');
var controller = require('./controller-DiB9pVnb.js');
var component = require('./component-BUJSMbIY.js');
var clsx = require('./clsx-Bm_HQUnh.js');
var dev_utils = require('./dev.utils-BeTuwcHU.js');
var i18n = require('./i18n-Cjy0vgJA.js');
var Alert = require('./Alert-C5eDyNdi.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' ||
(isArray.isObjectLike(value) && isArray.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 (_Uint8Array.isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = _Uint8Array.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 isArray.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 (_Uint8Array.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) => {
common.watchBoolean(component, '_adjustHeight', value);
};
const validateHideMsg = (component, value, options) => {
common.watchBoolean(component, '_hideMsg', value, options);
};
const validateHint = (component, value) => {
common.watchString(component, '_hint', value);
};
const validateMsg = (component, value) => {
common.objectObjectHandler(value, () => {
try {
value = common.parseJson(value);
}
catch (_a) {
}
common.watchValidator(component, `_msg`, (value) => {
if (value === undefined) {
return true;
}
if (typeof value === 'string' && value.length > 0) {
return true;
}
if (common.isObject(value) && value !== null) {
const desc = value._description;
return common.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 common.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) => {
common.watchBoolean(component, '_touched', value);
};
class ControlledInputController extends associated_controller.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) => {
common.setState(this.component, '_currentLengthDebounced', length);
}, 500);
this.component = component;
}
validateAccessKey(value) {
accessAndShortKey.validateAccessKey(this.component, value);
accessAndShortKey.validateAccessAndShortKey(value, this.component._shortKey);
}
validateAdjustHeight(value) {
validateAdjustHeight(this.component, value);
}
validateDisabled(value) {
disabled.validateDisabled(this.component, value);
}
validateTooltipAlign(value) {
tooltipAlign.validateTooltipAlign(this.component, value);
}
validateHideMsg(value) {
validateHideMsg(this.component, value, {
hooks: {
afterPatch: () => {
if (this.component.state._hideMsg) {
common.a11yHint('Property _hideMsg for inputs: Only use when the error message is shown outside of the input component.');
}
},
},
});
}
validateHideLabel(value) {
hideLabel.validateHideLabel(this.component, value, {
hooks: {
afterPatch: () => {
if (this.component.state._hideLabel) {
common.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) {
label.validateLabelWithExpertSlot(this.component, value, {
required: true,
});
}
validateMsg(value) {
validateMsg(this.component, value);
}
validateOn(value) {
if (typeof value === 'object') {
common.setState(this.component, '_on', value);
}
}
validateShortKey(value) {
accessAndShortKey.validateShortKey(this.component, value);
accessAndShortKey.validateAccessAndShortKey(this.component._accessKey, value);
}
validateSmartButton(value) {
common.objectObjectHandler(value, () => {
try {
value = common.parseJson(value);
}
catch (_a) {
}
common.setState(this.component, '_smartButton', value);
});
}
validateTabIndex(value) {
accessAndShortKey.validateTabIndex(this.component, value);
}
validateVariant(value) {
variantClassName.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);
accessAndShortKey.validateAccessAndShortKey(this.component._accessKey, this.component._shortKey);
}
emitEvent(type, value) {
if (this.host) {
events.dispatchDomEvent(this.host, type, value);
}
}
onBlur(event) {
var _a;
if (this.component._disabled) {
return;
}
this.component._touched = true;
this.emitEvent(events.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(events.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(events.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(events.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(events.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(events.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(dev_utils.createRelatedUniqueId(state._id, 'msg'));
}
if (hasHint === true) {
ariaDescribedBy.push(dev_utils.createRelatedUniqueId(state._id, 'hint'));
}
if (state._hasCounter) {
ariaDescribedBy.push(dev_utils.createRelatedUniqueId(state._id, 'counter'));
}
if (hasError === true) {
ariaDescribedBy.push(dev_utils.createRelatedUniqueId(state._id, 'error'));
}
return { hasError, hasHint, ariaDescribedBy };
};
const KolFormFieldHintFc = (_a) => {
var { id, class: classNames, hint, baseClassName = 'kol-form-field' } = _a, other = tslib_es6.__rest(_a, ["id", "class", "hint", "baseClassName"]);
if (!hint) {
return null;
}
return (index.h("span", Object.assign({ class: clsx.clsx(`${baseClassName}__hint`, classNames), id: dev_utils.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 = tslib_es6.__rest(_a, ["component", "id", "baseClassName", "class", "accessKey", "shortKey", "label", "hideLabel", "hasExpertSlot", "showBadge", "readOnly"]);
const useTooltipInsteadOfLabel = !hasExpertSlot && hideLabel;
const translateReadOnly = i18n.translate('kol-readonly');
const badgeText = showBadge === false ? undefined : component.buildBadgeTextString(accessKey, shortKey);
return (index.h(Component, Object.assign({}, other, { class: clsx.clsx(`${baseClassName}__label`, classNames), id: !useTooltipInsteadOfLabel ? dev_utils.createRelatedUniqueId(id, 'label') : undefined, hidden: useTooltipInsteadOfLabel, htmlFor: id }), index.h(component.SpanFC, { class: `${baseClassName}__label-text`, label: hasExpertSlot ? '' : (label !== null && label !== void 0 ? label : ''), badgeText: badgeText }, index.h("slot", { name: "expert" })), !hasExpertSlot && readOnly ? (index.h("span", { class: `${baseClassName}__label__read-only`, "aria-hidden": "true" }, "(", translateReadOnly, ")")) : null));
};
const KolFormFieldCharacterLimitHintFc = ({ id, maxLength }) => {
return (index.h("span", { id: dev_utils.createRelatedUniqueId(id, 'character-limit-hint'), class: "visually-hidden" }, i18n.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'
? i18n.translate('kol-character-counter-current-of-max', { placeholders: { current: String(currentLength), max: String(maxLength) } })
: i18n.translate('kol-character-counter-current', { placeholders: { current: String(currentLength) } });
ariaText =
typeof maxLength === 'number'
? i18n.translate('kol-character-counter-current-of-max-aria', { placeholders: { current: String(currentLengthDebounced), max: String(maxLength) } })
: i18n.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
? i18n.translate('kol-character-limit-exceeded', { placeholders: { over: String(Math.abs(remainingLive)) } })
: i18n.translate('kol-character-limit-remaining', { placeholders: { remaining: String(remainingLive) } });
ariaText = exceededDebounced
? i18n.translate('kol-character-limit-exceeded', { placeholders: { over: String(Math.abs(remainingDebounced)) } })
: i18n.translate('kol-character-limit-remaining', { placeholders: { remaining: String(remainingDebounced) } });
if (exceededLive) {
counterClasses.push('kol-form-field__counter--exceeded');
}
}
else {
return null;
}
return (index.h(index.Fragment, null, index.h("span", { class: clsx.clsx(counterClasses), "aria-hidden": "true", "data-testid": "input-counter" }, visualText), index.h("span", { id: dev_utils.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 = tslib_es6.__rest(_a, ["alert", "msg", "id", "class"]);
const message = normalizeMsg(msg);
return (index.h(Alert.KolAlertFc, Object.assign({ id: dev_utils.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.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 controller.TooltipController(variantQuote.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 = tslib_es6.__rest(_a, ["class"]);
return (index.h("div", Object.assign({ class: clsx.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 = tslib_es6.__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 = component.showExpertSlot(label);
const showMsg = isMsgDefinedAndInputTouched(msg, touched);
const badgeText = component.buildBadgeTextString(accessKey, shortKey);
const useTooltipInsteadOfLabel = showTooltip && !hasExpertSlot && hideLabel;
const labelId = dev_utils.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 (index.h(Component, Object.assign({ class: clsx.clsx('kol-form-field', stateCssClasses, classNames), "aria-describedby": ariaDescribedBy }, other), showLabel && (index.h(KolFormFieldLabelFc, Object.assign({}, (formFieldLabelProps || {}), { id: id, hasExpertSlot: hasExpertSlot, hideLabel: hideLabel, label: label, accessKey: accessKey, shortKey: shortKey, readOnly: readOnly, showBadge: showBadge }))), index.h(InputContainer, Object.assign({}, formFieldInputProps, { ref: setInputContainerRef }), children, useTooltipInsteadOfLabel && hideLabel === true && (index.h("div", { class: clsx.clsx('kol-form-field__tooltip', formFieldTooltipProps === null || formFieldTooltipProps === void 0 ? void 0 : formFieldTooltipProps.class) }, index.h(component$1.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 ? index.h(KolFormFieldCounterFc, Object.assign({ id: id }, counter)) : null, maxLength ? index.h(KolFormFieldCharacterLimitHintFc, { id: id, maxLength: maxLength }) : null, showMsg && !hideMsg && index.h(FormFieldMsgFc, Object.assign({}, (formFieldMsgProps || {}), { id: id, alert: alert, msg: msg })), showHint && index.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 = tslib_es6.__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 (index.h(KolFormFieldFc, Object.assign({}, baseProps, other, { ariaDescribedBy: ariaDescribedBy }), children));
};
exports.FormFieldStateWrapper = FormFieldStateWrapper;
exports.InputController = InputController;
exports.KolFormFieldHintFc = KolFormFieldHintFc;
exports.KolFormFieldLabelFc = KolFormFieldLabelFc;
exports.getDefaultProps = getDefaultProps;
exports.getMsgType = getMsgType;
exports.getRenderStates = getRenderStates;
exports.isMsgDefinedAndInputTouched = isMsgDefinedAndInputTouched;
//# sourceMappingURL=FormFieldStateWrapper-BZsSDU0S.js.map
//# sourceMappingURL=FormFieldStateWrapper-BZsSDU0S.js.map