An open source design system that's fully customizable and agent ready
TypeScript
fix(docsite): bridge controlled component callbacks in interactive preview (#2716) (#2904)
Cindy Zhang26ae4a3b56f6
diff --git a/apps/docsite/src/__tests__/component-preview-state.test.ts b/apps/docsite/src/__tests__/component-preview-state.test.tsindex 32845db7cf..66a3aa6d3f 100644--- a/apps/docsite/src/__tests__/component-preview-state.test.ts+++ b/apps/docsite/src/__tests__/component-preview-state.test.ts@@ -111,4 +111,101 @@ describe('component detail preview state', () => {expect(onPropChange).toHaveBeenCalledWith('isOpen', false);});++ it('bridges a controlled value/onChange pair so the preview updates', () => {+ const knobs = pickPrimaryProps('Pagination', [+ prop({name: 'page', type: 'number', required: true}),+ prop({+ name: 'onChange',+ type: '(page: number) => void',+ required: true,+ }),+ prop({name: 'totalItems', type: 'number'}),+ prop({name: 'pageSize', type: 'number', default: '10'}),+ prop({+ name: 'onPageSizeChange',+ type: '(pageSize: number) => void',+ }),+ ]);++ const onPropChange = vi.fn();+ const runtimeState = buildRuntimePreviewState(+ {page: 1, totalItems: 100, pageSize: 10},+ onPropChange,+ {knobs},+ );++ // onChange's first param is `page`, which is a value prop → wired.+ expect(runtimeState.onChange).toEqual(expect.any(Function));+ (runtimeState.onChange as (page: number) => void)(3);+ expect(onPropChange).toHaveBeenCalledWith('page', 3);++ // onPageSizeChange's first param is `pageSize`, also a value prop → wired.+ expect(runtimeState.onPageSizeChange).toEqual(expect.any(Function));+ (runtimeState.onPageSizeChange as (pageSize: number) => void)(25);+ expect(onPropChange).toHaveBeenCalledWith('pageSize', 25);+ });++ it('bridges a generic value/onChange pair', () => {+ const knobs = pickPrimaryProps('Slider', [+ prop({name: 'value', type: 'number', required: true}),+ prop({+ name: 'onChange',+ type: '(value: number) => void',+ required: true,+ }),+ ]);++ const onPropChange = vi.fn();+ const runtimeState = buildRuntimePreviewState({value: 10}, onPropChange, {+ knobs,+ });++ (runtimeState.onChange as (value: number) => void)(42);+ expect(onPropChange).toHaveBeenCalledWith('value', 42);+ });++ it('leaves callbacks alone when no matching value prop exists in state', () => {+ const knobs = pickPrimaryProps('Button', [+ prop({name: 'label', type: 'string'}),+ prop({name: 'onClick', type: '(e: MouseEvent) => void'}),+ ]);++ const state = {label: 'Click me'};+ const onPropChange = vi.fn();+ const runtimeState = buildRuntimePreviewState(state, onPropChange, {knobs});++ // No `e` value prop in state → callback not bridged; state returned as-is.+ expect(runtimeState).toBe(state);+ expect(runtimeState.onClick).toBeUndefined();+ });++ it('only bridges isOpen when the preview opts into controlling open state', () => {+ const knobs = pickPrimaryProps('Popover', [+ prop({name: 'isOpen', type: 'boolean', required: true}),+ prop({+ name: 'onOpenChange',+ type: '(isOpen: boolean) => void',+ required: true,+ }),+ ]);++ const onPropChange = vi.fn();++ const withoutOptIn = buildRuntimePreviewState(+ {isOpen: true},+ onPropChange,+ {+ knobs,+ },+ );+ expect(withoutOptIn.onOpenChange).toBeUndefined();++ const withOptIn = buildRuntimePreviewState({isOpen: true}, onPropChange, {+ knobs,+ canControlOpenState: true,+ });+ (withOptIn.onOpenChange as (isOpen: boolean) => void)(false);+ expect(onPropChange).toHaveBeenCalledWith('isOpen', false);+ });});diff --git a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsxindex d98c9b14a3..34a9d66581 100644--- a/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx+++ b/apps/docsite/src/components/component-detail/ComponentDetailClient.tsx@@ -199,6 +199,7 @@ function ComponentDetailInner({<InteractivePreviewStagename={comp.name}state={state}+ knobs={knobs}missingRequiredProps={missingRequiredProps}onPropChange={setProp}canControlOpenState={diff --git a/apps/docsite/src/components/component-detail/InteractivePreview.tsx b/apps/docsite/src/components/component-detail/InteractivePreview.tsxindex 7534148081..41cc926ab3 100644--- a/apps/docsite/src/components/component-detail/InteractivePreview.tsx+++ b/apps/docsite/src/components/component-detail/InteractivePreview.tsx@@ -25,6 +25,7 @@ import {buildRuntimePreviewState,getMissingRequiredProps,pickPrimaryProps,+ type KnobProp,} from './interactiveState';import type {PropDoc,@@ -187,12 +188,14 @@ export function useInteractiveState(export function InteractivePreviewStage({name,state,+ knobs,missingRequiredProps = [],onPropChange,canControlOpenState = false,}: {name: string;state: Record<string, unknown>;+ knobs?: KnobProp[];missingRequiredProps?: string[];onPropChange?: (propName: string, value: unknown) => void;canControlOpenState?: boolean;@@ -202,9 +205,12 @@ export function InteractivePreviewStage({const runtimeState = useMemo(() =>resolveValue(- buildRuntimePreviewState(state, onPropChange, {canControlOpenState}),+ buildRuntimePreviewState(state, onPropChange, {+ canControlOpenState,+ knobs,+ }),) as Record<string, unknown>,- [state, onPropChange, canControlOpenState],+ [state, onPropChange, canControlOpenState, knobs],);if (missingRequiredProps.length > 0) {diff --git a/apps/docsite/src/components/component-detail/interactiveState.ts b/apps/docsite/src/components/component-detail/interactiveState.tsindex 1c4b9557bd..3076e24d72 100644--- a/apps/docsite/src/components/component-detail/interactiveState.ts+++ b/apps/docsite/src/components/component-detail/interactiveState.ts@@ -207,21 +207,67 @@ export function getMissingRequiredProps(.map(({row}) => row.name);}+/**+ * Returns the name of a callback's first parameter from its stringified type,+ * e.g. `(page: number) => void` → `page`. Returns `null` for unnamed params.+ */+function getCallbackTargetProp(type: string): string | null {+ const match = /^\s*\(\s*([^):,]+)/.exec(type);+ if (!match) {+ return null;+ }+ const name = match[1].trim().replace(/\?$/, '');+ return /^[A-Za-z_$][\w$]*$/.test(name) ? name : null;+}++/**+ * Wires controlled-component change handlers back into playground state so the+ * preview reflects interaction (clicking a Pagination page, etc.). A callback+ * whose first parameter names a value prop in `state` (page/onChange,+ * value/onChange, pageSize/onPageSizeChange) replaces its noop with one that+ * updates that prop. isOpen/onOpenChange stays gated behind canControlOpenState.+ */export function buildRuntimePreviewState(state: Record<string, unknown>,onPropChange?: (propName: string, value: unknown) => void,- options?: {canControlOpenState?: boolean},+ options?: {canControlOpenState?: boolean; knobs?: KnobProp[]},): Record<string, unknown> {+ if (onPropChange == null) {+ return state;+ }++ const next: Record<string, unknown> = {...state};+ let changed = false;++ for (const {row, control} of options?.knobs ?? []) {+ if (control.kind !== 'callback') {+ continue;+ }+ // Only change handlers — not side-effect callbacks (changeAction) or+ // one-off events (onClick).+ if (!/^on[A-Z].*Change$/.test(row.name) && row.name !== 'onChange') {+ continue;+ }+ const target = getCallbackTargetProp(row.type);+ if (target == null || !(target in state)) {+ continue;+ }+ if (target === 'isOpen' && options?.canControlOpenState !== true) {+ continue;+ }+ next[row.name] = (value: unknown) => onPropChange(target, value);+ changed = true;+ }++ // Fallback when knobs aren't supplied: bridge a controllable isOpen pair.if (- onPropChange == null ||- options?.canControlOpenState !== true ||- typeof state.isOpen !== 'boolean'+ !changed &&+ options?.canControlOpenState === true &&+ typeof state.isOpen === 'boolean') {- return state;+ next.onOpenChange = (isOpen: boolean) => onPropChange('isOpen', isOpen);+ return next;}- return {- ...state,- onOpenChange: (isOpen: boolean) => onPropChange('isOpen', isOpen),- };+ return changed ? next : state;}diff --git a/packages/core/src/Pagination/Pagination.doc.mjs b/packages/core/src/Pagination/Pagination.doc.mjsindex af0a30afb8..66cf925680 100644--- a/packages/core/src/Pagination/Pagination.doc.mjs+++ b/packages/core/src/Pagination/Pagination.doc.mjs@@ -107,6 +107,14 @@ export const docs = {{className: 'xds-pagination-dot', visualProps: ['size'], states: ['active']},],},+ playground: {+ defaults: {+ page: 1,+ totalItems: 100,+ pageSize: 10,+ variant: 'pages',+ },+ },usage: {description:'Pagination lets users step through pages of content. Place it below a table, list, or card grid so users can move forward and backward through results. Pick a variant to match the context: numbered pages for data tables, a count for large lists, compact for tight spaces, or dots for carousels.',