Skip to content

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

TypeScript

feat(core): add composeEventHandlers; forward consumer onClick in SegmentedControlItem (#3863)

Cindy Zhanga3a4823ffe56
diff --git a/.changeset/compose-event-handlers.md b/.changeset/compose-event-handlers.md
new file mode 100644
index 0000000000..cddcc230b4
--- /dev/null
+++ b/.changeset/compose-event-handlers.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] SegmentedControlItem now forwards a consumer onClick, and add composeEventHandlers
+
+A consumer `onClick` on `SegmentedControlItem` was silently dropped — the internal selection handler clobbered it. It now runs alongside selection (call `preventDefault()` to opt out). The new `composeEventHandlers` utility chains handlers in order and stops when one prevents default, so components that own an interaction can also honor a consumer handler for the same event.
+@cixzhang
diff --git a/packages/core/src/SegmentedControl/SegmentedControl.test.tsx b/packages/core/src/SegmentedControl/SegmentedControl.test.tsx
index d29c2d27af..f6b93e1b40 100644
--- a/packages/core/src/SegmentedControl/SegmentedControl.test.tsx
+++ b/packages/core/src/SegmentedControl/SegmentedControl.test.tsx
@@ -701,3 +701,37 @@ describe('SegmentedControl data-testid forwarding', () => {
);
});
});
+
+describe('SegmentedControlItem onClick composition', () => {
+ it('calls a consumer onClick in addition to selecting the item', () => {
+ const onChange = vi.fn();
+ const onClick = vi.fn();
+ render(
+ <SegmentedControl value="grid" onChange={onChange} label="View mode">
+ <SegmentedControlItem value="list" label="List" onClick={onClick} />
+ </SegmentedControl>,
+ );
+
+ fireEvent.click(screen.getByRole('radio', {name: 'List'}));
+
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith('list');
+ });
+
+ it('lets a consumer onClick opt out of selection via preventDefault', () => {
+ const onChange = vi.fn();
+ render(
+ <SegmentedControl value="grid" onChange={onChange} label="View mode">
+ <SegmentedControlItem
+ value="list"
+ label="List"
+ onClick={e => e.preventDefault()}
+ />
+ </SegmentedControl>,
+ );
+
+ fireEvent.click(screen.getByRole('radio', {name: 'List'}));
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx b/packages/core/src/SegmentedControl/SegmentedControlItem.tsx
index b9d42ff4d0..5097f568fe 100644
--- a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx
+++ b/packages/core/src/SegmentedControl/SegmentedControlItem.tsx
@@ -15,7 +15,7 @@
* - /packages/cli/templates/blocks/components/SegmentedControl/ (showcase blocks)
*/
-import React, {useCallback, type ReactNode} from 'react';
+import React, {type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
@@ -29,7 +29,7 @@ import {
} from '../theme/tokens.stylex';
import {useSegmentedControlContext} from './SegmentedControlContext';
import type {SegmentedControlSize} from './SegmentedControlContext';
-import {mergeProps} from '../utils';
+import {mergeProps, composeEventHandlers} from '../utils';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
@@ -168,6 +168,7 @@ export function SegmentedControlItem({
isLabelHidden = false,
icon,
isDisabled = false,
+ onClick: onClickProp,
...rest
}: SegmentedControlItemProps) {
const ctx = useSegmentedControlContext();
@@ -183,11 +184,13 @@ export function SegmentedControlItem({
const size: SegmentedControlSize = ctx.size;
const isFill = ctx.layout === 'fill';
- const handleClick = useCallback(() => {
+ // Consumer-first: a consumer onClick can call preventDefault() to opt out of
+ // selection; otherwise selection proceeds when enabled and not selected.
+ const handleClick = composeEventHandlers(onClickProp, () => {
if (!isItemDisabled && !isSelected) {
ctx.onChange(value);
}
- }, [ctx, value, isItemDisabled, isSelected]);
+ });
const iconElement = icon ? (
<span {...stylex.props(styles.icon, iconSizeStyles[size])}>{icon}</span>
diff --git a/packages/core/src/utils/composeEventHandlers.test.ts b/packages/core/src/utils/composeEventHandlers.test.ts
new file mode 100644
index 0000000000..d1013072d6
--- /dev/null
+++ b/packages/core/src/utils/composeEventHandlers.test.ts
@@ -0,0 +1,71 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it, vi} from 'vitest';
+import type {SyntheticEvent} from 'react';
+import {composeEventHandlers} from './composeEventHandlers';
+
+function fakeEvent(): SyntheticEvent {
+ const event = {
+ defaultPrevented: false,
+ preventDefault() {
+ event.defaultPrevented = true;
+ },
+ };
+ return event as unknown as SyntheticEvent;
+}
+
+describe('composeEventHandlers', () => {
+ it('calls every handler in argument order', () => {
+ const calls: string[] = [];
+ const composed = composeEventHandlers(
+ () => calls.push('first'),
+ () => calls.push('second'),
+ );
+ composed(fakeEvent());
+ expect(calls).toEqual(['first', 'second']);
+ });
+
+ it('skips undefined handlers', () => {
+ const handler = vi.fn();
+ const composed = composeEventHandlers(undefined, handler, undefined);
+ composed(fakeEvent());
+ expect(handler).toHaveBeenCalledTimes(1);
+ });
+
+ it('passes the same event to each handler', () => {
+ const event = fakeEvent();
+ const a = vi.fn();
+ const b = vi.fn();
+ composeEventHandlers(a, b)(event);
+ expect(a).toHaveBeenCalledWith(event);
+ expect(b).toHaveBeenCalledWith(event);
+ });
+
+ it('stops after a handler prevents default', () => {
+ const first = vi.fn((e: SyntheticEvent) => e.preventDefault());
+ const second = vi.fn();
+ composeEventHandlers(first, second)(fakeEvent());
+ expect(first).toHaveBeenCalledTimes(1);
+ expect(second).not.toHaveBeenCalled();
+ });
+
+ it('lets a consumer handler opt out of later behavior (consumer-first order)', () => {
+ const consumer = vi.fn((e: SyntheticEvent) => e.preventDefault());
+ const ownBehavior = vi.fn();
+ composeEventHandlers(consumer, ownBehavior)(fakeEvent());
+ expect(ownBehavior).not.toHaveBeenCalled();
+ });
+
+ it('runs later handlers when default is not prevented', () => {
+ const consumer = vi.fn();
+ const ownBehavior = vi.fn();
+ composeEventHandlers(consumer, ownBehavior)(fakeEvent());
+ expect(ownBehavior).toHaveBeenCalledTimes(1);
+ });
+
+ it('returns a no-op-safe function when all handlers are undefined', () => {
+ expect(() =>
+ composeEventHandlers(undefined, undefined)(fakeEvent()),
+ ).not.toThrow();
+ });
+});
diff --git a/packages/core/src/utils/composeEventHandlers.ts b/packages/core/src/utils/composeEventHandlers.ts
new file mode 100644
index 0000000000..c1be087eb4
--- /dev/null
+++ b/packages/core/src/utils/composeEventHandlers.ts
@@ -0,0 +1,44 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file composeEventHandlers.ts
+ * @input Multiple React event handlers (or undefined)
+ * @output A single handler that calls each in order, stopping if one prevents default
+ * @position Utility; used by components that own an interaction (a click that
+ * selects, a keydown that drives arrow navigation) but also accept a consumer
+ * handler for the same event through {...rest}. Composes them instead of
+ * letting one clobber the other.
+ *
+ * Order is call order: the first argument runs first. Put the consumer handler
+ * first so it can opt out of the component's built-in behavior via
+ * `event.preventDefault()`; put the component's handler first when its behavior
+ * must always run regardless of the consumer.
+ */
+
+import type {SyntheticEvent} from 'react';
+
+/**
+ * Compose event handlers into one. Each handler runs in argument order; if any
+ * calls `event.preventDefault()`, the remaining handlers are skipped.
+ *
+ * @example
+ * ```tsx
+ * // Consumer first: a consumer onClick can preventDefault to block selection.
+ * <button onClick={composeEventHandlers(onClickProp, handleSelect)} />
+ *
+ * // Component first: built-in keyboard nav always runs.
+ * <div onKeyDown={composeEventHandlers(handleArrowKeys, onKeyDownProp)} />
+ * ```
+ */
+export function composeEventHandlers<E extends SyntheticEvent>(
+ ...handlers: (((event: E) => void) | undefined)[]
+): (event: E) => void {
+ return (event: E) => {
+ for (const handler of handlers) {
+ handler?.(event);
+ if (event.defaultPrevented) {
+ return;
+ }
+ }
+ };
+}
diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts
index 888343b4ab..d983ca154d 100644
--- a/packages/core/src/utils/index.ts
+++ b/packages/core/src/utils/index.ts
@@ -68,6 +68,7 @@ export {getKey, type Key, type KeyFallback} from './getKey';
export {mergeProps} from './mergeProps';
export {mergeRefs} from './mergeRefs';
+export {composeEventHandlers} from './composeEventHandlers';
export {themeProps, themeDataAttributes} from './themeProps';
export type {
ClassValue,