# Create Component

This guide explains how to create components using the `tasty` style helper and React Aria Hooks. Components in the Cube UI Kit follow consistent patterns for styling, accessibility, and functionality.

## Overview

Creating a component involves several optional but recommended elements:

- **Base properties** handling using `filterBaseProps`
- **Style properties** for direct styling capabilities
- **Modifiers (`mods`)** for state-based styling
- **Additional style properties** for styling inner elements
- **Sub-elements** for targeted styling within components
- **React Aria integration** for accessibility

Everything is optional - you can create simplified components without all features, but exported UI Kit components should be feature-rich and consistent.

Form-aware inputs use `useFieldProps` for both legacy instances and modern controllers. Map the control’s value API with `valuePropsMapper` and pass the resolved props to `wrapWithField`. The hook owns modern registration after commit, narrow subscriptions, cleanup, and unique accessible ids. Do not register during render, call the legacy adapter directly, or wrap a modern control in `Form.Item`. Modern validation options (`rules`, `deps`, `dependsOn`, `rulesKey`, `validationDelay`, `validateTrigger`, `errorPolicy`) flow through the same hook. A check the control's own prop implies (`NumberInput`'s `isInteger`) goes through the hook's `controlRules` param, which runs ahead of the caller's rules. Validators receive an AbortSignal and return or reject with a message; use `deps` for external closure inputs and `dependsOn` for form paths that trigger revalidation. `rulesKey` explicitly versions functions and skips source comparison while declarative constraints remain reactive. Extend `FieldBaseProps<Value>` to constrain typed modern descriptors to accepted model values, including `null | undefined` when supported even if change callbacks emit only non-null values; `useFieldProps` resolves descriptors and strips them before DOM forwarding. Descriptor options override only the input options they explicitly supply; put custom validation and structural rules together on the descriptor. See [Form](./components/form/Form.md) for the integration contract.

