feat : ajouts du composant select

This commit is contained in:
2026-03-02 14:05:40 +01:00
parent b4ffe0d29e
commit 6e70bc4d3e
12 changed files with 1142 additions and 182 deletions

View File

@@ -2,7 +2,8 @@
<div class="grid grid-cols-1 items-start gap-6 md:grid-cols-2">
<div class="rounded-lg border p-4">
<h2 class="mb-4 text-xl font-bold">Simple</h2>
<MalioInputText/>
<MalioInputText
/>
</div>
<div class="rounded-lg border p-4">

View File

@@ -0,0 +1,149 @@
<template>
<div class="grid grid-cols-1 items-start gap-6 md:grid-cols-2">
<div class="rounded-lg border p-4">
<h2 class="mb-4 text-xl font-bold">Simple</h2>
<MalioSelect
v-model="basicValue"
:options="options"
empty-option-label="Aucune selection"
/>
</div>
<div class="rounded-lg border p-4">
<h2 class="mb-4 text-xl font-bold">Avec label</h2>
<MalioSelect
v-model="labelValue"
:options="options"
label="Pays"
empty-option-label="Aucune selection"
/>
</div>
<div class="rounded-lg border p-4">
<h2 class="mb-4 text-xl font-bold">Valeur preselectionnee</h2>
<MalioSelect
v-model="selectedValue"
:options="options"
label="Pays"
empty-option-label="Aucune selection"
/>
</div>
<div class="rounded-lg border p-4">
<h2 class="mb-4 text-xl font-bold">Hint</h2>
<MalioSelect
v-model="hintValue"
:options="options"
label="Pays"
hint="Choisissez votre pays"
empty-option-label="Aucune selection"
/>
</div>
<div class="rounded-lg border p-4">
<h2 class="mb-4 text-xl font-bold">Erreur</h2>
<MalioSelect
v-model="errorValue"
:options="options"
label="Pays"
error="Ce champ est obligatoire"
empty-option-label="Aucune selection"
/>
</div>
<div class="rounded-lg border p-4">
<h2 class="mb-4 text-xl font-bold">Succes</h2>
<MalioSelect
v-model="successValue"
:options="options"
label="Pays"
success="Selection validee"
empty-option-label="Aucune selection"
/>
</div>
<div class="rounded-lg border p-4">
<h2 class="mb-4 text-xl font-bold">Desactive</h2>
<MalioSelect
v-model="disabledValue"
:options="options"
label="Pays"
disabled
empty-option-label="Aucune selection"
/>
</div>
<div class="rounded-lg border p-4">
<h2 class="mb-4 text-xl font-bold">Sans options</h2>
<MalioSelect
v-model="emptyValue"
label="Pays"
empty-option-label="Aucun pays disponible"
/>
</div>
<div class="rounded-lg border p-4 md:col-span-2">
<h2 class="mb-4 text-xl font-bold">Liste longue</h2>
<MalioSelect
v-model="longListValue"
:options="longOptions"
label="Pays"
hint="Permet de verifier la scrollbar"
empty-option-label="Aucune selection"
/>
</div>
<div class="rounded-lg border p-4 md:col-span-2">
<h2 class="mb-4 text-xl font-bold">Ouverture en bas de page</h2>
<div class="h-64" />
<MalioSelect
v-model="bottomValue"
:options="longOptions"
label="Ouverture adaptative"
hint="A ouvrir pres du bas de la page"
empty-option-label="Aucune selection"
/>
</div>
</div>
</template>
<script setup lang="ts">
import {ref} from 'vue'
const options = [
{label: 'France', value: 'fr'},
{label: 'Belgique', value: 'be'},
{label: 'Suisse', value: 'ch'},
{label: 'Canada', value: 'ca'},
{label: 'Allemagne', value: 'de'},
{label: 'Espagne', value: 'es'},
{label: 'Italie', value: 'it'},
{label: 'Portugal', value: 'pt'},
]
const longOptions = [
...options,
{label: 'Pays-Bas', value: 'nl'},
{label: 'Suede', value: 'se'},
{label: 'Norvege', value: 'no'},
{label: 'Danemark', value: 'dk'},
{label: 'Finlande', value: 'fi'},
{label: 'Autriche', value: 'at'},
{label: 'Irlande', value: 'ie'},
{label: 'Grece', value: 'gr'},
{label: 'Pologne', value: 'pl'},
{label: 'Hongrie', value: 'hu'},
{label: 'Republique tcheque', value: 'cz'},
]
const basicValue = ref<string | number | null>(null)
const labelValue = ref<string | number | null>(null)
const selectedValue = ref<string | number | null>('fr')
const hintValue = ref<string | number | null>(null)
const errorValue = ref<string | number | null>(null)
const successValue = ref<string | number | null>('be')
const disabledValue = ref<string | number | null>('ca')
const emptyValue = ref<string | number | null>(null)
const longListValue = ref<string | number | null>(null)
const bottomValue = ref<string | number | null>(null)
</script>

View File

