Textarea
A textarea element to input multi-line text.
Demo
Related Composables
This requires the following composables to be installed:
Related Utils
This requires the following utils to be installed:
Related Theme
This requires the following theme to be installed:
Component
vue
<script lang="ts">
import type { VariantProps } from 'tailwind-variants'
import { useFormField } from '@/ui/composables/useFormField'
import theme from '@/ui/theme/textarea'
import { looseToNumber } from '@/ui/utils/loose-to-number'
import { Primitive } from 'reka-ui'
import { tv } from 'tailwind-variants'
import { computed, nextTick, onMounted, ref, watch } from 'vue'
const textarea = tv(theme)
type TextareaVariants = VariantProps<typeof textarea>
export interface TextareaProps {
as?: any
id?: string
name?: string
placeholder?: string
color?: TextareaVariants['color']
variant?: TextareaVariants['variant']
size?: TextareaVariants['size']
required?: boolean
autofocus?: boolean
autofocusDelay?: number
disabled?: boolean
class?: any
rows?: number
maxrows?: number
autoresize?: boolean
highlight?: boolean
ui?: Partial<typeof textarea.slots>
}
export interface TextareaEmits {
(e: 'update:modelValue', payload: string | number): void
(e: 'blur', event: FocusEvent): void
(e: 'change', event: Event): void
}
export interface TextareaSlots {
default: (props?: object) => any
}
</script>
<script setup lang="ts">
defineOptions({ inheritAttrs: false })
const props = withDefaults(defineProps<TextareaProps>(), {
rows: 3,
maxrows: 0,
autofocusDelay: 0,
})
const emits = defineEmits<TextareaEmits>()
defineSlots<TextareaSlots>()
const [modelValue, modelModifiers] = defineModel<string | number>()
const { size, color, id, name, highlight, disabled, ariaAttrs } = useFormField<TextareaProps>(props)
const ui = computed(() => textarea({
color: color.value,
variant: props.variant,
size: size?.value,
highlight: highlight.value,
}))
const textareaRef = ref<HTMLTextAreaElement | null>(null)
function autoFocus() {
if (props.autofocus) {
textareaRef.value?.focus()
}
}
// Custom function to handle the v-model properties
function updateInput(value: string) {
if (modelModifiers.trim) {
value = value.trim()
}
if (modelModifiers.number) {
value = looseToNumber(value)
}
modelValue.value = value
}
function onInput(event: Event) {
autoResize()
if (!modelModifiers.lazy) {
updateInput((event.target as HTMLInputElement).value)
}
}
function onChange(event: Event) {
const value = (event.target as HTMLInputElement).value
if (modelModifiers.lazy) {
updateInput(value)
}
// Update trimmed textarea so that it has same behavior as native textarea https://github.com/vuejs/core/blob/5ea8a8a4fab4e19a71e123e4d27d051f5e927172/packages/runtime-dom/src/directives/vModel.ts#L63
if (modelModifiers.trim) {
(event.target as HTMLInputElement).value = value.trim()
}
emits('change', event)
}
function onBlur(event: FocusEvent) {
emits('blur', event)
}
onMounted(() => {
setTimeout(() => {
autoFocus()
}, props.autofocusDelay)
})
function autoResize() {
if (props.autoresize) {
if (!textareaRef.value) {
return
}
textareaRef.value.rows = props.rows
const overflow = textareaRef.value.style.overflow
textareaRef.value.style.overflow = 'hidden'
const styles = window.getComputedStyle(textareaRef.value)
const paddingTop = Number.parseInt(styles.paddingTop)
const paddingBottom = Number.parseInt(styles.paddingBottom)
const padding = paddingTop + paddingBottom
const lineHeight = Number.parseInt(styles.lineHeight)
const { scrollHeight } = textareaRef.value
const newRows = (scrollHeight - padding) / lineHeight
if (newRows > props.rows) {
textareaRef.value.rows = props.maxrows ? Math.min(newRows, props.maxrows) : newRows
}
textareaRef.value.style.overflow = overflow
}
}
watch(modelValue, () => {
nextTick(autoResize)
})
defineExpose({
textareaRef,
})
onMounted(() => {
setTimeout(() => {
autoResize()
}, 100)
})
</script>
<template>
<Primitive :as="as" :class="ui.root({ class: [props.class, props.ui?.root] })">
<textarea
:id="id"
ref="textareaRef"
:value="modelValue"
:name="name"
:rows="rows"
:placeholder="placeholder"
:class="ui.base({ class: props.ui?.base })"
:disabled="disabled"
:required="required"
v-bind="{ ...$attrs, ...ariaAttrs }"
@input="onInput"
@blur="onBlur"
@change="onChange"
/>
<slot />
</Primitive>
</template>vue
<script lang="ts">
import type { VariantProps } from 'tailwind-variants'
import { useFormField } from '@/UI/Composables/useFormField'
import theme from '@/UI/Theme/textarea'
import { looseToNumber } from '@/UI/Utils/loose-to-number'
import { Primitive } from 'reka-ui'
import { tv } from 'tailwind-variants'
import { computed, nextTick, onMounted, ref, watch } from 'vue'
const textarea = tv(theme)
type TextareaVariants = VariantProps<typeof textarea>
export interface TextareaProps {
as?: any
id?: string
name?: string
placeholder?: string
color?: TextareaVariants['color']
variant?: TextareaVariants['variant']
size?: TextareaVariants['size']
required?: boolean
autofocus?: boolean
autofocusDelay?: number
disabled?: boolean
class?: any
rows?: number
maxrows?: number
autoresize?: boolean
highlight?: boolean
ui?: Partial<typeof textarea.slots>
}
export interface TextareaEmits {
(e: 'update:modelValue', payload: string | number): void
(e: 'blur', event: FocusEvent): void
(e: 'change', event: Event): void
}
export interface TextareaSlots {
default: (props?: object) => any
}
</script>
<script setup lang="ts">
defineOptions({ inheritAttrs: false })
const props = withDefaults(defineProps<TextareaProps>(), {
rows: 3,
maxrows: 0,
autofocusDelay: 0,
})
const emits = defineEmits<TextareaEmits>()
defineSlots<TextareaSlots>()
const [modelValue, modelModifiers] = defineModel<string | number>()
const { size, color, id, name, highlight, disabled, ariaAttrs } = useFormField<TextareaProps>(props)
const ui = computed(() => textarea({
color: color.value,
variant: props.variant,
size: size?.value,
highlight: highlight.value,
}))
const textareaRef = ref<HTMLTextAreaElement | null>(null)
function autoFocus() {
if (props.autofocus) {
textareaRef.value?.focus()
}
}
// Custom function to handle the v-model properties
function updateInput(value: string) {
if (modelModifiers.trim) {
value = value.trim()
}
if (modelModifiers.number) {
value = looseToNumber(value)
}
modelValue.value = value
}
function onInput(event: Event) {
autoResize()
if (!modelModifiers.lazy) {
updateInput((event.target as HTMLInputElement).value)
}
}
function onChange(event: Event) {
const value = (event.target as HTMLInputElement).value
if (modelModifiers.lazy) {
updateInput(value)
}
// Update trimmed textarea so that it has same behavior as native textarea https://github.com/vuejs/core/blob/5ea8a8a4fab4e19a71e123e4d27d051f5e927172/packages/runtime-dom/src/directives/vModel.ts#L63
if (modelModifiers.trim) {
(event.target as HTMLInputElement).value = value.trim()
}
emits('change', event)
}
function onBlur(event: FocusEvent) {
emits('blur', event)
}
onMounted(() => {
setTimeout(() => {
autoFocus()
}, props.autofocusDelay)
})
function autoResize() {
if (props.autoresize) {
if (!textareaRef.value) {
return
}
textareaRef.value.rows = props.rows
const overflow = textareaRef.value.style.overflow
textareaRef.value.style.overflow = 'hidden'
const styles = window.getComputedStyle(textareaRef.value)
const paddingTop = Number.parseInt(styles.paddingTop)
const paddingBottom = Number.parseInt(styles.paddingBottom)
const padding = paddingTop + paddingBottom
const lineHeight = Number.parseInt(styles.lineHeight)
const { scrollHeight } = textareaRef.value
const newRows = (scrollHeight - padding) / lineHeight
if (newRows > props.rows) {
textareaRef.value.rows = props.maxrows ? Math.min(newRows, props.maxrows) : newRows
}
textareaRef.value.style.overflow = overflow
}
}
watch(modelValue, () => {
nextTick(autoResize)
})
defineExpose({
textareaRef,
})
onMounted(() => {
setTimeout(() => {
autoResize()
}, 100)
})
</script>
<template>
<Primitive :as="as" :class="ui.root({ class: [props.class, props.ui?.root] })">
<textarea
:id="id"
ref="textareaRef"
:value="modelValue"
:name="name"
:rows="rows"
:placeholder="placeholder"
:class="ui.base({ class: props.ui?.base })"
:disabled="disabled"
:required="required"
v-bind="{ ...$attrs, ...ariaAttrs }"
@input="onInput"
@blur="onBlur"
@change="onChange"
/>
<slot />
</Primitive>
</template>Theme
ts
import { buttonGroupVariantWithRoot } from '@/ui/theme/button-group'
export default {
slots: {
root: '',
base: '',
leading: '',
leadingIcon: '',
leadingAvatar: '',
leadingAvatarSize: '',
trailing: '',
trailingIcon: '',
},
variants: {
...buttonGroupVariantWithRoot,
size: {
xs: {
base: '',
leading: '',
trailing: '',
leadingIcon: '',
leadingAvatarSize: '',
trailingIcon: '',
},
sm: {
base: '',
leading: '',
trailing: '',
leadingIcon: '',
leadingAvatarSize: '',
trailingIcon: '',
},
md: {
base: '',
leading: '',
trailing: '',
leadingIcon: '',
leadingAvatarSize: '',
trailingIcon: '',
},
lg: {
base: '',
leading: '',
trailing: '',
leadingIcon: '',
leadingAvatarSize: '',
trailingIcon: '',
},
xl: {
base: '',
leading: '',
trailing: '',
leadingIcon: '',
leadingAvatarSize: '',
trailingIcon: '',
},
},
variant: {
outline: '',
soft: '',
subtle: '',
ghost: '',
none: '',
},
color: {
primary: '',
secondary: '',
success: '',
info: '',
warning: '',
error: '',
neutral: '',
},
leading: {
true: '',
},
trailing: {
true: '',
},
loading: {
true: '',
},
highlight: {
true: '',
},
type: {
file: '',
},
},
compoundVariants: [],
defaultVariants: {
size: 'md',
color: 'primary',
variant: 'outline',
} as const,
}View Nuxt UI theme
ts
import { buttonGroupVariantWithRoot } from '@/ui/theme/button-group'
export default {
slots: {
root: 'relative inline-flex items-center',
base: 'w-full rounded-md border-0 placeholder:text-dimmed focus:outline-none disabled:cursor-not-allowed disabled:opacity-75 transition-colors',
leading: 'absolute inset-y-0 start-0 flex items-center',
leadingIcon: 'shrink-0 text-dimmed',
leadingAvatar: 'shrink-0',
leadingAvatarSize: '',
trailing: 'absolute inset-y-0 end-0 flex items-center',
trailingIcon: 'shrink-0 text-dimmed',
},
variants: {
...buttonGroupVariantWithRoot,
size: {
xs: {
base: 'px-2 py-1 text-xs gap-1',
leading: 'ps-2',
trailing: 'pe-2',
leadingIcon: 'size-4',
leadingAvatarSize: '3xs',
trailingIcon: 'size-4',
},
sm: {
base: 'px-2.5 py-1.5 text-xs gap-1.5',
leading: 'ps-2.5',
trailing: 'pe-2.5',
leadingIcon: 'size-4',
leadingAvatarSize: '3xs',
trailingIcon: 'size-4',
},
md: {
base: 'px-2.5 py-1.5 text-sm gap-1.5',
leading: 'ps-2.5',
trailing: 'pe-2.5',
leadingIcon: 'size-5',
leadingAvatarSize: '2xs',
trailingIcon: 'size-5',
},
lg: {
base: 'px-3 py-2 text-sm gap-2',
leading: 'ps-3',
trailing: 'pe-3',
leadingIcon: 'size-5',
leadingAvatarSize: '2xs',
trailingIcon: 'size-5',
},
xl: {
base: 'px-3 py-2 text-base gap-2',
leading: 'ps-3',
trailing: 'pe-3',
leadingIcon: 'size-6',
leadingAvatarSize: 'xs',
trailingIcon: 'size-6',
},
},
variant: {
outline: 'text-highlighted bg-default ring ring-inset ring-accented',
soft: 'text-highlighted bg-elevated/50 hover:bg-elevated focus:bg-elevated disabled:bg-elevated/50',
subtle: 'text-highlighted bg-elevated ring ring-inset ring-accented',
ghost: 'text-highlighted bg-transparent hover:bg-elevated focus:bg-elevated disabled:bg-transparent dark:disabled:bg-transparent',
none: 'text-highlighted bg-transparent',
},
color: {
primary: '',
secondary: '',
success: '',
info: '',
warning: '',
error: '',
neutral: '',
},
leading: {
true: '',
},
trailing: {
true: '',
},
loading: {
true: '',
},
highlight: {
true: '',
},
type: {
file: 'file:me-1.5 file:font-medium file:text-muted file:outline-none',
},
},
compoundVariants: [
{
color: 'primary' as const,
variant: ['outline' as const, 'subtle' as const],
class: 'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary',
},
{
color: 'primary',
highlight: true,
class: 'ring ring-inset ring-primary',
} as const,
{
color: 'secondary' as const,
variant: ['outline' as const, 'subtle' as const],
class: 'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-secondary',
},
{
color: 'secondary',
highlight: true,
class: 'ring ring-inset ring-secondary',
} as const,
{
color: 'success' as const,
variant: ['outline' as const, 'subtle' as const],
class: 'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-success',
},
{
color: 'success',
highlight: true,
class: 'ring ring-inset ring-success',
} as const,
{
color: 'info' as const,
variant: ['outline' as const, 'subtle' as const],
class: 'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-info',
},
{
color: 'info',
highlight: true,
class: 'ring ring-inset ring-info',
} as const,
{
color: 'warning' as const,
variant: ['outline' as const, 'subtle' as const],
class: 'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-warning',
},
{
color: 'warning',
highlight: true,
class: 'ring ring-inset ring-warning',
} as const,
{
color: 'error' as const,
variant: ['outline' as const, 'subtle' as const],
class: 'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-error',
},
{
color: 'error',
highlight: true,
class: 'ring ring-inset ring-error',
} as const,
{
color: 'neutral' as const,
variant: ['outline' as const, 'subtle' as const],
class: 'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-inverted',
},
{
color: 'neutral',
highlight: true,
class: 'ring ring-inset ring-inverted',
} as const,
{
leading: true,
size: 'xs',
class: 'ps-7',
} as const,
{
leading: true,
size: 'sm',
class: 'ps-8',
} as const,
{
leading: true,
size: 'md',
class: 'ps-9',
} as const,
{
leading: true,
size: 'lg',
class: 'ps-10',
} as const,
{
leading: true,
size: 'xl',
class: 'ps-11',
} as const,
{
trailing: true,
size: 'xs',
class: 'pe-7',
} as const,
{
trailing: true,
size: 'sm',
class: 'pe-8',
} as const,
{
trailing: true,
size: 'md',
class: 'pe-9',
} as const,
{
trailing: true,
size: 'lg',
class: 'pe-10',
} as const,
{
trailing: true,
size: 'xl',
class: 'pe-11',
} as const,
{
loading: true,
leading: true,
class: {
leadingIcon: 'animate-spin',
},
} as const,
{
loading: true,
leading: false,
trailing: true,
class: {
trailingIcon: 'animate-spin',
},
} as const,
],
defaultVariants: {
size: 'md',
color: 'primary',
variant: 'outline',
} as const,
}Test
To test this component, you can use the following test file:
ts
import type { RenderOptions } from '@testing-library/vue'
import Textarea from '@/ui/components/Textarea.vue'
import theme from '@/ui/theme/textarea'
import { render } from '@testing-library/vue'
import { describe, expect, it } from 'vitest'
describe('textarea', () => {
const sizes = Object.keys(theme.variants.size) as any
const variants = Object.keys(theme.variants.variant) as any
it.each<RenderOptions<typeof Textarea>[]>([
// Props
['with id', { props: { id: 'id' } }],
['with name', { props: { name: 'name' } }],
['with placeholder', { props: { placeholder: 'placeholder' } }],
['with required', { props: { required: true } }],
['with disabled', { props: { disabled: true } }],
['with rows', { props: { rows: 5 } }],
...sizes.map((size: string) => [`with size ${size}`, { props: { size } }]),
...variants.map((variant: string) => [`with primary variant ${variant}`, { props: { variant } }]),
['with as', { props: { as: 'section' } }],
['with class', { props: { class: 'w-48' } }],
['with ui', { props: { ui: { wrapper: 'ms-4' } } }],
// Slots
['with default slot', { slots: { default: 'Default slot' } }],
])('renders %s correctly', (name, options) => {
const { html } = render(Textarea, options)
expect(html()).toMatchSnapshot()
})
})ts
import type { RenderOptions } from '@testing-library/vue'
import Textarea from '@/UI/Components/Textarea.vue'
import theme from '@/UI/Theme/textarea'
import { render } from '@testing-library/vue'
import { describe, expect, it } from 'vitest'
describe('textarea', () => {
const sizes = Object.keys(theme.variants.size) as any
const variants = Object.keys(theme.variants.variant) as any
it.each<RenderOptions<typeof Textarea>[]>([
// Props
['with id', { props: { id: 'id' } }],
['with name', { props: { name: 'name' } }],
['with placeholder', { props: { placeholder: 'placeholder' } }],
['with required', { props: { required: true } }],
['with disabled', { props: { disabled: true } }],
['with rows', { props: { rows: 5 } }],
...sizes.map((size: string) => [`with size ${size}`, { props: { size } }]),
...variants.map((variant: string) => [`with primary variant ${variant}`, { props: { variant } }]),
['with as', { props: { as: 'section' } }],
['with class', { props: { class: 'w-48' } }],
['with ui', { props: { ui: { wrapper: 'ms-4' } } }],
// Slots
['with default slot', { slots: { default: 'Default slot' } }],
])('renders %s correctly', (name, options) => {
const { html } = render(Textarea, options)
expect(html()).toMatchSnapshot()
})
})