Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 92 additions & 2 deletions packages/baukasten/src/components/TextArea/TextArea.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,18 +54,26 @@ const meta = {
resize: {
control: 'select',
options: ['none', 'vertical', 'horizontal', 'both'],
description: 'Resize behavior for the textarea',
description: 'Resize behavior for the textarea. When minRows/maxRows is set, defaults to "none"',
table: {
defaultValue: { summary: 'vertical' },
},
},
rows: {
control: 'number',
description: 'Number of visible text rows',
description: 'Number of visible text rows (static height, ignored when minRows/maxRows is set)',
table: {
defaultValue: { summary: '4' },
},
},
minRows: {
control: 'number',
description: 'Minimum number of rows for auto-grow behavior. Setting this enables auto-grow.',
},
maxRows: {
control: 'number',
description: 'Maximum number of rows for auto-grow behavior. Setting this enables auto-grow.',
},
},
} satisfies Meta<typeof TextArea>;

Expand Down Expand Up @@ -192,6 +200,76 @@ export const RowOptions: Story = {
},
};

/**
* Auto-grow textareas that expand as content is added.
*/
export const AutoGrow: Story = {
render: () => (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--bk-spacing-3)', width: '400px' }}>
<div>
<h4 style={{ marginBottom: 'var(--bk-spacing-2)', fontSize: 'var(--bk-font-size-sm)', fontWeight: 'var(--bk-font-weight-medium)' }}>
minRows={2}, maxRows={6}
</h4>
<TextArea
minRows={2}
maxRows={6}
placeholder="Type to see auto-grow. Starts at 2 rows, grows up to 6 rows, then scrolls."
fullWidth
/>
</div>
<div>
<h4 style={{ marginBottom: 'var(--bk-spacing-2)', fontSize: 'var(--bk-font-size-sm)', fontWeight: 'var(--bk-font-weight-medium)' }}>
minRows={1}, maxRows={4} (Compact)
</h4>
<TextArea
minRows={1}
maxRows={4}
placeholder="Single line that grows to 4 rows max"
fullWidth
/>
</div>
<div>
<h4 style={{ marginBottom: 'var(--bk-spacing-2)', fontSize: 'var(--bk-font-size-sm)', fontWeight: 'var(--bk-font-weight-medium)' }}>
minRows={3}, no maxRows (Unlimited)
</h4>
<TextArea
minRows={3}
placeholder="Starts at 3 rows, grows indefinitely with content"
fullWidth
/>
</div>
<div>
<h4 style={{ marginBottom: 'var(--bk-spacing-2)', fontSize: 'var(--bk-font-size-sm)', fontWeight: 'var(--bk-font-weight-medium)' }}>
maxRows={5} only (starts at default 4 rows)
</h4>
<TextArea
maxRows={5}
placeholder="Uses default 4 rows as min, max at 5 rows"
fullWidth
/>
</div>
<div>
<h4 style={{ marginBottom: 'var(--bk-spacing-2)', fontSize: 'var(--bk-font-size-sm)', fontWeight: 'var(--bk-font-weight-medium)' }}>
minRows={1}, maxRows={1}
</h4>
<TextArea
minRows={1}
maxRows={1}
placeholder="This one is a little awkward!"
fullWidth
/>
</div>
</div>
),
parameters: {
docs: {
description: {
story: 'Auto-grow textareas automatically expand as content is added. Use `minRows` to set the starting height and `maxRows` to limit growth. When maxRows is exceeded, the textarea becomes scrollable. Setting either `minRows` or `maxRows` enables auto-grow behavior.',
},
},
},
};

/**
* TextArea states: default, error, and disabled.
*/
Expand Down Expand Up @@ -402,6 +480,18 @@ export const Showcase: Story = {
</div>
</div>

{/* Auto-Grow */}
<div>
<h3 style={{ marginBottom: 'var(--bk-spacing-3)', fontSize: 'var(--bk-font-size-base)', fontWeight: 'var(--bk-font-weight-semibold)' }}>
Auto-Grow
</h3>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--bk-spacing-2)' }}>
<TextArea minRows={2} maxRows={6} placeholder="Grows from 2 to 6 rows" fullWidth />
<TextArea minRows={1} maxRows={4} placeholder="Compact: 1 to 4 rows" fullWidth />
<TextArea minRows={3} placeholder="Unlimited growth from 3 rows" fullWidth />
</div>
</div>

{/* Combinations */}
<div>
<h3 style={{ marginBottom: 'var(--bk-spacing-3)', fontSize: 'var(--bk-font-size-base)', fontWeight: 'var(--bk-font-weight-semibold)' }}>
Expand Down
131 changes: 123 additions & 8 deletions packages/baukasten/src/components/TextArea/TextArea.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useRef, useCallback, useLayoutEffect, forwardRef } from 'react';
import clsx from 'clsx';
import { type Size } from '../../styles';
import { textAreaWrapper, styledTextArea, errorText } from './TextArea.css';
Expand Down Expand Up @@ -31,15 +31,59 @@ export interface TextAreaProps extends Omit<React.TextareaHTMLAttributes<HTMLTex

/**
* Resize behavior for the textarea
* When minRows or maxRows is set, resize defaults to 'none' for auto-grow behavior
* @default 'vertical'
*/
resize?: TextAreaResize;

/**
* Number of visible text rows
* Number of visible text rows (static height)
* When minRows/maxRows are not set, this controls the fixed height
* When minRows/maxRows are set, this is ignored in favor of auto-grow
* @default 4
*/
rows?: number;