@@ -1,17 +1,17 @@
import {describe, expect, it} from 'vitest'
import {config, mount} from '@vue/test-utils'
import {mount} from '@vue/test-utils'
import type {DefineComponent} from 'vue'
import Input from './InputText.vue'
type InputProps = {
id?: string
label?: string
name?: string
autocomplete?: string
modelValue?: string | null
textSize?: string
inputClass?: string
labelClass?: string
groupClass?: string
required?: boolean
maxLength?: number | string
minLength?: number | string
@@ -21,245 +21,225 @@ type InputProps = {
error?: string
success?: string
iconName?: string
iconPosition?: 'left' | 'right'
iconSize?: string | number
iconColor?: string
}
const InputForTest = Input as DefineComponent<InputProps>
const iconStub = {
template: '<span data-test="icon" v-bind="$attrs" />',
}
config.global.stubs = {
...(config.global.stubs ?? {}),
Icon: iconStub,
}
describe('MalioInput', () => {
// Props de base: valeur, label, name, id, autocomplete
const mountInput = (props: InputProps = {}) =>
mount(InputForTest, {
props,
global: {
stubs: {
IconifyIcon: {
template: '<span data-test="icon" v-bind="$attrs" />',
},
},
},
})
describe('MalioInputText', () => {
it('renders the initial input value', () => {
const wrapper = mount(InputForTest, {
props: {modelValue: 'initialValueTest'},
})
const wrapper = mountInput({modelValue: 'initialValueTest'})
expect(wrapper.get('input').element.value).toBe('initialValueTest')
})
it('renders the label text', () => {
const wrapper = mount(InputForTest, {
props: {label: 'labelTest'},
})
const wrapper = mountInput({label: 'labelTest'})
expect(wrapper.get('label').text()).toBe('labelTest')
})
it('applies the name attribute', () => {
const wrapper = mount(InputForTest, {
props: {name: 'nameTest'},
})
const wrapper = mountInput({name: 'nameTest'})
expect(wrapper.get('input').attributes('name')).toBe('nameTest')
})
it('uses provided id on input and label', () => {
const wrapper = mount(InputForTest, {
props: {id: 'custom-id', label: 'Label'},
})
const wrapper = mountInput({id: 'custom-id', label: 'Label'})
expect(wrapper.get('input').attributes('id')).toBe('custom-id')
expect(wrapper.get('label').attributes('for')).toBe('custom-id')
})
it('applies a different size of rounded', () => {
const wrapper = mount(InputForTest, {
props: {rounded: 'rounded-md'},
})
it('keeps the default rounded class on input', () => {
const wrapper = mountInput()
expect(wrapper.get('input').classes()).toContain('rounded-md')
})
it('generates an id when missing and reuses it on label', () => {
const wrapper = mount(InputForTest, {
props: {label: 'Label'},
})
const wrapper = mountInput({label: 'Label'})
const inputId = wrapper.get('input').attributes('id')
expect(inputId).toBeDefined()
expect(inputId?.startsWith('malio-input-text-')).toBe(true)
expect(wrapper.get('label').attributes('for')).toBe(inputId)
})
it('applies the autocomplete attribute', () => {
const wrapper = mount(InputForTest, {
props: {autocomplete: 'autocompleteTest'},
})
const wrapper = mountInput({autocomplete: 'autocompleteTest'})
expect(wrapper.get('input').attributes('autocomplete')).toBe('autocompleteTest')
})
// États HTML: required, readonly, disabled
it('does not set required when false', () => {
const wrapper = mount(InputForTest, {
props: {required: false},
})
const wrapper = mountInput({required: false})
expect(wrapper.get('input').attributes('required')).toBeUndefined()
})
it('sets required when true', () => {
const wrapper = mount(InputForTest, {
props: {required: true},
})
const wrapper = mountInput({required: true})
expect(wrapper.get('input').attributes('required')).toBeDefined()
})
it('does not set readonly when false', () => {
const wrapper = mount(InputForTest, {
props: {readonly: false},
})
const wrapper = mountInput({readonly: false})
expect(wrapper.get('input').attributes('readonly')).toBeUndefined()
})
it('sets readonly when true', () => {
const wrapper = mount(InputForTest, {
props: {readonly: true},
})
const wrapper = mountInput({readonly: true})
expect(wrapper.get('input').attributes('readonly')).toBeDefined()
})
it('does not set disabled and keeps text cursor when false', () => {
const wrapper = mount(InputForTest, {
props: {disabled: false},
})
const wrapper = mountInput({disabled: false})
expect(wrapper.get('input').attributes('disabled')).toBeUndefined()
expect(wrapper.get('input').classes()).toContain('cursor-text')
})
it('sets disabled styles when true', () => {
const wrapper = mount(InputForTest, {
props: {disabled: true},
})
const wrapper = mountInput({disabled: true})
expect(wrapper.get('input').attributes('disabled')).toBeDefined()
expect(wrapper.get('input').classes()).toContain('cursor-not-allowed')
expect(wrapper.get('input').classes()).toContain('text-black/60')
})
// Émission d'événements
it('emits update:modelValue on input change', async () => {
const wrapper = mount(InputForTest, {
props: {modelValue: ''},
})
const wrapper = mountInput({modelValue: ''})
await wrapper.get('input').setValue('new value')
expect(wrapper.emitted('update:modelValue')?.[0]).toEqual(['new value'])
})
// Contraintes et classes de texte
it('applies maxLength to input', () => {
const wrapper = mount(InputForTest, {
props: {maxLength: 25},
})
const wrapper = mountInput({maxLength: 25})
expect(wrapper.get('input').attributes('maxlength')).toBe('25')
})
it('applies minLength to input', () => {
const wrapper = mount(InputForTest, {
props: {minLength: 25},
})
const wrapper = mountInput({minLength: 25})
expect(wrapper.get('input').attributes('minlength')).toBe('25')
})
it('applies textSize class on label', () => {
const wrapper = mount(InputForTest, {
props: {label: 'Label', textLabel: 'text-sm'},
})
expect(wrapper.get('label').classes()).toContain('text-sm')
it('applies labelClass on label', () => {
const wrapper = mountInput({label: 'Label', labelClass: 'text-red-500'})
expect(wrapper.get('label').classes()).toContain('text-red-500')
})
it('applies inputClass on input', () => {
const wrapper = mountInput({inputClass: 'text-sm'})
expect(wrapper.get('input').classes()).toContain('text-sm')
})
// États visuels: erreur et succès
it('shows error message without label and icon', () => {
const wrapper = mount(InputForTest, {
props: {error: 'Error message test'},
})
const wrapper = mountInput({error: 'Error message test'})
expect(wrapper.get('p.text-m-error').text()).toBe('Error message test')
expect(wrapper.get('input').classes()).toContain('border-m-error')
expect(wrapper.get('input').attributes('aria-invalid')).toBe('true')
expect(wrapper.get('p').classes()).toContain('text-m-error')
})
it('shows error message with label and without icon', () => {
const wrapper = mount(InputForTest, {
props: {error: 'Error message test', label: 'Error message'},
})
const wrapper = mountInput({error: 'Error message test', label: 'Error message'})
expect(wrapper.get('p.text-m-error').text()).toBe('Error message test')
expect(wrapper.get('input').classes()).toContain('border-m-error')
expect(wrapper.get('label').classes()).toContain('text-m-error')
expect(wrapper.get('label').classes()).toContain('text-m-error')
expect(wrapper.get('label').classes()).toContain('text-m-error')
expect(wrapper.get('p').classes()).toContain('text-m-error')
})
it('shows error message with label and icon', () => {
const wrapper = mount(InputForTest, {
props: {error: 'Error message test', label: 'Error message', iconName: 'mdi:key-outline'},
const wrapper = mountInput({
error: 'Error message test',
label: 'Error message',
iconName: 'mdi:key-outline',
})
expect(wrapper.get('p.text-m-error').text()).toBe('Error message test')
expect(wrapper.get('input').classes()).toContain('border-m-error')
expect(wrapper.get('label').classes()).toContain('text-m-error')
expect(wrapper.get('label').classes()).toContain('text-m-error')
expect(wrapper.get('label').classes()).toContain('text-m-error')
expect(wrapper.get('[data-test="icon"]').classes()).toContain('text-m-error')
expect(wrapper.get('p').classes()).toContain('text-m-error')
})
it('shows error message with icon and without label', () => {
const wrapper = mount(InputForTest, {
props: {error: 'Error message test', iconName: 'mdi:key-outline'},
})
const wrapper = mountInput({error: 'Error message test', iconName: 'mdi:key-outline'})
expect(wrapper.get('p.text-m-error').text()).toBe('Error message test')
expect(wrapper.get('input').classes()).toContain('border-m-error')
expect(wrapper.get('[data-test="icon"]').classes()).toContain('text-m-error')
})
it('shows success message without label and icon', () => {
const wrapper = mount(InputForTest, {
props: {success: 'Success message test'},
})
const wrapper = mountInput({success: 'Success message test'})
expect(wrapper.get('p.text-m-success').text()).toBe('Success message test')
expect(wrapper.get('input').classes()).toContain('border-m-success')
})
it('shows success message with label and without icon', () => {
const wrapper = mount(InputForTest, {
props: {success: 'Success message test', label: 'Success message'},
})
const wrapper = mountInput({success: 'Success message test', label: 'Success message'})
expect(wrapper.get('p.text-m-success').text()).toBe('Success message test')
expect(wrapper.get('input').classes()).toContain('border-m-success')
expect(wrapper.get('label').classes()).toContain('text-m-success')
expect(wrapper.get('label').classes()).toContain('text-m-success')
expect(wrapper.get('label').classes()).toContain('text-m-success')
})
it('shows success message with label and icon', () => {
const wrapper = mount(InputForTest, {
props: {success: 'Success message test', label: 'Success message', iconName: 'mdi:key-outline'},
const wrapper = mountInput({
success: 'Success message test',
label: 'Success message',
iconName: 'mdi:key-outline',
})
expect(wrapper.get('p.text-m-success').text()).toBe('Success message test')
expect(wrapper.get('input').classes()).toContain('border-m-success')
expect(wrapper.get('label').classes()).toContain('text-m-success')
expect(wrapper.get('label').classes()).toContain('text-m-success')
expect(wrapper.get('label').classes()).toContain('text-m-success')
expect(wrapper.get('[data-test="icon"]').classes()).toContain('text-m-success')
})
it('shows success message with icon and without label', () => {
const wrapper = mount(InputForTest, {
props: {success: 'Success message test', iconName: 'mdi:key-outline'},
})
const wrapper = mountInput({success: 'Success message test', iconName: 'mdi:key-outline'})
expect(wrapper.get('p.text-m-success').text()).toBe('Success message test')
expect(wrapper.get('input').classes()).toContain('border-m-success')
expect(wrapper.get('[data-test="icon"]').classes()).toContain('text-m-success')
})
it('prioritizes error over success when both are provided', () => {
const wrapper = mount(InputForTest, {
props: {
error: 'Error message test',
success: 'Success message test',
},
const wrapper = mountInput({
error: 'Error message test',
success: 'Success message test',
})
expect(wrapper.find('p.text-m-error').exists()).toBe(true)
expect(wrapper.get('p.text-m-error').text()).toBe('Error message test')
expect(wrapper.find('p.text-m-success').exists()).toBe(false)
@@ -267,34 +247,21 @@ describe('MalioInput', () => {
expect(wrapper.get('input').classes()).not.toContain('border-m-success')
})
// Aide et classes de label
it('shows hint message', () => {
const wrapper = mount(InputForTest, {
props: {hint: 'Hint message test'},
})
const wrapper = mountInput({hint: 'Hint message test'})
expect(wrapper.get('p.text-m-muted').text()).toBe('Hint message test')
})
it('applies labelClass on label', () => {
const wrapper = mount(InputForTest, {
props: {label: 'Label', textLabel: 'text-red-500'},
})
expect(wrapper.get('label').classes()).toContain('text-red-500')
})
it('does not render label when label prop is missing', () => {
const wrapper = mount(InputForTest, {
props: {labelClass: 'text-red-500'},
})
const wrapper = mountInput({labelClass: 'text-red-500'})
expect(wrapper.find('label').exists()).toBe(false)
})
// Icône : rendu et options
it('renders icon with default positioning and muted color', () => {
const wrapper = mount(InputForTest, {
props: {iconName: 'mdi:key-outline'},
})
const wrapper = mountInput({iconName: 'mdi:key-outline'})
expect(wrapper.get('[data-test="icon"]').classes()).toContain('text-m-muted')
expect(wrapper.get('[data-test="icon"]').classes()).toContain('pointer-events-none')
expect(wrapper.get('[data-test="icon"]').classes()).toContain('absolute')
@@ -303,17 +270,28 @@ describe('MalioInput', () => {
expect(wrapper.get('[data-test="icon"]').classes()).toContain('-translate-y-1/2')
})
it('passes icon size prop to icon component', () => {
const wrapper = mount(InputForTest, {
props: {iconName: 'mdi:key-outline', iconSize: '24'},
it('renders icon on the left when requested', () => {
const wrapper = mountInput({
iconName: 'mdi:key-outline',
iconPosition: 'left',
label: 'Password',
})
expect(wrapper.get('[data-test="icon"]').classes()).toContain('left-2')
expect(wrapper.get('input').classes()).toContain('!pl-11')
expect(wrapper.get('label').classes()).toContain('left-8')
})
it('passes icon size props to icon component', () => {
const wrapper = mountInput({iconName: 'mdi:key-outline', iconSize: '24'})
expect(wrapper.get('[data-test="icon"]').attributes('width')).toBe('24')
expect(wrapper.get('[data-test="icon"]').attributes('height')).toBe('24')
})
it('applies icon color class', () => {
const wrapper = mount(InputForTest, {
props: {iconName: 'mdi:key-outline', iconColor: 'text-m-primary'},
})
const wrapper = mountInput({iconName: 'mdi:key-outline', iconColor: 'text-m-primary'})
expect(wrapper.get('[data-test="icon"]').classes()).toContain('text-m-primary')
})
})

View File

@@ -1,26 +1,13 @@
<template>
<div
class="relative mt-4 flex h-12 w-full items-center"
:class="[minWidth, maxWidth]"
:class="mergedGroupClass"
>
<input
:id="inputId"
v-maska="mask"
:name="name"
:autocomplete="autocomplete"
class="floating-input grow-height peer min-h-[40px] w-full border bg-white pl-3 pr-3 py-1 outline-none placeholder:text-transparent focus:border-2 "
:class="[
disabled ? 'cursor-not-allowed text-black/60 [&:not(:placeholder-shown)]:border-m-muted border-m-muted' : 'cursor-text',
hasError
? 'border-m-error focus:border-m-error [&:not(:placeholder-shown)]:border-m-error'
: hasSuccess
? 'border-m-success focus:border-m-success [&:not(:placeholder-shown)]:border-m-success'
: 'border-m-muted focus:border-m-primary',
textInput,
iconInputPaddingClass,
focusPaddingClass,
rounded,
]"
:class="mergedInputClass"
:required="required"
:maxlength="maxLength"
:minlength="minLength"
@@ -40,18 +27,7 @@
<label
v-if="label"
:for="inputId"
class="floating-label absolute top-2 mt-1 inline-block origin-left transition-transform duration-150 font-medium"
:class="[
labelPositionClass,
shouldFloatLabel ? '-translate-y-[1.15rem] scale-90' : '',
disabled ? 'peer-[&:not(:placeholder-shown):not(:focus)]:text-black/60' : '',
hasError
? 'text-m-error'
: hasSuccess
? 'text-m-success'
: 'peer-placeholder-shown:text-m-muted peer-[&:not(:placeholder-shown):not(:focus)]:text-black peer-focus:text-m-primary',
textLabel,
]"
:class="mergedLabelClass"
>
{{ label }}
</label>
@@ -63,9 +39,11 @@
:height="iconSize"
data-test="icon"
:class="[
hasError ? 'text-m-error' : hasSuccess ? 'text-m-success' : '',
hasError
? 'text-m-error'
: hasSuccess
? 'text-m-success' : iconColor,
iconPositionClass,
iconColor,
]"
/>
@@ -92,6 +70,7 @@ import type {MaskInputOptions} from 'maska'
import {vMaska} from 'maska/vue'
import {computed, ref, useAttrs, useId} from 'vue'
import { Icon as IconifyIcon } from '@iconify/vue'
import {twMerge} from 'tailwind-merge'
defineOptions({name: 'MalioInputText', inheritAttrs: false})
@@ -102,10 +81,9 @@ const props = withDefaults(
name?: string
autocomplete?: string
modelValue?: string | null | undefined
minWidth?: string
maxWidth?: string
textInput?: string
textLabel?: string
inputClass?: string
labelClass?: string
groupClass?: string
required?: boolean
maxLength?: number | string
minLength?: number | string
@@ -116,7 +94,7 @@ const props = withDefaults(
success?: string
iconName?: string
iconPosition?: 'left' | 'right'
rounded?: string
iconSize?: string | number
iconColor?: string
mask?: string | MaskInputOptions
@@ -129,16 +107,14 @@ const props = withDefaults(
iconName: '',
iconPosition: 'right',
label: '',
minWidth: 'w-96',
maxWidth: '',
textInput: 'text-lg',
inputClass: '',
labelClass: '',
groupClass: '',
required: false,
maxLength: undefined,
minLength: undefined,
readonly: false,
textLabel: 'text-sm',
disabled: false,
rounded: 'rounded-md',
hint: '',
error: '',
success: '',
@@ -159,6 +135,42 @@ const currentValue = computed(() => (isControlled.value ? (props.modelValue ?? '
const shouldFloatLabel = computed(() => isFocused.value || currentValue.value.length > 0)
const hasError = computed(() => !!props.error)
const hasSuccess = computed(() => !!props.success)
const isFilled = computed(() => currentValue.value.trim().length > 0)
const mergedGroupClass = computed(() =>
twMerge(
'relative mt-4 flex h-12 w-full items-center',
props.groupClass,
),
)
const mergedInputClass = computed(() =>
twMerge(
'floating-input grow-height peer min-h-[40px] w-full border bg-white pl-3 pr-3 py-1 outline-none placeholder:text-transparent focus:border-2 text-lg rounded-md',
isFilled.value ? 'border-black' : 'border-m-muted',
disabled.value ? 'cursor-not-allowed text-black/60 [&:not(:placeholder-shown)]:border-m-muted border-m-muted' : 'cursor-text',
hasError.value
? 'border-m-error focus:border-m-error [&:not(:placeholder-shown)]:border-m-error'
: hasSuccess.value
? 'border-m-success focus:border-m-success [&:not(:placeholder-shown)]:border-m-success'
: 'focus:border-m-primary',
props.inputClass,
iconInputPaddingClass.value,
focusPaddingClass.value,
),
)
const mergedLabelClass = computed(() =>
twMerge(
'floating-label absolute top-2 mt-[5px] inline-block origin-left transition-transform duration-150 font-medium text-sm',
labelPositionClass.value,
shouldFloatLabel.value ? '-translate-y-[1.25rem] peer-focus:-translate-y-[1.55rem] scale-90' : '',
disabled.value ? 'peer-[&:not(:placeholder-shown):not(:focus)]:text-black/60' : '',
hasError.value
? 'text-m-error'
: hasSuccess.value
? 'text-m-success'
: 'peer-placeholder-shown:text-m-muted peer-[&:not(:placeholder-shown):not(:focus)]:text-black peer-focus:text-m-primary',
props.labelClass,
),
)
const describedBy = computed(() => {
const ids: string[] = []
@@ -185,6 +197,8 @@ const iconInputPaddingClass = computed(() => {
return props.iconPosition === 'left' ? '!pl-11 !pr-3' : '!pl-3'
})
const disabled = computed(() => props.disabled)
const labelPositionClass = computed(() => {
if (props.iconName && props.iconPosition === 'left') return 'left-8'
return 'left-3'

View File

@@ -0,0 +1,152 @@
import {describe, expect, it} from 'vitest'
import {mount} from '@vue/test-utils'
import type {DefineComponent} from 'vue'
import InputTextArea from './InputTextArea.vue'
type InputTextAreaProps = {
id?: string
label?: string
name?: string
autocomplete?: string
modelValue?: string | null
size?: number | string
textInput?: string
textLabel?: string
required?: boolean
maxLength?: number
showCounter?: boolean
disabled?: boolean
readonly?: boolean
hint?: string
error?: string
success?: string
rounded?: string
}
const InputTextAreaForTest = InputTextArea as DefineComponent<InputTextAreaProps>
describe('MalioInputTextArea', () => {
it('renders the initial textarea value', () => {
const wrapper = mount(InputTextAreaForTest, {
props: {modelValue: 'initial textarea value'},
})
expect(wrapper.get('textarea').element.value).toBe('initial textarea value')
})
it('renders the label text and reuses a provided id', () => {
const wrapper = mount(InputTextAreaForTest, {
props: {id: 'custom-textarea-id', label: 'Description'},
})
expect(wrapper.get('textarea').attributes('id')).toBe('custom-textarea-id')
expect(wrapper.get('label').attributes('for')).toBe('custom-textarea-id')
expect(wrapper.get('label').text()).toBe('Description')
})
it('generates an id when missing', () => {
const wrapper = mount(InputTextAreaForTest, {
props: {label: 'Description'},
})
const textareaId = wrapper.get('textarea').attributes('id')
expect(textareaId?.startsWith('malio-input-textarea-')).toBe(true)
expect(wrapper.get('label').attributes('for')).toBe(textareaId)
})
it('applies name, autocomplete and rows attributes', () => {
const wrapper = mount(InputTextAreaForTest, {
props: {name: 'bio', autocomplete: 'on', size: 4},
})
expect(wrapper.get('textarea').attributes('name')).toBe('bio')
expect(wrapper.get('textarea').attributes('autocomplete')).toBe('on')
expect(wrapper.get('textarea').attributes('rows')).toBe('4')
})
it('sets required, readonly and disabled attributes', () => {
const wrapper = mount(InputTextAreaForTest, {
props: {
required: true,
readonly: true,
disabled: true,
},
})
expect(wrapper.get('textarea').attributes('required')).toBeDefined()
expect(wrapper.get('textarea').attributes('readonly')).toBeDefined()
expect(wrapper.get('textarea').attributes('disabled')).toBeDefined()
expect(wrapper.get('textarea').classes()).toContain('cursor-not-allowed')
})
it('emits update:modelValue on input change', async () => {
const wrapper = mount(InputTextAreaForTest, {
props: {modelValue: ''},
})
await wrapper.get('textarea').setValue('new textarea value')
expect(wrapper.emitted('update:modelValue')?.[0]).toEqual(['new textarea value'])
})
it('shows the character counter when enabled', () => {
const wrapper = mount(InputTextAreaForTest, {
props: {
modelValue: 'hello',
showCounter: true,
maxLength: 20,
},
})
expect(wrapper.get('span.text-xs').text()).toBe('5/20')
expect(wrapper.get('textarea').classes()).toContain('pb-6')
})
it('shows hint message in muted color', () => {
const wrapper = mount(InputTextAreaForTest, {
props: {hint: 'Helpful hint'},
})
expect(wrapper.get('p.text-m-muted').text()).toBe('Helpful hint')
})
it('shows error state on textarea and label', () => {
const wrapper = mount(InputTextAreaForTest, {
props: {
label: 'Description',
error: 'Textarea error',
},
})
expect(wrapper.get('textarea').classes()).toContain('border-m-error')
expect(wrapper.get('label').classes()).toContain('text-m-error')
expect(wrapper.get('p.text-m-error').text()).toBe('Textarea error')
expect(wrapper.get('textarea').attributes('aria-invalid')).toBe('true')
})
it('shows success state on textarea and label', () => {
const wrapper = mount(InputTextAreaForTest, {
props: {
label: 'Description',
success: 'Textarea success',
},
})
expect(wrapper.get('textarea').classes()).toContain('border-m-success')
expect(wrapper.get('label').classes()).toContain('text-m-success')
expect(wrapper.get('p.text-m-success').text()).toBe('Textarea success')
})
it('prioritizes error over success', () => {
const wrapper = mount(InputTextAreaForTest, {
props: {
error: 'Textarea error',
success: 'Textarea success',
},
})
expect(wrapper.get('textarea').classes()).toContain('border-m-error')
expect(wrapper.find('p.text-m-success').exists()).toBe(false)
expect(wrapper.get('p.text-m-error').text()).toBe('Textarea error')
})
})

View File

@@ -9,12 +9,13 @@
:autocomplete="autocomplete"
class="floating-input peer w-full border bg-white pl-3 pr-3 py-1 outline-none placeholder:text-transparent focus:border-2 overflow-auto"
:class="[
isFilled ? 'border-black' : 'border-m-muted',
disabled ? 'cursor-not-allowed text-black/60 border-m-muted' : 'cursor-text',
hasError
? 'border-m-error focus:border-m-error focus:pl-[11px]'
: hasSuccess
? 'border-m-success focus:border-m-success focus:pl-[11px]'
: 'border-m-muted focus:border-m-primary focus:pl-[11px]',
: 'focus:border-m-primary focus:pl-[11px]',
textInput,
showCounterComputed ? 'pb-6' : '',
rounded,
@@ -39,7 +40,7 @@
:for="inputId"
class="floating-label absolute left-3 top-2 mt-1 inline-block origin-left transition-transform duration-150 font-medium"
:class="[
shouldFloatLabel ? '-translate-y-[1.15rem] scale-90' : '',
shouldFloatLabel ? '-translate-y-[1.30rem] scale-90' : '',
disabled ? 'text-black/60' : '',
hasError
? 'text-m-error'
@@ -159,7 +160,7 @@ const textareaStyle = computed(() => ({
minHeight: toCssSize(props.minResizeHeight),
maxHeight: toCssSize(props.maxResizeHeight),
}))
const isFilled = computed(() => currentValue.value.trim().length > 0)
const describedBy = computed(() =>
(hasError.value || hasSuccess.value || !!props.hint) ? `${inputId.value}-describedby` : undefined,
)

View File

@@ -0,0 +1,177 @@
import {describe, expect, it} from 'vitest'
import {mount} from '@vue/test-utils'
import type {DefineComponent} from 'vue'
import Select from './Select.vue'
type Option = {
label: string
value: string | number | null
}
type SelectProps = {
modelValue?: string | number | null
options?: Option[]
emptyOptionLabel?: string
label?: string
hint?: string
error?: string
success?: string
minWidth?: string
maxWidth?: string
textField?: string
textValue?: string
textLabel?: string
rounded?: string
disabled?: boolean
}
const SelectForTest = Select as DefineComponent<SelectProps>
const options: Option[] = [
{label: 'France', value: 'fr'},
{label: 'Belgique', value: 'be'},
{label: 'Canada', value: 'ca'},
]
describe('MalioSelect', () => {
it('renders the label text', () => {
const wrapper = mount(SelectForTest, {
props: {modelValue: null, label: 'Country'},
})
expect(wrapper.get('label').text()).toBe('Country')
})
it('generates button and listbox ids and links them together', async () => {
const wrapper = mount(SelectForTest, {
props: {modelValue: null, options},
})
const button = wrapper.get('button')
expect(button.attributes('id')?.startsWith('custom-select-btn-')).toBe(true)
expect(button.attributes('aria-controls')?.startsWith('custom-select-listbox-')).toBe(true)
await button.trigger('click')
expect(wrapper.get('ul').attributes('id')).toBe(button.attributes('aria-controls'))
})
it('uses disabled styles and prevents opening when disabled', async () => {
const wrapper = mount(SelectForTest, {
props: {modelValue: null, disabled: true, options},
})
const button = wrapper.get('button')
expect(button.attributes('disabled')).toBeDefined()
expect(button.classes()).toContain('cursor-not-allowed')
await button.trigger('click')
expect(wrapper.find('ul').exists()).toBe(false)
})
it('opens the list and rotates the icon on click', async () => {
const wrapper = mount(SelectForTest, {
props: {modelValue: null, options},
})
await wrapper.get('button').trigger('click')
expect(wrapper.get('ul').exists()).toBe(true)
expect(wrapper.get('button').attributes('aria-expanded')).toBe('true')
expect(wrapper.get('svg').classes()).toContain('rotate-180')
})
it('emits update:modelValue when selecting an option', async () => {
const wrapper = mount(SelectForTest, {
props: {modelValue: null, options},
})
await wrapper.get('button').trigger('click')
await wrapper.findAll('li')[2].trigger('click')
expect(wrapper.emitted('update:modelValue')?.[0]).toEqual(['be'])
})
it('renders the empty option with muted text style', async () => {
const wrapper = mount(SelectForTest, {
props: {
modelValue: null,
options,
emptyOptionLabel: 'Aucune selection',
},
})
await wrapper.get('button').trigger('click')
const firstOption = wrapper.findAll('li')[0]
expect(firstOption.text()).toBe('Aucune selection')
expect(firstOption.classes()).toContain('text-black/40')
})
it('shows the selected value text when an option is selected', () => {
const wrapper = mount(SelectForTest, {
props: {
options,
modelValue: 'fr',
},
})
expect(wrapper.text()).toContain('France')
expect(wrapper.get('button').classes()).toContain('border-black')
})
it('shows hint message in muted color', () => {
const wrapper = mount(SelectForTest, {
props: {modelValue: null, hint: 'Select a country'},
})
expect(wrapper.get('p.text-m-muted').text()).toBe('Select a country')
})
it('shows error state on button, label and helper text', () => {
const wrapper = mount(SelectForTest, {
props: {
modelValue: null,
options,
label: 'Country',
error: 'Selection error',
},
})
expect(wrapper.get('button').classes()).toContain('border-m-error')
expect(wrapper.get('label').classes()).toContain('text-m-error')
expect(wrapper.get('p.text-m-error').text()).toBe('Selection error')
expect(wrapper.get('button').attributes('aria-invalid')).toBe('true')
})
it('shows success state on button, label and helper text', () => {
const wrapper = mount(SelectForTest, {
props: {
modelValue: null,
options,
label: 'Country',
success: 'Selection success',
},
})
expect(wrapper.get('button').classes()).toContain('border-m-success')
expect(wrapper.get('label').classes()).toContain('text-m-success')
expect(wrapper.get('p.text-m-success').text()).toBe('Selection success')
})
it('prioritizes error over success', () => {
const wrapper = mount(SelectForTest, {
props: {
modelValue: null,
options,
error: 'Selection error',
success: 'Selection success',
},
})
expect(wrapper.get('button').classes()).toContain('border-m-error')
expect(wrapper.find('p.text-m-success').exists()).toBe(false)
expect(wrapper.get('p.text-m-error').text()).toBe('Selection error')
})
})

View File

@@ -0,0 +1,333 @@
<template>
<div
ref="root"
class="relative mt-4 w-full"
:class="[minWidth, maxWidth]"
>
<button
:id="buttonId"
type="button"
class="grow-height peer relative w-full border bg-white pl-3 pr-10 py-1 text-left outline-none focus-visible:border-2 focus-visible:border-m-primary"
:class="[
hasError
? isOpen
? openDirection === 'down'
? 'rounded-b-none !border-2 !border-m-error !border-b-0'
: 'rounded-t-none !border-2 !border-m-error !border-t-0'
: 'border-m-error'
: hasSuccess
? isOpen
? openDirection === 'down'
? 'rounded-b-none !border-2 !border-m-success !border-b-0'
: 'rounded-t-none !border-2 !border-m-success !border-t-0'
: 'border-m-success'
: isOpen
? openDirection === 'down'
? 'rounded-b-none !border-2 !border-m-primary !border-b-0'
: 'rounded-t-none !border-2 !border-m-primary !border-t-0'
: isOptionSelected
? 'border-black'
: 'border-m-muted',
disabled ? 'cursor-not-allowed border-m-muted text-black/60' : 'cursor-pointer',
label ? 'min-h-[40px]' : 'h-[40px] py-0',
rounded,
textField,
]"
:aria-expanded="isOpen"
:aria-controls="listboxId"
:aria-invalid="hasError"
:aria-describedby="describedBy"
:disabled="disabled"
@click="toggle"
>
<label
v-if="label"
class="floating-label pointer-events-none absolute left-3 inline-block origin-left transition-transform duration-150 font-medium"
:class="[
isOpen ? 'top-2 z-30' : 'top-2',
hasError
? 'text-m-error'
: hasSuccess
? 'text-m-success'
: isOpen
? 'text-m-primary'
: isOptionSelected
? 'text-black'
: 'text-m-muted',
textLabel,
]"
:style="labelTransformStyle"
>
{{ label }}
</label>
<span
class="block truncate"
:class="[
textValue,
isOptionSelected ? 'text-black' : 'select-none text-transparent'
]"
>
{{ selectedLabel || '\u00A0' }}
</span>
<span
class="absolute right-3 top-1/2 -translate-y-1/2"
:class="[
hasError
? 'text-m-error'
: hasSuccess
? 'text-m-success'
: 'text-current'
]"
>
<slot name="icon">
<IconifyIcon
icon="mdi:chevron-down"
width="20"
class="transition-transform duration-300"
:class="isOpen ? 'rotate-180' : 'rotate-0'"
/>
</slot>
</span>
</button>
<ul
v-if="isOpen"
:id="listboxId"
ref="listRef"
role="listbox"
:aria-labelledby="buttonId"
class="absolute left-0 right-0 z-20 max-h-60 w-full overflow-auto border-2 bg-white"
:class="[
openDirection === 'down'
? 'top-[calc(100%-2px)] rounded-b-md border-t-0'
: 'bottom-[calc(100%-2px)] rounded-t-md border-b-0',
hasError
? 'select-scrollbar-error'
: hasSuccess
? 'select-scrollbar-success'
: 'select-scrollbar-primary',
hasError
? 'border-m-error'
: hasSuccess
? 'border-m-success'
: 'border-m-primary'
]"
>
<li
v-for="(opt, index) in normalizedOptions"
:id="optionId(index)"
:key="String(opt.value)"
role="option"
:aria-selected="opt.value === modelValue"
class="cursor-pointer px-3 py-2"
:class="[
index === activeIndex ? 'bg-m-muted/10' : '',
opt.value === modelValue ? 'bg-m-muted/10 font-semibold' : '',
opt.value === null ? 'text-black/40' : 'text-black'
]"
@mouseenter="activeIndex = index"
@mousedown.prevent
@click="select(opt.value)"
>
{{ opt.label || '\u00A0' }}
</li>
</ul>
</div>
<p
v-if="hint || hasError || hasSuccess"
:id="`${buttonId}-describedby`"
:class="[
hasError
? 'text-m-error'
: hasSuccess
? 'text-m-success'
: 'text-m-muted',
'mt-1 ml-[2px] text-xs',
]"
>
{{ error || success || hint }}
</p>
</template>
<script setup lang="ts">
import {computed, onBeforeUnmount, onMounted, ref, useId, nextTick} from 'vue'
import {Icon as IconifyIcon} from '@iconify/vue'
defineOptions({name: 'MalioSelect', inheritAttrs: false})
type Option = {
label: string;
value: string | number | null
}
const props = withDefaults(defineProps<{
modelValue: string | number | null
options?: Option[]
emptyOptionLabel?: string
label?: string
hint?: string
error?: string
success?: string
minWidth?: string
maxWidth?: string
textField?: string
textValue?: string
textLabel?: string
rounded?: string
disabled?: boolean
}>(), {
options: () => [],
emptyOptionLabel: '',
label: '',
hint: '',
error: '',
success: '',
minWidth: 'w-96',
maxWidth: '',
textField: 'text-lg',
textValue: 'text-lg',
textLabel: 'text-sm',
rounded: 'rounded-md',
disabled: false,
})
const emit = defineEmits<{
(e: 'update:modelValue', v: string | number | null): void
}>()
const root = ref<HTMLElement | null>(null)
const isOpen = ref(false)
const activeIndex = ref(-1)
const openDirection = ref<'down' | 'up'>('down')
const uid = useId()
const buttonId = `custom-select-btn-${uid}`
const listboxId = `custom-select-listbox-${uid}`
const listRef = ref<HTMLElement | null>(null)
const listHeight = ref(0)
const normalizedOptions = computed<Option[]>(() => [
{label: props.emptyOptionLabel, value: null},
...props.options,
])
const hasError = computed(() => !!props.error)
const hasSuccess = computed(() => !!props.success && !hasError.value)
const isOptionSelected = computed(() =>
props.options.some(o => o.value === props.modelValue)
)
const shouldFloatLabel = computed(() =>
isOpen.value || isOptionSelected.value
)
const selectedLabel = computed(() =>
props.options.find(o => o.value === props.modelValue)?.label ?? ''
)
const describedBy = computed(() =>
(hasError.value || hasSuccess.value || !!props.hint) ? `${buttonId}-describedby` : undefined,
)
function optionId(index: number) {
return `custom-select-opt-${uid}-${index}`
}
function updateOpenDirection() {
if (!root.value) return
const rect = root.value.getBoundingClientRect()
const estimatedListHeight = Math.min(normalizedOptions.value.length * 40, 240)
const spaceBelow = window.innerHeight - rect.bottom
const spaceAbove = rect.top
openDirection.value =
spaceBelow >= estimatedListHeight || spaceBelow >= spaceAbove
? 'down'
: 'up'
}
function open() {
updateOpenDirection()
isOpen.value = true
const selectedIndex = normalizedOptions.value.findIndex(o => o.value === props.modelValue)
activeIndex.value = selectedIndex >= 0 ? selectedIndex : 0
nextTick(() => {
if (openDirection.value === 'up' && listRef.value) {
listHeight.value = listRef.value.offsetHeight
} else {
listHeight.value = 0
}
})
}
const labelTransformStyle = computed(() => {
// label non flottant
if (!shouldFloatLabel.value) {
return {}
}
// fermé ou ouverture vers le bas : comportement classique
if (!isOpen.value || openDirection.value === 'down') {
return {
transform: 'translateY(-1.15rem) scale(0.9)',
}
}
// ouverture vers le haut : on remonte en fonction de la hauteur de la liste
const extraOffset = 8 // marge visuelle au-dessus de la liste en px
const total = 4 +listHeight.value + extraOffset
// 18 ≈ 1.15rem pour garder la même base que votre flottant actuel
return {
transform: `translateY(-${total}px) scale(0.9)`,
}
})
function close() {
isOpen.value = false
}
function toggle() {
if (props.disabled) return
if (isOpen.value) {
close()
return
}
open()
}
function select(value: string | number | null) {
emit('update:modelValue', value)
close()
}
function onClickOutside(e: MouseEvent) {
if (!root.value) return
if (!root.value.contains(e.target as Node)) close()
}
onMounted(() => document.addEventListener('mousedown', onClickOutside))
onBeforeUnmount(() => document.removeEventListener('mousedown', onClickOutside))
</script>
<style scoped>
.floating-label {
background: white;
padding: 0 0.25rem;
}
:deep(ul[role="listbox"]) {
scrollbar-width: auto;
scrollbar-gutter: stable;
}
:deep(.select-scrollbar-primary) {
scrollbar-color: rgb(var(--m-primary)) transparent;
}
:deep(.select-scrollbar-error) {
scrollbar-color: #000000 transparent;
}
:deep(.select-scrollbar-success) {
scrollbar-color: #000000 transparent;
}
</style>

View File

@@ -0,0 +1,148 @@
<template>
<Story
title="Select"
>
<MalioSelect
v-model="value"
:options="options"
/>
</Story>
</template>
<docs lang="md">
# MalioSelect
Composant select personnalisé avec label flottant, option vide,
états visuels selon la sélection et ouverture/fermeture contrôlée.
------------------------------------------------------------------------
## Props détaillées
### modelValue
- Type: string | number | null
- Description: Valeur actuellement sélectionnée.
- Comportement:
- Compatible avec `v-model`.
- Peut valoir `null` pour représenter loption vide.
### options
- Type: Array<{ label: string; value: string | number | null }>
- Description: Liste des options affichées dans le menu.
- Défaut: tableau vide.
### emptyOptionLabel
- Type: string
- Description: Texte de loption vide injectée automatiquement.
- Comportement:
- Cette option porte toujours la valeur `null`.
- Si la prop est vide, loption reste visuellement discrète.
### label
- Type: string
- Description: Texte affiché comme label flottant au-dessus du champ.
- Comportement: Si absent, aucun label nest rendu.
------------------------------------------------------------------------
## Apparence & Style
### textField
- Type: string
- Description: Classes CSS appliquées au bouton du select.
### textValue
- Type: string
- Description: Classes CSS appliquées à la valeur affichée.
### textLabel
- Type: string
- Description: Classes CSS appliquées au label flottant.
### rounded
- Type: string
- Description: Classe Tailwind pour le border-radius.
- Défaut: rounded-md
### minWidth / maxWidth
- Type: string
- Description: Classes utilitaires Tailwind pour contraindre la
largeur.
------------------------------------------------------------------------
## Interaction
### disabled
- Type: boolean
- Description: Désactive complètement le composant.
- Effet:
- Empêche louverture du menu.
- Applique un style visuel désactivé.
------------------------------------------------------------------------
## Comportement visuel
- Au repos sans sélection: bordure grise.
- Ouvert: bordure et label en couleur primaire.
- Fermé avec valeur sélectionnée: bordure et texte en noir.
- Loption vide dans la liste peut être stylée différemment pour être
distinguée des autres.
------------------------------------------------------------------------
## Accessibilité
- Le bouton porte `aria-expanded` et `aria-controls`.
- La liste utilise `role="listbox"`.
- Chaque option utilise `role="option"` et `aria-selected`.
------------------------------------------------------------------------
## Events
### update:modelValue
- Émis à chaque sélection dans la liste.
- Permet lutilisation avec v-model.
- Peut émettre `null` si loption vide est sélectionnée.
</docs>
<script setup lang="ts">
import { ref } from 'vue'
import MalioSelect from '../components/malio/Select.vue'
const value = ref<string | number | null>(null)
const options = [
{ label: 'France', value: 'fr' },
{ label: 'Belgique', value: 'be' },
{ label: 'Suisse', value: 'ch' },
{ label: 'Canada', value: 'ca' },
{ label: 'Allemagne', value: 'de' },
{ label: 'Espagne', value: 'es' },
{ label: 'Italie', value: 'it' },
{ label: 'Portugal', value: 'pt' },
{ label: 'Pays-Bas', value: 'nl' },
{ label: 'Suède', value: 'se' },
{ label: 'Norvège', value: 'no' },
{ label: 'Danemark', value: 'dk' },
{ label: 'Finlande', value: 'fi' },
{ label: 'Autriche', value: 'at' },
{ label: 'Irlande', value: 'ie' },
{ label: 'Grèce', value: 'gr' },
{ label: 'Pologne', value: 'pl' },
{ label: 'Hongrie', value: 'hu' },
{ label: 'République tchèque', value: 'cz' },
]
</script>

13
package-lock.json generated
View File

@@ -10,7 +10,8 @@
"dependencies": {
"@nuxt/icon": "^2.2.1",
"@nuxtjs/tailwindcss": "^6.14.0",
"maska": "^3.2.0"
"maska": "^3.2.0",
"tailwind-merge": "^3.3.1"
},
"devDependencies": {
"@histoire/plugin-vue": "^1.0.0-beta.1",
@@ -15122,6 +15123,16 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/tailwind-merge": {
"version": "3.5.0",
"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.5.0.tgz",
"integrity": "sha512-I8K9wewnVDkL1NTGoqWmVEIlUcB9gFriAEkXkfCjX5ib8ezGxtR3xD7iZIxrfArjEsH7F1CHD4RFUtxefdqV/A==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/dcastil"
}
},
"node_modules/tailwindcss": {
"version": "3.4.19",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.19.tgz",

View File

@@ -40,6 +40,7 @@
"dependencies": {
"@nuxt/icon": "^2.2.1",
"@nuxtjs/tailwindcss": "^6.14.0",
"maska": "^3.2.0"
"maska": "^3.2.0",
"tailwind-merge": "^3.3.1"
}
}

View File

@@ -7,11 +7,6 @@ export default {
'./histoire.setup.ts',
'./histoire.config.ts',
],
safelist: [
{
pattern: /(sm:|md:|lg:|xl:|2xl:)?(text|rounded|w|min-w|max-w)-.+/,
},
],
theme: {
extend: {
borderRadius: {