Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(ChatComposerInput): a tap on a pasted-text token opens its preview without raising the keyboard (#9189)

Christopher Chedeau4f35412e2000
diff --git a/.changeset/chat-pasted-text-token-tap.md b/.changeset/chat-pasted-text-token-tap.md
new file mode 100644
index 0000000000..cba19d9aae
--- /dev/null
+++ b/.changeset/chat-pasted-text-token-tap.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] ChatComposerInput: a tap on a pasted-text token opens its preview without raising the keyboard. Before, the tap that opened the preview also focused the composer around the token and placed the caret in it, which on a phone raises the on-screen keyboard over the preview. Now a tap by finger or pen stops at the token, so touch reaches the preview and its Expand action without the keyboard covering them, the operable path `architecture:interaction-modality` INV4 asks of every modality; a mouse click on the token still places the caret in the composer, and hover still opens the preview.
+
+@vjeux
diff --git a/packages/core/src/Chat/ChatPastedTextToken.test.tsx b/packages/core/src/Chat/ChatPastedTextToken.test.tsx
index 448ef36b20..8d91867d43 100644
--- a/packages/core/src/Chat/ChatPastedTextToken.test.tsx
+++ b/packages/core/src/Chat/ChatPastedTextToken.test.tsx
@@ -3,13 +3,16 @@
/**
* @file ChatPastedTextToken.test.tsx
* @input Uses React Testing Library, ChatPastedTextToken, InternationalizationProvider
- * @output Verifies catalog-backed pasted-text counts and deterministic English fallback
+ * @output Verifies catalog-backed pasted-text counts, deterministic English
+ * fallback, and that a tap by finger or pen opens the preview and stops at
+ * the token while a mouse press goes on to the composer
*/
-import {render, screen} from '@testing-library/react';
-import {describe, expect, it} from 'vitest';
+import {fireEvent, render, screen, waitFor} from '@testing-library/react';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
import {InternationalizationProvider} from '../i18n';
import en from '../../locales/en.json';
+import {__resetInteractionModalityForTest} from '../utils/interactionModality';
import {ChatPastedTextToken} from './ChatPastedTextToken';
describe('ChatPastedTextToken', () => {
@@ -68,4 +71,87 @@ describe('ChatPastedTextToken', () => {
);
expect(screen.getByText('2 lines, 3 chars')).toBeInTheDocument();
});
+
+ describe('under each pointer', () => {
+ const originalShowPopover = HTMLElement.prototype.showPopover;
+ const originalHidePopover = HTMLElement.prototype.hidePopover;
+ const originalMatches = HTMLElement.prototype.matches;
+ beforeEach(() => {
+ __resetInteractionModalityForTest();
+ // jsdom has no Popover API: keep the open state where the test reads it.
+ HTMLElement.prototype.showPopover = function (this: HTMLElement) {
+ this.setAttribute('popover-open', '');
+ };
+ HTMLElement.prototype.hidePopover = function (this: HTMLElement) {
+ this.removeAttribute('popover-open');
+ };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = function (
+ this: HTMLElement,
+ selector: string,
+ ): boolean {
+ return selector === ':popover-open'
+ ? this.hasAttribute('popover-open')
+ : originalMatches.call(this, selector);
+ };
+ });
+ afterEach(() => {
+ HTMLElement.prototype.showPopover = originalShowPopover;
+ HTMLElement.prototype.hidePopover = originalHidePopover;
+ HTMLElement.prototype.matches = originalMatches;
+ });
+
+ const TEXT = 'first pasted line\nsecond pasted line';
+
+ /** The token inside an editable composer, as ChatComposerInput mounts it. */
+ const renderInComposer = () =>
+ render(
+ <div contentEditable suppressContentEditableWarning>
+ <span contentEditable={false}>
+ <ChatPastedTextToken text={TEXT} />
+ </span>
+ </div>,
+ );
+
+ /**
+ * A finger's (or a pen's) tap, in the order a browser dispatches it, with
+ * the mouse press it makes of the tap. Returns whether that press kept its
+ * default (moving focus and the caret into the composer).
+ */
+ const tap = (element: HTMLElement, pointerType = 'touch') => {
+ fireEvent.pointerEnter(element, {pointerType});
+ fireEvent.pointerDown(element, {pointerType});
+ fireEvent.pointerUp(element, {pointerType});
+ fireEvent.mouseEnter(element);
+ const kept = fireEvent.mouseDown(element);
+ fireEvent.mouseUp(element);
+ fireEvent.click(element);
+ return kept;
+ };
+
+ it.each(['touch', 'pen'])(
+ 'a %s tap opens the preview and keeps its press from the composer',
+ async pointerType => {
+ renderInComposer();
+ const token = screen.getByText('2 lines, 36 chars');
+
+ // A cancelled mouse press: the composer takes neither focus nor the
+ // caret.
+ expect(tap(token, pointerType)).toBe(false);
+ await waitFor(() => {
+ expect(
+ screen.getByText('first pasted line', {exact: false}),
+ ).toBeInTheDocument();
+ });
+ },
+ );
+
+ it('lets a mouse press go on to the composer', () => {
+ renderInComposer();
+ const token = screen.getByText('2 lines, 36 chars');
+
+ fireEvent.pointerDown(token, {pointerType: 'mouse'});
+ expect(fireEvent.mouseDown(token)).toBe(true);
+ });
+ });
});
diff --git a/packages/core/src/Chat/ChatPastedTextToken.tsx b/packages/core/src/Chat/ChatPastedTextToken.tsx
index 2a5f2ecd47..db3c44f1f3 100644
--- a/packages/core/src/Chat/ChatPastedTextToken.tsx
+++ b/packages/core/src/Chat/ChatPastedTextToken.tsx
@@ -4,12 +4,14 @@
/**
* @file ChatPastedTextToken.tsx
- * @input Uses React, StyleX, Badge, HoverCard, Button, provider-bound translator
+ * @input Uses React, StyleX, Badge, HoverCard, Button, provider-bound translator,
+ * the shared tap stop (`useTapStop`)
* @output Exports ChatPastedTextToken component
* @position Inline token for pasted text with hover card preview + expand
*
- * Hover: card with truncated text preview and "Expand" button.
- * Expand replaces the token with the full text in the contentEditable.
+ * Hover, or a tap by finger or pen: card with truncated text preview and
+ * "Expand" button. Expand replaces the token with the full text in the
+ * contentEditable.
*
* SYNC: When modified, update:
* - /packages/core/src/Chat/index.ts (exports)
@@ -26,6 +28,7 @@ import {Badge} from '../Badge';
import {Button} from '../Button';
import {HoverCard} from '../HoverCard';
import {useTranslator, type TranslatorFn} from '../i18n';
+import {useTapStop} from '../Layer/useTouchTrigger';
// =============================================================================
// Types
@@ -92,6 +95,13 @@ export function ChatPastedTextToken({
}: ChatPastedTextTokenProps) {
const t = useTranslator();
const label = formatLabel(text, t);
+ // A tap on the token, by finger or pen, asks for its preview, so it stops
+ // there: cancelling the mouse press the browser makes of it keeps the
+ // composer around the token from taking focus and the caret, which on a
+ // touch device raises the keyboard over the preview. The tap's click still
+ // reaches the card's trigger. A mouse press still places the caret, and
+ // hover opens the preview.
+ const tapStop = useTapStop('mousedown');
const cardContent = (
<div {...stylex.props(styles.preview)}>
@@ -116,7 +126,7 @@ export function ChatPastedTextToken({
placement="above"
alignment="start"
hasHoverIndication={false}>
- <Badge label={label} variant="neutral" />
+ <Badge label={label} variant="neutral" {...tapStop} />
</HoverCard>
);
}
diff --git a/packages/core/src/Chat/__tests__/ChatPastedTextTokenTap.a11y.browser.spec.ts b/packages/core/src/Chat/__tests__/ChatPastedTextTokenTap.a11y.browser.spec.ts
new file mode 100644
index 0000000000..2f08bdfe60
--- /dev/null
+++ b/packages/core/src/Chat/__tests__/ChatPastedTextTokenTap.a11y.browser.spec.ts
@@ -0,0 +1,151 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChatPastedTextTokenTap.a11y.browser.spec.ts
+ * @input The `Core/ChatComposerInput` Controlled story in a built Storybook,
+ * with a long paste turned into a pasted-text token, in Chromium and WebKit.
+ * @output Real-browser proof that a touch tap on a pasted-text token opens its
+ * preview and stops there: the composer around it takes no focus and no
+ * caret (which on a phone would raise the keyboard over the preview), while
+ * a mouse click on the token still places the caret in the composer and
+ * mouse hover still opens the preview.
+ * @position Run with `pnpm test:a11y-contract`. Focus and caret placement from
+ * a press need a real browser: jsdom moves neither.
+ */
+
+import {expect, test, type Locator, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+const STORY = 'core-chatcomposerinput--controlled';
+/** Long enough (over 200 characters) for the default paste-as-token rule. */
+const PASTED = Array.from(
+ {length: 12},
+ (_, i) => `line ${i + 1} of the pasted text`,
+).join('\n');
+/** Text only the token's preview shows. */
+const PREVIEW_TEXT = 'line 12 of the pasted text';
+
+let storybook: StaticServer;
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+/**
+ * Opens the story, pastes the long text into the composer, and returns the
+ * token it became, with focus taken out of the composer again.
+ */
+async function pastedToken(page: Page): Promise<Locator> {
+ await page.goto(`${storybook.origin}/iframe.html?id=${STORY}&viewMode=story`);
+ const composer = page.getByRole('textbox', {name: 'Message input'});
+ await composer.waitFor();
+ await composer.evaluate((element, text) => {
+ (element as HTMLElement).focus();
+ const data = new DataTransfer();
+ data.setData('text/plain', text);
+ element.dispatchEvent(
+ new ClipboardEvent('paste', {
+ clipboardData: data,
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ }, PASTED);
+ const token = composer.locator('[contenteditable="false"]');
+ // One token, painted: the presses below land on something real.
+ await expect(token).toHaveCount(1);
+ const box = await token.boundingBox();
+ expect(box?.width ?? 0).toBeGreaterThan(0);
+ expect(box?.height ?? 0).toBeGreaterThan(0);
+ await page.evaluate(() => {
+ (document.activeElement as HTMLElement | null)?.blur();
+ document.getSelection()?.removeAllRanges();
+ });
+ return token;
+}
+
+/**
+ * Whether the composer has focus or holds the caret. Throws when there is no
+ * composer, so a missing one never reads as "no focus, no caret".
+ */
+async function composerState(page: Page) {
+ return page.evaluate(() => {
+ const composers = document.querySelectorAll('[aria-label="Message input"]');
+ if (composers.length !== 1) {
+ throw new Error(`expected one composer, found ${composers.length}`);
+ }
+ const composer = composers[0];
+ const selection = document.getSelection();
+ const anchor = selection?.anchorNode ?? null;
+ return {
+ focused: document.activeElement === composer,
+ caret:
+ selection != null &&
+ selection.rangeCount > 0 &&
+ anchor != null &&
+ composer.contains(anchor),
+ };
+ });
+}
+
+/**
+ * The preview: the pasted text in full, in the token's hover card (a popover
+ * layer), apart from the story's own readout of the composer's value.
+ */
+function preview(page: Page): Locator {
+ return page.locator('[popover]').getByText(PREVIEW_TEXT);
+}
+
+test.describe('a touch tap on a pasted-text token', () => {
+ test.use({
+ hasTouch: true,
+ isMobile: true,
+ viewport: {width: 390, height: 844},
+ });
+
+ test('opens its preview and leaves the composer without focus or caret', async ({
+ page,
+ }) => {
+ const token = await pastedToken(page);
+ const box = await token.boundingBox();
+ if (box == null) {
+ throw new Error('the token has no layout box');
+ }
+ await page.touchscreen.tap(box.x + box.width / 2, box.y + box.height / 2);
+
+ await expect(preview(page)).toBeVisible();
+ // The tap asked for the preview, so the composer did not go on to take
+ // focus and the caret, which on a phone raises the keyboard over it.
+ expect(await composerState(page)).toEqual({focused: false, caret: false});
+ });
+});
+
+test.describe('a mouse on a pasted-text token', () => {
+ test('hover opens its preview', async ({page}) => {
+ const token = await pastedToken(page);
+ await token.hover();
+
+ await expect(preview(page)).toBeVisible();
+ });
+
+ test('a click places the caret in the composer, as before', async ({
+ page,
+ }) => {
+ const token = await pastedToken(page);
+ await token.click();
+
+ await expect
+ .poll(async () => composerState(page))
+ .toEqual({focused: true, caret: true});
+ });
+});
diff --git a/packages/core/src/Field/FieldLabel.tsx b/packages/core/src/Field/FieldLabel.tsx
index 7ee7cc4d3b..cf607abbb1 100644
--- a/packages/core/src/Field/FieldLabel.tsx
+++ b/packages/core/src/Field/FieldLabel.tsx
@@ -16,15 +16,7 @@
* - /packages/core/locales/en.json (@astryx.field.required / @astryx.field.optional)
*/
-import {
- use,
- useMemo,
- useRef,
- type MouseEvent,
- type PointerEvent,
- type ReactNode,
- type RefObject,
-} from 'react';
+import {use, useMemo, useRef, type ReactNode, type RefObject} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '../BaseProps';
import {mergeProps} from '../utils/mergeProps';
@@ -39,7 +31,7 @@ import {
import {Icon, renderIconSlot} from '../Icon/Icon';
import type {IconType} from '../Icon';
import {Tooltip} from '../Tooltip/Tooltip';
-import {TOUCH_POINTER_TYPES} from '../Layer/useTouchTrigger';
+import {useTapStop} from '../Layer/useTouchTrigger';
import {useTranslator} from '../i18n/useTranslator';
import {themeProps} from '../utils/themeProps';
import {useInputContainer} from '../hooks/useInputContainer';
@@ -269,18 +261,8 @@ export function FieldLabel({
// go on to activate the label's control, as a press anywhere else on the
// label would (focus the field, toggle a switch). A mouse click on the icon
// keeps that native activation, and hover shows the help.
- const iconPressIsTapRef = useRef(false);
- const handleIconPointerDown = (event: PointerEvent<Element>) => {
- // A finger or a pen: the pointers whose tap the shared touch trigger
- // answers, so the ones whose tap opens or closes the help.
- iconPressIsTapRef.current = TOUCH_POINTER_TYPES.has(event.pointerType);
- };
- const handleIconClick = (event: MouseEvent<Element>) => {
- if (iconPressIsTapRef.current) {
- event.preventDefault();
- }
- iconPressIsTapRef.current = false;
- };
+ const {onPointerDown: handleIconPointerDown, onClick: handleIconClick} =
+ useTapStop('click');
const controlRef = useMemo<RefObject<HTMLElement | null>>(
() => ({
get current() {
diff --git a/packages/core/src/Layer/useTouchTrigger.test.ts b/packages/core/src/Layer/useTouchTrigger.test.ts
index d72d85f808..930714463e 100644
--- a/packages/core/src/Layer/useTouchTrigger.test.ts
+++ b/packages/core/src/Layer/useTouchTrigger.test.ts
@@ -2,8 +2,9 @@
/**
* @file useTouchTrigger.test.ts
- * @input Uses vitest, isActionTrigger
+ * @input Uses vitest, Testing Library, isActionTrigger, useTapStop
* @output Unit tests for the action-trigger rule behind touchTrigger="auto"
+ * and for the tap stop a reveal-only trigger uses
* @position Testing; validates useTouchTrigger.ts implementation
*
* SYNC: When useTouchTrigger.ts changes, update tests to match new behavior
@@ -13,8 +14,10 @@
* (Tooltip.test.tsx, HoverCard.test.tsx) cover the gestures it feeds.
*/
+import {createElement} from 'react';
+import {fireEvent, render, screen} from '@testing-library/react';
import {describe, it, expect} from 'vitest';
-import {isActionTrigger} from './useTouchTrigger';
+import {isActionTrigger, useTapStop} from './useTouchTrigger';
function element(html: string): HTMLElement {
const host = document.createElement('div');
@@ -68,3 +71,42 @@ describe('isActionTrigger', () => {
expect(isActionTrigger(editable)).toBe(true);
});
});
+
+describe('useTapStop', () => {
+ function ClickStopTrigger() {
+ return createElement('span', {...useTapStop('click')}, 'trigger');
+ }
+ function MouseDownStopTrigger() {
+ return createElement('span', {...useTapStop('mousedown')}, 'trigger');
+ }
+
+ it.each(['touch', 'pen'])(
+ 'cancels the click that follows a %s press, and only that one',
+ pointerType => {
+ render(createElement(ClickStopTrigger));
+ const trigger = screen.getByText('trigger');
+ fireEvent.pointerDown(trigger, {pointerType});
+ // fireEvent returns false when the event's default was prevented.
+ expect(fireEvent.click(trigger)).toBe(false);
+ // The stop belongs to that press: a click with no new press keeps its
+ // default.
+ expect(fireEvent.click(trigger)).toBe(true);
+ },
+ );
+
+ it('cancels the mouse press that follows a finger press', () => {
+ render(createElement(MouseDownStopTrigger));
+ const trigger = screen.getByText('trigger');
+ fireEvent.pointerDown(trigger, {pointerType: 'touch'});
+ expect(fireEvent.mouseDown(trigger)).toBe(false);
+ // The click itself still goes through, so the layer can open.
+ expect(fireEvent.click(trigger)).toBe(true);
+ });
+
+ it('leaves a mouse press and its click alone', () => {
+ render(createElement(ClickStopTrigger));
+ const trigger = screen.getByText('trigger');
+ fireEvent.pointerDown(trigger, {pointerType: 'mouse'});
+ expect(fireEvent.click(trigger)).toBe(true);
+ });
+});
diff --git a/packages/core/src/Layer/useTouchTrigger.ts b/packages/core/src/Layer/useTouchTrigger.ts
index 16b9793c17..cf71b22ca7 100644
--- a/packages/core/src/Layer/useTouchTrigger.ts
+++ b/packages/core/src/Layer/useTouchTrigger.ts
@@ -5,7 +5,8 @@
/**
* @file useTouchTrigger.ts
* @input Touch trigger mode, layer open state, trigger ref, show/hide callbacks
- * @output Exports useTouchTrigger hook, isActionTrigger, LayerTouchTrigger type
+ * @output Exports useTouchTrigger hook, isActionTrigger, LayerTouchTrigger type,
+ * TOUCH_POINTER_TYPES and useTapStop (internal: not re-exported from index)
* @position Layer hook; shared touch behavior for useTooltip and useHoverCard
*
* SYNC: When modified, update:
@@ -37,7 +38,14 @@
* which is when UIKit dismisses a popover.
*/
-import {useCallback, useEffect, useRef, type RefObject} from 'react';
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ type MouseEvent as ReactMouseEvent,
+ type PointerEvent as ReactPointerEvent,
+ type RefObject,
+} from 'react';
import {currentGesture} from './gestureCounter';
import {useInteractionModalityTrackingFor} from '../utils/interactionModality';
@@ -60,6 +68,30 @@ export type LayerTouchTrigger = 'auto' | 'tap' | 'none';
*/
export const TOUCH_POINTER_TYPES = new Set(['touch', 'pen']);
+export function useTapStop(event: 'click'): {
+ onPointerDown: (event: ReactPointerEvent<Element>) => void;
+ onClick: (event: ReactMouseEvent<Element>) => void;
+};
+export function useTapStop(event: 'mousedown'): {
+ onPointerDown: (event: ReactPointerEvent<Element>) => void;
+ onMouseDown: (event: ReactMouseEvent<Element>) => void;
+};
+export function useTapStop(event: 'click' | 'mousedown') {
+ const pressIsTapRef = useRef(false);
+ const onPointerDown = (pointer: ReactPointerEvent<Element>) => {
+ pressIsTapRef.current = TOUCH_POINTER_TYPES.has(pointer.pointerType);
+ };
+ const cancel = (mouse: ReactMouseEvent<Element>) => {
+ if (pressIsTapRef.current) {
+ mouse.preventDefault();
+ }
+ pressIsTapRef.current = false;
+ };
+ return event === 'click'
+ ? {onPointerDown, onClick: cancel}
+ : {onPointerDown, onMouseDown: cancel};
+}
+
/**
* ARIA roles that make an element do something when activated. An explicit
* role wins over the tag: `<button role="presentation">` is scenery, and a