# Contributing The following guidance builds upon the existing [contribution guidelines for `@wordpress/components`](https://github.com/WordPress/gutenberg/blob/trunk/packages/components/CONTRIBUTING.md), which should serve as a starting point for contribution. The documentation included here encodes decisions and technical approaches which are unique to this package. ## Design principles - **Scope**: Only add components that are generic and reusable in building admin interfaces. If it can live in a higher-level package or one scoped to a particular feature (`admin-ui`, `block-editor`, `dataviews`, etc.), it should. - **Composition**: Prefer existing `@wordpress/ui` primitives over bespoke markup and styles when they fit. - **Spacing**: Components should not ship with outer margins. Consumers should provide their own spacing via layout like `Stack` or `className` custom styling. - **Tokens**: Visual values should use semantic `--wpds-*` design tokens, not hardcoded colors or spacing. Avoid props that accept arbitrary CSS values when a token or variant can express the intent. - **Token semantics**: Use `interactive` tokens for clickable UI and `content` tokens for static text. Prefer state variants (`-active`, `-disabled`) over mixing tones (for example, neutral at rest and brand on hover). - **Motion**: Animation should respect `prefers-reduced-motion`. ## Folder Structure Each component should be organized within its own folder under `src/` following this pattern: ```text src/ └── component-name/ ├── index.ts // Contains only exported public API ├── component-name.tsx // Main component matching the folder name (when applicable) ├── other-component.tsx // Any other ancillary / compound components ├── types.ts // TypeScript type definitions for all components in this folder ├── style.module.css // Styles for all components in this folder ├── stories/ │ ├── *.mdx // Storybook documentation files (optional) │ └── index.story.tsx // Storybook stories for all components in this folder └── test/ └── component-name.test.tsx // Tests for base component and all compound components ``` ### Folder Structure Guidelines - The folder name should match the primary component name - The `index.ts` file should contain only the public API exports for the component(s) ## Public APIs The package has a single entrypoint which exports all of the components of the package, and nothing else. Specifically: - Components are implemented as [compound components](#compound-components). Exported components will define their own subcomponents as properties of the top-level export. - Example: `import { Button } from '@wordpress/ui'; // Button, Button.Icon, etc.` - TypeScript types are not exported. If you need access to a component's prop types, use `React.ComponentProps`. - Example: `type ButtonProps = React.ComponentProps< typeof Button >;` - Styles are defined in the built JavaScript files and are not loaded separately. The package follows [semantic versioning](https://semver.org/), and the following are considered to be "the public API" for consideration of backwards-incompatible changes: - Component definitions (e.g. removing a component) - Component props (e.g. renaming, removing, or changing a props supported types such that existing usage would break in an update) - CSS properties prefixed with `--wp-ui-` (e.g. changing a CSS property such that it would negatively impact a user's experience). This surface is frozen: do not add new `--wp-ui-*` custom properties. See [Custom property names](#custom-property-names). ### Component naming Name components for what they are. In a name with a modifier, put the component's kind last and its appearance or purpose first. For example, `IconButton` is a button that displays an icon, while `ButtonLink` is a link styled as a button. Apply the same pattern to compound components. `Dialog.CloseIconButton`, `Drawer.CloseIconButton`, and `Notice.CloseIconButton` are icon buttons with a close or dismiss purpose. `ButtonLink.Icon` is the icon inside a link, not an interactive control of its own. Use the compound component's context when naming its parts. `Menu.LinkItem`, `Menu.CheckboxItem`, and `Menu.RadioItem` describe kinds of menu items; `Breadcrumb.LinkItem` describes a breadcrumb item. Names that describe a composition, such as `ControlWithError` and `ChipWithRemove`, can retain that structure. Keep filenames, prop types, display names, and Storybook names consistent with the public component name. Follow the [compound component conventions](#compound-components) when deciding whether to expose a standalone component or a `.Root` with required parts. ### Controlled and uncontrolled props When designing props for a new component: - Always offer both controlled and uncontrolled modes when the component has user-facing state. - Name the uncontrolled prop `defaultX`, the controlled prop `x`, and the callback `onXChange`. - In JSDoc comments, indicate which mode each prop is for and cross-reference the alternative: ```ts /** * Whether the panel is currently open (controlled). * * To render an uncontrolled component, use the `defaultOpen` prop instead. */ open?: boolean; /** * Whether the panel is initially open (uncontrolled). * @default false */ defaultOpen?: boolean; /** * Event handler called when the open state changes. */ onOpenChange?: ( open: boolean ) => void; ``` - Provide a `@default` JSDoc tag for the uncontrolled prop when there is a sensible default. ### Component status When you change a component's Storybook `parameters.componentStatus.status` or its public export, check the `@wordpress/ui` entry in the [`use-recommended-components`](../eslint-plugin/docs/rules/use-recommended-components.md) ESLint rule. `recommended` components belong in `allowed`, `use-with-caution` components in `caution`, and other statuses in neither. The Design System MCP catalog uses a curated Storybook manifest. Add `tags: [ 'manifest' ]` to a recommended component's story metadata, and remove the tag from the component it replaces. The tag is independent of `componentStatus`, so update both when changing the recommendation. Update the ESLint rule's replacement guidance and any migration documentation as needed. Run `npm run storybook:build` and `npm run storybook:manifest-snapshot`, then review and commit the generated snapshot and any allowlist reductions. See [Manifest snapshot regression testing](../../storybook/README.md#manifest-snapshot-regression-testing). When the component replaces one from `@wordpress/components`, the status change is one stage of [Replace a legacy component](../../docs/contributors/design/design-system-packages.md#replace-a-legacy-component). ## Compound Components This package follows the [compound component approach outlined in the `@wordpress/components` contributing guidelines](https://github.com/WordPress/gutenberg/blob/trunk/packages/components/CONTRIBUTING.md#compound-components). Some components will use a bare name (e.g. `Button`), while others will have a "root" component with modular children (e.g. `Tooltip.Root`). Use the base component name when it works standalone and any subcomponents are optional enhancements. Only introduce `.Root` when the component is modular and consumers are expected to compose multiple parts. Why? - `.Root` primarily coordinates, and isn't useful on its own - For example, a `Button` is useful on its own (renders an interactive element), unlike `Tabs.Root` - `.Root` has required subparts, signalling an expectation that it must be composed - A non-root component can still have _optional_ sub-parts, like a `Button.Icon` ### When exporting with `Object.assign` - Add the primary component's JSDoc description to both the implementation export, and the public `Object.assign` wrapper. Storybook reads the implementation component's JSDoc for the component description, while IDEs can read the latter. - All subcomponents should set their `displayName` to the full public name before the `Object.assign` export: ```ts ButtonIcon.displayName = 'Button.Icon'; /** * A versatile button component with multiple variants, tones, and sizes. */ export const Button = Object.assign( _Button, { /** * An icon component specifically designed to work well when rendered inside * a `Button` component. */ Icon: ButtonIcon, } ); ``` ### In Storybook - Include public subcomponents in the component's Storybook `subcomponents` metadata, keying them as the full compound name in dot notation: ```ts const meta: Meta< typeof Button > = { title: 'Components/@wordpress-ui/Button', id: 'design-system-components-button', component: Button, subcomponents: { 'Button.Icon': Button.Icon, }, }; ``` ## `render` Prop and Ref Forwarding All `@wordpress/ui` components support a `render` prop (via the `ComponentProps` utility type) that lets consumers swap the underlying HTML element. This section codifies the two canonical implementation patterns, the rules for handling `render`, and common anti-patterns to avoid. ### Canonical Patterns The correct approach depends on whether the component wraps a Base UI primitive or renders its own element. #### Pattern A: Custom components — `useRender` + `mergeProps` For components that do **not** wrap a Base UI primitive, use `useRender` and `mergeProps` from `@base-ui/react`. Destructure `render` from props (required by the `useRender` API), and pass it together with `ref` and merged props: ```tsx import { useRender, mergeProps } from '@base-ui/react'; import { forwardRef } from '@wordpress/element'; export const Root = forwardRef( function MyComponent( { render, className, ...restProps }, ref ) { const element = useRender( { render, defaultTagName: 'div', ref, props: mergeProps( { className: styles.root }, restProps ), } ); return element; } ); ``` `useRender` handles element creation, ref composition, and prop merging. #### Pattern B: Wrapper components — pass `ref` explicitly, spread `...props` For components that wrap a Base UI primitive or another `@wordpress/ui` component, pass the forwarded `ref` explicitly and spread `...props` (which carries `render` through implicitly): ```tsx import { Collapsible as _Collapsible } from '@base-ui/react/collapsible'; import { forwardRef } from '@wordpress/element'; export const Trigger = forwardRef( function MyTrigger( props, ref ) { return <_Collapsible.Trigger ref={ ref } { ...props } />; } ); ``` The inner component (Base UI or `@wordpress/ui`) handles `render` and ref composition internally. ### Explicit vs Implicit `render` Handling **Prefer implicit handling (via `...props` rest spread) unless the component needs to interact with `render`.** "Interact" means one of: 1. **Assign a default** — the component overrides the default element (e.g., `render = DEFAULT_TAG`). 2. **Transform** — the component wraps or modifies the value before passing it. 3. **Discard** — the component intentionally prevents element customization. In this case, destructure `render` to remove it from rest props, **and** `Omit` it from the type so consumers get a TypeScript error instead of silent no-op behavior. 4. **Pass to `useRender`** — Pattern A components where the hook API requires it as a named argument. In all other cases, let `render` flow through `...props`. Destructuring `render` only to write `render={ render }` is ceremony with no behavioral effect. ### Overriding the Default Element When a component needs to render a different element than its inner component's default (e.g., a `
` instead of ``), hoist the default to a **module-level constant** and assign it as a destructuring default. The default can be a **JSX element** or a **render function**, depending on what the component needs: ```tsx // JSX element — suitable when you only need to swap the tag. const DEFAULT_TAG =
; export const Title = forwardRef( function MyTitle( { render = DEFAULT_TAG, className, children, ...props }, ref ) { return ( { children } ); } ); ``` ```tsx // Render function — useful when the default needs to compose // other components or add additional props. const DEFAULT_RENDER = ( props: React.ComponentProps< typeof Stack > ) => ( ); export const Root = forwardRef( function MyRoot( { className, render = DEFAULT_RENDER, ...restProps }, ref ) { return ( <_Field.Root ref={ ref } className={ className } render={ render } { ...restProps } /> ); } ); ``` When using a JSX element, React elements are immutable descriptors — `useRender` calls `cloneElement` on them (creating a new element), never mutating the original. In both cases, a hoisted constant avoids allocating a fresh object every render and gives React/Base UI a stable reference for equality checks. ### Anti-patterns #### Bundling `ref` and `props` into a render fallback ```tsx // BAD: ref and props are lost when consumer provides render render={ render ??
} ``` When `render` is provided by the consumer, `ref` and `...props` remain on the unused fallback element and never reach the actual rendered element. Always pass `ref` and `...props` separately to the inner component. #### Unnecessary explicit destructure ```tsx // BAD: destructure-and-pass-through with no interaction function MyComponent( { render, ...props }, ref ) { return ; } // GOOD: let render flow through ...props function MyComponent( props, ref ) { return ; } ``` ## Overlay Slot Props Compound overlay primitives (`Tooltip`, `Popover`, `Select`, `Autocomplete`, etc.) expose their underlying Base UI subcomponents (`Portal`, `Positioner`, …) through **slot props** on `Popup` rather than as flat prop subsets. The corresponding subcomponents are exported alongside `Popup` (e.g. `Tooltip.Portal`, `Tooltip.Positioner`). ### Pattern For each Base UI subcomponent that we want to expose to consumers: 1. Export a renderable wrapper subcomponent matching the Base UI subcomponent's name (e.g. `Tooltip.Positioner`). 2. Add an optional slot prop on `Popup` named after the subcomponent (e.g. `positioner`). The prop type accepts a React element of the matching subcomponent: `ReactElement< Omit< MySubcomponentProps, 'children' > >`. 3. When the slot prop is omitted, `Popup` uses the wrapper subcomponent with default props. 4. When the slot prop is provided, `Popup` clones the given element and injects the rest of the subtree as `children`. Use the `renderSlotWithChildren` helper to keep this consistent across overlays. ```tsx } positioner={ } > Save ``` ### Why - One mental model across overlays — same prop names, same prop shape, regardless of which primitive is in use. - The wrapper subcomponents are also valid as standalone exports for advanced compositions. - `Popup` does not need to maintain a hand-picked `Pick<>` list of positioner/portal props. The full Base UI surface is reachable through the corresponding subcomponent. ### When to add a new slot prop Only when there is a concrete consumer that needs to reach a Base UI subcomponent's customization. Do not preemptively expose slots. High-level wrappers that hide `Popup` (for example `IconButton`, which renders a `Tooltip` internally) should re-expose the same slot props — same name, same shape — to keep the API uniform. ## CSS Architecture ### CSS Layers We use [CSS cascade layers](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Styling_basics/Cascade_layers) to ensure an expected order of precedence in style resolution. Component stylesheets follow this layering approach to maintain consistency and prevent specificity conflicts. `VisuallyHidden` is an exception: its styles are unlayered so global element styles cannot override its hiding behavior solely through cascade layer precedence. Layered component stylesheets must include the layer definition in the top-level `wp-ui` layer and wrap all styles within the appropriate layer: ```css @layer wp-ui { @layer utilities, components, compositions, overrides; @layer components { .stack { display: flex; } } } ``` #### CSS Layer Hierarchy All sub-layers are nested within the top-level `wp-ui` layer: - **`utilities`** - Shared utility styles (box-sizing, focus rings, resets) that apply before component styles - **`components`** - Default styles for design system components (`.stack`, etc.) - **`compositions`** - Internal compositions that extend base components - **`overrides`** - Last-resort styles to override default rules A rule that overrides a primitive defined in another stylesheet (e.g. a shared class from `overlay-chrome.module.css`) must live in a **higher** layer than that primitive — typically `wp-ui-compositions`. Placing both in the same layer leaves the conflict to be resolved by `