# Query builder

Build a controlled flat AND/OR rule set from consumer-defined fields, operators, and values.

Access: pro. Category: Forms. Kind: composite.

## When to use

- Use it when a page needs build a controlled flat and/or rule set from consumer-defined fields, operators, and values.
- Choose it when the host application can supply the required state and keep business logic outside the presentation component.

## Alternatives

- Choose form-field instead when a labeled email field with validation and help text is the actual interface need, rather than query 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 Query builder

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

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

## Minimal example

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

## Structured props

- `TidalQueryBuilder.conjunction: TidalQueryConjunction`: Required conjunction value accepted by this exported component.
- `TidalQueryBuilder.createRule: (event: MouseEvent<HTMLButtonElement>) => TidalQueryRule`: Required create rule value accepted by this exported component.
- `TidalQueryBuilder.fields: ReadonlyArray<TidalQueryField>`: Required fields value accepted by this exported component.
- `TidalQueryBuilder.label: ReactNode`: Required label value accepted by this exported component.
- `TidalQueryBuilder.onConjunctionChange: (next: TidalQueryConjunction, event: ChangeEvent<HTMLSelectElement>) => void`: Callback invoked when the conjunction change interaction is proposed.
- `TidalQueryBuilder.onRulesChange: (next: TidalQueryRule[], change: TidalQueryChange, event: RuleChangeEvent) => void`: Callback invoked when the rules change interaction is proposed.
- `TidalQueryBuilder.rules: ReadonlyArray<TidalQueryRule>`: Required rules value accepted by this exported component.
- `TidalQueryBuilder.addButtonProps?: NativeActionProps | undefined` (default {}): Optional add button props value accepted by this exported component.
- `TidalQueryBuilder.addButtonRef?: Ref<HTMLButtonElement> | undefined`: Optional add button ref value accepted by this exported component.
- `TidalQueryBuilder.conjunctionSelectProps?: NativeSelectProps | undefined` (default {}): Optional conjunction select props value accepted by this exported component.
- `TidalQueryBuilder.conjunctionSelectRef?: Ref<HTMLSelectElement> | undefined`: Optional conjunction select ref value accepted by this exported component.
- `TidalQueryBuilder.description?: ReactNode`: Optional description value accepted by this exported component.
- `TidalQueryBuilder.disabled?: boolean | undefined` (default false): Optional disabled value accepted by this exported component.
- `TidalQueryBuilder.emptyMessage?: ReactNode` (default "No rules yet. Add a rule to begin."): Optional empty message value accepted by this exported component.
- `TidalQueryBuilder.errors?: Readonly<Record<string, ReactNode>> | undefined` (default {}): Optional errors value accepted by this exported component.
- `TidalQueryBuilder.getRuleControlProps?: ((rule: TidalQueryRule, index: number) => TidalQueryRuleControlProps | undefined) | undefined`: Optional get rule control props value accepted by this exported component.
- `TidalQueryBuilder.labels?: Partial<TidalQueryBuilderLabels> | undefined`: Optional labels value accepted by this exported component.
- `TidalQueryBuilder.result?: ReactNode`: Optional result value accepted by this exported component.

## Complete usage example

