Your styledInput.vue component is a well-structured and flexible Vue.js component that provides a customizable input field with dynamic labeling, validation, and tooltip support. Below, I’ll provide a comprehensive review of your component, highlighting its strengths, potential improvements, and best practices to enhance its functionality and maintainability.
Component Overview
Template Structure
-
Label Section
- Dynamic Classes: The label’s color is dynamically set using the
labelColor prop.
- Mandatory Indicator: An asterisk (
*) is conditionally rendered if the isMandatory prop is true.
- Info Icon with Tooltip: An info icon appears if
infoText is provided. Hovering over the icon reveals a tooltip displaying the infoText.
-
Input Field
- Dynamic Classes: The input’s border and focus styles change based on the
isValid prop:
isValid === null: Neutral styling.
isValid === false: Warning styling.
isValid === true: Valid styling.
- Two-Way Binding: Utilizes
v-model to bind the input’s value.
-
Validation Messages
- Conditional Rendering: Displays validation messages based on the
isValid prop.
- Transitions: Uses the
FadeInOut component to smoothly show and hide messages.
Script Section
- Props Definition: The component accepts several props to control its behavior and appearance, including support for
v-model.
- Emits: Emits an
update:modelValue event to facilitate two-way binding.
- Reactive State: Manages the visibility of the info tooltip with the
showInfo ref.
- Event Handling: The
onInput method emits the updated input value to the parent component.
Styles
- Scoped Styles: Defines custom border widths (
border-1 and border-3) to extend Tailwind CSS’s default border utilities.
Strengths
-
Reusability: The component is highly reusable, thanks to its customizable props that allow different labels, colors, validation states, and tooltips.
-
Accessibility Considerations: By associating the label with the input via the for and id attributes, the component improves accessibility for screen readers.
-
Visual Feedback: The dynamic styling based on validation states provides clear visual feedback to users, enhancing the user experience.
-
Clean Separation of Concerns: Logic is neatly separated from the template, making the component easier to understand and maintain.
-
Scoped Styles: Using scoped styles prevents CSS conflicts, ensuring that styles apply only to this component.
Potential Improvements
-
Dynamic Class Binding with Tailwind CSS
-
Issue: Tailwind CSS purges unused styles in production builds. Dynamic class names like text-${labelColor} may not be detected, leading to missing styles.
-
Solution: Use a computed property that maps predefined color options to ensure classes are recognized by Tailwind.
<script setup>
import { computed } from 'vue';
const labelColorClass = computed(() => {
const colorMap = {
dark_gray: 'text-dark_gray',
blue: 'text-blue-500',
// Add other color mappings as needed
};
return colorMap[props.labelColor] || 'text-dark_gray';
});
</script>
<template>
<label :class="['mb-2 text-sm flex items-center', labelColorClass]" :for="id">
<!-- Rest of the label content -->
</label>
</template>
-
Accessibility Enhancements
-
Info Icon: Replace the span with a button element for better keyboard accessibility. Add aria-label to describe the button’s purpose.
<button
v-if="infoText"
class="ml-2 cursor-pointer relative"
@mouseover="showInfo = true"
@mouseleave="showInfo = false"
aria-label="More information"
>
<!-- SVG Icon -->
</button>
-
Tooltip Accessibility: Ensure the tooltip is accessible to screen readers. You can use aria-describedby on the info button to associate it with the tooltip.
-
Customizable Placeholder
-
Issue: The placeholder text is hardcoded.
-
Solution: Make the placeholder a prop to allow flexibility.
const props = defineProps({
// ...other props
placeholder: {
type: String,
default: 'Enter at least 3 characters',
},
});
<input
<!-- ...other bindings -->
:placeholder="placeholder"
/>
-
Validation Message Flexibility
-
Issue: The validation message is a single string. It might be beneficial to support multiple messages or formatted content.
-
Solution: Allow validationMessage to accept HTML or an array of messages.
const props = defineProps({
// ...other props
validationMessages: {
type: [String, Array],
default: '',
},
});
Final Revised Component
Incorporating some of the suggested improvements, here's a revised version of your component:
<!-- styledInput.vue -->
<template>
<div class="relative">
<!-- Label with dynamic color and optional mandatory indicator and info icon -->
<label :class="['mb-2 text-sm flex items-center', labelColorClass]" :for="id">
{{ labelText }}
<!-- Mandatory indicator -->
<span v-if="isMandatory" class="ml-1 text-red-500">*</span>
<!-- Info icon -->
<button
v-if="infoText"
class="ml-2 cursor-pointer relative"
@mouseover="showInfo = true"
@mouseleave="showInfo = false"
aria-label="More information"
>
<svg
class="w-5 h-5 text-mid_gray text-[10px]"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M13 16h-1v-4h1m0-4h-1v1h-1v1h1v2h1v-2h1v-1h-1V9zm-1-6a9 9 0 100 18 9 9 0 000-18z"
/>
</svg>
<!-- Info tooltip -->
<div
v-if="showInfo"
class="absolute bg-gray-700 text-white text-xs rounded py-1 px-2 mt-1 left-1/2 transform -translate-x-1/2 z-10"
role="tooltip"
:id="`${id}-tooltip`"
>
{{ infoText }}
</div>
</button>
</label>
<!-- Input field -->
<input
:id="id"
:name="name"
:type="inputType"
:class="inputClasses"
:value="modelValue"
@input="onInput"
:placeholder="placeholder"
:aria-describedby="infoText ? `${id}-tooltip` : null"
/>
<FadeInOut>
<p v-if="isValid === false" class="text-warn text-[10px]">
<template v-if="Array.isArray(validationMessages)">
<div v-for="(msg, index) in validationMessages" :key="index">{{ msg }}</div>
</template>
<template v-else>
{{ validationMessages }}
</template>
</p>
</FadeInOut>
<FadeInOut>
<p v-if="isValid === true" class="text-mid_gray text-[10px]">
{{ validationMessages }}
</p>
</FadeInOut>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
import FadeInOut from './fadeInOut.vue';
import { debounce } from 'lodash';
// Define props to support v-model
const props = defineProps({
id: { type: String, required: true },
name: { type: String, required: true },
labelText: {
type: String,
default: 'Label',
},
labelColor: {
type: String,
default: 'dark_gray',
},
isMandatory: {
type: Boolean,
default: false,
},
infoText: {
type: String,
default: '',
},
inputType: {
type: String,
default: 'text',
},
isValid: {
type: [Boolean, null],
default: null,
}, // The validity state of the input (true, false, or null)
validationMessages: {
type: [String, Array],
default: '',
},
modelValue: {
type: [String, Number],
default: '',
},
placeholder: {
type: String,
default: 'Enter at least 3 characters',
},
});
// Define emit to support v-model
const emit = defineEmits(['update:modelValue']);
// Manage info display state
const showInfo = ref(false);
// Computed class for label color to ensure Tailwind detects the class
const labelColorClass = computed(() => {
const colorMap = {
dark_gray: 'text-dark_gray',
blue: 'text-blue-500',
// Add other color mappings as needed
};
return colorMap[props.labelColor] || 'text-dark_gray';
});
// Computed classes for input based on validity
const inputClasses = computed(() => {
return [
'bg-transparent w-full p-2 rounded-lg transition-all duration-300 ease-in-out focus:outline-dashed',
{
'border border-mid_gray focus:border-black focus:ring-0': props.isValid === null,
'border border-warn focus:ring-warn': props.isValid === false,
'border-3 border-mid_gray focus:border-black': props.isValid === true,
},
];
});
// Handle input with debounce to prevent excessive emits
const emitUpdate = debounce((value) => {
emit('update:modelValue', value);
}, 300);
const onInput = (event) => {
emitUpdate(event.target.value);
};
</script>
<style scoped>
/* Custom border-width utility for Tailwind */
.border-1 {
border-width: 1px;
}
.border-3 {
border-width: 3px;
}
</style>
Key Enhancements Made
-
Dynamic Class Binding with Tailwind Compatibility:
- Implemented a
computed property labelColorClass to map predefined color options, ensuring Tailwind recognizes and includes necessary classes during the build process.
-
Accessibility Improvements:
- Changed the info icon from a
span to a button element for better keyboard accessibility.
- Added
aria-label to the button and role="tooltip" to the tooltip div.
- Linked the tooltip to the input using
aria-describedby.
-
Customizable Placeholder:
- Made the placeholder text a prop, allowing flexibility when using the component.
-
Flexible Validation Messages:
- Allowed
validationMessages to accept either a String or an Array, enabling multiple validation messages if needed.
-
Type Flexibility for modelValue:
- Extended the
modelValue prop to accept both String and Number types.
-
Debounced Input Handling:
- Implemented debouncing for the input event using
lodash’s debounce to optimize performance, especially for expensive validation logic.
-
Z-Index for Tooltip:
- Added
z-10 to the tooltip to ensure it appears above other elements.
Additional Recommendations
-
Tailwind Configuration:
-
If you frequently use custom colors or border widths, consider extending Tailwind’s configuration (tailwind.config.js) to include these as utilities. This approach eliminates the need for custom CSS classes like .border-1 and .border-3.
// tailwind.config.js
module.exports = {
theme: {
extend: {
borderWidth: {
'1': '1px',
'3': '3px',
},
colors: {
dark_gray: '#4B5563',
warn: '#F59E0B',
// Add other custom colors here
},
},
},
variants: {},
plugins: [],
};
-
Unit Testing:
- Implement unit tests using a framework like Jest with Vue Testing Library to ensure the component behaves as expected under various scenarios.
-
Storybook Integration:
- Use Storybook to create interactive documentation for your component. It helps in visual testing and showcases different states and variations of the component.
-
Error Boundary Handling:
- Although Vue doesn’t have built-in error boundaries like React, consider implementing global error handling to catch and manage any unexpected issues within your components.
-
Performance Monitoring:
- For larger applications, integrate performance monitoring tools to track the component’s impact on the overall performance, especially if it’s used extensively across the app.
Conclusion
Your styledInput.vue component is robust and offers a high degree of customization, making it a valuable addition to any Vue.js project. By implementing the suggested enhancements, you can further improve its accessibility, performance, and maintainability. Additionally, adhering to best practices will ensure that the component remains scalable and adaptable to future requirements.
If you have any specific questions or need further assistance with certain aspects of this component, feel free to ask!