An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): add maxLength character counter to RichTextEditor (#4502)
Sherry48f008544814
diff --git a/apps/storybook/stories/RichTextEditor.stories.tsx b/apps/storybook/stories/RichTextEditor.stories.tsxindex adcf383036..cb6008296e 100644--- a/apps/storybook/stories/RichTextEditor.stories.tsx+++ b/apps/storybook/stories/RichTextEditor.stories.tsx@@ -26,6 +26,7 @@ const meta: Meta<typeof RichTextEditor> = {isOptional: {control: 'boolean'},hasMarkdownShortcuts: {control: 'boolean'},hasAutoFocus: {control: 'boolean'},+ maxLength: {control: 'number'},size: {control: 'select', options: ['sm', 'md', 'lg']},},};@@ -56,6 +57,15 @@ export const Required: Story = {},};+export const WithCharacterLimit: Story = {+ args: {+ label: 'Bio',+ maxLength: 80,+ description: 'A character counter appears below the editor when maxLength is set.',+ placeholder: 'Type past 80 characters to see the counter turn red…',+ },+};+export const CustomTransformers: Story = {args: {label: 'Comment',diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjsindex 471169626f..798a2aa1c2 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs+++ b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs@@ -109,6 +109,12 @@ export const docs = {description: 'Automatically focus the editor on mount.',default: 'false',},+ {+ name: 'maxLength',+ type: 'number',+ description:+ 'Maximum number of characters. When set, a character counter (current/max) is displayed below the editor. Like TextArea, does not enforce the limit natively; the counter shows error styling when the plain-text length exceeds the limit.',+ },{name: 'width',type: 'number | string',diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsxindex dbc6c7ce18..b62095b22c 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx+++ b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx@@ -455,6 +455,43 @@ describe('RichTextEditor', () => {const text = state?.read(() => $getRoot().getTextContent());expect(text).toBe('Hello world');});++ it('does not render a character counter when maxLength is not set', () => {+ render(<RichTextEditor label="Notes" defaultValue={HELLO_STATE} />);+ expect(screen.queryByText(/\d+\/\d+/)).not.toBeInTheDocument();+ });++ it('renders a character counter reflecting the seeded content length', async () => {+ // HELLO_STATE is "Hello world" (11 chars).+ render(+ <RichTextEditor label="Notes" defaultValue={HELLO_STATE} maxLength={100} />,+ );+ await waitFor(() =>+ expect(screen.getByText('11/100')).toBeInTheDocument(),+ );+ });++ it('shows an over-limit counter when content exceeds maxLength', async () => {+ // 11 chars with a limit of 5 -> over limit.+ render(+ <RichTextEditor label="Notes" defaultValue={HELLO_STATE} maxLength={5} />,+ );+ await waitFor(() => expect(screen.getByText('11/5')).toBeInTheDocument());+ // aria-live region announces the overflow for screen readers.+ expect(screen.getByText('6 characters over limit')).toBeInTheDocument();+ });++ it('associates the counter with the editor via aria-describedby', async () => {+ render(+ <RichTextEditor label="Notes" defaultValue={HELLO_STATE} maxLength={100} />,+ );+ const counter = await screen.findByText('11/100');+ const describedBy = screen+ .getByRole('textbox')+ .getAttribute('aria-describedby');+ expect(describedBy).toBeTruthy();+ expect(describedBy!.split(' ')).toContain(counter.id);+ });});describe('RichTextView', () => {diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.tsx b/packages/lab/src/RichTextEditor/RichTextEditor.tsxindex 50d3e434a6..8644830441 100644--- a/packages/lab/src/RichTextEditor/RichTextEditor.tsx+++ b/packages/lab/src/RichTextEditor/RichTextEditor.tsx@@ -30,6 +30,7 @@ import {useImperativeHandle,useMemo,useRef,+ useState,forwardRef,type ReactNode,type Ref,@@ -50,6 +51,7 @@ import {inputStatusFocusWithinStyles,} from '@astryxdesign/core/Field';import type {BaseProps} from '@astryxdesign/core';+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';import type {SizeValue} from '@astryxdesign/core/utils';import {useSize} from '@astryxdesign/core/SizeContext';import {themeProps} from '@astryxdesign/core/utils';@@ -157,6 +159,17 @@ const styles = stylex.create({disabled: {cursor: 'not-allowed',},+ counter: {+ display: 'flex',+ justifyContent: 'flex-end',+ marginTop: spacingVars['--spacing-1'],+ fontFamily: typographyVars['--font-family-body'],+ fontSize: typeScaleVars['--text-supporting-size'],+ color: colorVars['--color-text-secondary'],+ },+ counterError: {+ color: colorVars['--color-error'],+ },});const sizeStyles = stylex.create({@@ -179,6 +192,12 @@ const DEFAULT_NODES: ReadonlyArray<Klass<LexicalNode>> = [CodeHighlightNode,];+/**+ * Fraction of `maxLength` at which the character counter begins announcing+ * remaining/over-limit characters to screen readers. Matches TextArea.+ */+const COUNTER_WARNING_THRESHOLD = 0.8;+export type RichTextEditorStatusType = 'warning' | 'error' | 'success';export type RichTextEditorSize = 'sm' | 'md' | 'lg';@@ -317,6 +336,14 @@ export interface RichTextEditorProps extends Omit<transformers?: ReadonlyArray<Transformer>;/** Whether to automatically focus the editor on mount. @default false */hasAutoFocus?: boolean;+ /**+ * Maximum number of characters. When set, a character counter+ * (current/max) is displayed below the editor. Like TextArea, this does+ * NOT enforce the limit natively — the counter shows error styling when the+ * plain-text length exceeds the limit. Count is the editor's plain-text+ * content length.+ */+ maxLength?: number;/*** The Lexical composer namespace, used for editor identity.* @default 'astryx-editor'@@ -372,6 +399,7 @@ export const RichTextEditor = forwardRef<hasMarkdownShortcuts = true,transformers = TRANSFORMERS,hasAutoFocus = false,+ maxLength,namespace = 'astryx-editor',xstyle,className,@@ -385,6 +413,11 @@ export const RichTextEditor = forwardRef<const descriptionID = useId();const statusMessageID = useId();const placeholderID = useId();+ const counterID = useId();++ // Plain-text character count, tracked from inside the composer via+ // CharCountPlugin. Only used when maxLength is set.+ const [charCount, setCharCount] = useState(0);// Theme is stable per render; build once.const themeRef = useRef<EditorThemeClasses | null>(null);@@ -417,6 +450,7 @@ export const RichTextEditor = forwardRef<description ? descriptionID : null,status?.message ? statusMessageID : null,placeholder ? placeholderID : null,+ maxLength != null ? counterID : null,].filter(Boolean).join(' ') || undefined;@@ -495,9 +529,29 @@ export const RichTextEditor = forwardRef<)}{plugins}<EditorRefBridge editorRef={ref} editable={editable} />+ {maxLength != null && (+ <CharCountPlugin onCountChange={setCharCount} />+ )}</div></LexicalComposer></div>+ {maxLength != null && (+ <div+ id={counterID}+ {...stylex.props(+ styles.counter,+ charCount > maxLength && styles.counterError,+ )}>+ {charCount}/{maxLength}+ <VisuallyHidden aria-live="polite">+ {charCount >= maxLength * COUNTER_WARNING_THRESHOLD+ ? charCount > maxLength+ ? `${charCount - maxLength} characters over limit`+ : `${maxLength - charCount} characters remaining`+ : ''}+ </VisuallyHidden>+ </div>+ )}</Field>);});@@ -560,6 +614,35 @@ function EditorRefBridge({return null;}+/**+ * Tracks the editor's plain-text length and reports it to the host component.+ * Split into its own plugin so it runs inside the composer context and can+ * read the editor state via `useLexicalComposerContext()`. Renders nothing.+ */+function CharCountPlugin({+ onCountChange,+}: {+ onCountChange: (count: number) => void;+}): null {+ const [editor] = useLexicalComposerContext();+ useEffect(() => {+ // Report the initial count (e.g. seeded via defaultValue) from the mounted+ // root element's text, then track changes via registerTextContentListener,+ // which hands us the plain-text content directly.+ //+ // We deliberately avoid importing `$getRoot` from the top-level `lexical`+ // package: that is a *runtime value* import, and in the sandbox's Next+ // build it forces Babel to transpile lexical's raw `src/*.ts` (which uses+ // `declare` class fields) and fails. Both APIs used here are methods on the+ // editor instance, so no top-level `lexical` value import is needed.+ onCountChange(editor.getRootElement()?.textContent?.length ?? 0);+ return editor.registerTextContentListener((textContent) => {+ onCountChange(textContent.length);+ });+ }, [editor, onCountChange]);+ return null;+}+/*** Renders the Lexical ContentEditable. Split out so the placeholder* discriminated union (`placeholder` + `aria-placeholder` present together, or