An open source design system that's fully customizable and agent ready
TypeScript
fix(richtext): links in a disabled editor do not navigate and add no tab stop (#10679)
Cindy Zhange25a6dc2ab4f
diff --git a/.changeset/richtext-disabled-links-inert.md b/.changeset/richtext-disabled-links-inert.mdnew file mode 100644index 0000000000..e516babffd--- /dev/null+++ b/.changeset/richtext-disabled-links-inert.md@@ -0,0 +1,7 @@+---+'@astryxdesign/richtext': patch+---++[fix] A link inside a disabled `RichTextEditor` no longer navigates, shows no pointer cursor, and is not a tab stop. Before, a disabled editor's links acted as live links: a click or Enter opened them, and Tab stopped on each one.++@cixzhangdiff --git a/apps/storybook/stories/RichTextEditor.stories.tsx b/apps/storybook/stories/RichTextEditor.stories.tsxindex 8be5bbb65a..84fa790a4f 100644--- a/apps/storybook/stories/RichTextEditor.stories.tsx+++ b/apps/storybook/stories/RichTextEditor.stories.tsx@@ -244,6 +244,18 @@ export const ReadOnly: Story = {},};+/** A disabled editor whose content holds a link. */+export const DisabledWithLink: Story = {+ name: 'Disabled with a link',+ args: {+ label: 'Notes',+ isDisabled: true,+ defaultValue: markdownToEditorStateJSON(+ 'Read [the guide](https://example.com/guide) before you edit.\n',+ ),+ },+};+const SEED = JSON.stringify({root: {children: [diff --git a/packages/richtext/src/DisabledLinkGuardPlugin.tsx b/packages/richtext/src/DisabledLinkGuardPlugin.tsxnew file mode 100644index 0000000000..3e7da7c040--- /dev/null+++ b/packages/richtext/src/DisabledLinkGuardPlugin.tsx@@ -0,0 +1,93 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file DisabledLinkGuardPlugin.tsx+ * @input The composer's editor, and whether RichTextEditor is disabled+ * @output DisabledLinkGuardPlugin (internal; not re-exported from index.ts):+ * while the editor is disabled, its links add no tab stop and never navigate+ * @position Rendered by RichTextEditor inside its LexicalExtensionComposer+ *+ * A disabled editor is not editable, so the browser treats each link in it as+ * a live link: a tab stop that navigates on a click or on Enter. A disabled+ * control must not navigate, and it keeps the focus order it has when enabled,+ * where its links are not tab stops.+ */++import {useEffect} from 'react';+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';++// Enter on a focused link and a screen reader's activation arrive as a click.+// A middle click arrives as auxclick.+function preventLinkActivation(event: MouseEvent) {+ if (event.target instanceof Element && event.target.closest('a[href]')) {+ event.preventDefault();+ }+}++/**+ * Guards the links under one root element. It records the links it changes,+ * so it restores only those.+ */+function createLinkGuard(root: HTMLElement) {+ const guarded = new Set<Element>();+ const guard = () => {+ for (const link of root.querySelectorAll('a[href]')) {+ if (!guarded.has(link)) {+ guarded.add(link);+ link.setAttribute('tabindex', '-1');+ // Assistive technology announces each link as disabled. Only the+ // link ignores the pointer, so a wide table still scrolls.+ link.setAttribute('aria-disabled', 'true');+ if (link instanceof HTMLElement) {+ link.style.pointerEvents = 'none';+ }+ }+ }+ };+ guard();+ root.addEventListener('click', preventLinkActivation, true);+ root.addEventListener('auxclick', preventLinkActivation, true);+ return {+ guard,+ release() {+ for (const link of guarded) {+ link.removeAttribute('tabindex');+ link.removeAttribute('aria-disabled');+ if (link instanceof HTMLElement) {+ link.style.removeProperty('pointer-events');+ }+ }+ guarded.clear();+ root.removeEventListener('click', preventLinkActivation, true);+ root.removeEventListener('auxclick', preventLinkActivation, true);+ },+ };+}++export function DisabledLinkGuardPlugin({isDisabled}: {isDisabled: boolean}) {+ const [editor] = useLexicalComposerContext();+ // Synchronizes the editor's link elements, which Lexical renders and owns,+ // with the disabled state: guarded while disabled, restored when enabled.+ useEffect(() => {+ if (!isDisabled) {+ return undefined;+ }+ let linkGuard: ReturnType<typeof createLinkGuard> | null = null;+ const unregisterRoot = editor.registerRootListener(next => {+ linkGuard?.release();+ linkGuard = next == null ? null : createLinkGuard(next);+ });+ // A new or changed document renders new link elements.+ const unregisterUpdate = editor.registerUpdateListener(() => {+ linkGuard?.guard();+ });+ return () => {+ unregisterUpdate();+ unregisterRoot();+ linkGuard?.release();+ };+ }, [editor, isDisabled]);+ return null;+}diff --git a/packages/richtext/src/RichTextEditor.doc.mjs b/packages/richtext/src/RichTextEditor.doc.mjsindex 39c68ccd6d..e2d7705271 100644--- a/packages/richtext/src/RichTextEditor.doc.mjs+++ b/packages/richtext/src/RichTextEditor.doc.mjs@@ -85,7 +85,7 @@ export const docs = {name: 'isDisabled',type: 'boolean',description:- 'Whether the editor is disabled: non-editable, dimmed, out of the tab order, and announced as disabled. Wins when isReadOnly is also set. Takes effect when changed after mount.',+ 'Whether the editor is disabled: non-editable, dimmed, out of the tab order, and announced as disabled. Its links do not navigate and are not tab stops. Wins when isReadOnly is also set. Takes effect when changed after mount.',default: 'false',},{diff --git a/packages/richtext/src/RichTextEditor.test.tsx b/packages/richtext/src/RichTextEditor.test.tsxindex 1ffe4716bd..582dad18e3 100644--- a/packages/richtext/src/RichTextEditor.test.tsx+++ b/packages/richtext/src/RichTextEditor.test.tsx@@ -493,6 +493,38 @@ describe('RichTextEditor', () => {expect(textbox).not.toHaveAttribute('tabindex', '0');});+ it('keeps a link in a disabled editor out of the tab order and inert', () => {+ render(+ <RichTextEditor+ label="Notes"+ isDisabled+ defaultValue={markdownToEditorStateJSON(+ 'See [the guide](https://example.com/guide).\n',+ )}+ />,+ );+ const link = screen.getByText('the guide').closest('a');+ expect(link).not.toBeNull();+ // An enabled editor's links are not tab stops; a disabled one adds none+ // (FR1), and activation never navigates (FR2).+ expect(link).toHaveAttribute('tabindex', '-1');+ expect(link).toHaveAttribute('aria-disabled', 'true');+ expect(fireEvent.click(link as HTMLAnchorElement)).toBe(false);+ });++ it('gives a link back its default behavior when the editor is enabled again', () => {+ const document = markdownToEditorStateJSON(+ 'See [the guide](https://example.com/guide).\n',+ );+ const {rerender} = render(+ <RichTextEditor label="Notes" isDisabled defaultValue={document} />,+ );+ rerender(<RichTextEditor label="Notes" defaultValue={document} />);+ const link = screen.getByText('the guide').closest('a');+ expect(link).not.toHaveAttribute('tabindex');+ expect(link).not.toHaveAttribute('aria-disabled');+ });+it('keeps the dimmed treatment on a disabled editor', () => {const {container} = render(<RichTextEditor label="Notes" isDisabled />);const wrapper = container.querySelector('.astryx-rich-text-editor');diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsxindex e1df3e0574..1cec7a5dc8 100644--- a/packages/richtext/src/RichTextEditor.tsx+++ b/packages/richtext/src/RichTextEditor.tsx@@ -85,6 +85,7 @@ import {MarkdownExtensionsPlugin} from './MarkdownExtensionsPlugin';import type {RichTextMarkdownExtension} from './markdownExtensions';import type {CodeLanguage} from '@astryxdesign/core/CodeBlock';import {TaskCheckboxPlugin} from './TaskCheckboxPlugin';+import {DisabledLinkGuardPlugin} from './DisabledLinkGuardPlugin';import {SelectAllScopePlugin} from './SelectAllScopePlugin';import {ImageSourceCaretPlugin} from './ImageSourceCaretPlugin';import {type Transformer} from '@lexical/markdown';@@ -361,7 +362,8 @@ export interface RichTextEditorProps extends Omit<isReadOnly?: boolean;/*** Whether the editor is disabled: non-editable, dimmed, out of the tab- * order, and announced as disabled. Wins when `isReadOnly` is also set.+ * order, and announced as disabled. Its links do not navigate and are not+ * tab stops. Wins when `isReadOnly` is also set.* Takes effect when changed after mount.* @default false*/@@ -715,6 +717,7 @@ export const RichTextEditor = function RichTextEditor({<ListPlugin /><TaskCheckboxPlugin isReadOnly={isReadOnly || isDisabled} /><LinkPlugin />+ <DisabledLinkGuardPlugin isDisabled={isDisabled} />{/* Tab keeps its editor meaning inside a table (indent, andEscape then Tab to leave the editor); arrow keys movebetween cells. GFM tables have no merged cells or celldiff --git a/packages/richtext/src/__tests__/RichTextDisabledLinks.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/RichTextDisabledLinks.a11y.chromium.spec.tsnew file mode 100644index 0000000000..a1213e7f98--- /dev/null+++ b/packages/richtext/src/__tests__/RichTextDisabledLinks.a11y.chromium.spec.ts@@ -0,0 +1,76 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope richtext/* ^(apps/storybook/stories/RichTextEditor\.stories|packages/richtext/src/__tests__/RichTextDisabledLinks) ^packages/richtext/src/++/**+ * @file RichTextDisabledLinks.a11y.chromium.spec.ts+ * @input The built Storybook's "Disabled with a link" RichTextEditor story.+ * @output Real-browser proof that a link in a disabled editor is inert: the+ * pointer gets no link cursor, a click does not navigate, and Tab does not+ * stop on the link.+ *+ * Run after building Storybook:+ * pnpm storybook:build+ * pnpm exec playwright test packages/richtext --project chromium+ */++import {expect, test} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++const STORYBOOK_DIR = process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR;+const STORY = 'richtext-richtexteditor--disabled-with-link';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(STORYBOOK_DIR);+});++test.afterAll(async () => {+ await storybook?.close();+});++test('a link in a disabled editor shows no link cursor, does not navigate, and is not a tab stop', async ({+ page,+}) => {+ const url = `${storybook.origin}/iframe.html?id=${STORY}&viewMode=story&globals=astryxTheme:neutral;colorMode:light`;+ await page.goto(url, {waitUntil: 'load'});+ const link = page.getByText('the guide');+ await expect(link).toBeVisible();++ // The element under the pointer decides the cursor the person sees.+ const hit = await link.evaluate(element => {+ const box = element.getBoundingClientRect();+ const target = document.elementFromPoint(+ box.left + box.width / 2,+ box.top + box.height / 2,+ );+ return {+ isLink: target?.closest('a') != null,+ cursor: target == null ? '' : getComputedStyle(target).cursor,+ };+ });+ expect(hit.isLink, 'the pointer does not reach the link').toBe(false);+ expect(hit.cursor).not.toBe('pointer');++ // Storybook rewrites the address while the story loads, so compare with+ // the address the page settled on.+ const before = page.url();+ await link.click({force: true});+ await expect(page).toHaveURL(before);+ await link.focus();+ await page.keyboard.press('Enter');+ await expect(page).toHaveURL(before);++ const tabStops: string[] = [];+ for (let step = 0; step < 6; step++) {+ await page.keyboard.press('Tab');+ tabStops.push(+ await page.evaluate(() => document.activeElement?.tagName ?? ''),+ );+ }+ expect(tabStops).not.toContain('A');+});