[Source](https://tidalui.com/examples/query-builder.tsx) | [Manifest](https://tidalui.com/examples/query-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
"use client";

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

import { useMemo, useRef, useState } from "react";

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

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



const tidalExampleStyles = ".query-builder-demo,\n.query-builder-demo * {\n  box-sizing: border-box;\n}\n\n.query-builder-demo {\n  display: grid;\n  width: min(760px, 100%);\n  min-width: 0;\n  gap: 12px;\n  padding: clamp(12px, 2.4vw, 18px);\n  border: 1px solid var(--t-border);\n  border-radius: 18px;\n  background: var(--t-surface);\n  box-shadow: 0 18px 54px var(--t-shadow-soft);\n}\n\n.query-builder-demo-footer {\n  display: flex;\n  min-width: 0;\n  align-items: center;\n  justify-content: space-between;\n  gap: 12px;\n  color: var(--t-muted);\n  font-size: 11px;\n  line-height: 1.4;\n}\n\n.query-builder-demo-footer > span {\n  min-width: 0;\n  overflow-wrap: anywhere;\n}\n\n.query-builder-demo-footer button {\n  display: inline-flex;\n  min-width: 64px;\n  min-height: 44px;\n  flex: 0 0 auto;\n  align-items: center;\n  justify-content: center;\n  padding: 0 13px;\n  border: 1px solid var(--t-border);\n  border-radius: 9px;\n  background: var(--t-surface);\n  color: var(--t-ink);\n  font: inherit;\n  font-size: 12px;\n  font-weight: 720;\n  cursor: pointer;\n}\n\n.query-builder-demo-footer button:hover {\n  border-color: var(--t-ink);\n}\n\n.query-builder-demo-footer button:focus-visible {\n  outline: 2px solid var(--t-accent);\n  outline-offset: 3px;\n}\n\n.query-builder-demo-note {\n  margin: 0;\n  color: var(--t-muted);\n  font-size: 11px;\n  line-height: 1.45;\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .query-builder-demo-footer button {\n    transition: none;\n  }\n}\n\n@media (forced-colors: active) {\n  .query-builder-demo,\n  .query-builder-demo-footer button {\n    border-color: CanvasText;\n    box-shadow: none;\n  }\n}";

const FIELDS: readonly TidalQueryField[] = [
  {
    id: "status",
    label: "Project status",
    kind: "enum",
    operators: [
      { id: "is", label: "is" },
      { id: "is-not", label: "is not" },
    ],
    options: [
      { value: "active", label: "Active" },
      { value: "review", label: "In review" },
      { value: "complete", label: "Complete" },
    ],
  },
  {
    id: "owner",
    label: "Owner",
    kind: "text",
    placeholder: "Name or team",
    operators: [
      { id: "contains", label: "contains" },
      { id: "is", label: "is exactly" },
      { id: "is-empty", label: "is empty", requiresValue: false },
    ],
  },
  {
    id: "estimate",
    label: "Estimate",
    kind: "number",
    placeholder: "Hours",
    operators: [
      { id: "greater", label: "is greater than" },
      { id: "less", label: "is less than" },
      { id: "equal", label: "equals" },
    ],
  },
];

const INITIAL_RULES: readonly TidalQueryRule[] = [
  {
    id: "sample-status",
    fieldId: "status",
    operatorId: "is",
    value: "active",
  },
  {
    id: "sample-estimate",
    fieldId: "estimate",
    operatorId: "less",
    value: "24",
  },
];

export function QueryBuilderDemo() {
  const [rules, setRules] = useState<TidalQueryRule[]>([...INITIAL_RULES]);
  const [conjunction, setConjunction] = useState<"and" | "or">("and");
  const nextId = useRef(1);
  const errors = useMemo(
    () =>
      Object.fromEntries(
        rules.flatMap((rule) => {
          const field = FIELDS.find(
            (candidate) => candidate.id === rule.fieldId,
          );
          const operator = field?.operators.find(
            (candidate) => candidate.id === rule.operatorId,
          );
          return operator?.requiresValue !== false && rule.value.trim() === ""
            ? [[rule.id, "Enter a value for this rule."]]
            : [];
        }),
      ),
    [rules],
  );
  const validCount = rules.length - Object.keys(errors).length;

  return (
    <section className="query-builder-demo" aria-label="Project query sample">
      <TidalQueryBuilder
        label="Project query"
        description="Build a local rule set for a saved project view."
        fields={FIELDS}
        rules={rules}
        conjunction={conjunction}
        onConjunctionChange={setConjunction}
        onRulesChange={(nextRules) => setRules(nextRules)}
        createRule={() => ({
          id: `sample-rule-${nextId.current++}`,
          fieldId: "owner",
          operatorId: "contains",
          value: "",
        })}
        errors={errors}
        getRuleControlProps={(rule) => ({
          fieldSelectProps: { name: `field-${rule.id}` },
          operatorSelectProps: { name: `operator-${rule.id}` },
          valueInputProps: { name: `value-${rule.id}` },
          valueSelectProps: { name: `value-${rule.id}` },
        })}
        result={
          <p>
            {rules.length === 0
              ? "No rules supplied."
              : `${validCount} of ${rules.length} rules ready. The host app decides how to use them.`}
          </p>
        }
      />
      <div className="query-builder-demo-footer">
        <span>
          {conjunction === "and" ? "Match every rule" : "Match any rule"}
        </span>
        <button
          type="button"
          onClick={() => {
            setRules([...INITIAL_RULES]);
            setConjunction("and");
          }}
        >
          Reset
        </button>
      </div>
      <p className="query-builder-demo-note">
        Sample rules. Nothing is queried or saved.
      </p>
    </section>
  );
}

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

```

## Gotchas

- Keep field state, validation results, submission, and persistence in the host form workflow.

## 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."}

Controlled flat builder accepts unique-ID field definitions for text, number, or enum values; field-owned operators; optional enum options; unique-ID controlled rules; and an AND/OR conjunction. onRulesChange receives the full proposed array, typed add/remove/field/operator/value change detail, and the native event so consumers can accept or decline. createRule supplies caller-owned IDs and defaults. Native fieldset props/ref, disabled state, description, per-rule errors, empty content, labels, caller-controlled result content, native conjunction/add props/refs, and per-rule native field/operator/value/remove props/refs are supported. Native value-input placeholder props override field-schema placeholders. Native controls are 44px, use ordinary Tab order, compose caller handlers first, recover focus after accepted add/remove only while the source still owns focus or an unmounted Remove leaves focus at body, and preserve exact string input values. Unknown fields/operators/enum values and duplicate rule IDs render linked errors without execution. Consumers own validation, serialization, persistence, data filtering, and every side effect; this component never runs a query.
