@adyen/bento-mcp 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/dist/assets/components/action-bar/action-bar.docs.mdx +40 -4
- package/dist/assets/components/action-bar/action-bar.stories.ts +1 -1
- package/dist/assets/components/action-bar/action-bar.vue +1 -1
- package/dist/assets/components/anchor-scroller/anchor-scroller.vue +1 -1
- package/dist/assets/components/checkbox/checkbox.vue +1 -1
- package/dist/assets/components/checkbox/components/checkbox-group/checkbox-group.vue +1 -1
- package/dist/assets/components/data-grid/components/data-grid-row/data-grid-row.vue +1 -1
- package/dist/assets/components/data-grid/components/data-grid-tag-with-text-cell/data-grid-tag-with-text-cell.vue +1 -1
- package/dist/assets/components/data-grid/data-grid.vue +1 -1
- package/dist/assets/components/date-picker/date-picker.vue +1 -1
- package/dist/assets/components/date-range-picker/components/date-range-picker-calendar/date-range-picker-calendar.vue +1 -1
- package/dist/assets/components/date-range-picker/date-range-picker.vue +1 -1
- package/dist/assets/components/dropdown/components/dropdown-base-textbox/dropdown-base-textbox.vue +1 -1
- package/dist/assets/components/dropdown/components/dropdown-options-container/dropdown-options-container.vue +1 -1
- package/dist/assets/components/dropdown/dropdown.stories.ts +1 -1
- package/dist/assets/components/dropdown/dropdown.vue +1 -1
- package/dist/assets/components/file-uploader/components/file-uploader-restrictions/file-uploader-restrictions.vue +1 -1
- package/dist/assets/components/file-uploader/file-uploader.docs.mdx +9 -0
- package/dist/assets/components/file-uploader/file-uploader.stories.ts +1 -1
- package/dist/assets/components/file-uploader/file-uploader.vue +1 -1
- package/dist/assets/components/filter-bar/components/all-filters-modal/all-filters-modal.vue +1 -1
- package/dist/assets/components/filter-bar/components/date-range-filter/date-range-filter.vue +1 -1
- package/dist/assets/components/filter-bar/filter-bar.vue +1 -1
- package/dist/assets/components/form-layout/components/form-layout-title/form-layout-title.vue +1 -1
- package/dist/assets/components/form-layout/form-layout.docs.mdx +4 -0
- package/dist/assets/components/input-field/input-field.stories.ts +1 -1
- package/dist/assets/components/input-field/input-field.vue +1 -1
- package/dist/assets/components/input-field-password/input-field-password.stories.ts +1 -1
- package/dist/assets/components/input-field-phone-number/input-field-phone-number.stories.ts +1 -1
- package/dist/assets/components/input-field-phone-number/input-field-phone-number.vue +1 -1
- package/dist/assets/components/internal/controls-group/controls-group.vue +1 -1
- package/dist/assets/components/internal/field-label/field-label.vue +1 -1
- package/dist/assets/components/internal/radio-input/radio-input.vue +1 -1
- package/dist/assets/components/modal-fullscreen/components/modal-fullscreen-page.vue +1 -1
- package/dist/assets/components/modal-fullscreen/modal-fullscreen.vue +1 -1
- package/dist/assets/components/pagination/components/pagination-context/pagination-context.vue +1 -1
- package/dist/assets/components/pagination/components/pagination-results-per-page/pagination-results-per-page.vue +1 -1
- package/dist/assets/components/pagination/pagination.vue +1 -1
- package/dist/assets/components/radio-group/radio-group.vue +1 -1
- package/dist/assets/components/rich-text-editor/rich-text-editor.vue +1 -1
- package/dist/assets/components/selection-card/components/selection-card-group/selection-card-group.vue +1 -1
- package/dist/assets/components/textarea/textarea.vue +1 -1
- package/dist/main.js +145 -136
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <bento-typography class="b-input-field" data-testid="input-text-container" :class="inputFieldConditionalClasses" el="div" variant="body" > <field-label v-if="hasSlot('default') || label" :for="inputFieldId" data-testid="input-field-label" :tooltip-text="tooltipText" :optional="optional" :required="required" :label="label" @click="focusInput" > <slot></slot> </field-label> <div class="b-input-field__input-box" data-testid="input-box" :aria-disabled="disabled" @click="focusInput"> <!-- Optional Icon for Default text variant --> <span v-if="isDefaultVariant && (hasSlot('defaultIconBefore') || hasSlot('iconBefore'))" :aria-hidden="ariaHidden ? 'true' : undefined" class="b-input-field__icon-before" > <slot v-if="hasSlot('iconBefore')" name="iconBefore" /> <slot v-if="hasSlot('defaultIconBefore') && !hasSlot('iconBefore')" name="defaultIconBefore" /> </span> <!-- Mandatory Icon for Payment Method variant --> <span v-if="isPaymentMethodVariant && hasSlot('paymentMethod')" :aria-hidden="ariaHidden ? 'true' : undefined" class="b-input-field__payment-method" > <slot name="paymentMethod" /> </span> <!-- Dropdown at start --> <div v-if="shouldDisplayDropdownAtStart" :id="dropdownId" class="b-input-field__dropdown b-input-field__dropdown--start" @click.stop > <bento-dropdown v-if="dropdown" ref="inputDropdownElement" v-bind="inputFieldDropdownProps" :disabled="disabled" :readonly="isDropdownReadOnly" @update:model-value="onDropdownInput" /> </div> <!-- Static Value at start --> <bento-typography v-if="shouldDisplayStaticValueAtStart" :id="staticValueId" class="b-input-field__static-value b-input-field__static-value--start" el="span" variant="body" > <slot name="staticValue" /> </bento-typography> <div class="b-input-field__input-container"> <input :id="inputFieldId" v-bind="attrs" ref="inputFieldElement" class="b-input-field__input" :aria-label="computedAriaLabel" :aria-describedby="computedAriaDescribedBy" :aria-owns="computedAriaOwns" :aria-invalid="shouldShowError" :placeholder="placeholder" :required="required" :type="type" :value="modelValue ?? value" :disabled="disabled" :readonly="isReadOnly" @input="onInput" @change="emit('change')" @focus="onFocus" @blur="onBlur" @keydown="emit('keydown', $event)" @keyup="emit('keyup', $event)" @keydown.esc="emit('escape-pressed')" @click="emit('click', $event)" /> <!-- Hint at the end --> <bento-typography v-if="hint && isFocused && (modelValue || value)" el="span" class="b-input-field__hint" > {{ hint }} </bento-typography> </div> <span v-if="hasSlot('iconAfter')" :aria-hidden="ariaHidden ? 'true' : undefined" class="b-input-field__icon-after" data-testid="input-text__icon-after" > <slot name="iconAfter" /> </span> <!-- Static Value at the end --> <bento-typography v-if="shouldDisplayStaticValueAtEnd" :id="staticValueId" class="b-input-field__static-value b-input-field__static-value--end" el="span" variant="body" > <slot name="staticValue" /> </bento-typography> <!-- Dropdown at end --> <div v-if="shouldDisplayDropdownAtEnd" :id="dropdownId" data-testid="input-field-dropdown-container-end" class="b-input-field__dropdown b-input-field__dropdown--end" @click.stop > <bento-dropdown v-if="dropdown" :id="dropdownId" ref="inputDropdownElement" v-bind="inputFieldDropdownProps" :disabled="disabled" :readonly="isDropdownReadOnly" @update:model-value="onDropdownInput" /> </div> </div> <error-message v-if="shouldShowError && !!errorMessage" :id="errorId" :error-message="errorMessage" class="b-input-field__error-message" /> <span v-if="hasSlot('description') || description" :id="descriptionId" class="b-input-field__description" @click="focusInput" > <bento-typography el="span" variant="body"> <slot id="description" name="description"> {{ description }} </slot> </bento-typography> </span> </bento-typography> </template> <script setup lang="ts"> import { computed, inject, provide, type Ref, ref, toRef, toRefs, useAttrs, useSlots } from 'vue'; // Components import { BentoDropdown } from '@/components/dropdown'; import { BentoTypography } from '@/components/typography'; import { ErrorMessage, FieldLabel } from '@/internal'; // Utils import { deprecate } from '@/utils/ts/deprecate'; import { useFormFieldEmits } from '@/utils/ts/form-field/form-field'; import { generateUid } from '@/core/utils/ts'; import { getSlotText } from '@/utils/ts/get-slot-text'; import { useAriaLabel } from '@/utils/ts/aria-label'; import { useI18n } from '@/utils/ts/i18n'; import { printDevelopmentWarning } from '@/utils/ts/print-development-warning'; import { INPUT_FIELD_COMPONENT_INJECTION_KEY, INPUT_FIELD_HINT_INJECTION_KEY, INPUT_FIELD_PARENT_COMPONENT_INJECTION_KEY, } from '@/components/input-field/input-field.keys'; import { type BentoListboxSelectedValue } from '@/types/listbox'; // Composables import { useFormLayoutFieldLoading, useHasSlot } from '@/composables'; // Types import { type BentoInputDropdownProps, BentoInputFieldElementPosition, type BentoInputFieldProps, BentoInputFieldStateClass, BentoInputFieldType, type BentoInputFieldValue, BentoInputFieldVariant, } from './input-field.types'; import messages from './messages.json'; type MessageSchema = (typeof messages)['en-US']; const attrs = useAttrs(); const slots = useSlots(); const props = withDefaults(defineProps<BentoInputFieldProps>(), { ariaHidden: true, ariaLabel: undefined, condensed: false, description: '', disabled: false, dropdown: undefined, dropdownPosition: BentoInputFieldElementPosition.START, error: false, errorMessage: null, label: '', modelValue: undefined, optional: false, placeholder: '', required: false, readonly: false, slashedZero: false, staticValue: '', staticValuePosition: BentoInputFieldElementPosition.START, tooltipText: null, type: BentoInputFieldType.TEXT, value: undefined, variant: BentoInputFieldVariant.DEFAULT, }); const emit = defineEmits<{ /** * Emitted when the element has lost focus */ (e: 'blur'): void; /** * Emitted when the input is clicked */ (e: 'click', event: MouseEvent); /** * Emitted when the user modifies the element's value. Unlike the 'input' event, the change event is not necessarily fired for each alteration to an element's value */ (e: 'change'): void; /** * Emitted when the Input Field's internal dropdown changes it's value */ (e: 'dropdown-input', selectedValue: BentoListboxSelectedValue): void; /** * Emitted when the "ESC" key is pressed */ (e: 'escape-pressed'): void; /** * Emitted when the element has received focus */ (e: 'focus'): void; /** * Emitted when a key is pressed down */ (e: 'keydown', event: KeyboardEvent): void; /** * Emitted when a key is pressed and lifted up */ (e: 'keyup', event: KeyboardEvent): void; /** * Emitted when the component's model changes * @deprecated since version 2.0. Use `v-model` or `update:model-value` instead. */ (e: 'input', inputValue: string): void; /** * Emitted when the Input Field's internal dropdown changes it's value. Contains every dropdown prop passed with the updated selected value as 'value' */ (e: 'update:dropdown', updatedDropdownProps: BentoInputDropdownProps): void; /** * Emitted when the component's model changes */ (e: 'update:model-value', inputValue: BentoInputFieldValue): void; }>(); const { emitValue } = useFormFieldEmits<BentoInputFieldValue>(emit); const { t } = useI18n<{ message: MessageSchema }>({ messages }); const hasSlot = useHasSlot(slots); const inputFieldElement = ref(null); const inputDropdownElement = ref(null); const inputFieldId = generateUid('input'); const dropdownId = generateUid('input-dropdown'); const staticValueId = generateUid('input-static-value'); const descriptionId = generateUid('input-description'); const errorId = generateUid('input-error'); const isFocused = ref(false); // Provide INPUT_FIELD_COMPONENT_INJECTION_KEY as true, to set the input only dropdown size variant in the BentoDropdown comp provide(INPUT_FIELD_COMPONENT_INJECTION_KEY, true); // Renders the input with a hint if a string is provided const hint = inject<Ref<string | undefined>>(INPUT_FIELD_HINT_INJECTION_KEY, ref(undefined)); const onFocus = () => { isFocused.value = true; emit('focus'); }; const onBlur = () => { isFocused.value = false; emit('blur'); }; const { isReadOnly } = useFormLayoutFieldLoading(toRef(props, 'readonly')); const isDropdownReadOnly = computed<BentoInputDropdownProps['readonly']>( () => isReadOnly.value || props.dropdown?.readonly ); const shouldShowStaticValue = computed( () => props.variant === BentoInputFieldVariant.STATIC_VALUE && !!slots.staticValue ); const isDefaultVariant = computed(() => props.variant === BentoInputFieldVariant.DEFAULT); const isPaymentMethodVariant = computed(() => props.variant === BentoInputFieldVariant.PAYMENT_METHOD); const shouldDisplayStaticValueAtStart = computed( () => shouldShowStaticValue.value && props.staticValuePosition === BentoInputFieldElementPosition.START ); const shouldDisplayStaticValueAtEnd = computed( () => shouldShowStaticValue.value && props.staticValuePosition === BentoInputFieldElementPosition.END ); const shouldShowDropdown = computed(() => props.variant === BentoInputFieldVariant.DROPDOWN && !!props.dropdown); const shouldDisplayDropdownAtStart = computed( () => shouldShowDropdown.value && props.dropdownPosition === BentoInputFieldElementPosition.START ); const shouldDisplayDropdownAtEnd = computed( () => shouldShowDropdown.value && props.dropdownPosition === BentoInputFieldElementPosition.END ); const shouldShowError = computed( () => !props.disabled && !isReadOnly.value && (!!props.errorMessage || props.error) ); const computedLabel = computed(() => (getSlotText(slots)('default') as string) || props.label); const computedDescription = computed(() => (getSlotText(slots)('description') as string) || props.description); const computedAriaOwns = computed(() => { if (shouldShowDropdown.value === true && shouldShowStaticValue.value === true) { return `${staticValueId} ${dropdownId}`; } if (shouldShowDropdown.value === true) { return `${dropdownId}`; } if (shouldShowStaticValue.value === true) { return `${staticValueId}`; } return null; }); // vue-i18n issue with t() used in script - direct usage in template works // requires either createI18n({ legacy: false }) or to be wrapped in computed() const computedAriaLabelFallbackMessage = computed(() => t('ariaLabelFallback')); const computedAriaLabelDropdowFallback = computed(() => t('ariaLabelDropdownFallback', { inputLabel: computedAriaLabel.value }) ); const ariaLabelAttribute = ref(attrs['aria-label']); const { ariaLabel } = toRefs(props); const computedAriaLabel = useAriaLabel({ ariaLabel: ariaLabelAttribute.value as string, // TODO: take this line away when the aria-label props is removed label: ariaLabel, defaultFallback: computedLabel.value || computedAriaLabelFallbackMessage, }); const computedAriaDescribedBy = computed( () => `${computedDescription.value ? descriptionId : ''} ${ shouldShowError.value && !!props.errorMessage ? errorId : '' }` ); const inputFieldConditionalClasses = computed(() => ({ [`b-input-field--${BentoInputFieldStateClass.CONDENSED}`]: props.condensed, [`b-input-field--${BentoInputFieldStateClass.DISABLED}`]: props.disabled, [`b-input-field--${BentoInputFieldStateClass.READONLY}`]: isReadOnly.value, [`b-input-field--${BentoInputFieldStateClass.ERROR}`]: shouldShowError.value, [`b-input-field--slashed-zero`]: props.slashedZero, })); const inputFieldDropdownProps = computed(() => ({ 'aria-label': computedAriaLabelDropdowFallback.value, ...props.dropdown, })); const onInput = (event: Event) => { const inputValue = (event.target as HTMLInputElement).value; if (!props.disabled && !isReadOnly.value) { emitValue(inputValue); } }; const onDropdownInput = (selectedValue: BentoListboxSelectedValue) => { emit('dropdown-input', selectedValue); emit('update:dropdown', { ...props?.dropdown, value: selectedValue }); }; const focusInput = () => { inputFieldElement.value.focus(); }; const focus = () => { if (props.variant === 'dropdown') { inputDropdownElement.value.focus(); } else { focusInput(); } }; // Expose method so that other components can focus on it in Vue3 defineExpose({ focusInput, focus, }); const inputFieldParentComponent = inject(INPUT_FIELD_PARENT_COMPONENT_INJECTION_KEY, ''); if (!Object.values(BentoInputFieldType).includes(props.type as BentoInputFieldType) && !inputFieldParentComponent) { if (props.type === 'tel') { printDevelopmentWarning( `"bento-input-field" dropdown does not support the type '${props.type}', use "bento-input-field-phone-number" instead.` ); } else if (props.type === 'password') { printDevelopmentWarning( `"bento-input-field" dropdown does not support the type '${props.type}', use "bento-input-field-password" instead.` ); } else { printDevelopmentWarning(`"bento-input-field" dropdown does not support the type '${props.type}'`); } } /** * Deprecations */ if (props.error) { deprecate( 'BentoInputField "error" property', `Use the BentoInputField "errorMessage" property instead to indicate that there is a modifier error. Having the field as "undefined" will hide/remove the error. <bento-dropdown errorMessage="Error message text" />`, '2.0.0' ); } if (hasSlot('defaultIconBefore')) { deprecate( 'BentoInputField "defaultIconBefore" slot', `Use the BentoInputField "iconBefore" slot instead to add an icon at the left side of the input field <bento-input-field> \t<template #iconBefore> \t\t<my-icon-goes-here /> \t</template> </bento-input-field>`, '2.0.0' ); } if (props.value) { deprecate( 'BentoInputField "value" property', `The use of "value" prop in "BentoInputField" is no longer supported. Use the "v-model" or "model-value" property instead.`, '2.0.0' ); } </script> <script lang="ts"> /** * Input field component is used to create interactive controls for web-based * forms in order to accept data from the user. * * @example * import { BentoInputField } from '@adyen/bento-vue2' * * const inputValue = ref(''); * * export default { * components: { BentoInputField }, * tempate: ` * <bento-input-field * :model-value="inputValue" * :@update:model-value="newValue => inputValue.value = newValue" * > * } */ export default { name: 'bento-input-field', model: { prop: 'modelValue' }, i18n: { messages }, }; </script> <style lang="scss" scoped src="./input-field.scss" />
|
|
1
|
+
<template> <bento-typography class="b-input-field" data-testid="input-text-container" :class="inputFieldConditionalClasses" el="div" variant="body" > <field-label v-if="hasSlot('default') || label" :for="inputFieldId" data-testid="input-field-label" :tooltip-text="tooltipText" :optional="optional" :required="required" :label="label" @click="focusInput" > <slot></slot> </field-label> <div class="b-input-field__input-box" data-testid="input-box" :aria-disabled="disabled" @click="focusInput"> <!-- Optional Icon for Default text variant --> <span v-if="isDefaultVariant && (hasSlot('defaultIconBefore') || hasSlot('iconBefore'))" :aria-hidden="ariaHidden ? 'true' : undefined" class="b-input-field__icon-before" > <slot v-if="hasSlot('iconBefore')" name="iconBefore" /> <slot v-if="hasSlot('defaultIconBefore') && !hasSlot('iconBefore')" name="defaultIconBefore" /> </span> <!-- Mandatory Icon for Payment Method variant --> <span v-if="isPaymentMethodVariant && hasSlot('paymentMethod')" :aria-hidden="ariaHidden ? 'true' : undefined" class="b-input-field__payment-method" > <slot name="paymentMethod" /> </span> <!-- Dropdown at start --> <div v-if="shouldDisplayDropdownAtStart" :id="dropdownId" class="b-input-field__dropdown b-input-field__dropdown--start" @click.stop > <bento-dropdown v-if="dropdown" ref="inputDropdownElement" v-bind="inputFieldDropdownProps" :disabled="disabled" :readonly="isDropdownReadOnly" @update:model-value="onDropdownInput" /> </div> <!-- Static Value at start --> <bento-typography v-if="shouldDisplayStaticValueAtStart" :id="staticValueId" class="b-input-field__static-value b-input-field__static-value--start" el="span" variant="body" > <slot name="staticValue" /> </bento-typography> <div class="b-input-field__input-container"> <input :id="inputFieldId" v-bind="attrs" ref="inputFieldElement" class="b-input-field__input" :aria-label="computedAriaLabel" :aria-describedby="computedAriaDescribedBy" :aria-owns="computedAriaOwns" :aria-invalid="shouldShowError" :placeholder="placeholder" :required="required" :aria-required="required" :type="type" :value="modelValue ?? value" :disabled="disabled" :readonly="isReadOnly" @input="onInput" @change="emit('change')" @focus="onFocus" @blur="onBlur" @keydown="emit('keydown', $event)" @keyup="emit('keyup', $event)" @keydown.esc="emit('escape-pressed')" @click="emit('click', $event)" /> <!-- Hint at the end --> <bento-typography v-if="hint && isFocused && (modelValue || value)" el="span" class="b-input-field__hint" > {{ hint }} </bento-typography> </div> <span v-if="hasSlot('iconAfter')" :aria-hidden="ariaHidden ? 'true' : undefined" class="b-input-field__icon-after" data-testid="input-text__icon-after" > <slot name="iconAfter" /> </span> <!-- Static Value at the end --> <bento-typography v-if="shouldDisplayStaticValueAtEnd" :id="staticValueId" class="b-input-field__static-value b-input-field__static-value--end" el="span" variant="body" > <slot name="staticValue" /> </bento-typography> <!-- Dropdown at end --> <div v-if="shouldDisplayDropdownAtEnd" :id="dropdownId" data-testid="input-field-dropdown-container-end" class="b-input-field__dropdown b-input-field__dropdown--end" @click.stop > <bento-dropdown v-if="dropdown" :id="dropdownId" ref="inputDropdownElement" v-bind="inputFieldDropdownProps" :disabled="disabled" :readonly="isDropdownReadOnly" @update:model-value="onDropdownInput" /> </div> </div> <error-message v-if="shouldShowError && !!errorMessage" :id="errorId" :error-message="errorMessage" class="b-input-field__error-message" /> <span v-if="hasSlot('description') || description" :id="descriptionId" class="b-input-field__description" @click="focusInput" > <bento-typography el="span" variant="body"> <slot id="description" name="description"> {{ description }} </slot> </bento-typography> </span> </bento-typography> </template> <script setup lang="ts"> import { computed, inject, provide, type Ref, ref, toRef, toRefs, useAttrs, useSlots } from 'vue'; // Components import { BentoDropdown } from '@/components/dropdown'; import { BentoTypography } from '@/components/typography'; import { ErrorMessage, FieldLabel } from '@/internal'; // Utils import { deprecate } from '@/utils/ts/deprecate'; import { useFormFieldEmits } from '@/utils/ts/form-field/form-field'; import { generateUid } from '@/core/utils/ts'; import { getSlotText } from '@/utils/ts/get-slot-text'; import { useAriaLabel } from '@/utils/ts/aria-label'; import { useI18n } from '@/utils/ts/i18n'; import { printDevelopmentWarning } from '@/utils/ts/print-development-warning'; import { INPUT_FIELD_COMPONENT_INJECTION_KEY, INPUT_FIELD_HINT_INJECTION_KEY, INPUT_FIELD_PARENT_COMPONENT_INJECTION_KEY, } from '@/components/input-field/input-field.keys'; import { type BentoListboxSelectedValue } from '@/types/listbox'; // Composables import { useFormLayoutFieldLoading, useHasSlot } from '@/composables'; // Types import { type BentoInputDropdownProps, BentoInputFieldElementPosition, type BentoInputFieldProps, BentoInputFieldStateClass, BentoInputFieldType, type BentoInputFieldValue, BentoInputFieldVariant, } from './input-field.types'; import messages from './messages.json'; type MessageSchema = (typeof messages)['en-US']; const attrs = useAttrs(); const slots = useSlots(); const props = withDefaults(defineProps<BentoInputFieldProps>(), { ariaHidden: true, ariaLabel: undefined, condensed: false, description: '', disabled: false, dropdown: undefined, dropdownPosition: BentoInputFieldElementPosition.START, error: false, errorMessage: null, label: '', modelValue: undefined, optional: false, placeholder: '', required: false, readonly: false, slashedZero: false, staticValue: '', staticValuePosition: BentoInputFieldElementPosition.START, tooltipText: null, type: BentoInputFieldType.TEXT, value: undefined, variant: BentoInputFieldVariant.DEFAULT, }); const emit = defineEmits<{ /** * Emitted when the element has lost focus */ (e: 'blur'): void; /** * Emitted when the input is clicked */ (e: 'click', event: MouseEvent); /** * Emitted when the user modifies the element's value. Unlike the 'input' event, the change event is not necessarily fired for each alteration to an element's value */ (e: 'change'): void; /** * Emitted when the Input Field's internal dropdown changes it's value */ (e: 'dropdown-input', selectedValue: BentoListboxSelectedValue): void; /** * Emitted when the "ESC" key is pressed */ (e: 'escape-pressed'): void; /** * Emitted when the element has received focus */ (e: 'focus'): void; /** * Emitted when a key is pressed down */ (e: 'keydown', event: KeyboardEvent): void; /** * Emitted when a key is pressed and lifted up */ (e: 'keyup', event: KeyboardEvent): void; /** * Emitted when the component's model changes * @deprecated since version 2.0. Use `v-model` or `update:model-value` instead. */ (e: 'input', inputValue: string): void; /** * Emitted when the Input Field's internal dropdown changes it's value. Contains every dropdown prop passed with the updated selected value as 'value' */ (e: 'update:dropdown', updatedDropdownProps: BentoInputDropdownProps): void; /** * Emitted when the component's model changes */ (e: 'update:model-value', inputValue: BentoInputFieldValue): void; }>(); const { emitValue } = useFormFieldEmits<BentoInputFieldValue>(emit); const { t } = useI18n<{ message: MessageSchema }>({ messages }); const hasSlot = useHasSlot(slots); const inputFieldElement = ref(null); const inputDropdownElement = ref(null); const inputFieldId = generateUid('input'); const dropdownId = generateUid('input-dropdown'); const staticValueId = generateUid('input-static-value'); const descriptionId = generateUid('input-description'); const errorId = generateUid('input-error'); const isFocused = ref(false); // Provide INPUT_FIELD_COMPONENT_INJECTION_KEY as true, to set the input only dropdown size variant in the BentoDropdown comp provide(INPUT_FIELD_COMPONENT_INJECTION_KEY, true); // Renders the input with a hint if a string is provided const hint = inject<Ref<string | undefined>>(INPUT_FIELD_HINT_INJECTION_KEY, ref(undefined)); const onFocus = () => { isFocused.value = true; emit('focus'); }; const onBlur = () => { isFocused.value = false; emit('blur'); }; const { isReadOnly } = useFormLayoutFieldLoading(toRef(props, 'readonly')); const isDropdownReadOnly = computed<BentoInputDropdownProps['readonly']>( () => isReadOnly.value || props.dropdown?.readonly ); const shouldShowStaticValue = computed( () => props.variant === BentoInputFieldVariant.STATIC_VALUE && !!slots.staticValue ); const isDefaultVariant = computed(() => props.variant === BentoInputFieldVariant.DEFAULT); const isPaymentMethodVariant = computed(() => props.variant === BentoInputFieldVariant.PAYMENT_METHOD); const shouldDisplayStaticValueAtStart = computed( () => shouldShowStaticValue.value && props.staticValuePosition === BentoInputFieldElementPosition.START ); const shouldDisplayStaticValueAtEnd = computed( () => shouldShowStaticValue.value && props.staticValuePosition === BentoInputFieldElementPosition.END ); const shouldShowDropdown = computed(() => props.variant === BentoInputFieldVariant.DROPDOWN && !!props.dropdown); const shouldDisplayDropdownAtStart = computed( () => shouldShowDropdown.value && props.dropdownPosition === BentoInputFieldElementPosition.START ); const shouldDisplayDropdownAtEnd = computed( () => shouldShowDropdown.value && props.dropdownPosition === BentoInputFieldElementPosition.END ); const shouldShowError = computed( () => !props.disabled && !isReadOnly.value && (!!props.errorMessage || props.error) ); const computedLabel = computed(() => (getSlotText(slots)('default') as string) || props.label); const computedDescription = computed(() => (getSlotText(slots)('description') as string) || props.description); const computedAriaOwns = computed(() => { if (shouldShowDropdown.value === true && shouldShowStaticValue.value === true) { return `${staticValueId} ${dropdownId}`; } if (shouldShowDropdown.value === true) { return `${dropdownId}`; } if (shouldShowStaticValue.value === true) { return `${staticValueId}`; } return null; }); // vue-i18n issue with t() used in script - direct usage in template works // requires either createI18n({ legacy: false }) or to be wrapped in computed() const computedAriaLabelFallbackMessage = computed(() => t('ariaLabelFallback')); const computedAriaLabelDropdowFallback = computed(() => t('ariaLabelDropdownFallback', { inputLabel: computedAriaLabel.value }) ); const ariaLabelAttribute = ref(attrs['aria-label']); const { ariaLabel } = toRefs(props); const computedAriaLabel = useAriaLabel({ ariaLabel: ariaLabelAttribute.value as string, // TODO: take this line away when the aria-label props is removed label: ariaLabel, defaultFallback: computedLabel.value || computedAriaLabelFallbackMessage, }); const computedAriaDescribedBy = computed( () => `${computedDescription.value ? descriptionId : ''} ${ shouldShowError.value && !!props.errorMessage ? errorId : '' }` ); const inputFieldConditionalClasses = computed(() => ({ [`b-input-field--${BentoInputFieldStateClass.CONDENSED}`]: props.condensed, [`b-input-field--${BentoInputFieldStateClass.DISABLED}`]: props.disabled, [`b-input-field--${BentoInputFieldStateClass.READONLY}`]: isReadOnly.value, [`b-input-field--${BentoInputFieldStateClass.ERROR}`]: shouldShowError.value, [`b-input-field--slashed-zero`]: props.slashedZero, })); const inputFieldDropdownProps = computed(() => ({ 'aria-label': computedAriaLabelDropdowFallback.value, ...props.dropdown, })); const onInput = (event: Event) => { const inputValue = (event.target as HTMLInputElement).value; if (!props.disabled && !isReadOnly.value) { emitValue(inputValue); } }; const onDropdownInput = (selectedValue: BentoListboxSelectedValue) => { emit('dropdown-input', selectedValue); emit('update:dropdown', { ...props?.dropdown, value: selectedValue }); }; const focusInput = () => { inputFieldElement.value.focus(); }; const focus = () => { if (props.variant === 'dropdown') { inputDropdownElement.value.focus(); } else { focusInput(); } }; // Expose method so that other components can focus on it in Vue3 defineExpose({ focusInput, focus, }); const inputFieldParentComponent = inject(INPUT_FIELD_PARENT_COMPONENT_INJECTION_KEY, ''); if (!Object.values(BentoInputFieldType).includes(props.type as BentoInputFieldType) && !inputFieldParentComponent) { if (props.type === 'tel') { printDevelopmentWarning( `"bento-input-field" dropdown does not support the type '${props.type}', use "bento-input-field-phone-number" instead.` ); } else if (props.type === 'password') { printDevelopmentWarning( `"bento-input-field" dropdown does not support the type '${props.type}', use "bento-input-field-password" instead.` ); } else { printDevelopmentWarning(`"bento-input-field" dropdown does not support the type '${props.type}'`); } } /** * Deprecations */ if (props.error) { deprecate( 'BentoInputField "error" property', `Use the BentoInputField "errorMessage" property instead to indicate that there is a modifier error. Having the field as "undefined" will hide/remove the error. <bento-dropdown errorMessage="Error message text" />`, '2.0.0' ); } if (hasSlot('defaultIconBefore')) { deprecate( 'BentoInputField "defaultIconBefore" slot', `Use the BentoInputField "iconBefore" slot instead to add an icon at the left side of the input field <bento-input-field> \t<template #iconBefore> \t\t<my-icon-goes-here /> \t</template> </bento-input-field>`, '2.0.0' ); } if (props.value) { deprecate( 'BentoInputField "value" property', `The use of "value" prop in "BentoInputField" is no longer supported. Use the "v-model" or "model-value" property instead.`, '2.0.0' ); } </script> <script lang="ts"> /** * Input field component is used to create interactive controls for web-based * forms in order to accept data from the user. * * @example * import { BentoInputField } from '@adyen/bento-vue2' * * const inputValue = ref(''); * * export default { * components: { BentoInputField }, * tempate: ` * <bento-input-field * :model-value="inputValue" * :@update:model-value="newValue => inputValue.value = newValue" * > * } */ export default { name: 'bento-input-field', model: { prop: 'modelValue' }, i18n: { messages }, }; </script> <style lang="scss" scoped src="./input-field.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import { action } from '@storybook/addon-actions'; import { isVue2 } from 'vue-demi'; import { storybookDocsParameter } from '@/utils/ts/storybook'; import BentoInputFieldPassword from './input-field-password.vue'; import type { Meta, StoryObj } from '@storybook/vue'; import { minLength } from '@/components/input-field-password/utilities/input-field-password.validation'; import { type BentoInputFieldPasswordValidation } from './input-field-password.types'; const meta: Meta = { title: 'Input Field Password', component: BentoInputFieldPassword, argTypes: { condensed: { table: { type: { summary: 'boolean' }, }, }, disabled: { table: { type: { summary: 'boolean' }, }, }, errorMessage: { table: { type: { summary: 'string' }, }, }, placeholder: { table: { type: { summary: 'string' }, }, }, readonly: { table: { type: { summary: 'boolean' }, }, }, modelValue: { control: { type: 'text' }, table: { type: { summary: 'string | number' }, }, }, label: { table: { type: { summary: 'string' }, }, }, // Events 'input:valid': { table: { type: { summary: '() => void' }, }, control: { disable: true }, }, // Deprecated input: { description: 'Deprecated since version 2.0. Use `v-model` or `update:model-value instead', table: { category: 'Deprecated' }, control: { disable: true }, }, value: { control: { type: 'text' }, table: { category: 'Deprecated' }, description: 'Deprecated for usage with properties since version 2.0. Use `v-model` or `model-value` property instead', }, }, }; export default meta; type Story = StoryObj<typeof BentoInputFieldPassword>; const DEFAULT_PROPS = { label: 'Password', withHint: true, condensed: false, disabled: false, readonly: false, description: 'Enter your password', }; const CUSTOM_VALIDATION: BentoInputFieldPasswordValidation = { extendDefaultValidation: true, list: [ { label: 'Always true', key: 'alwaysTrue', validate: () => true, }, { label: '18 characters', key: 'minLength', validate: minLength, additionalArgs: [18], }, { key: 'requireSpecialCharacter', disabled: true, }, ], }; const defaultCode = ` <template> <bento-input-field-password label="Label" :error-message="errors.password" @update:model-value="updateModelValue" @input:valid="inputValidAction" @input:error="inputErrorAction" /> </template> <script setup lang="ts"> import { BentoInputFieldPassword } from '@adyen/bento-vue2' import { reactive } from 'vue'; const errors = reactive({ password: '', }); const updateModelValue = () => { // do something when the input value changes } const inputValidAction = () => { // do something when password is valid } const inputErrorAction = () => { errors.password = 'Password field has an error'; } </script> `; export const Default: Story = { render: (_args, { argTypes }) => ({ components: { BentoInputFieldPassword }, props: Object.keys(argTypes), template: ` <bento-input-field-password v-bind="args" @update:model-value="updateModelValue" @input:valid="inputValidAction" @input:error="inputErrorAction"
|
|
1
|
+
import { action } from '@storybook/addon-actions'; import { isVue2 } from 'vue-demi'; import { storybookDocsParameter } from '@/utils/ts/storybook'; import BentoInputFieldPassword from './input-field-password.vue'; import type { Meta, StoryObj } from '@storybook/vue'; import { minLength } from '@/components/input-field-password/utilities/input-field-password.validation'; import { type BentoInputFieldPasswordValidation } from './input-field-password.types'; const meta: Meta = { title: 'Input Field Password', component: BentoInputFieldPassword, argTypes: { condensed: { table: { type: { summary: 'boolean' }, }, }, disabled: { table: { type: { summary: 'boolean' }, }, }, errorMessage: { table: { type: { summary: 'string' }, }, }, placeholder: { table: { type: { summary: 'string' }, }, }, readonly: { table: { type: { summary: 'boolean' }, }, }, description: { name: 'description', description: 'If set, displays a description text for the input.', table: { category: 'props', type: { summary: 'string' }, }, control: { type: 'text', }, }, 'slot:description': { name: 'description', defaultValue: '', description: 'If set, displays a description text for the input. Overrides the `description` prop when provided.', table: { category: 'slots', type: { summary: 'VNode[]' }, }, control: { type: 'text', }, }, modelValue: { control: { type: 'text' }, table: { type: { summary: 'string | number' }, }, }, label: { table: { type: { summary: 'string' }, }, }, // Events 'input:valid': { table: { type: { summary: '() => void' }, }, control: { disable: true }, }, // Deprecated input: { description: 'Deprecated since version 2.0. Use `v-model` or `update:model-value instead', table: { category: 'Deprecated' }, control: { disable: true }, }, value: { control: { type: 'text' }, table: { category: 'Deprecated' }, description: 'Deprecated for usage with properties since version 2.0. Use `v-model` or `model-value` property instead', }, }, }; export default meta; type Story = StoryObj<typeof BentoInputFieldPassword>; const DEFAULT_PROPS = { label: 'Password', withHint: true, condensed: false, disabled: false, readonly: false, description: 'Enter your password', }; const CUSTOM_VALIDATION: BentoInputFieldPasswordValidation = { extendDefaultValidation: true, list: [ { label: 'Always true', key: 'alwaysTrue', validate: () => true, }, { label: '18 characters', key: 'minLength', validate: minLength, additionalArgs: [18], }, { key: 'requireSpecialCharacter', disabled: true, }, ], }; const defaultCode = ` <template> <bento-input-field-password label="Label" :error-message="errors.password" @update:model-value="updateModelValue" @input:valid="inputValidAction" @input:error="inputErrorAction" /> </template> <script setup lang="ts"> import { BentoInputFieldPassword } from '@adyen/bento-vue2' import { reactive } from 'vue'; const errors = reactive({ password: '', }); const updateModelValue = () => { // do something when the input value changes } const inputValidAction = () => { // do something when password is valid } const inputErrorAction = () => { errors.password = 'Password field has an error'; } </script> `; export const Default: Story = { render: (_args, { argTypes }) => ({ components: { BentoInputFieldPassword }, props: Object.keys(argTypes), template: ` <bento-input-field-password v-bind="args" @update:model-value="updateModelValue" @input:valid="inputValidAction" @input:error="inputErrorAction" > <template #description v-if="args['slot:description']">{{ args['slot:description'] }}</template> </bento-input-field-password> `, setup(props) { return { // Values args: isVue2 ? props : _args, // Events updateModelValue: (value: string) => action('update:model-value')(value), inputErrorAction: (value: string) => action('input:error')(value), inputValidAction: action('input:valid'), }; }, }), args: DEFAULT_PROPS, parameters: storybookDocsParameter(defaultCode), }; const customValidationCode = ` <template> <bento-input-field-password label="Label" :error-message="errors.password" :validation="{ extendDefaultValidation: true, list: [ { // custom rule label: 'Always true', key: 'alwaysTrue', validate: () => true, }, { // override existing rule label: '18 characters', key: 'minLength', validate: minLength, additionalArgs: [18], }, { // disable existing rule key: 'requireSpecialCharacter', disabled: true, }, ], }" @update:model-value="updateModelValue" @input:valid="inputValidAction" @input:error="inputErrorAction" /> </template> <script setup lang="ts"> import { BentoInputFieldPassword, minLength } from '@adyen/bento-vue2' import { reactive } from 'vue'; const errors = reactive({ password: '', }); const updateModelValue = () => { // do something when the input value changes } const inputValidAction = () => { // do something when password is valid } const inputErrorAction = () => { errors.password = 'Password field has an error'; } </script> `; export const CustomValidation: Story = { render: (_args, { argTypes }) => ({ components: { BentoInputFieldPassword }, props: Object.keys(argTypes), template: ` <bento-input-field-password v-bind="args" @update:model-value="updateModelValue" @input:valid="inputValidAction" @input:error="inputErrorAction" > <template #description v-if="args['slot:description']">{{ args['slot:description'] }}</template> </bento-input-field-password> `, setup(props) { return { // Values args: isVue2 ? props : _args, // Events updateModelValue: (value: string) => action('update:model-value')(value), inputErrorAction: (value: string) => action('input:error')(value), inputValidAction: action('input:valid'), }; }, }), args: { ...DEFAULT_PROPS, validation: CUSTOM_VALIDATION, }, parameters: storybookDocsParameter(customValidationCode), };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import { isVue2 } from 'vue-demi'; import { action } from '@storybook/addon-actions'; import { nextTick, onMounted, ref } from 'vue'; import { storybookDocsParameter } from '@/utils/ts/storybook'; import BentoInputFieldPhoneNumber from './input-field-phone-number.vue'; import type { Meta, StoryObj } from '@storybook/vue'; import type { BentoInputFieldPhoneNumberDropdownProps } from './input-field-phone-number.types'; import InputFieldPhoneNumberDefaultExample from './__tests__/input-field-phone-number-default-example.vue?raw'; const meta: Meta = { title: 'Input field phone number', component: BentoInputFieldPhoneNumber, argTypes: { input: { description: 'Deprecated since version 2.0. Use `v-model` or `update:model-value instead', table: { category: 'Deprecated' }, control: { disable: true }, }, value: { control: { type: 'text' }, table: { category: 'Deprecated' }, description: 'Deprecated for usage with properties since version 2.0. Use `v-model` or `model-value` property instead', }, }, }; export default meta; type Story = StoryObj<typeof BentoInputFieldPhoneNumber>; export const Default: Story = { render: (_args, { argTypes }) => ({ components: { BentoInputFieldPhoneNumber }, props: Object.keys(argTypes), template: ` <bento-input-field-phone-number v-bind="args" :model-value="value" :selected-country="country" :error-message="errorMessage" @update:model-value="updateModelValue" @update:selected-country="onSelectedCountry" @blur="onBlur" @input:valid="validate" > <template #default v-if='args.default'> {{ args.default }} </template> <template #description v-if='
|
|
1
|
+
import { isVue2 } from 'vue-demi'; import { action } from '@storybook/addon-actions'; import { nextTick, onMounted, ref } from 'vue'; import { storybookDocsParameter } from '@/utils/ts/storybook'; import BentoInputFieldPhoneNumber from './input-field-phone-number.vue'; import type { Meta, StoryObj } from '@storybook/vue'; import type { BentoInputFieldPhoneNumberDropdownProps } from './input-field-phone-number.types'; import InputFieldPhoneNumberDefaultExample from './__tests__/input-field-phone-number-default-example.vue?raw'; const meta: Meta = { title: 'Input field phone number', component: BentoInputFieldPhoneNumber, argTypes: { description: { name: 'description', description: 'If set, displays a description text for the input.', table: { category: 'props', type: { summary: 'string' }, }, control: { type: 'text', }, }, 'slot:description': { name: 'description', defaultValue: '', description: 'If set, displays a description text for the input. Overrides the `description` prop when provided.', table: { category: 'slots', type: { summary: 'VNode[]' }, }, control: { type: 'text', }, }, input: { description: 'Deprecated since version 2.0. Use `v-model` or `update:model-value instead', table: { category: 'Deprecated' }, control: { disable: true }, }, value: { control: { type: 'text' }, table: { category: 'Deprecated' }, description: 'Deprecated for usage with properties since version 2.0. Use `v-model` or `model-value` property instead', }, }, }; export default meta; type Story = StoryObj<typeof BentoInputFieldPhoneNumber>; export const Default: Story = { render: (_args, { argTypes }) => ({ components: { BentoInputFieldPhoneNumber }, props: Object.keys(argTypes), template: ` <bento-input-field-phone-number v-bind="args" :model-value="value" :selected-country="country" :error-message="errorMessage" @update:model-value="updateModelValue" @update:selected-country="onSelectedCountry" @blur="onBlur" @input:valid="validate" > <template #default v-if='args.default'> {{ args.default }} </template> <template #description v-if="args['slot:description']"> {{ args['slot:description'] }} </template> </bento-input-field-phone-number> `, setup(props) { const value = ref('+12025550123'); const country = ref('US'); const errorMessage = ref(''); const isValid = ref(false); const updateErrorMessage = () => { if (!isValid.value && value.value) { errorMessage.value = 'This number is not valid.'; } else { errorMessage.value = ''; } }; const onSelectedCountry = async updatedCountry => { country.value = updatedCountry; action('update:selected-country')(updatedCountry); await nextTick(); updateErrorMessage(); }; const updateModelValue = input => { value.value = input; action('update:model-value')(input); }; const validate = (validity: boolean) => { isValid.value = validity; if (validity) { updateErrorMessage(); } action('input:valid')(validity); }; const onBlur = () => { updateErrorMessage(); action('blur')(); }; onMounted(() => { updateErrorMessage(); }); return { // Values args: isVue2 ? props : _args, value, country, errorMessage, // Methods onSelectedCountry, updateModelValue, onBlur, validate, }; }, }), args: { label: 'Phone number', description: 'Select your country and input the phone number', dropdown: { readonly: false, } satisfies BentoInputFieldPhoneNumberDropdownProps, }, parameters: storybookDocsParameter(InputFieldPhoneNumberDefaultExample), };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <bento-input-field v-bind="computedProps" ref="inputField" variant="dropdown" :dropdown="dropdown" class="b-input-field-phone-number" :model-value="displayValue" :placeholder="computedPlaceholder" type="tel" @blur="onBlur" @update:model-value="onUpdateModelValue" @keydown="onKeydown" @dropdown-input="onCountryChange" > <template v-if="label">{{ label }}</template> <template v-else><slot /></template> <template #description> <slot name="description">{{ description }}</slot> </template> </bento-input-field> </template> <script setup lang="ts"> import { computed, nextTick, provide, ref, watch } from 'vue'; import { type BentoInputDropdownProps, BentoInputField } from '@/components/input-field'; import { AsYouType, type CountryCode } from 'libphonenumber-js'; import { useI18n } from '@/utils/ts/i18n'; import { appendRegionCode, BentoInputFieldPhoneNumberCountries, getCountriesDropdownItems, getFormattedPhoneCode, getPhoneNumberPlaceholder, handleInputCursor, hasDefaultRegionCode, parsePhoneAndCountry, preventRegionCodeRepetition, stripRegionCode, } from './utils'; import { useFormFieldEmits } from '@/utils/ts/form-field/form-field'; import { deprecate } from '@/utils/ts/deprecate'; import type { BentoInputFieldPhoneNumberProps } from './input-field-phone-number.types'; import messages from './messages.json'; import { INPUT_FIELD_PARENT_COMPONENT_INJECTION_KEY } from '@/components/input-field/input-field.keys'; type MessageSchema = (typeof messages)['en-US']; const { t, locale } = useI18n<{ message: MessageSchema }>({ messages }); const props = withDefaults(defineProps<BentoInputFieldPhoneNumberProps>(), { countries: () => BentoInputFieldPhoneNumberCountries, description: undefined, dynamicFiltering: true, }); /** * Avoid passing `value` to `bento-input-field`. * This component uses `displayValue` instead. */ const computedProps = computed(() => { const { value, ...allProps } = props; return allProps; }); const emit = defineEmits<{ /** * Emitted when the element has lost focus */ (e: 'blur'): void; /** * Emitted when the value changes. The value is the unformatted phone number in E.164 format. * @deprecated from version 2.0.0. Use `v-model` or `update:model-value` instead. */ (e: 'input', value: string): void; /** * Emitted when the value changes. The value is the unformatted phone number in E.164 format. */ (e: 'update:model-value', value: string): void; /** * Emitted when the selected country is updated. */ (e: 'update:selected-country', country: CountryCode): void; /** * Emitted when the phone number's validity changes. * The payload is a boolean indicating whether the number is valid. */ (e: 'input:valid', value: boolean): void; }>(); const inputField = ref(null); const displayValue = ref(''); const internalValue = ref(''); const insertedChar = ref(''); const { emitValue } = useFormFieldEmits<string>(emit); provide(INPUT_FIELD_PARENT_COMPONENT_INJECTION_KEY, 'bento-input-field-phone-number'); const computedPlaceholder = computed(() => { if (props.placeholder) { return props.placeholder; } if (props.selectedCountry) { return getPhoneNumberPlaceholder(props.selectedCountry); } return ''; }); const isDropdownReadonly = computed(() => props.dropdown?.readonly); const countryItems = computed(() => getCountriesDropdownItems(props.countries, locale.value)); const dropdown = computed<BentoInputDropdownProps>(() => ({ items: countryItems.value, modelValue: props.selectedCountry, readonly: isDropdownReadonly.value, dynamicFiltering: props.dynamicFiltering, 'aria-label': t('countrySelectorDropdown'), })); const onBlur = () => emit('blur'); const onUpdateModelValue = async (value: string) => { const inputEl = inputField.value.$refs.inputFieldElement; let formatter: AsYouType; // Check if the input value starts with '+' or '00', indicating it includes a country code. if (value.startsWith('+') || value.startsWith('00')) { // Reset displayValue to ensure changes are always reflected. // For example, if you paste '+1 264 123 4567' multiple times, the display value should always be '1234567'. // Without this, the displayValue will be '1234567' the first time but subsequently stay as '+1 264 123 4567'. displayValue.value = ''; // Normalize the value by replacing '00' with '+'. const normalizedValue = value.startsWith('00') ? `+${value.slice(2)}` : value; // Create a new AsYouType formatter to format the number as it's typed. formatter = new AsYouType(); formatter.input(normalizedValue); // Get the country code from the formatted number. const country = formatter.getCountry(); // Check if the extracted country code is valid and included in the allowed countries. const isValidCountry = country && props.countries.includes(country); // If the dropdown is readonly, determine whether to strip the region code based on the selected country. if (isDropdownReadonly.value) { displayValue.value = props.selectedCountry === country ? stripRegionCode(formatter.getNationalNumber(), country) : value; } else { // Emit an event to update the selected country, if valid. Otherwise, set it to null. emit('update:selected-country', isValidCountry ? country : null); // Strip the region code from the formatted number if the country is valid. displayValue.value = isValidCountry ? stripRegionCode(formatter.getNationalNumber(), country) : value; } const numberValue = formatter.getNumberValue() ?? ''; const formattedPhoneCode = getFormattedPhoneCode(country); const shouldClearInput = isValidCountry && numberValue.startsWith(formattedPhoneCode) && numberValue.length <= formattedPhoneCode.length; internalValue.value = shouldClearInput ? '' : numberValue; emitValue(internalValue.value); } else { // If the input doesn't start with a country code, format the number based on the selected country. formatter = new AsYouType(props.selectedCountry); const formatted = formatter.input(appendRegionCode(value, props.selectedCountry)); // Prevent repetition of the region code and get the unformatted number. const unformattedNumber = preventRegionCodeRepetition(value, formatter.getNumberValue(), props.selectedCountry) ?? ''; // Emit the unformatted number value and update the display value with the stripped region code. internalValue.value = unformattedNumber; emitValue(internalValue.value); displayValue.value = stripRegionCode(formatted, props.selectedCountry); } await nextTick(); // Re-parse the number to ensure correct formatting, e.g., adding a leading '0' for NL numbers if valid and `hasDefaultRegionCode` returns false. if (formatter.isValid() && props.selectedCountry && !hasDefaultRegionCode(props.selectedCountry)) { const { displayNumber, isValid } = parsePhoneAndCountry( displayValue.value?.toString(), props.selectedCountry, props.countries ); displayValue.value = displayNumber; emitValidation(isValid); } else { emitValidation(formatter.isValid()); } handleInputCursor(inputEl, displayValue.value.toString(), insertedChar.value); }; const emitValidation = (isValid: boolean) => { // Numbers shorter than 5 digits are never valid phone numbers. // `libphonenumber-js` rejects numbers under 5 digits (`TOO_SHORT`). // We don’t call that check directly here, but use the same value for consistency. const MIN_PHONE_NUMBER_LENGTH_FOR_VALIDATION = 5; const numberLength = displayValue.value?.toString().replace(/\D/g, '')?.length ?? 0; const isValidNumberLength = numberLength >= MIN_PHONE_NUMBER_LENGTH_FOR_VALIDATION; emit('input:valid', isValidNumberLength && isValid); }; const onKeydown = event => { if (/^[a-zA-Z]$/.test(event.key) && !event.metaKey && !event.ctrlKey) { event.preventDefault(); return; } insertedChar.value = event.key; }; const onCountryChange = (country: CountryCode) => { emit('update:selected-country', country); const isUnformatted = displayValue.value?.toString().startsWith('+'); if (hasDefaultRegionCode(country) && !isUnformatted) { let formatter = new AsYouType(country); const formatted = formatter.input(appendRegionCode(displayValue.value?.toString(), country)); const unformattedNumber = preventRegionCodeRepetition(displayValue.value?.toString(), formatter.getNumberValue(), country) ?? ''; internalValue.value = unformattedNumber; emitValue(internalValue.value); displayValue.value = stripRegionCode(formatted, country); emitValidation(formatter.isValid()); } else { const { displayNumber, unformattedNumber, isValid } = parsePhoneAndCountry( displayValue.value?.toString(), country, props.countries ); internalValue.value = unformattedNumber ?? ''; emitValue(internalValue.value); displayValue.value = displayNumber; emitValidation(isValid); } }; watch( () => [props.value, props.modelValue], () => { const newValue = props.modelValue ?? props.value; if (newValue === internalValue.value) { return; } const { displayNumber, country, isValid } = parsePhoneAndCountry( newValue?.toString(), props.selectedCountry, props.countries ); if (country && country !== props.selectedCountry && !isDropdownReadonly.value) { emit('update:selected-country', country); } displayValue.value = stripRegionCode(displayNumber, country); emitValidation(isValid); }, { immediate: true } ); if (props.value) { deprecate( 'BentoInputFieldPhoneNumber "value" property', `The use of "value" prop in "BentoInputFieldPhoneNumber" is no longer supported. Use the "v-model" or "model-value" property instead.`, '2.0.0' ); } </script> <script lang="ts"> /** * Input field phone number can be used to display phone numbers that come with a country code. * * @example * import { BentoInputFieldPhoneNumber } from '@adyen/bento-vue2'; * * export default { * components: { BentoInputFieldPhoneNumber }, * template: ` * <bento-input-field-phone-number * label="Phone number" * :countries="['NL', 'BE']" * model-value="0612345678" * selected-country="NL" * /> * ` * } */ export default { i18n: { messages }, model: { prop: 'modelValue' }, }; </script> <style lang="scss" scoped src="./input-field-phone-number.scss" />
|
|
1
|
+
<template> <bento-input-field v-bind="computedProps" ref="inputField" variant="dropdown" :dropdown="dropdown" class="b-input-field-phone-number" :model-value="displayValue" :placeholder="computedPlaceholder" type="tel" @blur="onBlur" @update:model-value="onUpdateModelValue" @keydown="onKeydown" @dropdown-input="onCountryChange" > <template v-if="label">{{ label }}</template> <template v-else><slot /></template> <template #description> <slot name="description">{{ description }}</slot> </template> </bento-input-field> </template> <script setup lang="ts"> import { computed, nextTick, provide, ref, watch } from 'vue'; import { type BentoInputDropdownProps, BentoInputField } from '@/components/input-field'; import { AsYouType, type CountryCode } from 'libphonenumber-js'; import { useI18n } from '@/utils/ts/i18n'; import { appendRegionCode, BentoInputFieldPhoneNumberCountries, getCountriesDropdownItems, getFormattedPhoneCode, getPhoneNumberPlaceholder, handleInputCursor, hasDefaultRegionCode, parsePhoneAndCountry, preventRegionCodeRepetition, stripRegionCode, } from './utils'; import { useFormFieldEmits } from '@/utils/ts/form-field/form-field'; import { deprecate } from '@/utils/ts/deprecate'; import type { BentoInputFieldPhoneNumberProps } from './input-field-phone-number.types'; import messages from './messages.json'; import { INPUT_FIELD_PARENT_COMPONENT_INJECTION_KEY } from '@/components/input-field/input-field.keys'; type MessageSchema = (typeof messages)['en-US']; const { t, locale } = useI18n<{ message: MessageSchema }>({ messages }); const props = withDefaults(defineProps<BentoInputFieldPhoneNumberProps>(), { countries: () => BentoInputFieldPhoneNumberCountries, description: undefined, dynamicFiltering: true, }); /** * Avoid passing `value` to `bento-input-field`. * This component uses `displayValue` instead. */ const computedProps = computed(() => { const { value, ...allProps } = props; return allProps; }); const emit = defineEmits<{ /** * Emitted when the element has lost focus */ (e: 'blur'): void; /** * Emitted when the value changes. The value is the unformatted phone number in E.164 format. * @deprecated from version 2.0.0. Use `v-model` or `update:model-value` instead. */ (e: 'input', value: string): void; /** * Emitted when the value changes. The value is the unformatted phone number in E.164 format. */ (e: 'update:model-value', value: string): void; /** * Emitted when the selected country is updated. */ (e: 'update:selected-country', country: CountryCode): void; /** * Emitted when the phone number's validity changes. * The payload is a boolean indicating whether the number is valid. */ (e: 'input:valid', value: boolean): void; }>(); const inputField = ref(null); const displayValue = ref(''); const internalValue = ref(''); const insertedChar = ref(''); const { emitValue } = useFormFieldEmits<string>(emit); provide(INPUT_FIELD_PARENT_COMPONENT_INJECTION_KEY, 'bento-input-field-phone-number'); const computedPlaceholder = computed(() => { if (props.placeholder) { return props.placeholder; } if (props.selectedCountry) { return getPhoneNumberPlaceholder(props.selectedCountry); } return ''; }); const isDropdownReadonly = computed(() => props.dropdown?.readonly); const countryItems = computed(() => getCountriesDropdownItems(props.countries, locale.value)); const dropdown = computed<BentoInputDropdownProps>(() => ({ items: countryItems.value, modelValue: props.selectedCountry, readonly: isDropdownReadonly.value, dynamicFiltering: props.dynamicFiltering, 'aria-label': t('countrySelectorDropdown'), })); const onBlur = () => emit('blur'); const onUpdateModelValue = async (value: string) => { const inputEl = inputField.value.$refs.inputFieldElement; let formatter: AsYouType; // Check if the input value starts with '+' or '00', indicating it includes a country code. if (value.startsWith('+') || value.startsWith('00')) { // Reset displayValue to ensure changes are always reflected. // For example, if you paste '+1 264 123 4567' multiple times, the display value should always be '1234567'. // Without this, the displayValue will be '1234567' the first time but subsequently stay as '+1 264 123 4567'. displayValue.value = ''; // Normalize the value by replacing '00' with '+'. const normalizedValue = value.startsWith('00') ? `+${value.slice(2)}` : value; // Create a new AsYouType formatter to format the number as it's typed. formatter = new AsYouType(); formatter.input(normalizedValue); // Get the country code from the formatted number. const country = formatter.getCountry(); // Check if the extracted country code is valid and included in the allowed countries. const isValidCountry = country && props.countries.includes(country); // If the dropdown is readonly, determine whether to strip the region code based on the selected country. if (isDropdownReadonly.value) { displayValue.value = props.selectedCountry === country ? stripRegionCode(formatter.getNationalNumber(), country) : value; } else { // Emit an event to update the selected country, if valid. Otherwise, set it to null. emit('update:selected-country', isValidCountry ? country : null); // Strip the region code from the formatted number if the country is valid. displayValue.value = isValidCountry ? stripRegionCode(formatter.getNationalNumber(), country) : value; } const numberValue = formatter.getNumberValue() ?? ''; const formattedPhoneCode = getFormattedPhoneCode(country); const shouldClearInput = isValidCountry && numberValue.startsWith(formattedPhoneCode) && numberValue.length <= formattedPhoneCode.length; internalValue.value = shouldClearInput ? '' : numberValue; emitValue(internalValue.value); } else { // If the input doesn't start with a country code, format the number based on the selected country. formatter = new AsYouType(props.selectedCountry); const formatted = formatter.input(appendRegionCode(value, props.selectedCountry)); // Prevent repetition of the region code and get the unformatted number. const numberValue = formatter.getNumberValue(); const unformattedNumber = numberValue ? preventRegionCodeRepetition(value, numberValue, props.selectedCountry) : value; // Emit raw input when parsing fails i.e. number do not have country code // Emit the unformatted number value and update the display value with the stripped region code. internalValue.value = unformattedNumber; emitValue(internalValue.value); displayValue.value = stripRegionCode(formatted, props.selectedCountry); } await nextTick(); // Re-parse the number to ensure correct formatting, e.g., adding a leading '0' for NL numbers if valid and `hasDefaultRegionCode` returns false. if (formatter.isValid() && props.selectedCountry && !hasDefaultRegionCode(props.selectedCountry)) { const { displayNumber, isValid } = parsePhoneAndCountry( displayValue.value?.toString(), props.selectedCountry, props.countries ); displayValue.value = displayNumber; emitValidation(isValid); } else { emitValidation(formatter.isValid()); } handleInputCursor(inputEl, displayValue.value.toString(), insertedChar.value); }; const emitValidation = (isValid: boolean) => { // Numbers shorter than 5 digits are never valid phone numbers. // `libphonenumber-js` rejects numbers under 5 digits (`TOO_SHORT`). // We don’t call that check directly here, but use the same value for consistency. const MIN_PHONE_NUMBER_LENGTH_FOR_VALIDATION = 5; const numberLength = displayValue.value?.toString().replace(/\D/g, '')?.length ?? 0; const isValidNumberLength = numberLength >= MIN_PHONE_NUMBER_LENGTH_FOR_VALIDATION; emit('input:valid', isValidNumberLength && isValid); }; const onKeydown = event => { if (/^[a-zA-Z]$/.test(event.key) && !event.metaKey && !event.ctrlKey) { event.preventDefault(); return; } insertedChar.value = event.key; }; const onCountryChange = (country: CountryCode) => { emit('update:selected-country', country); const isUnformatted = displayValue.value?.toString().startsWith('+'); if (hasDefaultRegionCode(country) && !isUnformatted) { let formatter = new AsYouType(country); const formatted = formatter.input(appendRegionCode(displayValue.value?.toString(), country)); const unformattedNumber = preventRegionCodeRepetition(displayValue.value?.toString(), formatter.getNumberValue(), country) ?? ''; internalValue.value = unformattedNumber; emitValue(internalValue.value); displayValue.value = stripRegionCode(formatted, country); emitValidation(formatter.isValid()); } else { const { displayNumber, unformattedNumber, isValid } = parsePhoneAndCountry( displayValue.value?.toString(), country, props.countries ); internalValue.value = unformattedNumber ?? ''; emitValue(internalValue.value); displayValue.value = displayNumber; emitValidation(isValid); } }; watch( () => [props.value, props.modelValue], () => { const newValue = props.modelValue ?? props.value; if (newValue === internalValue.value) { return; } const { displayNumber, country, isValid } = parsePhoneAndCountry( newValue?.toString(), props.selectedCountry, props.countries ); if (country && country !== props.selectedCountry && !isDropdownReadonly.value) { emit('update:selected-country', country); } displayValue.value = stripRegionCode(displayNumber, country); emitValidation(isValid); }, { immediate: true } ); if (props.value) { deprecate( 'BentoInputFieldPhoneNumber "value" property', `The use of "value" prop in "BentoInputFieldPhoneNumber" is no longer supported. Use the "v-model" or "model-value" property instead.`, '2.0.0' ); } </script> <script lang="ts"> /** * Input field phone number can be used to display phone numbers that come with a country code. * * @example * import { BentoInputFieldPhoneNumber } from '@adyen/bento-vue2'; * * export default { * components: { BentoInputFieldPhoneNumber }, * template: ` * <bento-input-field-phone-number * label="Phone number" * :countries="['NL', 'BE']" * model-value="0612345678" * selected-country="NL" * /> * ` * } */ export default { i18n: { messages }, model: { prop: 'modelValue' }, }; </script> <style lang="scss" scoped src="./input-field-phone-number.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <fieldset class="b-controls-group" :class="conditionalClasses" :form="form" :disabled="disabled"
|
|
1
|
+
<template> <fieldset class="b-controls-group" v-bind="attrs" :class="conditionalClasses" :form="form" :disabled="disabled"> <legend class="b-controls-group__label-container" :class="legendConditionalClasses"> <field-label v-if="label" class="b-controls-group__label" :label="label" :tooltip-text="tooltipText" :optional="optional" :required="required" /> <bento-typography v-if="description || hasSlot('description')" class="b-controls-group__description" el="span" > <slot name="description"> {{ description }} </slot> </bento-typography> </legend> <slot /> </fieldset> </template> <script setup lang="ts"> import { computed, useAttrs, useSlots } from 'vue'; import { BentoTypography } from '@/components/typography'; import { FieldLabel } from '@/components/internal/field-label'; import { deprecate } from '@/utils/ts/deprecate'; import { useHasSlot } from '@/composables'; const attrs = useAttrs(); const slots = useSlots(); const hasSlot = useHasSlot(slots); const props = defineProps({ /** * Descriptive supporting text visbile underneath the label. */ description: { type: String, default: null }, /** * The name of the component to cite when throwing a depreacte error. */ componentName: { type: String, required: true }, /** * Sets all child controls of the <fieldset> as disabled. */ disabled: { type: Boolean, default: false }, /** * The value of the id attribute of a <form> element the <fieldset> is to part of, even if it is not inside the form itself. */ form: { type: String, default: null }, /** * Shows/hides the group label. */ hideLabel: { type: Boolean, default: null }, /** * The name associated with the group. Required for accessibility purposes. * The label is shown when `hideLabel` is set to `true` or if `description` is passed */ label: { type: String, required: true }, /** * Indicates the field is optional. */ optional: { type: Boolean, default: false }, /** * Indicates the field is required. */ required: { type: Boolean, default: false }, /** * Tooltip message. */ tooltipText: { type: String, default: null }, }); const conditionalClasses = computed(() => ({ 'b-controls-group--disabled': props.disabled, })); const legendConditionalClasses = computed(() => { const isLabelAndDescriptionPresent = props.label && (props.description || hasSlot('description')); const shouldShowLabel = isLabelAndDescriptionPresent || props.hideLabel === false; return { 'b-controls-group__label-container--hidden': !shouldShowLabel, }; }); // eslint-disable-next-line eqeqeq -- Needs to show deprecate message when hideLabel is not set and no description available const hasNoPropsDefined = !(props.description || hasSlot('description')) && props.hideLabel == undefined; if (hasNoPropsDefined) { deprecate( `${props.componentName}: The property \`label\` will always be rendered by default.`, `After version 2.0.0, the label will be shown by default. To continue hiding the label set \`:hide-label="true"\`. Up until version 2.0.0, to display the label set \`hide-label="false"\`. \`label\` will always be rendered when \`description\` is passed alongside with \`label\``, `2.0.0` ); } </script> <script lang="ts"> /** * A controls group components should be used whenever it is necessary to group a set of controls (i.e. radio buttons or checkboxes) * This component conforms to the official WAI-ARIA guidelines for grouping controls: https://www.w3.org/WAI/tutorials/forms/grouping/ * * NOTE: This component should not be used by itself but more implemented by other exported components * @example * import { ControlsGroup, BentoCheckbox, BentoRadioButton } from '@adyen/bento-vue2/'; * * export default { * components: { ControlsGroup, BentoRadioButton }, * template: ` * <controls-group * label="Your group label" * description="Description" * > * <bento-radio-button * disabled * value="inputRadio" * > * Label text * </bento-radio-button> * <bento-radio-button * value="inputRadio" * > * Another label text * </bento-radio-button> * </controls-group> * ` * }; */ export default {}; </script> <style lang="scss" scoped src="./controls-group.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <label class="b-field-label" :class="conditionalClasses"> <bento-typography el="span" stronger> <template v-if="label">{{ label }}</template> <template v-else><slot></slot></template> </bento-typography> <bento-typography v-if="!!tooltipText" el="span" class="b-field-label__tooltip-wrapper"> <bento-info-icon :tooltip-text="tooltipText" class="b-field-label__tooltip" /> </bento-typography> <bento-typography v-if="required" class="b-field-label__requirement" el="span"
|
|
1
|
+
<template> <label class="b-field-label" :class="conditionalClasses"> <bento-typography el="span" stronger> <template v-if="label">{{ label }}</template> <template v-else><slot></slot></template> </bento-typography> <bento-typography v-if="!!tooltipText" el="span" class="b-field-label__tooltip-wrapper"> <bento-info-icon :tooltip-text="tooltipText" class="b-field-label__tooltip" /> </bento-typography> <bento-typography v-if="required" class="b-field-label__requirement" el="span">*</bento-typography> <bento-typography v-else-if="optional" class="b-field-label__requirement" el="span" >({{ t('optional') }})</bento-typography > </label> </template> <script setup lang="ts"> import { BentoInfoIcon } from '@/components/info-icon'; import { BentoTypography } from '@/components/typography'; import { useI18n } from '@/utils/ts/i18n'; import messages from './messages.json'; import { computed } from 'vue'; type MessageSchema = (typeof messages)['en-US']; const props = defineProps({ /** * Renders the dropdown with a condensed style. */ condensed: { type: Boolean, default: false }, /** * Field label */ label: { type: String, default: null, }, /** * Sets the field as optional */ optional: { type: Boolean, default: false, }, /** * Sets the field as required */ required: { type: Boolean, default: false, }, /** * Adds a info icon next to the label to display the passed tooltip message. */ tooltipText: { type: String, default: null, }, }); const { t } = useI18n<{ message: MessageSchema }>({ messages }); const conditionalClasses = computed(() => ({ 'b-field-label--condensed': props.condensed })); </script> <script lang="ts"> /** * Internal component to handle the labels for all field components * @example * import { FieldLabel } from '@/components/internal/field-label'; * * export default { * components: { FieldLabel }, * template: ` * <field-label label="Label" tooltip-text="Tooltip info" required /> * ` * } */ export default { i18n: { messages }, }; </script> <style lang="scss" scoped src="./field-label.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <input :id="id" ref="inputRef" :aria-checked="isChecked" :aria-label="ariaLabel" :aria-invalid="ariaInvalid" :aria-describedby="ariaDescribedby" :checked="isChecked" :disabled="disabled" :value="value" :name="name" type="radio" class="b-radio-
|
|
1
|
+
<template> <div class="b-radio-input"> <input :id="id" ref="inputRef" :aria-checked="isChecked" :aria-label="ariaLabel" :aria-invalid="ariaInvalid" :aria-describedby="ariaDescribedby" :checked="isChecked" :disabled="disabled" :value="value" :name="name" type="radio" class="b-radio-input__input" :class="conditionalClasses" role="radio" @click="onClick" @change="onChange" /> </div> </template> <script setup lang="ts"> import { computed, type ComputedRef, type PropType, ref, toRefs } from 'vue'; import { RadioInputStateClass, type RadioInputValue } from './radio-input.types'; import type { HTMLAttributes } from 'vue/types/jsx.d.ts'; const props = defineProps({ /** * The aria label associated to the input checkbox. */ ariaLabel: { type: String, default: '' }, /** * An additional string that serves as description for the input checkbox (useful if the component shows a description). */ ariaDescribedby: { type: String, default: '' }, /** * Disable the radio button (optional) */ disabled: { type: Boolean, default: false }, /** * Shows bento-radio-button in error state (optional) */ hasError: { type: Boolean, default: false }, /** * Sets the id of the radio input. Required for accessibility purposes */ id: { type: String, default: null }, /** * This property should not be used directly. * It will be used by v-model directive on radio component. */ modelValue: { type: [String, Number] as PropType<RadioInputValue>, default: null, }, /** * Sets the radio button to readonly (optional) */ readonly: { type: Boolean, default: false }, /** * Indicates the value of the input that will be returned when it's checked */ value: { type: [String, Number] as PropType<RadioInputValue>, required: true, }, /** * Sets the name of the radio input. * Used for differentiating radio groups or accessing input via form submission. */ name: { type: String, default: null }, }); const emit = defineEmits<{ /** * Emit that emits the input value */ (e: 'update:model-value', value: RadioInputValue): void; }>(); const { value } = toRefs(props); const inputRef = ref(null); const conditionalClasses = computed(() => ({ [`b-radio-input__input--${RadioInputStateClass.DISABLED}`]: props.disabled, [`b-radio-input__input--${RadioInputStateClass.ERROR}`]: props.hasError, [`b-radio-input__input--${RadioInputStateClass.READONLY}`]: props.readonly, })); const ariaInvalid = computed<HTMLAttributes['aria-invalid']>(() => props.hasError); const isChecked: ComputedRef<boolean> = computed(() => props.value === props.modelValue); const onChange = () => { if (!props.disabled && !props.readonly) { emit('update:model-value', props.value); } }; // readonly attr doesn't work with radio button, so we need to manually ignore the click instead const onClick = event => { if (props.readonly) { event.preventDefault(); } }; const focus = () => { inputRef.value.focus(); }; defineExpose({ focus, }); </script> <script lang="ts"> /** * Internal component that renders a radio input (without label) * * @example * import { RadioInput } from '@/internal/radio-input'; * * export default { * components: { BentoCheckboxInput }, * template: ` * <label for="checkbox-id">Your label</label> * <span id="description-id">Description</span> * <radio-input id="checkbox-id" aria=label="Your label" aria-describedby="description-id" /> * ` * } */ export default { name: 'radio-input', inheritAttrs: false, }; </script> <style lang="scss" scoped src="./radio-input.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <dialog-page class="b-modal-fullscreen-page" :page-id="pageId" :previous-page="previousPage" always-show-border> <template #header> <div class="b-modal-fullscreen-page__header"> <div class="b-modal-fullscreen-page__header-section b-modal-fullscreen-page__header-section--title"> <bento-typography v-if="title" el="h2" variant="title" class="b-modal-fullscreen-page__title" :title="title" >{{ title }}</bento-typography > </div> <div v-if="hasSlot('header')" class="b-modal-fullscreen-page__header-section b-modal-fullscreen-page__header-section--slot" > <slot name="header" /> </div> <div class="b-modal-fullscreen-page__header-section b-modal-fullscreen-page__header-section--actions"> <bento-typography v-if="contextualLabel" class="b-modal-fullscreen-page__contextual-label" el="span" :title="contextualLabel" >{{ contextualLabel }}</bento-typography > <bento-button-actions v-if="actions" class="b-modal-fullscreen-page__actions" :actions="actions" /> <div class="b-modal-fullscreen-page__separator"></div> </div> </div> </template> <template #content> <
|
|
1
|
+
<template> <dialog-page class="b-modal-fullscreen-page" :page-id="pageId" :previous-page="previousPage" always-show-border> <template #header> <div class="b-modal-fullscreen-page__header"> <div class="b-modal-fullscreen-page__header-section b-modal-fullscreen-page__header-section--title"> <bento-typography v-if="title" :id="computedTitleId" el="h2" variant="title" class="b-modal-fullscreen-page__title" :title="title" >{{ title }}</bento-typography > </div> <div v-if="hasSlot('header')" class="b-modal-fullscreen-page__header-section b-modal-fullscreen-page__header-section--slot" > <slot name="header" /> </div> <div class="b-modal-fullscreen-page__header-section b-modal-fullscreen-page__header-section--actions"> <bento-typography v-if="contextualLabel" class="b-modal-fullscreen-page__contextual-label" el="span" :title="contextualLabel" >{{ contextualLabel }}</bento-typography > <bento-button-actions v-if="actions" class="b-modal-fullscreen-page__actions" :actions="actions" /> <div class="b-modal-fullscreen-page__separator"></div> <div class="b-modal-fullscreen-page__close-button"> <bento-button variant="tertiary" :aria-label="t('close')" @click="handleClose"> <template #iconLeft><cross-icon :aria-hidden="true" /></template> </bento-button> </div> </div> </div> </template> <template #content> <slot /> </template> </dialog-page> </template> <script setup lang="ts"> import { inject, onMounted, type PropType, useSlots } from 'vue'; import { BentoButton, BentoButtonActions, type BentoButtonActionsList } from '@/components/button'; import { BentoTypography } from '@/components/typography'; import { DialogPage } from '@/internal'; import { useHasSlot } from '@/composables'; import { useI18n } from '@/utils/ts/i18n'; import { MODAL_FULLSCREEN_CLOSE_INJECTION_KEY, MODAL_FULLSCREEN_TITLE_ID_INJECTION_KEY, } from '@/components/modal-fullscreen/modal-fullscreen.keys'; import CrossIcon from '@adyen/ui-assets-icons-16/vue/cross'; import messages from './messages.json'; type MessageSchema = (typeof messages)['en-US']; const { t } = useI18n<{ message: MessageSchema }>({ messages }); const props = defineProps({ /** * List of actions that will be used to render the buttons. * First element in the list will be rendered as "primary". * All elements after the first will be rendered as "secondary". * * Each object in the list should have a `title`, an `event` and * (optional) a Vue `icon` from the library `@adyen/ui-assets-icons-16`. * * @see BentoButton for a list of all the other props supported by each button action. */ actions: { type: Array as PropType<BentoButtonActionsList>, default: null, }, /** * Label shown next to the modal actions */ contextualLabel: { type: String, default: null, }, /** * Identifier of the page, used with activePage prop to handle sidepanel navigation */ pageId: { type: String, default: undefined, }, /** * ID of the page for the back button to navigate to. Only use it to overwrite the default back behavior * Used when the back button should not take the user to the natural previous page * Set to `null` to hide back button in the page */ previousPage: { type: String, default: undefined, }, /** * Title of the modal */ title: { type: String, default: null, }, /** * ID to be applied to the title to be used with aria-labelledby */ titleId: { type: String, default: undefined, }, }); const emit = defineEmits<{ /** * Emits event when close button is clicked */ (e: 'close'); }>(); const slots = useSlots(); const hasSlot = useHasSlot(slots); const injectedTitleId = inject(MODAL_FULLSCREEN_TITLE_ID_INJECTION_KEY, undefined); const computedTitleId = props.titleId ?? injectedTitleId; const closeModal = inject(MODAL_FULLSCREEN_CLOSE_INJECTION_KEY, undefined); const handleClose = () => { emit('close'); closeModal?.(); }; onMounted(() => { if (props.actions && props.actions.length > 2) { throw new Error('Not more than 2 action buttons may be provided in Bento Modal Fullscreen'); } }); </script> <script lang="ts"> /** * ModalFullscreenPage is used to render different pages of ModalFullscreen component * * @example * import { BentoModalFullscreen, BentoModalFullscreenPage } from '@adyen/bento-vue2'; * * export default { * components: { BentoModalFullscreen, BentoModalFullscreenPage }, * template: ` * <bento-modal-fullscreen active-page='page1' is-open='true'> * <bento-modal-fullscreen-page * title='Page 1' * pageId='page1' * contextual-label='Move to next page' * :actions="[ * { * title: 'Next page', * event: () => { * activePage.value = 'page2'; * }, * }]"> * Page 1 info * </bento-modal-fullscreen-page> * <bento-modal-fullscreen-page * title='Page 2' * pageId='page2' * :actions="[ * { * title: 'Save', * event: () => {}, * }]"> * Page 2 info * </bento-modal-fullscreen-page> * </bento-modal-fullscreen> * ` * } */ export default { i18n: { messages }, }; </script> <style lang="scss" scoped src="./modal-fullscreen-page.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <dialog :id="modalFullscreenId" ref="modal" class="b-modal-fullscreen" :class="conditionalClasses" data-dialog-element="modal-fullscreen" @animationend="closeModalAfterAnimation" @keydown.esc.prevent="closeModal" > <bento-focus-trap v-if="internalIsOpen" class="b-modal-fullscreen__wrapper"> <template v-if="props.activePage"> <slot /> </template> <bento-modal-fullscreen-page v-else :actions="actions" :contextual-label="contextualLabel" :title="title"> <template v-if="hasSlot('default')" #default> <slot name="default"></slot> </template> <template v-if="hasSlot('header')" #header> <slot name="header"></slot> </template> </bento-modal-fullscreen-page>
|
|
1
|
+
<template> <dialog :id="modalFullscreenId" ref="modal" class="b-modal-fullscreen" :class="conditionalClasses" data-dialog-element="modal-fullscreen" :aria-labelledby="titleId" @animationend="closeModalAfterAnimation" @keydown.esc.prevent="closeModal" > <bento-focus-trap v-if="internalIsOpen" class="b-modal-fullscreen__wrapper"> <template v-if="props.activePage"> <slot /> </template> <bento-modal-fullscreen-page v-else :actions="actions" :contextual-label="contextualLabel" :title="title" :title-id="titleId" @close="closeModal" > <template v-if="hasSlot('default')" #default> <slot name="default"></slot> </template> <template v-if="hasSlot('header')" #header> <slot name="header"></slot> </template> </bento-modal-fullscreen-page> </bento-focus-trap> <!-- Enable the toast inside the fullscreen-modal --> <template v-if="isOpen"> <bento-toast /> </template> </dialog> </template> <script setup lang="ts"> import { computed, onMounted, onUnmounted, type PropType, provide, ref, toRefs, useSlots, watch } from 'vue'; import { isVue2 } from 'vue-demi'; import { BentoToast } from '@/components/toast'; import { type BentoButtonActionsList } from '@/components/button'; import { BentoFocusTrap } from '@/components/focus-trap'; import BentoModalFullscreenPage from './components/modal-fullscreen-page.vue'; import { generateUid } from '@/core/utils/ts'; import { useHasSlot } from '@/composables'; import { useListeners } from '@/composables/use-listeners'; import { MODAL_FULLSCREEN_CLOSE_INJECTION_KEY, MODAL_FULLSCREEN_DIALOG_ID_INJECTION_KEY, MODAL_FULLSCREEN_TITLE_ID_INJECTION_KEY, } from '@/components/modal-fullscreen/modal-fullscreen.keys'; import { BentoDialogPageAnimation, type BentoDialogPageConfigData, type BentoDialogPageRegisterPage, DIALOG_PAGE_CONFIG_INJECTION_KEY, DIALOG_PAGE_REGISTER_PAGE_INJECTION_KEY, } from '@/internal'; const props = defineProps({ /** * List of actions that will be used to render the buttons. * First element in the list will be rendered as "primary". * All elements after the first will be rendered as "secondary". * * Each object in the list should have a `title`, an `event` and * (optional) a Vue `icon` from the library `@adyen/ui-assets-icons-16`. * * @see BentoButton for a list of all the other props supported by each button action. */ actions: { type: Array as PropType<BentoButtonActionsList>, default: null, }, /** * The id of the current active page * Should be the same as the pageId of the BentoModalFullscreenPage to be displayed */ activePage: { type: String, default: null, }, /** * Label shown next to the modal actions */ contextualLabel: { type: String, default: null, }, /** * Controls the modal's state from the outside. Set it to true to open the modal */ isOpen: { type: Boolean, default: null, }, /** * Title of the modal */ title: { type: String, default: null, }, }); const emit = defineEmits<{ /** * Handles closing the modal. The behavior changes depending on whether a `before-close` event listener is present. * * - **When listening for the `before-close` event:** * The `before-close` event is emitted immediately, skipping the animation. This allows for logic to run before the modal closes. * The `isOpen` prop must then be set to `false` to trigger the closing animation. * * - **When not listening for the `before-close` event:** * The closing animation plays, then `update:is-open` is emitted with `false`. * This is the default behavior, compatible with `v-model` or `.sync` on the `isOpen` prop. */ (e: 'before-close'): void; /** * Emits update event when page is changed internally */ (e: 'update:active-page', page: string): void; /** * Emits 'update:is-open' event when the modal is closed */ (e: 'update:is-open', isOpen: boolean): void; }>(); // Refs const { activePage, isOpen } = toRefs(props); const modal = ref(null); const isClosing = ref(false); const modalFullscreenId = generateUid('modal-fullscreen'); const titleId = generateUid('modal-fullscreen-title'); const internalIsOpen = ref(false); const isMounted = ref(false); const listeners = useListeners(); const slots = useSlots(); const hasSlot = useHasSlot(slots); // Animation styling const conditionalClasses = computed(() => ({ 'b-modal-fullscreen--hide': isClosing.value, })); // Handle closing and closing animation for dialog element const closeModalAfterAnimation = () => { if (isClosing.value && modal.value) { modal.value.close(); if (previousPages.value[0]) { emit('update:active-page', previousPages.value[0]); } previousPages.value = []; isClosing.value = false; internalIsOpen.value = false; emit('update:is-open', false); } }; /** * Emits the `beforeClose` event, if it is being listened to, * before closing the modal and omits the closing animation. * The animation will be triggered by the change of the `isOpen` prop instead. * * If no listener for the `before-close`, then the animation will be triggered, * which will close the modal and emit the `update:is-open` event instead, after it was closed. */ function closeModal() { /** * Vue3 appends the prefix "on" and changes to camelCase */ const eventName = isVue2 ? 'before-close' : 'onBeforeClose'; if (listeners[eventName]) { emit('before-close'); return; } startCloseModalAnimation(); } const startCloseModalAnimation = () => { if (!modal.value || !modal.value.open) { return; } isClosing.value = true; }; onMounted(() => { isMounted.value = true; }); onUnmounted(() => { isMounted.value = false; }); // Watching isOpen prop to toggle open/close the dialog element watch( [() => isOpen.value, modal], ([newIsOpen, newModalValue]) => { if (!isMounted.value || !newModalValue) { return; } if (newIsOpen) { internalIsOpen.value = true; if (!newModalValue.open) { newModalValue.showModal(); } if (!previousPages.value.length) { previousPages.value.push(activePage.value); } } else if (newModalValue.open) { startCloseModalAnimation(); } }, { immediate: true, flush: 'post' } ); // lets children components know they are inside a Modal (dialog element) provide(MODAL_FULLSCREEN_DIALOG_ID_INJECTION_KEY, modalFullscreenId); provide(MODAL_FULLSCREEN_TITLE_ID_INJECTION_KEY, titleId); provide(MODAL_FULLSCREEN_CLOSE_INJECTION_KEY, closeModal); // Pages const animation = ref(BentoDialogPageAnimation.TRANSITION_LEVEL_DEEPER); const pages = ref<Array<string>>([]); const previousPages = ref([]); const updatePage = page => emit('update:active-page', page); provide<BentoDialogPageConfigData>(DIALOG_PAGE_CONFIG_INJECTION_KEY, { activePage, animation, isOpen: internalIsOpen, pages, previousPages, updatePage, }); // unregister page if removed / destroyed const unregisterPage = (pageIdToRemove: string) => () => { pages.value = pages.value?.filter(pageId => pageId !== pageIdToRemove); }; // Provide data and function to register page to subcomponent const registerPage: BentoDialogPageRegisterPage = pageId => { if (pageId) { pages.value.push(pageId); } return { unregisterPage: unregisterPage(pageId) }; }; provide(DIALOG_PAGE_REGISTER_PAGE_INJECTION_KEY, registerPage); </script> <script lang="ts"> /** * Fullscreen modal takes full available space (no content underneath is visible) and focuses the user's attention exclusively on one complex task or piece of complex information. * * @example * import { BentoModalFullscreen } from '@adyen/bento-vue2'; * * export default { * components: { BentoModalFullscreen }, * template: ` * <bento-modal-fullscreen * :is-open="isOpen" * @update:is-open="isOpen = $event" * title='Fullscreen modal title' * contextual-label='Contextual label' * :actions="[{ title: 'Action', event: () => {}]" * > * <template #header>{{ header slot }}</template> * {{ content }} * </bento-modal-fullscreen> * ` * } */ export default {}; </script> <style lang="scss" scoped src="./modal-fullscreen.scss" />
|
package/dist/assets/components/pagination/components/pagination-context/pagination-context.vue
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <div class="b-pagination-context"> <bento-typography v-if="totalPages > 1" el="div"> <component :is="i18nComponent" v-bind="getI18nProps('pageNumber')" tag="div"> <template #page> <bento-dropdown :id="dropdownId" :aria-label="t('pageNumber', { page: n(page) })" class="b-pagination-context__dropdown" condensed :items="listOfAvailablePages" :model-value="page" :virtual-scroll="virtualScroll" @update:model-value="onPageSelectChange" /> </template> </component> </bento-typography> <bento-typography v-else-if="
|
|
1
|
+
<template> <div class="b-pagination-context"> <bento-typography v-if="totalPages > 1 && !hidePageSelection" el="div"> <component :is="i18nComponent" v-bind="getI18nProps('pageNumber')" tag="div"> <template #page> <bento-dropdown :id="dropdownId" :aria-label="t('pageNumber', { page: n(page) })" class="b-pagination-context__dropdown" condensed :items="listOfAvailablePages" :model-value="page" :virtual-scroll="virtualScroll" @update:model-value="onPageSelectChange" /> </template> </component> </bento-typography> <bento-typography v-else-if="showPageNumberOfTotal" el="span"> {{ t('pageNumberOfTotal', { page: n(page), totalPages: n(totalPages) }) }} </bento-typography> <bento-typography v-else el="span"> {{ t('pageNumber', { page: n(page) }) }} </bento-typography> </div> </template> <script setup lang="ts"> import { computed } from 'vue'; import { BentoTypography } from '@/components/typography'; import { BentoDropdown } from '@/components/dropdown'; import { type BentoListboxOptionItem } from '@/types/listbox'; import { generateUid } from '@/core/utils/ts'; import messages from './messages.json'; import { getI18nComponent, getI18nProps, useI18n } from '@/utils/ts/i18n'; type MessageSchema = (typeof messages)['en-US']; const props = withDefaults( defineProps<{ /** * Hides the page selection dropdown and displays a static "Page X of Y" text instead. * Useful for very large datasets where rendering all page options would cause performance issues. */ hidePageSelection?: boolean; /** * The current page number of the pager. */ page?: number; /** * The total number of items the pager is paging through. */ totalPages?: number; /** * Enables virtual scrolling on all dropdowns if set to true. */ virtualScroll?: boolean; }>(), { hidePageSelection: false, page: 1, totalPages: null, virtualScroll: false, } ); const emit = defineEmits<{ (e: 'page-selected', value: string | number); }>(); const { t, n } = useI18n<{ message: MessageSchema }>({ messages }); const dropdownId = generateUid('bento-pagination-context-current-page'); const onPageSelectChange = (selectedPage: string | number) => emit('page-selected', selectedPage); const i18nComponent = getI18nComponent(); // Generate a list of pages from 1 to "totalPages" const transformIntoOption = (value: number): BentoListboxOptionItem => ({ label: n(value), value, }); const transformToPageNumber = (_, index) => index + 1; const listOfAvailablePages = computed(() => Array.from(new Array(props.totalPages), transformToPageNumber).map(transformIntoOption) ); const showPageNumberOfTotal = computed( () => props.totalPages === 1 || (props.hidePageSelection && props.page <= props.totalPages) ); </script> <script lang="ts"> export default { i18n: { messages }, }; </script> <style lang="scss" scoped src="./pagination-context.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <div class="b-pagination-results-per-page"> <bento-typography el="div"> <component :is="i18nComponent" v-bind="getI18nProps(translationPathKey)" class="b-pagination-results-per-page__dropdown-container" tag="div" :plural="totalCount" > <template #itemCount> <bento-dropdown :id="dropdownId" :aria-label="t(translationPathKey, { itemCount: itemsPerPage, totalCount })" class="b-pagination-results-per-page__dropdown" condensed :items="predefinedDropdownOptions" :model-value="itemsPerPage" @update:model-value="onSelectChange" /> </template> <template v-if="!!totalCount" #totalCount>{{ totalCount }}</template> </component> </bento-typography> </div> </template> <script setup lang="ts"> import { computed } from 'vue'; import { BentoTypography } from '@/components/typography'; import { BentoDropdown } from '@/components/dropdown'; import { generateUid } from '@/core/utils/ts'; import { getI18nComponent, getI18nProps, useI18n } from '@/utils/ts/i18n'; import messages from './messages.json'; type MessageSchema = (typeof messages)['en-US']; const { t, n } = useI18n<{ message: MessageSchema }>({ messages }); const props = withDefaults( defineProps<{ /** * The amount of items the pager is paging through. */ itemsPerPage?: number; /** * The total number of items the pager is paging through. */ totalCount?: number; }>(), { itemsPerPage: 50, totalCount: null, } ); const emit = defineEmits<{ (e: 'select', value: number); }>(); const
|
|
1
|
+
<template> <div class="b-pagination-results-per-page"> <bento-typography el="div"> <component :is="i18nComponent" v-bind="getI18nProps(translationPathKey)" class="b-pagination-results-per-page__dropdown-container" tag="div" :plural="totalCount" > <template v-if="hidePageSizeSelection" #itemCount>{{ itemsPerPage }}</template> <template v-else #itemCount> <bento-dropdown :id="dropdownId" :aria-label="t(translationPathKey, { itemCount: itemsPerPage, totalCount })" class="b-pagination-results-per-page__dropdown" condensed :items="predefinedDropdownOptions" :model-value="itemsPerPage" @update:model-value="onSelectChange" /> </template> <template v-if="!!totalCount" #totalCount>{{ totalCount }}</template> </component> </bento-typography> </div> </template> <script setup lang="ts"> import { computed, watch } from 'vue'; import { BentoTypography } from '@/components/typography'; import { BentoDropdown } from '@/components/dropdown'; import { generateUid } from '@/core/utils/ts'; import { getI18nComponent, getI18nProps, useI18n } from '@/utils/ts/i18n'; import { printDevelopmentWarning } from '@/utils/ts/print-development-warning'; import messages from './messages.json'; type MessageSchema = (typeof messages)['en-US']; const { t, n } = useI18n<{ message: MessageSchema }>({ messages }); const props = withDefaults( defineProps<{ /** * Determines whether to hide the dropdown that allows users to change the number of results per page. * When set to `true`, the current `itemsPerPage` value is displayed as plain static text. */ hidePageSizeSelection?: boolean; /** * The amount of items the pager is paging through. */ itemsPerPage?: number; /** * The total number of items the pager is paging through. */ totalCount?: number; /** * The predefined options for the results per page dropdown. */ pageSizeItems?: Array<number>; }>(), { hidePageSizeSelection: false, itemsPerPage: 50, totalCount: null, pageSizeItems: () => [10, 20, 50, 75, 100], } ); const emit = defineEmits<{ (e: 'select', value: number); }>(); const isValid = computed( () => Array.isArray(props.pageSizeItems) && props.pageSizeItems.every(option => Number.isInteger(option)) ); watch( isValid, valid => { if (!valid) { printDevelopmentWarning('BentoPagination: pageSizeItems must be an array of integers.'); } }, { immediate: true } ); const dropdownId = generateUid('b-pagination-context-number-elements'); const predefinedDropdownOptions = computed(() => props.pageSizeItems.map(option => ({ label: n(option), value: option, })) ); const i18nComponent = getI18nComponent(); const onSelectChange = (selectedNumberOfResults: number) => { emit('select', selectedNumberOfResults); }; const translationPathKey = computed(() => (props.totalCount ? 'showingItemsWithTotal' : 'showingItems')); </script> <script lang="ts"> export default { i18n: { messages }, }; </script> <style lang="scss" scoped src="./pagination-results-per-page.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <div class="b-pagination"> <nav :aria-label="computedAriaLabel" class="b-pagination__navigation" :class="navigationConditionalClasses()"> <bento-pagination-results-per-page v-if="!hidePageSize" class="b-pagination__results-per-page" :items-per-page="size" :total-count="totalCount" @select="onItemsPerPageChange" /> <bento-typography v-else-if="hasSlot('default')"><slot /></bento-typography> <div class="b-pagination__page-navigator"> <bento-pagination-context class="b-pagination__context" :total-pages="totalPages" :page="page" :
|
|
1
|
+
<template> <div class="b-pagination"> <nav :aria-label="computedAriaLabel" class="b-pagination__navigation" :class="navigationConditionalClasses()"> <bento-pagination-results-per-page v-if="!hidePageSize" class="b-pagination__results-per-page" :hide-page-size-selection="hidePageSizeSelection" :items-per-page="size" :total-count="totalCount" :page-size-items="pageSizeItems" @select="onItemsPerPageChange" /> <bento-typography v-else-if="hasSlot('default')"><slot /></bento-typography> <div class="b-pagination__page-navigator"> <bento-pagination-context class="b-pagination__context" :total-pages="totalPages" :page="page" :virtual-scroll="virtualScroll" :hide-page-selection="hidePageSelection" @page-selected="onPageSelected" /> <div class="b-pagination__divider"></div> <bento-pagination-controls class="b-pagination__controls" :has-next="hasNext" :page="page" :total-pages="totalPages" @navigate="navigate" /> </div> </nav> </div> </template> <script setup lang="ts"> import { computed, ref, toRefs, useAttrs, useSlots } from 'vue'; import { BentoTypography } from '@/components/typography'; import BentoPaginationResultsPerPage from './components/pagination-results-per-page/pagination-results-per-page.vue'; import BentoPaginationContext from './components/pagination-context/pagination-context.vue'; import BentoPaginationControls from './components/pagination-controls/pagination-controls.vue'; import { useAriaLabel } from '@/utils/ts/aria-label'; import { useHasSlot } from '@/composables'; import type { BentoPaginationProps } from './pagination.types'; const props = withDefaults(defineProps<BentoPaginationProps>(), { ariaLabel: null, hasNext: null, hidePageSize: false, hidePageSelection: false, hidePageSizeSelection: false, page: 1, pageSizeItems: undefined, size: 20, totalCount: null, virtualScroll: false, }); const emit = defineEmits<{ /** * Triggered when the navigation controls are clicked or the items per page is changed (i.e. when the arrow buttons to the * rightmost of the screen or either dropdown is updated). It indicates to which page it should go next and also the page size. */ (e: 'navigate', page: number, items?: number): void; /** * Triggered when the number of items per page is changed from the left hand dropdown. * It indicates the new number of items that will be displayed. */ (e: 'items-page', size: number): void; /** * Triggered when the navigation controls are clicked, whether the arrow buttons to the * right most of the screen or the dropdown on the right hand is updated. * It indicates to which page it should go next * (easily achieved using the [sync modifier](https://v2.vuejs.org/v2/guide/components-custom-events.html#sync-Modifier)) * e.g. `:page.sync="currentPage"` */ (e: 'update:page', page: number): void; /** * Triggered when the number of items per page is changed from the left hand dropdown. * It indicates the new number of items that will be displayed. * (easily achieved using the [sync modifier](https://v2.vuejs.org/v2/guide/components-custom-events.html#sync-Modifier)) * e.g. `:size.sync="itemsPerPage"` */ (e: 'update:size', size: number): void; }>(); const slots = useSlots(); const hasSlot = useHasSlot(slots); const attrs = useAttrs(); const ariaLabelAttribute = ref(attrs['aria-label']); const { ariaLabel } = toRefs(props); const computedAriaLabel = useAriaLabel({ ariaLabel: ariaLabelAttribute.value as string, // TODO: take this line away when the aria-label props is removed label: ariaLabel, }); const totalPages = computed(() => !props.totalCount || !props.size ? null : Math.ceil(props.totalCount / props.size) ); const navigate = (pageArg: number, itemsPerPage?: number) => { if (props.hidePageSize) { emit('navigate', pageArg); } else { emit('navigate', pageArg, itemsPerPage ?? props?.size); } emit('update:page', pageArg); }; const onPageSelected = (pageNumber: number) => { navigate(pageNumber); }; const onItemsPerPageChange = (elements: number) => { emit('items-page', elements); emit('update:size', elements); // Always go to first page when the // number of items page changes navigate(1, elements); }; const navigationConditionalClasses = () => ({ 'b-pagination__navigation--only-page-navigator': !hasSlot('default') && props.hidePageSize, }); </script> <script lang="ts"> /** * Paginiation component to help users page through data sets. * * There are two ways of doing navigation in this component: * 1. (Basic) You tell the component if there is a next page (hasNext) * 2. (Enhanced) You tell the component: * - How many total items exist (totalCount) * - The max number of items that you show/fetch per page (size) * - In this case you should not set the hasNext props * * If you have the data available and opt to use the Enhanced way you get extra controls: * - Page dropdown selector * - Last page button * - "Showing 10 of 200 items" text * * @usage * import { BentoPagination } from '@adyen/bento-vue2'; * * export default { * components: { BentoPagination }, * template: ` * <bento-pagination :has-next="isNextPage" /> * `, * } */ export default {}; </script> <style lang="scss" scoped src="./pagination.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <div class="b-radio-group"> <controls-group class="b-radio-group__buttons" :aria-describedby="shouldShowErrorMessage ? errorId : ''" :component-name="COMPONENT_NAME" :class="conditionalClasses" :description="description" :disabled="disabled" :form="formId" :label="label" :optional="optional" :required="required" :hide-label="hideLabel" :tooltip-text="tooltipText" role="radiogroup" :aria-readonly="isReadOnly" > <bento-radio-button v-for="item in items" ref="radioButton" :key="item.value" :model-value="inputValue" :value="item.value" :disabled="disabled || item.disabled" :readonly="isReadOnly || item.readonly" :has-error="shouldShowError || item.hasError" :tag="item.tag" :name="formId || label" @update:model-value="onUpdateModelValue" > <template #default>{{ item.label }}</template> <template v-if="item.description" #description>{{ item.description }}</template> <template v-if="hasSlot('content') && isVertical" #content> <slot name="content"></slot> </template> </bento-radio-button> <template v-if="hasSlot('description')" #description> <slot name="description" /> </template> </controls-group> <error-message v-if="shouldShowErrorMessage" :id="errorId" :error-message="errorMessage" class="b-radio-group__error-message" /> </div> </template> <script setup lang="ts"> import { computed, ref, toRef, useSlots, watch } from 'vue'; import { ControlsGroup, ErrorMessage } from '@/components/internal'; import { BentoRadioButton } from './components/radio-button'; import { useHasSlot } from '@/composables'; import { generateUid } from '@/core/utils/ts'; import { deprecate } from '@/utils/ts/deprecate'; import { useFormFieldEmits } from '@/utils/ts/form-field/form-field'; import { type BentoRadioGroupEmits, type BentoRadioGroupProps, BentoRadioGroupVariant } from './radio-group.types'; import { useFormLayoutFieldLoading } from '@/composables/use-form-layout-loading/use-form-layout-loading'; /** * The name of the component to be used in the Vue devtools and console warnings. */ const COMPONENT_NAME = 'bento-radio-group'; const slots = useSlots(); const hasSlot = useHasSlot(slots); const emit = defineEmits<BentoRadioGroupEmits>(); const props = withDefaults(defineProps<BentoRadioGroupProps>(), { description: null, disabled: false, errorMessage: null, formId: null, hasError: false, hideLabel: null, modelValue: null, optional: false, readonly: false, required: false, tooltipText: null, variant: BentoRadioGroupVariant.VERTICAL, }); const inputValue = toRef(props, 'modelValue'); const errorId = generateUid('error'); const { isReadOnly } = useFormLayoutFieldLoading(toRef(props, 'readonly')); const { emitValue } = useFormFieldEmits(emit); const radioButton = ref(null); const shouldShowError = computed( () => !props.disabled && !isReadOnly.value && (!!props.errorMessage || props.hasError) ); const shouldShowErrorMessage = computed(() => !props.disabled && !isReadOnly.value && !!props.errorMessage); const conditionalClasses = computed(() => ({ 'b-radio-group__buttons--horizontal': props.variant === BentoRadioGroupVariant.HORIZONTAL, })); // Content slot logic const isVertical = computed(() => props.variant === 'vertical'); const shouldShowSlotError = computed(() => hasSlot('content') && !isVertical?.value); const onUpdateModelValue = value => { emitValue(value); }; if (props.hasError) { deprecate( 'BentoRadioGroup "hasError" property', `Use the BentoRadioGroup "errorMessage" property instead to indicate that there is a modifier error. Having the field as "undefined" will hide/remove the error. <bento-radio-group errorMessage="Error message text" />`, '2.0.0' ); } watch( shouldShowSlotError, newVal => { if (newVal) { throw new Error('The content slot is only available for the vertical radio group layout'); } }, { immediate: true, } ); const focus = () => { radioButton.value[0].focus(); }; defineExpose({ focus, }); </script> <script lang="ts"> /** * A radio group component should be used whenever it is necessary to use a set of radio buttons * This component conforms to the official WAI-ARIA guidelines for grouping controls: https://www.w3.org/WAI/tutorials/forms/grouping/ * * import { BentoRadioGroup } from '@adyen/bento-vue2/'; * * export default { * components: { BentoRadioGroup }, * template: ` * <bento-radio-group * label="Your group label" * :items="[ * { value: 1, label: 'Your label' }, * { value: 2, label: 'Another label', description: 'Your descriptive sub label' }, * ]" * variant="horizontal" * /> * ` * }; */ export default { name: 'bento-radio-group', model: { prop: 'modelValue' }, }; </script> <style lang="scss" scoped src="./radio-group.scss" />
|
|
1
|
+
<template> <div class="b-radio-group"> <controls-group class="b-radio-group__buttons" :aria-describedby="shouldShowErrorMessage ? errorId : ''" :aria-required="required" :component-name="COMPONENT_NAME" :class="conditionalClasses" :description="description" :disabled="disabled" :form="formId" :label="label" :optional="optional" :required="required" :hide-label="hideLabel" :tooltip-text="tooltipText" role="radiogroup" :aria-readonly="isReadOnly" > <bento-radio-button v-for="item in items" ref="radioButton" :key="item.value" :model-value="inputValue" :value="item.value" :disabled="disabled || item.disabled" :readonly="isReadOnly || item.readonly" :has-error="shouldShowError || item.hasError" :tag="item.tag" :name="formId || label" @update:model-value="onUpdateModelValue" > <template #default>{{ item.label }}</template> <template v-if="item.description" #description>{{ item.description }}</template> <template v-if="hasSlot('content') && isVertical" #content> <slot name="content"></slot> </template> </bento-radio-button> <template v-if="hasSlot('description')" #description> <slot name="description" /> </template> </controls-group> <error-message v-if="shouldShowErrorMessage" :id="errorId" :error-message="errorMessage" class="b-radio-group__error-message" /> </div> </template> <script setup lang="ts"> import { computed, ref, toRef, useSlots, watch } from 'vue'; import { ControlsGroup, ErrorMessage } from '@/components/internal'; import { BentoRadioButton } from './components/radio-button'; import { useHasSlot } from '@/composables'; import { generateUid } from '@/core/utils/ts'; import { deprecate } from '@/utils/ts/deprecate'; import { useFormFieldEmits } from '@/utils/ts/form-field/form-field'; import { type BentoRadioGroupEmits, type BentoRadioGroupProps, BentoRadioGroupVariant } from './radio-group.types'; import { useFormLayoutFieldLoading } from '@/composables/use-form-layout-loading/use-form-layout-loading'; /** * The name of the component to be used in the Vue devtools and console warnings. */ const COMPONENT_NAME = 'bento-radio-group'; const slots = useSlots(); const hasSlot = useHasSlot(slots); const emit = defineEmits<BentoRadioGroupEmits>(); const props = withDefaults(defineProps<BentoRadioGroupProps>(), { description: null, disabled: false, errorMessage: null, formId: null, hasError: false, hideLabel: null, modelValue: null, optional: false, readonly: false, required: false, tooltipText: null, variant: BentoRadioGroupVariant.VERTICAL, }); const inputValue = toRef(props, 'modelValue'); const errorId = generateUid('error'); const { isReadOnly } = useFormLayoutFieldLoading(toRef(props, 'readonly')); const { emitValue } = useFormFieldEmits(emit); const radioButton = ref(null); const shouldShowError = computed( () => !props.disabled && !isReadOnly.value && (!!props.errorMessage || props.hasError) ); const shouldShowErrorMessage = computed(() => !props.disabled && !isReadOnly.value && !!props.errorMessage); const conditionalClasses = computed(() => ({ 'b-radio-group__buttons--horizontal': props.variant === BentoRadioGroupVariant.HORIZONTAL, })); // Content slot logic const isVertical = computed(() => props.variant === 'vertical'); const shouldShowSlotError = computed(() => hasSlot('content') && !isVertical?.value); const onUpdateModelValue = value => { emitValue(value); }; if (props.hasError) { deprecate( 'BentoRadioGroup "hasError" property', `Use the BentoRadioGroup "errorMessage" property instead to indicate that there is a modifier error. Having the field as "undefined" will hide/remove the error. <bento-radio-group errorMessage="Error message text" />`, '2.0.0' ); } watch( shouldShowSlotError, newVal => { if (newVal) { throw new Error('The content slot is only available for the vertical radio group layout'); } }, { immediate: true, } ); const focus = () => { radioButton.value[0].focus(); }; defineExpose({ focus, }); </script> <script lang="ts"> /** * A radio group component should be used whenever it is necessary to use a set of radio buttons * This component conforms to the official WAI-ARIA guidelines for grouping controls: https://www.w3.org/WAI/tutorials/forms/grouping/ * * import { BentoRadioGroup } from '@adyen/bento-vue2/'; * * export default { * components: { BentoRadioGroup }, * template: ` * <bento-radio-group * label="Your group label" * :items="[ * { value: 1, label: 'Your label' }, * { value: 2, label: 'Another label', description: 'Your descriptive sub label' }, * ]" * variant="horizontal" * /> * ` * }; */ export default { name: 'bento-radio-group', model: { prop: 'modelValue' }, }; </script> <style lang="scss" scoped src="./radio-group.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <bento-typography el="div" class="b-rich-text-editor" rich-text> <field-label v-if="!hideLabel" :label="label" :tooltip-text="tooltipText" :required="required" /> <div v-bind="attrs" class="b-rich-text-editor__container" data-testid="rich-text-editor-container" :aria-disabled="disabled" :class="conditionalClasses" > <div class="b-rich-text-editor__toolbar"> <bento-segmented-control v-model="selectedMode" :items="richTextEditorModeOptions" /> </div> <keep-alive> <rich-text-editor-content-area v-if="selectedMode === 'markdown'" :value="internalValue" role="textbox" aria-multiline="true" :disabled="disabled" :aria-label="computedAriaLabel" :aria-describedby="ariaDescribedBy" @input="onInput" /> <bento-alert v-else-if="error" type="critical"> <template #default> {{ t('errorProcessingMarkdown', { value: error }) }} </template> </bento-alert> <rich-text-editor-renderer v-else :node="node" class="b-rich-text-editor__renderer" :class="rendererConditionalClasses" /> </keep-alive> </div> <error-message v-if="!!errorMessage" :id="errorId" :error-message="errorMessage" class="b-rich-text-editor__error-message" /> <span v-if="description" :id="descriptionId" class="b-rich-text-editor__description"> <bento-typography el="span" variant="body">{{ description }}</bento-typography> </span> </bento-typography> </template> <script setup lang="ts"> import { computed, ref, useAttrs, watch } from 'vue'; import type { Root } from 'mdast'; // Components import BentoTypography from '@/components/typography/typography.vue'; import BentoSegmentedControl from '@/components/segmented-control/segmented-control.vue'; import BentoAlert from '@/components/alert/alert.vue'; import { ErrorMessage, FieldLabel } from '@/internal'; import RichTextEditorContentArea from './components/rich-text-editor-content-area/rich-text-editor-content-area.vue'; import RichTextEditorRenderer from './components/rich-text-editor-renderer/rich-text-editor-renderer'; import type { BentoRichTextEditorMode, BentoRichTextEditorProps } from './rich-text-editor.types'; // Utils import { useI18n } from '@/utils/ts/i18n'; import { useAriaLabel } from '@/utils/ts/aria-label'; import { generateUid } from '@/core/utils/ts'; import { parseMarkdown } from './utils'; import messages from './messages.json'; type MessageSchema = (typeof messages)['en-US']; const { t } = useI18n<{ message: MessageSchema }>({ messages }); const errorId = generateUid('rich-text-editor-error'); const descriptionId = generateUid('rich-text-editor-description'); const attrs = useAttrs(); const props = withDefaults(defineProps<BentoRichTextEditorProps>(), { description: null, disabled: false, errorMessage: null, hideLabel: null, label: null, mode: 'markdown', required: false, tooltipText: null, value: null, }); const emit = defineEmits<{ /** * Emmited when the content of the editor changes */ (e: 'input', value: string): void; }>(); const selectedMode = ref<BentoRichTextEditorMode>(props.mode); const internalValue = ref(props.value); const node = ref<Root>(null); const error = ref<Error>(null); const richTextEditorModeOptions = computed< Array<{ label: string; value: BentoRichTextEditorMode; disabled: boolean; }> >(() => [ { label: t('visual'), value: 'visual', disabled: props.disabled, }, { label: t('markdown'), value: 'markdown', disabled: props.disabled, }, ]); const conditionalClasses = computed(() => ({ 'b-rich-text-editor__container--disabled': props.disabled, 'b-rich-text-editor__container--error': props.errorMessage, })); const rendererConditionalClasses = computed(() => ({ 'b-rich-text-editor__renderer--disabled': props.disabled, })); // ARIA const computedAriaLabelFallbackMessage = computed(() => t('ariaLabelFallback')); const ariaLabelAttribute = ref(attrs['aria-label']); const computedAriaLabel = useAriaLabel({ ariaLabel: ariaLabelAttribute.value as string, defaultFallback: computedAriaLabelFallbackMessage, }); const ariaDescribedBy = computed( () => `${props.description ? descriptionId : ''} ${props.errorMessage ? errorId : ''}`.trim() || null ); /** * Turns internal value into an AST Node */ function updateNodeValue() { try { node.value = parseMarkdown(internalValue.value); error.value = null; } catch (e) { node.value = null; error.value = e.message.split(':')[1]; } } const onInput = (newContentValue: string) => { internalValue.value = newContentValue; }; watch(internalValue, (newValue: string) => { node.value = null; // Invalidate previously parsed node emit('input', newValue); }); watch( selectedMode, newVal => { if (newVal === 'visual' && !node.value) { updateNodeValue(); } }, { immediate: true } ); </script> <script lang="ts"> /** * An editable content area with additional functionality * that allows to change text styling and add links and tables. * * @example * import { BentoRichTextEditor } from '@adyen/bento-vue2'; * * export default { * components: { BentoRichTextEditor }, * template: ` * <bento-rich-text-editor * v-model="value" * :label="label" * :description="description" * :disabled="false" * /> * ` * } */ export default { i18n: { messages }, }; </script> <style lang="scss" scoped src="./rich-text-editor.scss" />
|
|
1
|
+
<template> <bento-typography el="div" class="b-rich-text-editor" rich-text> <field-label v-if="!hideLabel" :label="label" :tooltip-text="tooltipText" :required="required" /> <div v-bind="attrs" class="b-rich-text-editor__container" data-testid="rich-text-editor-container" :aria-disabled="disabled" :class="conditionalClasses" > <div class="b-rich-text-editor__toolbar"> <bento-segmented-control v-model="selectedMode" :items="richTextEditorModeOptions" /> </div> <keep-alive> <rich-text-editor-content-area v-if="selectedMode === 'markdown'" :value="internalValue" role="textbox" aria-multiline="true" :disabled="disabled" :aria-label="computedAriaLabel" :aria-describedby="ariaDescribedBy" :aria-required="required" @input="onInput" /> <bento-alert v-else-if="error" type="critical"> <template #default> {{ t('errorProcessingMarkdown', { value: error }) }} </template> </bento-alert> <rich-text-editor-renderer v-else :node="node" class="b-rich-text-editor__renderer" :class="rendererConditionalClasses" /> </keep-alive> </div> <error-message v-if="!!errorMessage" :id="errorId" :error-message="errorMessage" class="b-rich-text-editor__error-message" /> <span v-if="description" :id="descriptionId" class="b-rich-text-editor__description"> <bento-typography el="span" variant="body">{{ description }}</bento-typography> </span> </bento-typography> </template> <script setup lang="ts"> import { computed, ref, useAttrs, watch } from 'vue'; import type { Root } from 'mdast'; // Components import BentoTypography from '@/components/typography/typography.vue'; import BentoSegmentedControl from '@/components/segmented-control/segmented-control.vue'; import BentoAlert from '@/components/alert/alert.vue'; import { ErrorMessage, FieldLabel } from '@/internal'; import RichTextEditorContentArea from './components/rich-text-editor-content-area/rich-text-editor-content-area.vue'; import RichTextEditorRenderer from './components/rich-text-editor-renderer/rich-text-editor-renderer'; import type { BentoRichTextEditorMode, BentoRichTextEditorProps } from './rich-text-editor.types'; // Utils import { useI18n } from '@/utils/ts/i18n'; import { useAriaLabel } from '@/utils/ts/aria-label'; import { generateUid } from '@/core/utils/ts'; import { parseMarkdown } from './utils'; import messages from './messages.json'; type MessageSchema = (typeof messages)['en-US']; const { t } = useI18n<{ message: MessageSchema }>({ messages }); const errorId = generateUid('rich-text-editor-error'); const descriptionId = generateUid('rich-text-editor-description'); const attrs = useAttrs(); const props = withDefaults(defineProps<BentoRichTextEditorProps>(), { description: null, disabled: false, errorMessage: null, hideLabel: null, label: null, mode: 'markdown', required: false, tooltipText: null, value: null, }); const emit = defineEmits<{ /** * Emmited when the content of the editor changes */ (e: 'input', value: string): void; }>(); const selectedMode = ref<BentoRichTextEditorMode>(props.mode); const internalValue = ref(props.value); const node = ref<Root>(null); const error = ref<Error>(null); const richTextEditorModeOptions = computed< Array<{ label: string; value: BentoRichTextEditorMode; disabled: boolean; }> >(() => [ { label: t('visual'), value: 'visual', disabled: props.disabled, }, { label: t('markdown'), value: 'markdown', disabled: props.disabled, }, ]); const conditionalClasses = computed(() => ({ 'b-rich-text-editor__container--disabled': props.disabled, 'b-rich-text-editor__container--error': props.errorMessage, })); const rendererConditionalClasses = computed(() => ({ 'b-rich-text-editor__renderer--disabled': props.disabled, })); // ARIA const computedAriaLabelFallbackMessage = computed(() => t('ariaLabelFallback')); const ariaLabelAttribute = ref(attrs['aria-label']); const computedAriaLabel = useAriaLabel({ ariaLabel: ariaLabelAttribute.value as string, defaultFallback: computedAriaLabelFallbackMessage, }); const ariaDescribedBy = computed( () => `${props.description ? descriptionId : ''} ${props.errorMessage ? errorId : ''}`.trim() || null ); /** * Turns internal value into an AST Node */ function updateNodeValue() { try { node.value = parseMarkdown(internalValue.value); error.value = null; } catch (e) { node.value = null; error.value = e.message.split(':')[1]; } } const onInput = (newContentValue: string) => { internalValue.value = newContentValue; }; watch(internalValue, (newValue: string) => { node.value = null; // Invalidate previously parsed node emit('input', newValue); }); watch( selectedMode, newVal => { if (newVal === 'visual' && !node.value) { updateNodeValue(); } }, { immediate: true } ); </script> <script lang="ts"> /** * An editable content area with additional functionality * that allows to change text styling and add links and tables. * * @example * import { BentoRichTextEditor } from '@adyen/bento-vue2'; * * export default { * components: { BentoRichTextEditor }, * template: ` * <bento-rich-text-editor * v-model="value" * :label="label" * :description="description" * :disabled="false" * /> * ` * } */ export default { i18n: { messages }, }; </script> <style lang="scss" scoped src="./rich-text-editor.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <controls-group ref="containerRef" :aria-describedby="shouldShowGroupError ? errorMessageId : null" :label="label" :hide-label="hideLabel" :description="description" :disabled="disabled" :tooltip-text="tooltipText" :readonly="readonly" :required="required" :optional="optional" class="b-selection-card-group" component-name="selection-card-group" > <div v-if="!itemsPerRow || layout === 'vertical'" class="b-selection-card-group__items" :class="conditionalItemsClasses" > <bento-selection-card v-for="item in items" :key="`selection-card-${item.value}`" class="b-selection-card-group__item" v-bind="item" :model-value="inputValue" :readonly="readonly || item.readonly" :has-error="shouldShowGroupError" :disabled="disabled || item.disabled" @update:model-value="onInput" > <template v-if="hasSlot('icon') && item.icon" #icon> <slot name="icon" v-bind="item"></slot> </template> <template v-if="hasSlot('content') && item.content" #content> <slot name="content" v-bind="item"></slot> </template> <template v-if="hasSlot('dynamicContent') && item.dynamicContent" #dynamicContent> <slot name="dynamicContent" v-bind="item"></slot> </template> </bento-selection-card> </div> <template v-else> <div :key="`selection-card-group-layout-breakpoint-${currentBreakpoint}`"> <grid-layout v-for="(row, rowIndex) in computedRows" :key="`selection-card-group-row-${rowIndex}-cols-${computedItemsPerRow}`" class="b-selection-card-group__items--wrap" :column-width="computedColumnWidth" > <template v-for="(item, columnIndex) in row" #[`col-${columnIndex+1}`]> <bento-selection-card :key="`selection-card-${item.value}`" class="b-selection-card-group__item b-selection-card-group__item--full-height" v-bind="item" :model-value="inputValue" :readonly="readonly || item.readonly" :has-error="shouldShowGroupError" :disabled="disabled || item.disabled" @update:model-value="onInput" > <template v-if="hasSlot('icon') && item.icon" #icon> <slot name="icon" v-bind="item"></slot> </template> <template v-if="hasSlot('content') && item.content" #content> <slot name="content" v-bind="item"></slot> </template> <template v-if="hasSlot('dynamicContent') && item.dynamicContent" #dynamicContent> <slot name="dynamicContent" v-bind="item"></slot> </template> </bento-selection-card> </template> </grid-layout> </div> </template> <error-message v-if="shouldShowGroupError" :id="errorMessageId" :error-message="errorMessage" class="b-selection-card-group__error-message" /> </controls-group> </template> <script setup lang="ts"> import { computed, onMounted, provide, ref, useSlots, watch } from 'vue'; import { useElementSize } from '@vueuse/core'; import { BMediaQueryMMax, BMediaQuerySMax } from '@adyen/bento-design-tokens/dist/js/bento/es6'; import { type BentoSelectionCardGroupEmits, type BentoSelectionCardGroupProps } from './selection-card-group.types'; import BentoSelectionCard from '../../selection-card.vue'; import { ControlsGroup, ErrorMessage, GridLayout } from '../../../internal'; import { SELECTION_CARD_RADIO_INPUT_INJECTION_KEY } from '../../selection-card.keys'; import { generateUid } from '@/core/utils/ts'; import { useFormFieldEmits } from '@/utils/ts/form-field/form-field'; const props = withDefaults(defineProps<BentoSelectionCardGroupProps>(), { description: null, disabled: false, errorMessage: null, formId: null, hideLabel: null, label: null, layout: 'vertical', itemsPerRow: undefined, modelValue: null, optional: false, required: false, tooltipText: null, readonly: false, variant: 'checkbox', }); const emit = defineEmits<BentoSelectionCardGroupEmits>(); const { emitValue } = useFormFieldEmits(emit); const slots = useSlots(); // Slots logic // Temporary, use-has-slots composable doesn't currently work for vue3 named scoped slots // We do the same in bento-checkbox-group const hasSlot = name => !!slots[name]; const conditionalItemsClasses = computed(() => ({ 'b-selection-card-group__items--horizontal': props.layout === 'horizontal', })); const inputValue = ref(props.modelValue); watch( () => props.modelValue, () => { inputValue.value = props.modelValue; } ); // Error message logic const errorMessageId = generateUid('error'); const shouldShowGroupError = computed(() => !props.disabled && !props.readonly && !!props.errorMessage); // itemsPerRow logic const containerRef = ref<HTMLElement | null>(null); const { width } = useElementSize(containerRef); const smallBreakpoint = computed(() => BMediaQuerySMax.split('px')[0]); const mediumBreakpoint = computed(() => BMediaQueryMMax.split('px')[0]); const currentBreakpoint = computed(() => { if (width.value < smallBreakpoint.value) { return 'small'; } if (width.value >= smallBreakpoint.value && width.value < mediumBreakpoint.value) { return 'medium'; } return 'large'; }); const computedItemsPerRow = computed(() => { return (props.itemsPerRow?.[currentBreakpoint?.value] as number) || props.items.length; }); const computedRows = computed(() => { if (!props.itemsPerRow) { return []; } const rows = []; for (let i = 0; i < props.items.length; i += computedItemsPerRow?.value) { rows.push(props.items.slice(i, i + computedItemsPerRow?.value)); } return rows; }); // We need to compute the column width on 12 because we're using a 12-column system for out grid-layout logic const itemColumnWidth = computed(() => 12 / computedItemsPerRow?.value); /** * Filling the columnWidth array with the same parameters per item to pass * to the `grid-layout` layout so the each card can have * the same width according to the screen size. */ const computedColumnWidth = computed(() => { return computedItemsPerRow?.value ? new Array(computedItemsPerRow?.value).fill({ // Instead of passing the actual screen sizes values, passing the same values per each screen size and recomputing it makes sure visually the change is smoother and not laggy small: itemColumnWidth.value, medium: itemColumnWidth.value, large: itemColumnWidth.value, }) : []; }); const onInput = value => { inputValue.value = value; emitValue(value); }; const isRadioVariant = computed(() => props.variant === 'radio'); provide(SELECTION_CARD_RADIO_INPUT_INJECTION_KEY, isRadioVariant); onMounted(() => { if (props.itemsPerRow) { Object.values(props.itemsPerRow).forEach(el => { if (el && (el < 2 || el > 6)) { throw new Error( 'itemsPerRow values must have a value between 2 and 6 items per row. Read the documentation for more information.' ); } }); } }); </script> <script lang="ts"> /** * Group of bento-selection-cards. * * @example * import { BentoSelectionCardGroup } from '@adyen/bento-vue2'; * * export default { * components: { BentoSelectionCardGroup }, * template: ` * <bento-selection-card-group * :items="[ * { * title: 'Card 1', * value: 'card-1', * content: 'Slot content 1', * icon: RetailIcon, * }, * { * title: 'Card 2', * value: 'card-2', * content: 'Slot content 2', * icon: LeafIcon, * }, * ]" * > * <template #icon="{ icon }"> * <component :is="icon"/> * </template> * <template #content="{ content }"> * <div>{{ content }}</div> * </template> * </bento-selection-card-group> * `, * } */ export default { model: { prop: 'modelValue' }, }; </script> <style lang="scss" scoped src="./selection-card-group.scss" />
|
|
1
|
+
<template> <controls-group ref="containerRef" :aria-describedby="shouldShowGroupError ? errorMessageId : null" :aria-required="required" :label="label" :hide-label="hideLabel" :description="description" :disabled="disabled" :tooltip-text="tooltipText" :readonly="readonly" :required="required" :optional="optional" class="b-selection-card-group" component-name="selection-card-group" > <div v-if="!itemsPerRow || layout === 'vertical'" class="b-selection-card-group__items" :class="conditionalItemsClasses" > <bento-selection-card v-for="item in items" :key="`selection-card-${item.value}`" class="b-selection-card-group__item" v-bind="item" :model-value="inputValue" :readonly="readonly || item.readonly" :has-error="shouldShowGroupError" :disabled="disabled || item.disabled" @update:model-value="onInput" > <template v-if="hasSlot('icon') && item.icon" #icon> <slot name="icon" v-bind="item"></slot> </template> <template v-if="hasSlot('content') && item.content" #content> <slot name="content" v-bind="item"></slot> </template> <template v-if="hasSlot('dynamicContent') && item.dynamicContent" #dynamicContent> <slot name="dynamicContent" v-bind="item"></slot> </template> </bento-selection-card> </div> <template v-else> <div :key="`selection-card-group-layout-breakpoint-${currentBreakpoint}`"> <grid-layout v-for="(row, rowIndex) in computedRows" :key="`selection-card-group-row-${rowIndex}-cols-${computedItemsPerRow}`" class="b-selection-card-group__items--wrap" :column-width="computedColumnWidth" > <template v-for="(item, columnIndex) in row" #[`col-${Number(columnIndex)+1}`]> <bento-selection-card :key="`selection-card-${item.value}`" class="b-selection-card-group__item b-selection-card-group__item--full-height" v-bind="item" :model-value="inputValue" :readonly="readonly || item.readonly" :has-error="shouldShowGroupError" :disabled="disabled || item.disabled" @update:model-value="onInput" > <template v-if="hasSlot('icon') && item.icon" #icon> <slot name="icon" v-bind="item"></slot> </template> <template v-if="hasSlot('content') && item.content" #content> <slot name="content" v-bind="item"></slot> </template> <template v-if="hasSlot('dynamicContent') && item.dynamicContent" #dynamicContent> <slot name="dynamicContent" v-bind="item"></slot> </template> </bento-selection-card> </template> </grid-layout> </div> </template> <error-message v-if="shouldShowGroupError" :id="errorMessageId" :error-message="errorMessage" class="b-selection-card-group__error-message" /> </controls-group> </template> <script setup lang="ts"> import { computed, onMounted, provide, ref, useSlots, watch } from 'vue'; import { useElementSize } from '@vueuse/core'; import { BMediaQueryMMax, BMediaQuerySMax } from '@adyen/bento-design-tokens/dist/js/bento/es6'; import { type BentoSelectionCardGroupEmits, type BentoSelectionCardGroupProps } from './selection-card-group.types'; import BentoSelectionCard from '../../selection-card.vue'; import { ControlsGroup, ErrorMessage, GridLayout } from '../../../internal'; import { SELECTION_CARD_RADIO_INPUT_INJECTION_KEY } from '../../selection-card.keys'; import { generateUid } from '@/core/utils/ts'; import { useFormFieldEmits } from '@/utils/ts/form-field/form-field'; const props = withDefaults(defineProps<BentoSelectionCardGroupProps>(), { description: null, disabled: false, errorMessage: null, formId: null, hideLabel: null, label: null, layout: 'vertical', itemsPerRow: undefined, modelValue: null, optional: false, required: false, tooltipText: null, readonly: false, variant: 'checkbox', }); const emit = defineEmits<BentoSelectionCardGroupEmits>(); const { emitValue } = useFormFieldEmits(emit); const slots = useSlots(); // Slots logic // Temporary, use-has-slots composable doesn't currently work for vue3 named scoped slots // We do the same in bento-checkbox-group const hasSlot = name => !!slots[name]; const conditionalItemsClasses = computed(() => ({ 'b-selection-card-group__items--horizontal': props.layout === 'horizontal', })); const inputValue = ref(props.modelValue); watch( () => props.modelValue, () => { inputValue.value = props.modelValue; } ); // Error message logic const errorMessageId = generateUid('error'); const shouldShowGroupError = computed(() => !props.disabled && !props.readonly && !!props.errorMessage); // itemsPerRow logic const containerRef = ref<HTMLElement | null>(null); const { width } = useElementSize(containerRef); const smallBreakpoint = computed(() => BMediaQuerySMax.split('px')[0]); const mediumBreakpoint = computed(() => BMediaQueryMMax.split('px')[0]); const currentBreakpoint = computed(() => { if (width.value < smallBreakpoint.value) { return 'small'; } if (width.value >= smallBreakpoint.value && width.value < mediumBreakpoint.value) { return 'medium'; } return 'large'; }); const computedItemsPerRow = computed(() => { return (props.itemsPerRow?.[currentBreakpoint?.value] as number) || props.items.length; }); const computedRows = computed(() => { if (!props.itemsPerRow) { return []; } const rows = []; for (let i = 0; i < props.items.length; i += computedItemsPerRow?.value) { rows.push(props.items.slice(i, i + computedItemsPerRow?.value)); } return rows; }); // We need to compute the column width on 12 because we're using a 12-column system for out grid-layout logic const itemColumnWidth = computed(() => 12 / computedItemsPerRow?.value); /** * Filling the columnWidth array with the same parameters per item to pass * to the `grid-layout` layout so the each card can have * the same width according to the screen size. */ const computedColumnWidth = computed(() => { return computedItemsPerRow?.value ? new Array(computedItemsPerRow?.value).fill({ // Instead of passing the actual screen sizes values, passing the same values per each screen size and recomputing it makes sure visually the change is smoother and not laggy small: itemColumnWidth.value, medium: itemColumnWidth.value, large: itemColumnWidth.value, }) : []; }); const onInput = value => { inputValue.value = value; emitValue(value); }; const isRadioVariant = computed(() => props.variant === 'radio'); provide(SELECTION_CARD_RADIO_INPUT_INJECTION_KEY, isRadioVariant); onMounted(() => { if (props.itemsPerRow) { Object.values(props.itemsPerRow).forEach(el => { if (el && (el < 2 || el > 6)) { throw new Error( 'itemsPerRow values must have a value between 2 and 6 items per row. Read the documentation for more information.' ); } }); } }); </script> <script lang="ts"> /** * Group of bento-selection-cards. * * @example * import { BentoSelectionCardGroup } from '@adyen/bento-vue2'; * * export default { * components: { BentoSelectionCardGroup }, * template: ` * <bento-selection-card-group * :items="[ * { * title: 'Card 1', * value: 'card-1', * content: 'Slot content 1', * icon: RetailIcon, * }, * { * title: 'Card 2', * value: 'card-2', * content: 'Slot content 2', * icon: LeafIcon, * }, * ]" * > * <template #icon="{ icon }"> * <component :is="icon"/> * </template> * <template #content="{ content }"> * <div>{{ content }}</div> * </template> * </bento-selection-card-group> * `, * } */ export default { model: { prop: 'modelValue' }, }; </script> <style lang="scss" scoped src="./selection-card-group.scss" />
|
|
@@ -1 +1 @@
|
|
|
1
|
-
<template> <div ref="textareaComponent" class="b-textarea" :class="conditionalClasses"> <div :style="{ width: textareaWrapperWidth }"> <div class="b-textarea__label-box" :class="conditionalClassesLabelBox"> <field-label v-if="label" :for="textareaId" :label="label" :tooltip-text="tooltipText" :optional="optional" :required="required" /> <bento-typography v-if="characterLimit" el="span" class="b-textarea__label-item" :class="conditionalClassesLabelItem" > {{ counter }} </bento-typography> </div> <bento-typography el="div" class="b-textarea__input-box" :aria-disabled="disabled"> <textarea :id="textareaId" ref="textareaElement" :value="textareaValue" class="b-textarea__input" :class="conditionalClassesInput" :aria-label="computedAriaLabel" :aria-invalid="invalidInput" :readonly="isReadOnly" :required="required" :disabled="disabled" :placeholder="placeholder" :style="{ resize: resizable, height: textareaHeight }" @blur="onBlur" @change="onChange" @focus="onFocus" @input="onInput" @keydown.esc="onPressEscape" @keydown="onKeyDown" @keyup="onKeyUp" @mousedown="onMouseDown" @mouseup="onMouseUp" > </textarea> <div v-if="showClearButton" class="b-textarea__clear-button"> <bento-button variant="tertiary" :disabled="disabled" @click="onClear" @keypress.enter="onClear" @keyup.space="onClear" > <template #iconLeft> <cross-circle-fill-small-icon :svg-title="t('clearText')" /> </template> </bento-button> </div> </bento-typography> <error-message v-if="isOverCharacterLimit" :error-message="counterErrorText" /> <error-message v-if="errorMessage" :error-message="errorMessage" /> <bento-typography v-if="description" class="b-textarea__description" el="span"> {{ description }} </bento-typography> </div> </div> </template> <script setup lang="ts"> import { computed, nextTick, onMounted, onUnmounted, ref, toRef, toRefs, useAttrs, watch } from 'vue'; // Components import { BentoButton } from '@/components/button'; import { BentoTypography } from '@/components/typography'; import { ErrorMessage, FieldLabel } from '@/internal'; import CrossCircleFillSmallIcon from '@adyen/ui-assets-icons-16/vue/cross-circle-fill-small'; // Utils import { generateUid } from '@/core/utils/ts'; import { observeSizeOfElement } from '@/utils/ts/resize'; import { useAriaLabel } from '@/utils/ts/aria-label'; import { useI18n } from '@/utils/ts/i18n'; import { deprecate } from '@/utils/ts/deprecate'; import { useFormFieldEmits } from '@/utils/ts/form-field/form-field'; // Composables import { useFormLayoutFieldLoading } from '@/composables/use-form-layout-loading/use-form-layout-loading'; // Constants import { BBorderWidthAttention } from '@adyen/bento-design-tokens/dist/js/bento/es6'; // Types import { BentoTextareaEvent, type BentoTextareaProps, BentoTextareaStateClass } from './textarea.types'; import messages from './messages.json'; type MessageSchema = (typeof messages)['en-US']; const attrs = useAttrs(); const props = withDefaults(defineProps<BentoTextareaProps>(), { ariaLabel: undefined, characterLimit: undefined, description: '', disabled: false, clearable: false, errorMessage: '', height: null, label: '', optional: false, placeholder: '', readonly: false, resizable: 'both', required: false, tooltipText: null, value: '', modelValue: '', }); const emit = defineEmits<{ /** * Emitted when the element has lost focus */ (e: BentoTextareaEvent.BLUR): void; /** * Emitted when the user modifies the element's value. Unlike the 'input' event, the change event is not necessarily fired for each alteration to an element's value */ (e: BentoTextareaEvent.CHANGE): void; /** * Emitted when the "Clear" button was clicked */ (e: BentoTextareaEvent.CLEAR): void; /** * Emitted when the "ESC" key is pressed */ (e: BentoTextareaEvent.ESCAPE_PRESSED): void; /** * Emitted when the element has received focus */ (e: BentoTextareaEvent.FOCUS): void; /** * Emitted when the component's model changes * * @deprecated since version 2.0. Use `v-model` or `update:model-value` instead. * */ (e: BentoTextareaEvent.INPUT, value: string): void; /** * Emitted when the component's model changes */ (e: BentoTextareaEvent.UPDATE_MODEL_VALUE, value: string): void; /** * Emitted when the text area keydown event is fired */ (e: BentoTextareaEvent.KEYDOWN, event: KeyboardEvent): void; /** * Emitted when the text area keyup event is fired */ (e: BentoTextareaEvent.KEYUP, event: KeyboardEvent): void; }>(); const { height } = toRefs(props); const textareaId = generateUid('textarea'); const textareaElement = ref<HTMLTextAreaElement>(null); const textareaComponent = ref<HTMLDivElement>(null); const textareaValue = ref(props.modelValue || props.value); const defaultTextareaHeight = 44; const textareaHeight = ref(props.height || `${defaultTextareaHeight}px`); const userSetHeight = ref<number>(0); const textareaWrapperWidth = ref('100%'); // The width set to the wrapper of the label, textarea and description const isUserResizing = ref(false); let textareaElementObserver: ResizeObserver | null = null; let textareaComponentObserver: ResizeObserver | null = null; const { t, n } = useI18n<{ message: MessageSchema }>({ messages }); const { isReadOnly } = useFormLayoutFieldLoading(toRef(props, 'readonly')); const { emitValue } = useFormFieldEmits<string>(emit); const counter = computed(() => `${n(textareaValue?.value?.length ?? 0)} / ${n(props.characterLimit)}`); const isDynamicHeight = computed(() => !height.value); const isOverCharacterLimit = computed( () => props.characterLimit && textareaValue.value.length > props.characterLimit ); /** * Calculates and sets the height of the textarea. * The height is determined by the maximum of the following values: * * 1. The content's scroll height (with a minimum of `defaultTextareaHeight`) + the border width. * 2. The height set by the user manually resizing the textarea (`userSetHeight`). * 3. The default minimum height (`defaultTextareaHeight`). * * This ensures the textarea grows with content, shrinks when content is removed, * but never goes below the manually set height or the default height. */ const calculateHeight = () => { if (textareaElement.value) { const newHeight = Math.max( textareaElement.value.scrollHeight <= defaultTextareaHeight ? defaultTextareaHeight : textareaElement.value.scrollHeight + TEXTAREA_BORDER_WIDTH * 2, userSetHeight.value, defaultTextareaHeight ); textareaHeight.value = `${newHeight}px`; } }; watch(height, () => { if (isDynamicHeight.value) { calculateHeight(); } else { textareaHeight.value = height.value; } }); watch( () => [props.value, props.modelValue], () => { textareaValue.value = props.modelValue || props.value; }, { immediate: true } ); watch( () => textareaValue.value, async () => { if (isDynamicHeight.value) { // Hack to make the textarea calculate its height properly // Set the textarea back to the original value before calculating the height textareaHeight.value = `${defaultTextareaHeight}px`; if (!textareaValue.value) { return; } await nextTick(); calculateHeight(); } }, { immediate: true } ); const invalidInput = computed(() => !!props.errorMessage || isOverCharacterLimit.value); const conditionalClasses = computed(() => ({ [`b-textarea--${BentoTextareaStateClass.DISABLED}`]: props.disabled, })); const conditionalClassesInput = computed(() => ({ [`b-textarea__input--${BentoTextareaStateClass.CLEARABLE}`]: props.clearable, [`b-textarea__input--${BentoTextareaStateClass.READONLY}`]: isReadOnly.value, [`b-textarea__input--${BentoTextareaStateClass.ERROR}`]: invalidInput.value, [`b-textarea__input--dynamic-height`]: isDynamicHeight.value, })); const conditionalClassesLabelBox = computed(() => ({ [`b-textarea__label-box--no-label`]: !props.label, })); const conditionalClassesLabelItem = computed(() => ({ [`b-textarea__label-item--${BentoTextareaStateClass.ERROR}`]: isOverCharacterLimit.value, })); const counterErrorText = computed(() => t('yourTextCanBenAtMost', { characterLimit: props.characterLimit })); const ariaLabelAttribute = ref(attrs['aria-label']); const { ariaLabel, label } = toRefs(props); const computedAriaLabel = useAriaLabel({ ariaLabel: ariaLabelAttribute.value as string, // TODO: take this line away when the aria-label props is removed label: ariaLabel, defaultFallback: label, }); const showClearButton = computed( () => props.clearable && textareaValue.value && !props.disabled && !isReadOnly.value ); const onClear = () => { textareaValue.value = ''; emit(BentoTextareaEvent.CLEAR); emitValue(''); }; const onInput = (event: InputEvent) => { event.stopImmediatePropagation(); if (!props.disabled && !isReadOnly.value) { textareaValue.value = (event.target as HTMLInputElement).value; /** * Triggered when input value is changed * * @event input * @property {String} inputValue - the updated textarea value */ emitValue(textareaValue.value); } }; const onBlur = () => { textareaElement.value.scrollTop = 0; emit(BentoTextareaEvent.BLUR); }; const onFocus = () => { textareaElement.value.focus(); emit(BentoTextareaEvent.FOCUS); }; const onChange = () => { emit(BentoTextareaEvent.CHANGE); }; const onPressEscape = () => { emit(BentoTextareaEvent.ESCAPE_PRESSED); }; const onKeyDown = (event: KeyboardEvent) => { event.stopPropagation(); emit(BentoTextareaEvent.KEYDOWN, event); }; const onKeyUp = (event: KeyboardEvent) => { event.stopPropagation(); emit(BentoTextareaEvent.KEYUP, event); }; const onMouseDown = () => { isUserResizing.value = true; }; const onMouseUp = () => { isUserResizing.value = false; }; /** * Updates the textarea width depending if the container or the user update its size. * @param isTextareaElement - sets to true if the element being observed is the textarea HTML element. */ const resizeTextareaWrapper = (isTextareaElement = false) => { // Width assigned by the browser whenever the textarea is manually resized. String of the format `<value>px`. const textareaStyleWidth = textareaElement.value.style.width; // Make sure the tracked textareaHeight is always in sync with the height size in case we manually resize the textarea if (textareaElement.value.style.height) { if (isUserResizing.value) { userSetHeight.value = parseInt(textareaElement.value.style.height, 10); } textareaHeight.value = textareaElement.value.style.height; } // If the textarea element observer is being triggered, but there's no textareaStyleWidth, we want to ignore it, as no manual resize as happened yet // The component wrapper will handle the resizing logic instead if (isTextareaElement && !textareaStyleWidth) { return; } // Width of the whole bento-textarea component const textareaComponentWidth = textareaComponent?.value?.offsetWidth; // If there is no textareaStyleWidth or the textareaStyleWidth is larger than the component container, the wrapper should be 100% of the container if (!textareaStyleWidth || parseInt(textareaStyleWidth, 10) > textareaComponentWidth) { textareaWrapperWidth.value = '100%'; } else { // Else the wrapper should always be as wide as the textarea element itself textareaWrapperWidth.value = textareaStyleWidth; } }; const focus = () => { textareaElement.value.focus(); }; defineExpose({ focus, }); onMounted(() => { textareaElementObserver = observeSizeOfElement(textareaElement.value, () => { resizeTextareaWrapper(true); }); textareaComponentObserver = observeSizeOfElement(textareaComponent.value, () => { resizeTextareaWrapper(); }); if (isDynamicHeight.value) { calculateHeight(); } if (props.value) { deprecate( 'BentoTextarea "value" property', `The use of "value" prop in "BentoTextarea" is no longer supported. Use the "v-model" or "model-value" property instead.`, '2.0.0' ); } }); onUnmounted(() => { textareaElementObserver?.disconnect(); textareaComponentObserver?.disconnect(); }); </script> <script lang="ts"> const TEXTAREA_BORDER_WIDTH = parseFloat(BBorderWidthAttention); export default { i18n: { messages }, name: 'bento-textarea', model: { prop: 'modelValue' }, }; </script> <style lang="scss" scoped src="./textarea.scss" />
|
|
1
|
+
<template> <div ref="textareaComponent" class="b-textarea" :class="conditionalClasses"> <div :style="{ width: textareaWrapperWidth }"> <div class="b-textarea__label-box" :class="conditionalClassesLabelBox"> <field-label v-if="label" :for="textareaId" :label="label" :tooltip-text="tooltipText" :optional="optional" :required="required" /> <bento-typography v-if="characterLimit" el="span" class="b-textarea__label-item" :class="conditionalClassesLabelItem" > {{ counter }} </bento-typography> </div> <bento-typography el="div" class="b-textarea__input-box" :aria-disabled="disabled"> <textarea :id="textareaId" ref="textareaElement" :value="textareaValue" class="b-textarea__input" :class="conditionalClassesInput" :aria-label="computedAriaLabel" :aria-invalid="invalidInput" :readonly="isReadOnly" :required="required" :aria-required="required" :disabled="disabled" :placeholder="placeholder" :style="{ resize: resizable, height: textareaHeight }" @blur="onBlur" @change="onChange" @focus="onFocus" @input="onInput" @keydown.esc="onPressEscape" @keydown="onKeyDown" @keyup="onKeyUp" @mousedown="onMouseDown" @mouseup="onMouseUp" > </textarea> <div v-if="showClearButton" class="b-textarea__clear-button"> <bento-button variant="tertiary" :disabled="disabled" @click="onClear" @keypress.enter="onClear" @keyup.space="onClear" > <template #iconLeft> <cross-circle-fill-small-icon :svg-title="t('clearText')" /> </template> </bento-button> </div> </bento-typography> <error-message v-if="isOverCharacterLimit" :error-message="counterErrorText" /> <error-message v-if="errorMessage" :error-message="errorMessage" /> <bento-typography v-if="description" class="b-textarea__description" el="span"> {{ description }} </bento-typography> </div> </div> </template> <script setup lang="ts"> import { computed, nextTick, onMounted, onUnmounted, ref, toRef, toRefs, useAttrs, watch } from 'vue'; // Components import { BentoButton } from '@/components/button'; import { BentoTypography } from '@/components/typography'; import { ErrorMessage, FieldLabel } from '@/internal'; import CrossCircleFillSmallIcon from '@adyen/ui-assets-icons-16/vue/cross-circle-fill-small'; // Utils import { generateUid } from '@/core/utils/ts'; import { observeSizeOfElement } from '@/utils/ts/resize'; import { useAriaLabel } from '@/utils/ts/aria-label'; import { useI18n } from '@/utils/ts/i18n'; import { deprecate } from '@/utils/ts/deprecate'; import { useFormFieldEmits } from '@/utils/ts/form-field/form-field'; // Composables import { useFormLayoutFieldLoading } from '@/composables/use-form-layout-loading/use-form-layout-loading'; // Constants import { BBorderWidthAttention } from '@adyen/bento-design-tokens/dist/js/bento/es6'; // Types import { BentoTextareaEvent, type BentoTextareaProps, BentoTextareaStateClass } from './textarea.types'; import messages from './messages.json'; type MessageSchema = (typeof messages)['en-US']; const attrs = useAttrs(); const props = withDefaults(defineProps<BentoTextareaProps>(), { ariaLabel: undefined, characterLimit: undefined, description: '', disabled: false, clearable: false, errorMessage: '', height: null, label: '', optional: false, placeholder: '', readonly: false, resizable: 'both', required: false, tooltipText: null, value: '', modelValue: '', }); const emit = defineEmits<{ /** * Emitted when the element has lost focus */ (e: BentoTextareaEvent.BLUR): void; /** * Emitted when the user modifies the element's value. Unlike the 'input' event, the change event is not necessarily fired for each alteration to an element's value */ (e: BentoTextareaEvent.CHANGE): void; /** * Emitted when the "Clear" button was clicked */ (e: BentoTextareaEvent.CLEAR): void; /** * Emitted when the "ESC" key is pressed */ (e: BentoTextareaEvent.ESCAPE_PRESSED): void; /** * Emitted when the element has received focus */ (e: BentoTextareaEvent.FOCUS): void; /** * Emitted when the component's model changes * * @deprecated since version 2.0. Use `v-model` or `update:model-value` instead. * */ (e: BentoTextareaEvent.INPUT, value: string): void; /** * Emitted when the component's model changes */ (e: BentoTextareaEvent.UPDATE_MODEL_VALUE, value: string): void; /** * Emitted when the text area keydown event is fired */ (e: BentoTextareaEvent.KEYDOWN, event: KeyboardEvent): void; /** * Emitted when the text area keyup event is fired */ (e: BentoTextareaEvent.KEYUP, event: KeyboardEvent): void; }>(); const { height } = toRefs(props); const textareaId = generateUid('textarea'); const textareaElement = ref<HTMLTextAreaElement>(null); const textareaComponent = ref<HTMLDivElement>(null); const textareaValue = ref(props.modelValue || props.value); const defaultTextareaHeight = 44; const textareaHeight = ref(props.height || `${defaultTextareaHeight}px`); const userSetHeight = ref<number>(0); const textareaWrapperWidth = ref('100%'); // The width set to the wrapper of the label, textarea and description const isUserResizing = ref(false); let textareaElementObserver: ResizeObserver | null = null; let textareaComponentObserver: ResizeObserver | null = null; const { t, n } = useI18n<{ message: MessageSchema }>({ messages }); const { isReadOnly } = useFormLayoutFieldLoading(toRef(props, 'readonly')); const { emitValue } = useFormFieldEmits<string>(emit); const counter = computed(() => `${n(textareaValue?.value?.length ?? 0)} / ${n(props.characterLimit)}`); const isDynamicHeight = computed(() => !height.value); const isOverCharacterLimit = computed( () => props.characterLimit && textareaValue.value.length > props.characterLimit ); /** * Calculates and sets the height of the textarea. * The height is determined by the maximum of the following values: * * 1. The content's scroll height (with a minimum of `defaultTextareaHeight`) + the border width. * 2. The height set by the user manually resizing the textarea (`userSetHeight`). * 3. The default minimum height (`defaultTextareaHeight`). * * This ensures the textarea grows with content, shrinks when content is removed, * but never goes below the manually set height or the default height. */ const calculateHeight = () => { if (textareaElement.value) { const newHeight = Math.max( textareaElement.value.scrollHeight <= defaultTextareaHeight ? defaultTextareaHeight : textareaElement.value.scrollHeight + TEXTAREA_BORDER_WIDTH * 2, userSetHeight.value, defaultTextareaHeight ); textareaHeight.value = `${newHeight}px`; } }; watch(height, () => { if (isDynamicHeight.value) { calculateHeight(); } else { textareaHeight.value = height.value; } }); watch( () => [props.value, props.modelValue], () => { textareaValue.value = props.modelValue || props.value; }, { immediate: true } ); watch( () => textareaValue.value, async () => { if (isDynamicHeight.value) { // Hack to make the textarea calculate its height properly // Set the textarea back to the original value before calculating the height textareaHeight.value = `${defaultTextareaHeight}px`; if (!textareaValue.value) { return; } await nextTick(); calculateHeight(); } }, { immediate: true } ); const invalidInput = computed(() => !!props.errorMessage || isOverCharacterLimit.value); const conditionalClasses = computed(() => ({ [`b-textarea--${BentoTextareaStateClass.DISABLED}`]: props.disabled, })); const conditionalClassesInput = computed(() => ({ [`b-textarea__input--${BentoTextareaStateClass.CLEARABLE}`]: props.clearable, [`b-textarea__input--${BentoTextareaStateClass.READONLY}`]: isReadOnly.value, [`b-textarea__input--${BentoTextareaStateClass.ERROR}`]: invalidInput.value, [`b-textarea__input--dynamic-height`]: isDynamicHeight.value, })); const conditionalClassesLabelBox = computed(() => ({ [`b-textarea__label-box--no-label`]: !props.label, })); const conditionalClassesLabelItem = computed(() => ({ [`b-textarea__label-item--${BentoTextareaStateClass.ERROR}`]: isOverCharacterLimit.value, })); const counterErrorText = computed(() => t('yourTextCanBenAtMost', { characterLimit: props.characterLimit })); const ariaLabelAttribute = ref(attrs['aria-label']); const { ariaLabel, label } = toRefs(props); const computedAriaLabel = useAriaLabel({ ariaLabel: ariaLabelAttribute.value as string, // TODO: take this line away when the aria-label props is removed label: ariaLabel, defaultFallback: label, }); const showClearButton = computed( () => props.clearable && textareaValue.value && !props.disabled && !isReadOnly.value ); const onClear = () => { textareaValue.value = ''; emit(BentoTextareaEvent.CLEAR); emitValue(''); }; const onInput = (event: InputEvent) => { event.stopImmediatePropagation(); if (!props.disabled && !isReadOnly.value) { textareaValue.value = (event.target as HTMLInputElement).value; /** * Triggered when input value is changed * * @event input * @property {String} inputValue - the updated textarea value */ emitValue(textareaValue.value); } }; const onBlur = () => { textareaElement.value.scrollTop = 0; emit(BentoTextareaEvent.BLUR); }; const onFocus = () => { textareaElement.value.focus(); emit(BentoTextareaEvent.FOCUS); }; const onChange = () => { emit(BentoTextareaEvent.CHANGE); }; const onPressEscape = () => { emit(BentoTextareaEvent.ESCAPE_PRESSED); }; const onKeyDown = (event: KeyboardEvent) => { event.stopPropagation(); emit(BentoTextareaEvent.KEYDOWN, event); }; const onKeyUp = (event: KeyboardEvent) => { event.stopPropagation(); emit(BentoTextareaEvent.KEYUP, event); }; const onMouseDown = () => { isUserResizing.value = true; }; const onMouseUp = () => { isUserResizing.value = false; }; /** * Updates the textarea width depending if the container or the user update its size. * @param isTextareaElement - sets to true if the element being observed is the textarea HTML element. */ const resizeTextareaWrapper = (isTextareaElement = false) => { // Width assigned by the browser whenever the textarea is manually resized. String of the format `<value>px`. const textareaStyleWidth = textareaElement.value.style.width; // Make sure the tracked textareaHeight is always in sync with the height size in case we manually resize the textarea if (textareaElement.value.style.height) { if (isUserResizing.value) { userSetHeight.value = parseInt(textareaElement.value.style.height, 10); } textareaHeight.value = textareaElement.value.style.height; } // If the textarea element observer is being triggered, but there's no textareaStyleWidth, we want to ignore it, as no manual resize as happened yet // The component wrapper will handle the resizing logic instead if (isTextareaElement && !textareaStyleWidth) { return; } // Width of the whole bento-textarea component const textareaComponentWidth = textareaComponent?.value?.offsetWidth; // If there is no textareaStyleWidth or the textareaStyleWidth is larger than the component container, the wrapper should be 100% of the container if (!textareaStyleWidth || parseInt(textareaStyleWidth, 10) > textareaComponentWidth) { textareaWrapperWidth.value = '100%'; } else { // Else the wrapper should always be as wide as the textarea element itself textareaWrapperWidth.value = textareaStyleWidth; } }; const focus = () => { textareaElement.value.focus(); }; defineExpose({ focus, }); onMounted(() => { textareaElementObserver = observeSizeOfElement(textareaElement.value, () => { resizeTextareaWrapper(true); }); textareaComponentObserver = observeSizeOfElement(textareaComponent.value, () => { resizeTextareaWrapper(); }); if (isDynamicHeight.value) { calculateHeight(); } if (props.value) { deprecate( 'BentoTextarea "value" property', `The use of "value" prop in "BentoTextarea" is no longer supported. Use the "v-model" or "model-value" property instead.`, '2.0.0' ); } }); onUnmounted(() => { textareaElementObserver?.disconnect(); textareaComponentObserver?.disconnect(); }); </script> <script lang="ts"> const TEXTAREA_BORDER_WIDTH = parseFloat(BBorderWidthAttention); export default { i18n: { messages }, name: 'bento-textarea', model: { prop: 'modelValue' }, }; </script> <style lang="scss" scoped src="./textarea.scss" />
|