/**
* Minimum number of rows when auto-grow is enabled
* Setting this enables auto-grow behavior
*/
minRows?: number;

/**
* Maximum number of rows when auto-grow is enabled
* Setting this enables auto-grow behavior
*/
maxRows?: number;
}

/**
* Merge multiple refs into a single callback ref
*/
function mergeRefs<T>(...refs: (React.Ref<T> | undefined)[]): React.RefCallback<T> {
return (value) => {
refs.forEach((ref) => {
if (typeof ref === 'function') {
ref(value);
} else if (ref != null) {
(ref as React.MutableRefObject<T | null>).current = value;
}
});
};
}

/**
* Get computed styles for calculating row height
*/
function getRowHeight(textarea: HTMLTextAreaElement): { lineHeight: number; paddingTop: number; paddingBottom: number; borderTop: number; borderBottom: number } {
const computedStyle = window.getComputedStyle(textarea);
return {
lineHeight: parseFloat(computedStyle.lineHeight) || parseFloat(computedStyle.fontSize) * 1.2,
paddingTop: parseFloat(computedStyle.paddingTop) || 0,
paddingBottom: parseFloat(computedStyle.paddingBottom) || 0,
borderTop: parseFloat(computedStyle.borderTopWidth) || 0,
borderBottom: parseFloat(computedStyle.borderBottomWidth) || 0,
};
}

/**
Expand Down Expand Up @@ -77,6 +121,10 @@ export interface TextAreaProps extends Omit<React.TextareaHTMLAttributes<HTMLTex
* <TextArea resize="horizontal" placeholder="Horizontal resize" />
* <TextArea resize="both" placeholder="Resize both directions" />
*
* // Auto-grow with minRows/maxRows
* <TextArea minRows={2} maxRows={6} placeholder="Auto-growing textarea" />
* <TextArea minRows={3} placeholder="Grows from 3 rows, no max limit" />
*
* // With FormGroup
* <FormGroup>
* <FieldLabel htmlFor="description">Description</FieldLabel>
Expand All @@ -85,26 +133,93 @@ export interface TextAreaProps extends Omit<React.TextareaHTMLAttributes<HTMLTex
* </FormGroup>
* ```
*/
export const TextArea: React.FC<TextAreaProps> = ({
export const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(({
size = 'md',
error,
fullWidth = false,
resize = 'vertical',
resize,
rows = 4,
minRows,
maxRows,
className,
onChange,
value,
defaultValue,
...props
}) => {
}, forwardedRef) => {
const internalRef = useRef<HTMLTextAreaElement>(null);

// Determine if auto-grow is enabled
const isAutoGrow = minRows !== undefined || maxRows !== undefined;

// When auto-grow is enabled, default resize to 'none' unless explicitly set
const effectiveResize = resize ?? (isAutoGrow ? 'none' : 'vertical');

// Calculate the effective minRows and maxRows
const effectiveMinRows = minRows ?? rows;
const effectiveMaxRows = maxRows;

// Auto-grow resize function
const adjustHeight = useCallback(() => {
const textarea = internalRef.current;
if (!textarea || !isAutoGrow) return;

const { lineHeight, paddingTop, paddingBottom, borderTop, borderBottom } = getRowHeight(textarea);
const verticalPadding = paddingTop + paddingBottom + borderTop + borderBottom;

// Calculate min and max heights
const minHeight = lineHeight * effectiveMinRows + verticalPadding;
const maxHeight = effectiveMaxRows ? lineHeight * effectiveMaxRows + verticalPadding : Infinity;

// Neutralize any CSS min-height so it doesn't inflate scrollHeight
textarea.style.minHeight = '0';

// Reset height to auto to get the correct scrollHeight
textarea.style.height = 'auto';

// Calculate the new height based on content
const scrollHeight = textarea.scrollHeight;
const newHeight = Math.min(Math.max(scrollHeight, minHeight), maxHeight);

textarea.style.height = `${newHeight}px`;
textarea.style.minHeight = `${minHeight}px`;

// Set overflow based on whether content exceeds maxHeight
if (effectiveMaxRows && scrollHeight > maxHeight) {
textarea.style.overflowY = 'auto';
} else {
textarea.style.overflowY = 'hidden';
}
}, [isAutoGrow, effectiveMinRows, effectiveMaxRows]);

// Adjust height on mount and when value changes
useLayoutEffect(() => {
adjustHeight();
}, [adjustHeight, value, defaultValue]);

// Handle onChange to adjust height
const handleChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
onChange?.(e);
adjustHeight();
}, [onChange, adjustHeight]);

// Only show error text if error is a string (not just boolean)
const errorMessage = typeof error === 'string' ? error : undefined;

return (
<div className={textAreaWrapper({ fullWidth })}>
<textarea
className={clsx(styledTextArea({ size, resize, hasError: !!error }), className)}
rows={rows}
ref={mergeRefs(internalRef, forwardedRef)}
className={clsx(styledTextArea({ size, resize: effectiveResize, hasError: !!error }), className)}
rows={isAutoGrow ? effectiveMinRows : rows}
onChange={handleChange}
value={value}
defaultValue={defaultValue}
{...props}
/>
{errorMessage && <span className={errorText}>{errorMessage}</span>}
</div>
);
};
});

TextArea.displayName = 'TextArea';
Loading