# Rule builder

Define controlled IF conditions and ordered THEN actions without executing an automation.

Access: pro. Category: Blocks. Kind: composite.

## When to use

- Use it when a page needs define controlled if conditions and ordered then actions without executing an automation.
- Choose it inside an authenticated product surface when the host application owns routing, persistence, and service calls.

## Alternatives

- Choose empty-state instead when empty collections, search results and errors with a clear next action is the actual interface need, rather than rule builder.

## Setup for agents

Use React 19 and TypeScript. Initialize shadcn for your framework, then merge this exact entry into components.json:

```json
{
  "registries": {
    "@tidal-pro": {
      "url": "https://tidalui.com/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${TIDALUI_TOKEN}"
      }
    }
  }
}
```

The namespace must be named **@tidal-pro** because transitive Pro dependencies use that namespace. Obtain an agent key from your active Pro account at https://tidalui.com/account. Keep TIDALUI_TOKEN in your local environment, never in components.json, client code, Git or logs.

```sh
export TIDALUI_TOKEN='your-private-agent-key'
npx shadcn@latest add @tidal-pro/waitlist-form
npx shadcn@latest add https://tidalui.com/r/tidal-button.json
```

Free command: `npx shadcn@latest add https://tidalui.com/r/<name>.json`.
Pro command: `npx shadcn@latest add @tidal-pro/<name>`.

Import the base stylesheet and every stylesheet listed on the installed item's metadata. For example:

```tsx
import "./components/ui/tidal.css";
import "./components/ui/hero-section.css";
// Place installed components inside this wrapper:
<div className="tidal-scope" data-theme="dark">...</div>
```

Omit data-theme for the default light theme. Put the attribute on the same tidal-scope element for dark mode. Every component installs the shared free tidal-base dependency. After upgrading, run `npx shadcn@latest add https://tidalui.com/r/tidal-base.json --overwrite` to receive current tokens. Review local modifications before overwriting.

