Files
web/packages/design-system/lib/components/Form/FormTextArea/index.tsx
Rasmus Langvad 4980cc830d Merged in feat/3685-new-textarea-component (pull request #3392)
feat(SW-3685): Add new TextArea and FormTextArea components

* Add new TextArea and FormTextArea components

* Update example form with description

* Merge branch 'master' into feat/3685-new-textarea-component

* Formatting new files with new prettier config

* Added custom controls for the text area story


Approved-by: Linus Flood
2026-01-07 17:04:30 +00:00

103 lines
3.0 KiB
TypeScript

"use client"
import { forwardRef } from "react"
import { Text, TextField } from "react-aria-components"
import { Controller, useFormContext } from "react-hook-form"
import { useIntl, type IntlShape } from "react-intl"
import { cx } from "class-variance-authority"
import { Error } from "../ErrorMessage/Error"
import { mergeRefs } from "../utils/mergeRefs"
import { TextArea } from "../../TextArea"
import styles from "./textarea.module.css"
import type { FormTextAreaProps } from "./textarea"
import { MaterialIcon, MaterialIconProps } from "../../Icons/MaterialIcon"
const defaultErrorFormatter = (
_intl: IntlShape,
errorMessage?: string
): string => errorMessage ?? ""
export const FormTextArea = forwardRef<HTMLTextAreaElement, FormTextAreaProps>(
function FormTextArea(
{
className = "",
description = "",
descriptionIcon = "info" as MaterialIconProps["icon"],
disabled = false,
errorFormatter,
hideError,
label,
name,
placeholder,
readOnly = false,
registerOptions = {},
...props
},
ref
) {
const intl = useIntl()
const { control } = useFormContext()
const formatErrorMessage = errorFormatter ?? defaultErrorFormatter
return (
<Controller
control={control}
name={name}
rules={registerOptions}
render={({ field, fieldState }) => {
const isDisabled = disabled || field.disabled
const hasError = fieldState.invalid && !hideError
const showDescription = description && !fieldState.error
return (
<TextField
className={cx(styles.wrapper, className)}
isDisabled={isDisabled}
isReadOnly={readOnly}
isInvalid={fieldState.invalid}
isRequired={!!registerOptions.required}
>
<TextArea
{...props}
ref={mergeRefs(field.ref, ref)}
name={field.name}
onBlur={field.onBlur}
onChange={field.onChange}
value={field.value ?? ""}
id={field.name}
label={label}
placeholder={placeholder}
readOnly={readOnly}
disabled={isDisabled}
required={!!registerOptions.required}
/>
{showDescription ? (
<Text className={styles.description} slot="description">
<MaterialIcon icon={descriptionIcon} size={20} />
{description}
</Text>
) : null}
{hasError && fieldState.error ? (
<Text slot="errorMessage" aria-live="polite">
<Error>
{formatErrorMessage(intl, fieldState.error.message)}
</Error>
</Text>
) : null}
</TextField>
)
}}
/>
)
}
)
FormTextArea.displayName = "FormTextArea"
// Default export for backwards compatibility
export default FormTextArea