Skip to content
Open
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
125 changes: 125 additions & 0 deletions packages/react/src/components/TextArea/TextArea-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,67 @@ describe('TextArea', () => {
});

describe('behaves as expected - Component API', () => {
it.each([
[false, 'character'],
[true, 'character'],
[false, 'word'],
[true, 'word'],
])(
'should process rapid controlled input with enableCounter=%s and counterMode=%s',
async (enableCounter, counterMode) => {
const onChange = jest.fn();
const onError = jest.fn((event) => event.preventDefault());
const previousActEnvironment = globalThis.IS_REACT_ACT_ENVIRONMENT;
function ControlledTextArea() {
const [value, setValue] = React.useState('');
return (
<TextArea
id="textarea-1"
labelText="TextArea label"
value={value}
enableCounter={enableCounter}
counterMode={counterMode}
maxCount={200}
onChange={(event) => {
onChange(event);
setValue(event.target.value);
}}
/>
);
}

const { unmount } = render(<ControlledTextArea />);
const textarea = screen.getByRole('textbox');
const setValue = Object.getOwnPropertyDescriptor(
HTMLTextAreaElement.prototype,
'value'
).set;
const character = counterMode === 'word' ? 'word ' : 'x';
window.addEventListener('error', onError);
// Preserve the microtask burst instead of flushing each event with act.
globalThis.IS_REACT_ACT_ENVIRONMENT = false;
try {
for (let count = 1; count <= 150; count++) {
setValue.call(textarea, character.repeat(count));
textarea.dispatchEvent(new Event('input', { bubbles: true }));
await Promise.resolve();
}
await new Promise((resolve) => setTimeout(resolve, 50));

expect(onError).not.toHaveBeenCalled();
expect(onChange).toHaveBeenCalledTimes(150);
expect(textarea).toHaveValue(character.repeat(150));
if (enableCounter) {
expect(screen.getByText('150/200')).toBeInTheDocument();
}
} finally {
unmount();
window.removeEventListener('error', onError);
globalThis.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
}
}
);

it('should respect onChange prop', async () => {
const onChange = jest.fn();
render(
Expand Down Expand Up @@ -490,6 +551,53 @@ describe('TextArea', () => {
});

describe('word counter behaves as expected', () => {
it('should preserve the controlled value when pasted text exceeds the word limit', () => {
const onChange = jest.fn();
render(
<TextArea
id="input-1"
labelText="TextArea label"
value="one"
onChange={onChange}
enableCounter
counterMode="word"
maxCount={3}
/>
);
const textarea = screen.getByRole('textbox');
const paste = createEvent.paste(textarea, {
clipboardData: { getData: () => 'two three four' },
});

fireEvent(textarea, paste);

expect(paste.defaultPrevented).toBe(true);
expect(textarea).toHaveValue('one');
expect(screen.getByText('1/3')).toBeInTheDocument();
expect(onChange).not.toHaveBeenCalled();
});

it('should count programmatic controlled values when switching counter modes', () => {
const props = {
id: 'input-1',
labelText: 'TextArea label',
enableCounter: true,
maxCount: 20,
onChange: jest.fn(),
};
const { rerender } = render(
<TextArea {...props} value="one two" counterMode="word" />
);
expect(screen.getByText('2/20')).toBeInTheDocument();

rerender(<TextArea {...props} value="one two" counterMode="character" />);
expect(screen.getByText('7/20')).toBeInTheDocument();

rerender(<TextArea {...props} value="" counterMode="word" />);
expect(screen.getByText('0/20')).toBeInTheDocument();
expect(screen.getByRole('textbox')).toHaveValue('');
});

it('should correctly increase word count', async () => {
render(
<TextArea
Expand Down Expand Up @@ -711,6 +819,23 @@ describe('TextArea', () => {
jest.useRealTimers();
});

it('should update announcements for controlled values without a visible counter', () => {
const props = {
id: 'textarea-1',
labelText: 'TextArea label',
maxCount: 10,
onChange: jest.fn(),
};
const { rerender } = render(<TextArea {...props} value="" />);

rerender(<TextArea {...props} value="abcdef" />);
act(() => {
jest.advanceTimersByTime(1000);
});

expect(screen.getByRole('alert')).toHaveTextContent('4 characters left.');
});

it.each([
['character', '123456789', 1000, '1 character left.'],
['character', '12345', 1000, '5 characters left.'],
Expand Down
52 changes: 37 additions & 15 deletions packages/react/src/components/TextArea/TextArea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,16 @@ export interface TextAreaProps
counterMode?: 'character' | 'word';
}

function getTextCount(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion to convert this function and setTextCount to arrow functions for consistency with the other functions in this file.

value: string | number,
counterMode: TextAreaProps['counterMode']
Comment on lines +214 to +215

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

counterMode's type is derived from TextAreaProps but value's type isn't. Should they both be?

Suggested change
value: string | number,
counterMode: TextAreaProps['counterMode']
value: NonNullable<TextAreaProps['value']>,
counterMode: TextAreaProps['counterMode']

): number {
const strValue = value.toString();
return counterMode === 'character'
? strValue.length
: strValue.match(/\p{L}+/gu)?.length || 0;
}

const frFn = forwardRef<HTMLTextAreaElement, TextAreaProps>;

const TextArea = frFn((props, forwardRef) => {
Expand Down Expand Up @@ -253,24 +263,31 @@ const TextArea = frFn((props, forwardRef) => {

const ref = useMergedRefs([forwardRef, textareaRef]);

function getInitialTextCount(): number {
const targetValue =
defaultValue || value || textareaRef.current?.value || '';
const strValue = targetValue.toString();

if (counterMode === 'character') {
return strValue.length;
} else {
return strValue.match(/\p{L}+/gu)?.length || 0;
const isControlled = value != null;
const [uncontrolledTextCount, setUncontrolledTextCount] = useState(() =>
getTextCount(defaultValue ?? '', counterMode)
);
// Keep controlled counts derived so rapid input doesn't queue extra state updates.
const textCount = isControlled
? getTextCount(value, counterMode)
: uncontrolledTextCount;

function setTextCount(count: number) {
if (!isControlled) {
setUncontrolledTextCount(count);
}
}

const [textCount, setTextCount] = useState(getInitialTextCount());

useEffect(() => {
setTextCount(getInitialTextCount());
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value, defaultValue, counterMode]);
if (!isControlled) {
setUncontrolledTextCount(
getTextCount(
defaultValue || textareaRef.current?.value || '',
counterMode
)
);
}
}, [isControlled, defaultValue, counterMode]);

useIsomorphicEffect(() => {
if (other.cols && textareaRef.current) {
Expand Down Expand Up @@ -341,6 +358,11 @@ const TextArea = frFn((props, forwardRef) => {
if (totalWords > maxCount) {
evt.preventDefault();

// The consumer owns the value of a controlled field.
if (isControlled) {
return;
}

const allowedWords = existingWords
.concat(pastedWords)
.slice(0, maxCount);
Expand All @@ -358,7 +380,7 @@ const TextArea = frFn((props, forwardRef) => {
if (!disabled) {
if (counterMode == 'character') {
evt?.persist?.();
// delay textCount assignation to give the textarea element value time to catch up if is a controlled input
// Read the final DOM value after the change handler has run.
setTimeout(() => {
setTextCount(evt.target?.value?.length);
}, 0);
Expand Down
82 changes: 82 additions & 0 deletions packages/react/src/components/TextInput/TextInput.stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { IconButton } from '../IconButton';
import mdx from './TextInput.mdx';

import { default as TextInput, TextInputSkeleton } from '../TextInput';
import TextArea from '../TextArea'; //need remove this later

const getTextInputStoryArgs = ({
defaultWidth,
Expand Down Expand Up @@ -362,3 +363,84 @@ TestInvalidTextNoOverlap.args = { ...defaultArgs };
* - Still be a tested variant
*/
TestInvalidTextNoOverlap.tags = ['!dev', '!autodocs'];

// Temporary example for review. Remove before merging.
function RapidInputExample({ kind, enableCounter }) {
const [value, setValue] = React.useState('');
const [result, setResult] = React.useState('');
const inputRef = React.useRef(null);
const changes = React.useRef(0);
const label = kind === 'native' ? 'Native input' : kind;
const Field = kind === 'TextInput' ? TextInput : TextArea;

function handleChange(event) {
changes.current++;
setValue(event.target.value);
}

async function handleTest() {
const input = inputRef.current;
const prototype =
kind === 'TextArea'
? HTMLTextAreaElement.prototype
: HTMLInputElement.prototype;
const setInputValue = Object.getOwnPropertyDescriptor(
prototype,
'value'
).set;
changes.current = 0;
setResult('Running...');
input.focus();

for (let count = 1; count <= 150; count++) {
setInputValue.call(input, 'x'.repeat(count));
input.dispatchEvent(new Event('input', { bubbles: true }));
await Promise.resolve();
}
await new Promise((resolve) => setTimeout(resolve, 50));
setResult(`Last run: ${changes.current}/150 onChange calls`);
}

return (
<div style={{ width: 300 }}>
{kind === 'native' ? (
<label>
{label}
<input ref={inputRef} value={value} onChange={handleChange} />
</label>
) : (
<Field
id={`rapid-input-${kind}`}
labelText={label}
ref={inputRef}
value={value}
onChange={handleChange}
enableCounter={enableCounter}
maxCount={200}
/>
)}
<p>Current value: {value.length} characters</p>
<Button
kind="secondary"
disabled={result === 'Running...'}
onClick={handleTest}>
Send 150 input events
</Button>
<output aria-label={`${label} result`}>{result}</output>
</div>
);
}

export const TestRapidControlledInput = ({ enableCounter }) => (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 32 }}>
{['TextInput', 'TextArea', 'native'].map((kind) => (
<RapidInputExample key={kind} kind={kind} enableCounter={enableCounter} />
))}
</div>
);

TestRapidControlledInput.args = { enableCounter: false };
TestRapidControlledInput.parameters = {
controls: { include: ['enableCounter'] },
};
TestRapidControlledInput.tags = ['!autodocs'];
26 changes: 15 additions & 11 deletions packages/react/src/components/TextInput/TextInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -226,18 +226,20 @@ const TextInput = forwardRef<unknown, TextInputProps>(
const labelRef = useRef<HTMLLabelElement>(null);
const mergedRef = useMergedRefs([ref, inputRef]);

function getInitialTextCount(): number {
const targetValue =
defaultValue || value || inputRef.current?.value || '';
return targetValue.toString().length;
}

const [textCount, setTextCount] = useState(getInitialTextCount());
const isControlled = value != null;
const [uncontrolledTextCount, setTextCount] = useState(
() => (defaultValue ?? '').toString().length
);
// Keep controlled counts derived so rapid input doesn't queue extra state updates.
const textCount = value?.toString().length ?? uncontrolledTextCount;

useEffect(() => {
setTextCount(getInitialTextCount());
// eslint-disable-next-line react-hooks/exhaustive-deps -- https://github.com/carbon-design-system/carbon/issues/20452
}, [value, defaultValue, enableCounter]);
if (!isControlled) {
setTextCount(
(defaultValue || inputRef.current?.value || '').toString().length
);
}
}, [isControlled, defaultValue, enableCounter]);

const normalizedProps = useNormalizedInputProps({
id,
Expand All @@ -260,7 +262,9 @@ const TextInput = forwardRef<unknown, TextInputProps>(
id,
onChange: (evt) => {
if (!normalizedProps.disabled) {
setTextCount(evt.target.value?.length);
if (!isControlled) {
setTextCount(evt.target.value?.length);
}
onChange(evt);
}
},
Expand Down
Loading
Loading