Vite: Use React + TypeScript. Map @/* to ./src/* in paths and Vite resolve.alias. Import tidal.css and each component stylesheet in your application entry.

Next.js 15 App Router: Next.js App Router: import tidal.css and component CSS in app/layout.tsx. Interactive examples belong in a client component with "use client". Map @/* to ./* or ./src/* to match your project.

TypeScript 6: use paths without baseUrl:

```json
{
  "compilerOptions": {
    "paths": {
      "@/*": [
        "./src/*"
      ]
    }
  }
}
```

Pro registry requests are server/CLI-only. Use the same-origin account interface in a browser; cross-origin Authorization preflights are intentionally unsupported.


## Install Rule builder

```sh
npx shadcn@latest add @tidal-pro/rule-builder
```

Stylesheets: `components/ui/tidal.css`, `components/ui/rule-builder.css`.

## Minimal example

```tsx
import"./components/ui/tidal.css";
import"./components/ui/rule-builder.css";
import{TidalRuleBuilder}from"./components/ui/rule-builder";
export default(p:Parameters<typeof TidalRuleBuilder>[0])=><div className="tidal-scope"><TidalRuleBuilder {...p}/></div>;
```

## Structured props

- `TidalRuleBuilder.actionDefinitions: ReadonlyArray<TidalRuleActionDefinition>`: Required action definitions value accepted by this exported component.
- `TidalRuleBuilder.actions: ReadonlyArray<TidalRuleAction>`: Required actions value accepted by this exported component.
- `TidalRuleBuilder.conditions: TidalRuleConditionConfig`: Required conditions value accepted by this exported component.
- `TidalRuleBuilder.createAction: (event: MouseEvent<HTMLButtonElement>) => TidalRuleAction`: Required create action value accepted by this exported component.
- `TidalRuleBuilder.onActionsChange: (next: readonly TidalRuleAction[], change: TidalRuleActionChange, event: ActionEvent) => void`: Callback invoked when the actions change interaction is proposed.
- `TidalRuleBuilder.title: ReactNode`: Required title value accepted by this exported component.
- `TidalRuleBuilder.actionErrors?: Readonly<Record<string, ReactNode>> | undefined` (default {}): Optional action errors value accepted by this exported component.
- `TidalRuleBuilder.addActionButtonProps?: NativeButtonProps | undefined` (default {}): Optional add action button props value accepted by this exported component.
- `TidalRuleBuilder.addActionButtonRef?: Ref<HTMLButtonElement> | undefined`: Optional add action button ref value accepted by this exported component.
- `TidalRuleBuilder.description?: ReactNode`: Optional description value accepted by this exported component.
- `TidalRuleBuilder.disabled?: boolean | undefined` (default false): Optional disabled value accepted by this exported component.
- `TidalRuleBuilder.emptyActions?: ReactNode`: Optional empty actions value accepted by this exported component.
- `TidalRuleBuilder.getActionControlProps?: ((action: TidalRuleAction, index: number) => TidalRuleActionControlProps | undefined) | undefined`: Optional get action control props value accepted by this exported component.
- `TidalRuleBuilder.headingLevel?: "h2" | "h3" | "h4" | "h5" | undefined` (default "h2"): Optional heading level value accepted by this exported component.
- `TidalRuleBuilder.labels?: Partial<TidalRuleBuilderLabels> | undefined`: Optional labels value accepted by this exported component.
- `TidalRuleBuilder.namePrefix?: string | undefined` (default "rule"): Optional name prefix value accepted by this exported component.
- `TidalRuleBuilder.onSubmit?: ((event: FormEvent<HTMLFormElement>) => void) | undefined`: Callback invoked when the submit interaction is proposed.
- `TidalRuleBuilder.pending?: boolean | undefined` (default false): Optional pending value accepted by this exported component.
- `TidalRuleBuilder.submitButtonProps?: NativeButtonProps | undefined` (default {}): Optional submit button props value accepted by this exported component.
- `TidalRuleBuilder.submitButtonRef?: Ref<HTMLButtonElement> | undefined`: Optional submit button ref value accepted by this exported component.
- `TidalRuleBuilder.submitLabel?: ReactNode`: Optional submit label value accepted by this exported component.
- `TidalRuleBuilder.summary?: ReactNode`: Optional summary value accepted by this exported component.

## Complete usage example

[Source](https://tidalui.com/examples/rule-builder.tsx) | [Manifest](https://tidalui.com/examples/rule-builder.json). Install the listed additional dependencies. Consumer fixture: TypeScript pass; Vite pass. This fixture check is distinct from the actual shadcn install receipt.

```tsx
import "./components/ui/tidal.css";

import { useId, useRef, useState, type FormEvent } from "react";

import { TidalRuleBuilder, type TidalRuleAction, type TidalRuleActionDefinition } from "./components/ui/rule-builder";

import type { TidalQueryField, TidalQueryRule, TidalQueryConjunction } from "./components/ui/query-builder";

import "./components/ui/rule-builder.css";

import "./components/ui/query-builder.css";



const tidalExampleStyles = ".tidal-scope .rule-builder-demo {\n  display: grid;\n  width: min(100%, 920px);\n  min-width: 0;\n  gap: 12px;\n}\n\n.tidal-scope .rule-builder-demo-status,\n.tidal-scope .rule-builder-demo-note {\n  min-width: 0;\n  margin: 0;\n  color: var(--t-muted);\n  font-size: 11px;\n  line-height: 1.5;\n  overflow-wrap: anywhere;\n}\n\n.tidal-scope .rule-builder-demo-status {\n  padding-inline-start: 2px;\n  color: var(--t-ink);\n  font-weight: 650;\n}\n\n.tidal-scope .rule-builder-demo-note {\n  padding-block-start: 10px;\n  border-block-start: 1px solid var(--t-border);\n}";

const fields: readonly TidalQueryField[] = [
  {
    id: "plan",
    label: "Plan",
    kind: "enum",
    operators: [
      { id: "is", label: "is" },
      { id: "is-not", label: "is not" },
    ],
    options: [
      { value: "starter", label: "Starter" },
      { value: "team", label: "Team" },
      { value: "scale", label: "Scale" },
    ],
  },
  {
    id: "open-tasks",
    label: "Open tasks",
    kind: "number",
    operators: [
      { id: "above", label: "is above" },
      { id: "below", label: "is below" },
      { id: "equal", label: "equals" },
    ],
    placeholder: "0",
  },
  {
    id: "project-name",
    label: "Project name",
    kind: "text",
    operators: [
      { id: "contains", label: "contains" },
      { id: "starts", label: "starts with" },
    ],
    placeholder: "Launch",
  },
];

const definitions: readonly TidalRuleActionDefinition[] = [
  {
    id: "assign",
    label: "Assign owner",
    kind: "enum",
    options: [
      { value: "ava", label: "Ava Chen" },
      { value: "noah", label: "Noah Patel" },
      { value: "mila", label: "Mila Santos" },
    ],
  },
  {
    id: "label",
    label: "Add label",
    kind: "text",
    placeholder: "Needs review",
  },
  {
    id: "priority",
    label: "Set priority",
    kind: "enum",
    options: [
      { value: "normal", label: "Normal" },
      { value: "high", label: "High" },
      { value: "urgent", label: "Urgent" },
    ],
  },
  { id: "pause", label: "Pause intake", kind: "none" },
];

const initialRules: readonly TidalQueryRule[] = [
  { id: "plan-team", fieldId: "plan", operatorId: "is", value: "team" },
  {
    id: "tasks-above",
    fieldId: "open-tasks",
    operatorId: "above",
    value: "8",
  },
];

const initialActions: readonly TidalRuleAction[] = [
  { id: "owner", definitionId: "assign", value: "ava" },
  { id: "review", definitionId: "label", value: "Needs review" },
];

export function RuleBuilderDemo() {
  const base = useId().replace(/:/g, "");
  const nextRule = useRef(0);
  const nextAction = useRef(0);
  const [rules, setRules] = useState<readonly TidalQueryRule[]>(initialRules);
  const [actions, setActions] =
    useState<readonly TidalRuleAction[]>(initialActions);
  const [conjunction, setConjunction] = useState<TidalQueryConjunction>("and");
  const [status, setStatus] = useState(
    "Adjust the conditions and ordered actions, then save the local draft.",
  );

  function save(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    const actionTypes = [...data.entries()].filter(([name]) =>
      name.endsWith(".type"),
    ).length;
    setStatus(
      `Draft saved locally with ${rules.length} conditions and ${actionTypes} actions. Nothing was run.`,
    );
  }

  return (
    <div className="rule-builder-demo">
      <TidalRuleBuilder
        title="Routing rule"
        description="Define the conditions, then order the actions that should follow."
        namePrefix="routing"
        conditions={{
          fields,
          rules,
          conjunction,
          onConjunctionChange: (next) => setConjunction(next),
          onRulesChange: (next) => setRules(next),
          createRule: () => ({
            id: `${base}-condition-${++nextRule.current}`,
            fieldId: "plan",
            operatorId: "is",
            value: "starter",
          }),
        }}
        actionDefinitions={definitions}
        actions={actions}
        onActionsChange={(next) => setActions(next)}
        createAction={() => ({
          id: `${base}-action-${++nextAction.current}`,
          definitionId: "assign",
          value: "noah",
        })}
        summary={
          <p>
            <strong>Draft:</strong> Match{" "}
            {conjunction === "and" ? "all" : "any"} of {rules.length}{" "}
            conditions, then run {actions.length} ordered actions.
          </p>
        }
        submitLabel="Save rule draft"
        onSubmit={save}
      />
      <output className="rule-builder-demo-status" aria-live="polite">
        {status}
      </output>
      <p className="rule-builder-demo-note">
        Sample data. Changes stay in this preview and no automation runs.
      </p>
    </div>
  );
}

export default function AgentExample() {
  return (
    <div className="tidal-scope" data-theme="light" dir="ltr">
      <style>{tidalExampleStyles}</style>
      <RuleBuilderDemo />
    </div>
  );
}

```

## Gotchas

- The host application owns data, validation, persistence, navigation, and service side effects described by this API.

## Theme and accessibility

{"tokens":["--t-accent","--t-border","--t-border-strong","--t-canvas","--t-danger","--t-display","--t-ease-out","--t-ease-spring","--t-faint","--t-font","--t-ink","--t-line","--t-muted","--t-primary","--t-primary-contrast","--t-radius-card","--t-radius-control","--t-radius-overlay","--t-radius-panel","--t-ring","--t-shadow-lg","--t-shadow-soft","--t-soft","--t-subtle","--t-surface","--t-wash"],"darkMode":true}

{"keyboard":["Tab and Shift+Tab follow the component's native focus order.","Arrow-key behavior follows the exported composite-control implementation."],"aria":"The component wires labels and relationships from consumer-provided visible text or ARIA props; preserve those labels in production.","notes":"Verify focus visibility, text alternatives, contrast, and reduced motion in the final composition."}

Consumer-owned conditions compose the accepted Query builder and retain its flat AND/OR field, operator, value, validation, native-handler, ref and focus contracts. Ordered actions use unique IDs plus consumer-defined text, finite-number, enum or no-value definitions. onActionsChange receives the complete proposed array, typed add/remove/move/definition/value detail and native event, so consumers may accept or decline every change. Enabled native action handlers run first and prevention stops proposals; disabled handlers do not run. Add and accepted removal recover focus only from the exact source and use visible action controls, Add or the persistent labelled actions region without scrolling unrelated ancestors. Move controls remain native buttons and keyed rows preserve their focus. The native form supports action/method and exact FormData names through namePrefix, plus cleanup-aware form/control refs, per-action native props, aggregate disabled/pending state, optional errors, summary and submit action. Invalid condition configuration, unknown or duplicate action IDs, unavailable definitions/enum values, malformed finite numbers and malformed definitions fail visibly and block native submission. Controls retain ordinary Tab order, 44px targets, 16px narrow inputs, RTL, forced colors and reduced motion. Consumers own validation, serialization, persistence and execution; the component never runs an action, request or timer-backed workflow.