The [compiled custom-control example](https://github.com/cube-js/cube-ui-kit/blob/main/typecheck/consumer/modern-form-examples.tsx) shows explicit DOM forwarding, async validation, and default adoption. Shared input rule props accept existing legacy validators; use `ModernValidationRule` for strict modern success/error return types, and adapt legacy validators that resolve data before migrating them.

## Style forwarding through overlays

Forward consumer styles to the element that owns them. DialogContainer's `styles` targets the overlay content shell, while Dialog owns its own root styles. Layout.Panel keeps these channels explicit: `dialogProps.styles` for the shell and `dialogStyles` for its implicit Dialog, separate from inline panel `styles`. Avoid selectors that reach through the overlay to override its child.

## Core Concepts

### 1. Base Properties for Component Roots

For a component that owns its slots and appearance, use the kit’s `ComponentBaseProps` (or `ComponentBasePropsWithoutChildren`) and `filterComponentBaseProps`. Add a component-level `theme` or `title` only when the component gives it a defined meaning. Keep `className` and `style` available for third-party integrations.

```tsx
import { tasty } from '@tenphi/tasty';

import {
  type ComponentBaseProps,
  filterComponentBaseProps,
} from '../../../utils/react/componentBaseProps';

const MyElement = tasty({});

interface MyComponentProps extends ComponentBaseProps {
  customProp?: string;
}

function MyComponent(props: MyComponentProps) {
  return (
    <MyElement {...filterComponentBaseProps(props, { eventProps: true })}>
      {props.children}
    </MyElement>
  );
}
```

**Filter options:**

- `eventProps: true` - Include standard DOM event handlers (onClick, onFocus, etc.)
- `labelable: true` - Include ARIA labeling properties
- `propNames: Set<string>` - Include specific additional properties

### 2. Style Properties

Style properties allow consumers to apply layout and styling directly as component props. There are two approaches:

**Approach A — `styleProps` on `tasty()`** (simpler, when rest props go directly to the tasty element):

`styleProps` tells tasty which CSS properties the component accepts as typed React props. The component still needs to declare the matching TypeScript interfaces so consumers get autocomplete. This works when rest props are spread directly onto the tasty element.

```tsx
import { tasty, BaseProps, OUTER_STYLES, CONTAINER_STYLES } from '@tenphi/tasty';
import type { OuterStyleProps, ContainerStyleProps } from '@tenphi/tasty';

interface CubeMyComponentProps extends BaseProps, OuterStyleProps, ContainerStyleProps {
  label?: string;
  isDisabled?: boolean;
}

const MyElement = tasty({
  qa: 'MyComponent',
  styles: {
    display: 'flex',
    flow: 'column',
    padding: '2x',
    fill: '#surface',
    radius: '1r',
    border: {
      '': '#border',
      disabled: '#border.5',
    },
  },
  styleProps: [...OUTER_STYLES, ...CONTAINER_STYLES],
});

function MyComponent({ label, isDisabled, ...props }: CubeMyComponentProps) {
  return (
    <MyElement {...props} mods={{ disabled: isDisabled }}>
      {label}
    </MyElement>
  );
}
```

**Approach B — `extractStyles` + `filterBaseProps`** (when you need to split props between multiple elements or add custom logic):

```tsx
import {
  CONTAINER_STYLES,
  ContainerStyleProps,
  TEXT_STYLES,
  TextStyleProps,
  extractStyles,
  filterBaseProps,
} from '@tenphi/tasty';

interface MyComponentProps
  extends AllBaseProps,
    ContainerStyleProps,
    TextStyleProps {
}

function MyComponent(props: MyComponentProps) {
  const styles = extractStyles(props, [...CONTAINER_STYLES, ...TEXT_STYLES]);

  return (
    <Element
      {...filterBaseProps(props, { eventProps: true })}
      styles={styles}
    />
  );
}
```

**Available style property sets:**

- `BASE_STYLES` - `display`, `font`, `preset`, `hide`, `opacity`, `whiteSpace`
- `POSITION_STYLES` - `gridArea`, `order`, `margin`, `inset`, `position`, `zIndex`, etc.
- `BLOCK_STYLES` - `padding`, `border`, `radius`, `shadow`, `overflow`, etc.
- `COLOR_STYLES` - `color`, `fill`, `fade`
- `TEXT_STYLES` - `textTransform` (for other text styling, use `preset`)
- `DIMENSION_STYLES` - `width`, `height`, `flex`, `flexBasis`, etc.
- `FLOW_STYLES` - `flow`, `gap`, `align`, `justify`, `gridColumns`, etc.
- `CONTAINER_STYLES` - Combination of all above styles
- `OUTER_STYLES` - Position and dimension styles only

### 3. Modifiers (`mods`) Property

Modifiers enable state-based styling through the `mods` prop, which creates `data-*` attributes:

```tsx
interface MyComponentProps extends AllBaseProps {
  isLoading?: boolean;
}

function MyComponent({ isLoading, mods, ...props }: MyComponentProps) {
  return (
    <Element
      mods={{
        loading: isLoading,
        ...mods, // Allow external mods to override
      }}
      styles={{
        color: {
          '': '#dark',
          loading: '#gray',
          'loading & hovered': '#light-gray',
        }
      }}
    />
  );
}
```

**Usage:**

```tsx
<MyComponent mods={{ custom: true, highlighted: isHighlighted }} />
// Renders: <div data-custom data-highlighted class="...">
```

### 4. Sub-elements for Targeted Styling

Sub-elements allow styling inner parts through the main `styles` prop. They automatically inherit the parent's state and modifiers, making them ideal for tightly coupled UI elements.

```tsx
const MyElement = tasty({
  styles: {
    display: 'flex',
    gap: '1x',

    // Sub-element styles
    Icon: {
      preset: 'h3',
      color: '#purple',
    },
    Label: {
      preset: 'default / bold',
    },
  },
});

function MyComponent(props) {
  return (
    <MyElement {...props}>
      <span data-element="Icon">🎉</span>
      <span data-element="Label">{props.children}</span>
    </MyElement>
  );
}
```

**Usage with style overrides:**

```tsx
<MyComponent
  styles={{
    Icon: { color: '#red' },      // Override icon color
    Label: { preset: 'h4' }, // Override label size
  }}
>
  Custom styled content
</MyComponent>
```

**When to use sub-elements:**

- Elements that should share the parent's state (hover, focus, disabled, etc.)
- Tightly coupled UI parts (icon + label, title + subtitle)
- When you want a single `styles` prop to control everything
- Simpler components with predictable inner structure

### 5. Additional Style Properties

Create dedicated style properties for styling inner elements independently. This approach gives more control and allows inner elements to have their own state.

```tsx
import { Styles } from '@tenphi/tasty';

interface MyComponentProps extends AllBaseProps {
  styles?: Styles;
  iconStyles?: Styles; // Additional style property
  labelStyles?: Styles; // Another additional style property
}

function MyComponent({ iconStyles, labelStyles, ...props }: MyComponentProps) {
  const styles = extractStyles(props, CONTAINER_STYLES);

  return (
    <Element styles={styles}>
      <IconElement styles={iconStyles} />
      <LabelElement styles={labelStyles} />
    </Element>
  );
}
```

**When to use additional style properties:**

- Inner elements need independent state management (separate hover, focus behaviors)
- Complex components with multiple logical sections
- Components that need fine-grained styling control
- When different parts of the component might have different interaction patterns

### 6. React Aria Integration

Use React Aria hooks for accessibility and behavior:

```tsx
import { useButton } from 'react-aria';
import { useRef } from 'react';

import { omitActivationEventProps } from '../../../utils/react/disabledProps';

function MyButton(props) {
  const ref = useRef();
  const { buttonProps } = useButton(props, ref);

  return (
    <Element
      {...(props.isDisabled
        ? omitActivationEventProps(buttonProps)
        : buttonProps)}
      ref={ref}
      styles={extractStyles(props, CONTAINER_STYLES)}
    />
  );
}
```

Chrome still sends pointer events to a natively disabled `<button>`, and a press React Aria starts there makes the first click after it is enabled do nothing. So while disabled, drop the press handlers with `omitActivationEventProps` (`src/utils/react/disabledProps.ts`), or build on `useAction` or `Item`, which already do.

## Examples

### Example 1: Block Component (Basic)

This demonstrates a basic component with:

- Base properties support
- All container style properties
- Clean, minimal implementation

```tsx
import type { Ref } from 'react';
import {
  AllBaseProps,
  CONTAINER_STYLES,
  ContainerStyleProps,
  extractStyles,
  filterBaseProps,
  tasty,
} from '@tenphi/tasty';

const BlockElement = tasty({
  styles: {
    display: 'block',
  },
});

export interface CubeBlockProps
  extends Omit<AllBaseProps, keyof ContainerStyleProps | 'as' | 'ref'>,
    ContainerStyleProps {
  ref?: Ref<HTMLDivElement>;
}

export function Block({ ref, ...props }: CubeBlockProps) {
  const styles = extractStyles(props, CONTAINER_STYLES);

  return (
    <BlockElement
      {...filterBaseProps(props, { eventProps: true })}
      ref={ref}
      styles={styles}
    />
  );
}
```

### Example 2: Action Component (Advanced)

This demonstrates advanced features:

- React Aria integration (`useButton`)
- Complex modifier handling
- Multiple style property sets
- Custom behavior logic

```tsx
import type { Ref } from 'react';
import { useObjectRef } from '@react-aria/utils';
import { AriaButtonProps, useButton, useHover } from 'react-aria';
import {
  AllBaseProps,
  BaseStyleProps,
  CONTAINER_STYLES,
  ContainerStyleProps,
  extractStyles,
  Styles,
  TagName,
  tasty,
  TEXT_STYLES,
  TextStyleProps,
} from '@tenphi/tasty';

import { omitActivationEventProps } from '../../../utils/react/disabledProps';

export interface CubeActionProps<T extends TagName = 'button'>
  extends Omit<AllBaseProps<T>, 'htmlType' | 'ref'>,
    BaseStyleProps,
    ContainerStyleProps,
    TextStyleProps,
    Omit<AriaButtonProps, 'type'> {
  to?: string;
  label?: string;
  htmlType?: 'button' | 'submit' | 'reset';
  ref?: Ref<HTMLElement>;
}

const DEFAULT_ACTION_STYLES: Styles = {
  recipe: 'reset button',
  position: 'relative',
  preset: 'inherit',
  outline: {
    '': '#purple-03.0',
    focused: '#purple-03',
  },
  transition: 'theme',
  cursor: '$pointer',
} as const;

const ActionElement = tasty({
  as: 'button',
  styles: DEFAULT_ACTION_STYLES,
});

const STYLE_PROPS = [...CONTAINER_STYLES, ...TEXT_STYLES];

export function Action(
  {
    to,
    as = 'button',
    htmlType,
    label,
    theme,
    mods,
    onPress,
    isDisabled,
    ref,
    ...props
  }: CubeActionProps,
) {
  const domRef = useObjectRef(ref);
  const { buttonProps, isPressed } = useButton(
    {
      'aria-label': label,
      onPress,
      isDisabled,
      ...props,
    },
    domRef,
  );

  const { hoverProps, isHovered } = useHover({ isDisabled });

  const styles = extractStyles(props, STYLE_PROPS);

  return (
    <ActionElement
      data-theme={theme}
      // A disabled button takes no press handlers (see React Aria Integration).
      {...(isDisabled ? omitActivationEventProps(buttonProps) : buttonProps)}
      {...hoverProps}
      mods={{
        hovered: isHovered && !isDisabled,
        pressed: isPressed && !isDisabled,
        disabled: isDisabled,
        ...mods, // Allow external mods to override
      }}
      ref={domRef}
      type={htmlType || 'button'}
      as={as}
      styles={styles}
    />
  );
}
```

## Form Integration

Call `wrapWithField(control, props)` consistently: it renders the field chrome when the field has something to show, and `isBare` decides when set. Attach the field's ref to the control's own root, as the `Action` above does; the chrome takes none, so the ref reaches the control with or without it, and `labelRef` reaches the label. `useFieldProps` works out whether a field without a label needs the chrome, and asks for it with `isBare={false}`; a control that shows messages of its own asks the same way after it, with `isBare: props.isBare ?? false`, as `TagInput` does. A control that shows the errors of its `validate` passes `showsValidateErrors: true` to `useFieldProps`, so a `validate` asks too. Never infer presentation from message content. Pass React Aria's label props to the wrapper so a supplied label remains associated with the control in both modes. Inner controls whose parent owns the field chrome should receive `isBare` to avoid nested fields, written after any spread of the parent's resolved props, which can carry `isBare={false}`. An input's style props are `FieldLayoutStyleProps` and go to its outer element: route them with `splitFieldLayout`, put its `styles` on the control and pass `{ ...props, ...field }` to `wrapWithField`.

For input components that need to integrate with forms, see the [Field documentation](./components/form/Field.md) for comprehensive guidance on:

- Form state management
- Validation integration
- Label and help text handling
- Error state management
- Accessibility requirements for form controls

## Best Practices

1. **Choose the supported base properties**: Use `ComponentBaseProps` and `filterComponentBaseProps` for component-owned roots

2. **Provide appropriate style properties**: Choose the right combination of style property sets for your component's needs

3. **Design for extensibility**: Allow `mods` overrides and provide additional style properties for inner elements

4. **Use React Aria**: Integrate appropriate React Aria hooks for accessibility and standard behavior

5. **Follow naming conventions**: Use `Cube[ComponentName]Props` for interfaces and descriptive names for sub-elements

6. **Document sub-elements**: Clearly document what sub-elements are available for styling

7. **Keep it simple when appropriate**: Not every component needs all features - use what makes sense for your use case

8. **Use named React imports**: Import `useState`, `useRef`, `useEffectEvent` etc. directly from `'react'` instead of using `React.useState(...)`.

   **Use plain derived values and handlers.** Follow the [React Compiler rules](https://github.com/cube-js/cube-ui-kit/blob/main/docs/rules/react-compiler.md). Manual memoization controls identity only when required; it does not own a persistent per-mount lifetime.

9. **Choose callbacks by ownership**: Ordinary handlers are plain functions. Local effect-owned notifications use the canonical named `useEffectEvent` import. Keep resource configuration reactive and exclude Effect Events from dependencies. Retain internal `useEvent` only when a previously stored reference must keep its identity and call the latest committed implementation.

```tsx
import { useEffect, useEffectEvent } from 'react';

function Connection({ roomId, connect, notify, theme }) {
  const handleClick = () => notify(theme);
  const onConnected = useEffectEvent(() => notify(theme));

  useEffect(() => {
    const connection = connect(roomId);
    connection.on('connected', onConnected);
    connection.connect();
    return () => connection.disconnect();
  }, [connect, roomId]);

  return <button onClick={handleClick}>Notify</button>;
}
```

10. **Use `variants` for theming, not sizing**: The `variants` option in `tasty()` defines mutually exclusive visual variations (e.g. `default`, `danger`, `outline`). CSS is only generated for variants actually rendered at runtime. Use modifiers for dimensions like `size`.

## Component Checklist

When creating a new component, consider:

- [ ] Base properties match the component API and are forwarded to the correct root
- [ ] Appropriate style property sets
- [ ] Modifier (`mods`) support for state-based styling
- [ ] Additional style properties for inner elements
- [ ] Sub-element definitions for targeted styling
- [ ] React Aria integration for accessibility
- [ ] TypeScript interfaces following naming conventions
- [ ] Ref prop with the exposed DOM/imperative type and correct target; preserve generic inference and callback cleanup
- [ ] Default styles and theme support
- [ ] Documentation following UI Kit standards

Remember: Start simple and add features as needed. A basic, working component is better than an over-engineered one!
