@workday/canvas-kit-docs
Version:
Documentation components of Canvas Kit components
32 lines (31 loc) • 1.71 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from 'react';
import { AccessibleHide, AriaLiveRegion } from '@workday/canvas-kit-react/common';
import { FormField } from '@workday/canvas-kit-react/form-field';
import { TextArea } from '@workday/canvas-kit-react/text-area';
const MAX_CHARACTERS = 200;
const DEBOUNCE_DELAY = 2000; // 2 seconds after user stops typing
export const CommentBoxWithCharLimit = () => {
const [value, setValue] = React.useState('');
const [liveUpdateStr, setLiveUpdateStr] = React.useState('');
const hintTextStr = `${value.length} of ${MAX_CHARACTERS} characters`;
const handleChange = (event) => {
setValue(event.target.value);
};
const handleBlur = () => {
setLiveUpdateStr('');
};
React.useEffect(() => {
// Immediately announce when limit is reached (bypass debounce)
if (value.length === MAX_CHARACTERS) {
setLiveUpdateStr(`Character limit reached. ${value.length} of ${MAX_CHARACTERS} characters`);
return;
}
// Otherwise, debounce the updates
const timer = setTimeout(() => {
setLiveUpdateStr(`${value.length} of ${MAX_CHARACTERS} characters`);
}, DEBOUNCE_DELAY);
return () => clearTimeout(timer);
}, [value.length]);
return (_jsxs(FormField, { children: [_jsx(FormField.Label, { children: "Comments" }), _jsxs(FormField.Field, { children: [_jsx(FormField.Input, { as: TextArea, onChange: handleChange, onBlur: handleBlur, value: value, maxLength: MAX_CHARACTERS }), _jsx(FormField.Hint, { children: hintTextStr }), _jsx(AriaLiveRegion, { as: AccessibleHide, children: liveUpdateStr })] })] }));
};