# QueryBuilder

> A nested AND/OR/NOT rule editor from @salmonui/query-builder, sharing its tree with the Data Grid filter builder, with SQL and MongoDB converters.

Canonical: https://salmonui.dev/docs/inputs/query-builder

`QueryBuilder` edits a filter as a tree of groups (AND / OR, optionally
NOT) and rules (`field operator value`). Its value is a `QueryGroup`, the
same shape as a Data Grid `DataGridFilterGroup` plus `id`, `not` and
`locked`, so `<DataGrid filtering={{ filters: [query] }}>` and
`@salmonui/data` queries take it as is.

```tsx
import { QueryBuilder, type QueryField, type QueryGroup } from '@salmonui/query-builder';
import '@salmonui/query-builder/styles.css';

const fields: QueryField[] = [
  { field: 'name', label: 'Name' },
  { field: 'age', label: 'Age', type: 'number' },
  { field: 'address', label: 'Address', fields: [{ field: 'city', label: 'City' }] },
];

<QueryBuilder fields={fields} defaultValue={{ logic: 'and', filters: [] }} onValueChange={(value) => save(value)} />
```

### Live demo: Query builder basics

Live demo: https://salmonui.dev/demos/inputs/query-builder-basics

A QueryBuilder with typed fields, categories, a nested path, NOT groups, lock, clone and drag reorder, its summary view and filterRows over local rows.

`Demo.tsx`:

```tsx
'use client';

import { useMemo, useState } from 'react';
import { filterRows, QueryBuilder, type QueryField, type QueryGroup } from '@salmonui/query-builder';

const fields: QueryField[] = [
  { field: 'name', label: 'Name', category: 'Employee' },
  { field: 'age', label: 'Age', type: 'number', category: 'Employee', step: 1, validation: { min: 18, max: 70 } },
  { field: 'hired', label: 'Hired', type: 'date', format: 'yMMMd' },
  { field: 'remote', label: 'Remote', type: 'boolean' },
  { field: 'team', label: 'Team', values: ['Design', 'Platform', 'Sales'] },
  { field: 'office', label: 'Office', category: 'Location', fields: [{ field: 'city', label: 'City' }] },
];

const rows = [
  { name: 'Ada', age: 36, hired: '2021-03-01', remote: true, team: 'Platform', office: { city: 'London' } },
  { name: 'Grace', age: 45, hired: '2019-07-15', remote: false, team: 'Design', office: { city: 'New York' } },
  { name: 'Linus', age: 29, hired: '2023-01-09', remote: true, team: 'Platform', office: { city: 'Helsinki' } },
  { name: 'Margaret', age: 52, hired: '2015-11-30', remote: false, team: 'Sales', office: { city: 'Boston' } },
];

// NOT groups, lock, clone and drag handles; the rows below are filtered with filterRows.
export default function QueryBuilderBasicsDemo() {
  const [value, setValue] = useState<QueryGroup>({
    logic: 'and',
    filters: [
      { field: 'team', operator: 'equal', value: 'Platform' },
      { logic: 'or', filters: [{ field: 'age', operator: 'greaterThan', value: 30 }, { field: 'remote', operator: 'equal', value: true }] },
    ],
  });
  const shown = useMemo(() => filterRows(rows, value, fields), [value]);
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <QueryBuilder aria-label="Employees" fields={fields} value={value} onValueChange={setValue} notCondition reorderable buttons={{ clone: true, lock: true }} />
      <output>Matches: {shown.map((r) => r.name).join(', ') || 'none'}</output>
      <QueryBuilder aria-label="Summary" fields={fields} value={value} onValueChange={setValue} summary />
    </div>
  );
}
```

The stylesheet carries the rules of the families it renders (Select,
Combobox, TreeSelect, Button, TextField, NumberField, Checkbox, DateField),
so one import besides `@salmonui/core/styles.css` (the theme, once per app)
styles the whole builder.

## One tree editor

QueryBuilder and the Data Grid filter builder dialog are the same
internal `QueryTree`: one model (immutable edits with structural sharing,
fields described by a `QueryFieldInfo` adapter built from compiled columns
in the grid and from `fields` here) and one memoized group / rule editor.
The grid dialog stays a lazy chunk; `bundle:check` gates the Data Grid
rows.

### Live demo: Query builder and the Data Grid filter builder

Live demo: https://salmonui.dev/demos/inputs/query-builder-grid

One filter edited both in a QueryBuilder and in the Data Grid filter builder dialog, which share the internal QueryTree editor and the filter value shape.

`Demo.tsx`:

```tsx
'use client';

import { useMemo, useState } from 'react';
import { DataGrid, type DataGridColumn, type DataGridFilter } from '@salmonui/data-grid';
import { isQueryGroup, QueryBuilder, type QueryField, type QueryGroup } from '@salmonui/query-builder';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(300, 7);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'category', header: 'Category', width: 120 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 110 },
  { field: 'shipped', header: 'Shipped', type: 'boolean', displayAsCheckbox: true, align: 'center', width: 120 },
];

// The same fields for the QueryBuilder (the grid derives them from its columns).
const fields: QueryField[] = [
  { field: 'customer', label: 'Customer' },
  { field: 'country', label: 'Country' },
  { field: 'category', label: 'Category' },
  { field: 'amount', label: 'Amount', type: 'number' },
  { field: 'shipped', label: 'Shipped', type: 'boolean' },
];

// The grid reports top-level filters; one group is the query itself, several are ANDed.
const toQuery = (filters: readonly DataGridFilter[]): QueryGroup =>
  filters.length === 1 && isQueryGroup(filters[0] as QueryGroup) ? (filters[0] as QueryGroup) : ({ logic: 'and', filters } as QueryGroup);

export default function QueryBuilderGridDemo() {
  const [query, setQuery] = useState<QueryGroup>({
    logic: 'and',
    filters: [
      { field: 'amount', operator: 'greaterThan', value: 200 },
      { logic: 'or', filters: [{ field: 'country', operator: 'equal', value: 'Japan' }, { field: 'country', operator: 'equal', value: 'Germany' }] },
    ],
  });
  // The QueryGroup is a Data Grid filter group as is.
  const filtering = useMemo(() => ({ ui: 'menu' as const, builder: true, filters: query.filters.length ? [query as DataGridFilter] : [] }), [query]);
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <QueryBuilder aria-label="Order filter" fields={fields} value={query} onValueChange={setQuery} notCondition />
      <DataGrid<Order>
        aria-label="Orders filtered by the query"
        data={orders}
        columns={columns}
        filtering={filtering}
        toolbar={['filterBuilder']}
        resizeMode="auto"
        height={320}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        onFilterChange={(event) => setQuery(toQuery(event.filters))}
      />
    </div>
  );
}
```

## Value

- `value` / `defaultValue` / `onValueChange(value, details)` with
  `details = { source, reason, action, nodeId }`. Nodes
  without an `id` get one from their path (`q`, `q.0`, `q.1.0`), so server
  and client markup agree; emitted values carry the ids.
- Groups: `{ logic: 'and' | 'or', not?, locked?, filters }`; rules:
  `{ field, operator, value?, matchCase?, ignoreAccents?, locked? }`.
  `between` values are `[from, to]`, `in` / `notIn` values arrays.
- `matchCase` writes `matchCase` to every edited condition.
- `onBeforeChange(event)` runs before every change with `{ action,
  nodeId, previousValue, value, source }`; `event.preventDefault()`
  cancels it.
- `name` adds a hidden input with the valid value as JSON; a form `reset`
  restores `defaultValue`.
- Controlled or uncontrolled: pass `value` with `onValueChange` and store
  what it reports (the builder never edits a controlled value itself), or
  `defaultValue` and read the value through `onValueChange` or
  `api.getValue()`.

## Fields

| `QueryField` | Meaning |
| --- | --- |
| `field`, `label`, `type` | Name (a path segment for nested fields), text, `'string' \| 'number' \| 'date' \| 'datetime' \| 'boolean'` |
| `operators` | Data Grid filter operator names or custom ones; default `operatorsFor(type)` |
| `values` | Fixed values (`'gold'` or `{ value, label }`): a Select, multiple for `in` / `notIn` |
| `defaultValue` | Value of a new rule on the field |
| `format` | Display format of values in the summary: `'N2'`, `'C2'`, `'P1'`, skeletons (`'yMMMd'`), `'dd/MM/yyyy'` patterns or format options |
| `step` | NumberField step |
| `validation` | Rules in the Form vocabulary (`required`, `min`, `max`, `minLength`, `pattern`, `validate`, ...) |
| `category` | Group of the field in the field Select |
| `fields` | Nested fields; paths join with `pathSeparator` (default `'.'`, `address.city`) |
| `renderValueEditor(ctx)` | Custom value editor; `ctx.setValue` writes the value |

`operatorsFor(type)` returns the built-in list of a type;
`fieldSort: 'asc' | 'desc'` sorts the field list. The field picker
is a `Select` grouped by `field.category` (`fieldPicker: 'list'`, the
default) or a `TreeSelect` (`fieldPicker: 'tree'`) with the categories and
nested `field.fields` as parents that cannot be picked themselves. The tree picker is a lazy chunk
of `/query-builder`: the list picker renders on the server, during
hydration and until the chunk loads.

### Live demo: Query builder fields

Live demo: https://salmonui.dev/demos/inputs/query-builder-fields

Per-field operators, fixed values and defaults, display formats, number steps, validation rules, a custom value editor and rule layout, the tree field picker, editor props, operatorsFor and localized labels.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import {
  operatorsFor,
  QueryBuilder,
  type QueryBuilderApi,
  type QueryBuilderEditorProps,
  type QueryBuilderLocaleText,
  type QueryField,
  type QueryGroup,
  type QueryRuleRenderContext,
  type QueryValueEditorContext,
} from '@salmonui/query-builder';
import { Rating } from '@salmonui/inputs/rating';
import { Select } from '@salmonui/dropdowns/select';

const PICKERS = [
  { value: 'list', label: 'list' },
  { value: 'tree', label: 'tree' },
];
const TYPES = ['string', 'number', 'date', 'boolean'].map((value) => ({ value, label: value }));

// A custom value editor: a Rating that writes the rule's value with ctx.setValue.
function ratingEditor(ctx: QueryValueEditorContext) {
  return (
    <span role="group" aria-label={ctx.label} style={{ display: 'inline-flex', alignItems: 'center', minBlockSize: 32 }}>
      <Rating min={1} value={typeof ctx.value === 'number' ? ctx.value : 1} disabled={ctx.disabled} onValueChange={(next) => ctx.setValue(next)} />
    </span>
  );
}

const fields: QueryField[] = [
  { field: 'product', label: 'Product', category: 'Item', operators: ['contains', 'startsWith', 'equal'] },
  { field: 'price', label: 'Price', type: 'number', category: 'Item', format: 'C2', step: 0.5, validation: { required: true, min: 0, max: 500 } },
  { field: 'rating', label: 'Rating', type: 'number', category: 'Item', operators: ['equal', 'greaterThanOrEqual'], defaultValue: 4, renderValueEditor: ratingEditor },
  { field: 'released', label: 'Released', type: 'date', category: 'Item', format: 'yMMMd' },
  {
    field: 'tier',
    label: 'Tier',
    category: 'Customer',
    values: [
      { value: 'bronze', label: 'Bronze' },
      { value: 'silver', label: 'Silver' },
      { value: 'gold', label: 'Gold' },
    ],
    defaultValue: 'gold',
  },
  { field: 'address', label: 'Address', category: 'Customer', fields: [{ field: 'city', label: 'City' }] },
];

const GERMAN: Partial<QueryBuilderLocaleText> = {
  and: 'Und',
  or: 'Oder',
  addCondition: 'Bedingung hinzufügen',
  addGroup: 'Gruppe hinzufügen',
  removeCondition: 'Bedingung entfernen',
  removeGroup: 'Gruppe entfernen',
  filterField: 'Feld',
  filterValue: 'Wert',
  selectField: 'Feld wählen',
  selectOperator: 'Operator wählen',
  groupLabel: '{connector}-Gruppe',
  ruleLabel: 'Bedingung {index}',
  incomplete: 'Bedingung vervollständigen',
  operatorContains: 'Enthält',
  operatorStartsWith: 'Beginnt mit',
  operatorEqual: 'Gleich',
  operatorLessThan: 'Kleiner als',
  operatorGreaterThan: 'Größer als',
  operatorGreaterThanOrEqual: 'Größer oder gleich',
};

// Forwarded to the built-in editors: a search box in the field list, wider value editors.
const EDITORS: QueryBuilderEditorProps = { field: { searchable: true, searchPlaceholder: 'Search fields' }, value: { style: { minInlineSize: '14rem' } } };

// A rule row with its position and its errors.
function ruleRow(ctx: QueryRuleRenderContext) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'auto minmax(0, 1fr) auto', gap: 8, alignItems: 'start', flex: '1 1 100%' }}>
      <span aria-hidden="true" style={{ minInlineSize: 20, lineHeight: '32px', fontWeight: 600 }}>
        {ctx.index + 1}.
      </span>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(10em, 1fr))', gap: 8, alignItems: 'center' }}>
        {ctx.fieldPicker}
        {ctx.operatorPicker}
        {ctx.valueEditor}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 4, minBlockSize: 32 }}>{ctx.actions}</div>
    </div>
  );
}

export default function QueryBuilderFieldsDemo() {
  const api = useRef<QueryBuilderApi>(null);
  const [value, setValue] = useState<QueryGroup>({
    logic: 'and',
    filters: [
      { field: 'product', operator: 'contains', value: 'lamp' },
      { field: 'price', operator: 'lessThan', value: 49.5 },
      { field: 'rating', operator: 'greaterThanOrEqual', value: 4 },
      { field: 'released', operator: 'greaterThan', value: '2025-01-01' },
      { field: 'tier', operator: 'equal', value: 'gold' },
    ],
  });
  const [picker, setPicker] = useState<'list' | 'tree'>('list');
  const [tuned, setTuned] = useState(false);
  const [german, setGerman] = useState(false);
  const [valid, setValid] = useState<boolean | null>(null);
  const [type, setType] = useState<'string' | 'number' | 'date' | 'boolean'>('number');
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <div className="demo-toolbar">
        <label>
          Field picker
          <Select aria-label="Field picker" data={PICKERS} value={picker} onValueChange={(next) => next != null && setPicker(next as 'list' | 'tree')} />
        </label>
        <Checkbox checked={tuned} onCheckedChange={(checked) => setTuned(checked)}>
          Searchable fields, wide values
        </Checkbox>
        <Checkbox checked={german} onCheckedChange={(checked) => setGerman(checked)}>
          German labels
        </Checkbox>
        <Button type="button" variant="outline" onClick={() => setValid(api.current?.validate() ?? null)}>
          Validate
        </Button>
        <output>{valid === null ? '' : valid ? 'Valid' : 'Fix the marked conditions'}</output>
      </div>
      <QueryBuilder
        ref={api}
        aria-label="Products"
        fields={fields}
        value={value}
        onValueChange={setValue}
        validation
        fieldPicker={picker}
        {...(tuned ? { editorProps: EDITORS } : {})}
        {...(german ? { localeText: GERMAN } : {})}
        renderRule={ruleRow}
      />
      <QueryBuilder aria-label="Summary" fields={fields} value={value} onValueChange={setValue} summary />
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
        <label style={{ display: 'inline-flex', gap: 8, alignItems: 'center' }}>
          Default operators of
          <Select aria-label="Default operators of" data={TYPES} value={type} onValueChange={(next) => next != null && setType(next as typeof type)} />
        </label>
        <span>
          fields (<code>operatorsFor</code>): <output>{operatorsFor(type).join(', ')}</output>
        </span>
      </div>
    </div>
  );
}
```

## Editing

- Built-in value editors: TextField (text), NumberField (numbers),
  DateField (dates; `datetime` to the minute), Checkbox (booleans), Select
  for fixed `values`, a multiple creatable Combobox for `in` / `notIn`,
  two editors for `between`.
- `editorProps: { field, operator, value }` are spread on the field
  Select, the operator Select and the value editors. A `value`
  prop that only some editors take (`clearable`, `showStepper`,
  `hourCycle`, `searchable`, ...) reaches only those editors; DOM,
  `aria-*` and `data-*` attributes reach every value editor.
- `buttons: { deleteRule, addGroup, deleteGroup, clone, lock }` (the first
  three default true); clone copies a rule or group next to itself
  and focuses it; lock makes a node and its members read-only.
- `notCondition` shows a NOT toggle on every group.
- `maxGroups` limits group nesting, the root included (default 5);
  `addRuleToNewGroups` (default true) starts new groups with a rule;
`autoSelectField` (default false) starts new rules on the first
  field and `autoSelectOperator` (default true) picks a field's first
  operator.
- `readOnly` renders the tree with disabled editors and without the add,
  remove, clone, lock and drag buttons.
- `summary` shows the value as a sentence ("Name contains an AND (Age
  greater than 30 OR ...)") with an Edit button; Done returns.
- `renderRule(ctx)` replaces a rule row (`fieldPicker`, `operatorPicker`,
  `valueEditor`, `actions`, `errors`, `setRule`, `remove`) and
  `renderGroupHeader(ctx)` a group bar (`controls`, `actions`, `depth`,
  `isRoot`).

## Reorder

`reorderable` adds a drag handle to every rule and group. Dragging
shows a drop line (drag state never enters React state); `onDragStart`,
`onDrag` (once per frame) and the cancellable `onDrop` report it. Escape
cancels a drag.

## Validation

`validation` checks every rule when the owning form submits and cancels
the submit while one is invalid; `api.validate()` does the same on demand
and returns a boolean. Incomplete rules (no field, operator or
value) and values failing `field.validation` show an inline error that the
rule references with `aria-describedby`; editing the rule clears it.
`api.getValidValue()` drops incomplete rules and empty groups.

## API

`ref` receives a `QueryBuilderApi`:

| Method | Meaning |
| --- | --- |
| `getValue()`, `setValue(value)` | Current value (with ids) / propose a value |
| `getValidValue()` | Without incomplete rules and empty groups |
| `getNode(id)` | A rule or group by id |
| `addRules(rules, groupId?)`, `addGroups(groups, groupId?)` | Append; return the new ids |
| `remove(ids)` | Remove rules or groups (`onBeforeChange` action `removeGroup` or `removeCondition`, after the first id) |
| `clone(id, { parentId, index }?)` | Copy a node; returns the copy's id |
| `lock(id, locked = true)` | Lock or unlock |
| `validate()` | Show errors, return validity |
| `reset()`, `focus()` | Back to `defaultValue` (proposed through `onValueChange` when controlled); focus the first control |

### Live demo: Query builder API and options

Live demo: https://salmonui.dev/demos/inputs/query-builder-api

A controlled QueryBuilder driven by its imperative API (addRules, addGroups, remove, getValue, setValue, getNode, reset, getValidValue, validate), with button, nesting, new-rule, field order, matchCase, read-only and group header options and a cancellable onBeforeChange.

`Demo.tsx`:

```tsx
'use client';

import { useId, useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { QueryBuilder, type QueryBuilderApi, type QueryBuilderButtons, type QueryField, type QueryGroup, type QueryGroupHeaderContext } from '@salmonui/query-builder';
import { Select } from '@salmonui/dropdowns/select';
import { EventLog, useEventLog } from '../../components/demo-kit';

const fields: QueryField[] = [
  { field: 'customer', label: 'Customer' },
  { field: 'country', label: 'Country', values: ['Brazil', 'Japan', 'Kenya', 'Malaysia', 'Norway'] },
  { field: 'amount', label: 'Amount', type: 'number' },
  { field: 'placed', label: 'Placed', type: 'date' },
  { field: 'shipped', label: 'Shipped', type: 'boolean' },
];

const PRESET: QueryGroup = {
  logic: 'or',
  filters: [
    { field: 'country', operator: 'equal', value: 'Japan' },
    { logic: 'and', filters: [{ field: 'amount', operator: 'greaterThan', value: 500 }, { field: 'shipped', operator: 'equal', value: false }] },
  ],
};

type ButtonKey = keyof QueryBuilderButtons;
const BUTTONS: readonly ButtonKey[] = ['deleteRule', 'addGroup', 'deleteGroup', 'clone', 'lock'];

const MAX_GROUPS = [1, 2, 3, 4, 5].map((n) => ({ value: String(n), label: String(n) }));
const FIELD_SORTS = [
  { value: 'given', label: 'as given' },
  { value: 'asc', label: 'asc' },
  { value: 'desc', label: 'desc' },
];

// A group header with the default controls, the nesting depth and the actions.
function header(ctx: QueryGroupHeaderContext) {
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
      {ctx.controls}
      <small style={{ opacity: 0.75 }}>{ctx.isRoot ? 'Root group' : `Nested group, depth ${ctx.depth}`}</small>
      {ctx.actions}
    </div>
  );
}

export default function QueryBuilderApiDemo() {
  const api = useRef<QueryBuilderApi>(null);
  const buttonsLabel = useId();
  const [value, setValue] = useState<QueryGroup>({
    logic: 'and',
    filters: [
      { field: 'customer', operator: 'contains', value: 'Ltd' },
      { field: 'amount', operator: 'greaterThan', value: 100 },
    ],
  });
  const [buttons, setButtons] = useState<Record<ButtonKey, boolean>>({ deleteRule: true, addGroup: true, deleteGroup: true, clone: false, lock: false });
  const [maxGroups, setMaxGroups] = useState(3);
  const [addRuleToNewGroups, setAddRuleToNewGroups] = useState(true);
  const [autoSelectField, setAutoSelectField] = useState(false);
  const [autoSelectOperator, setAutoSelectOperator] = useState(true);
  const [fieldSort, setFieldSort] = useState<'asc' | 'desc' | null>(null);
  const [matchCase, setMatchCase] = useState(false);
  const [readOnly, setReadOnly] = useState(false);
  const [customHeader, setCustomHeader] = useState(true);
  const [confirmRemovals, setConfirmRemovals] = useState(false);
  const [result, setResult] = useState('');
  const [log, push] = useEventLog(10);

  const check = (label: string, checked: boolean, set: (v: boolean) => void) => (
    <Checkbox key={label} checked={checked} onCheckedChange={(next) => set(next)}>
      {label}
    </Checkbox>
  );
  const show = (label: string, data: unknown) => setResult(`${label}: ${JSON.stringify(data)}`);

  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <div className="demo-toolbar" style={{ marginBlockEnd: 0 }} role="group" aria-labelledby={buttonsLabel}>
        <span id={buttonsLabel}>Buttons:</span>
        {BUTTONS.map((key) => check(key, buttons[key], (v) => setButtons((b) => ({ ...b, [key]: v }))))}
      </div>
      <div className="demo-toolbar" style={{ marginBlockEnd: 0 }}>
        <label>
          maxGroups
          <Select aria-label="maxGroups" data={MAX_GROUPS} value={String(maxGroups)} onValueChange={(next) => next != null && setMaxGroups(Number(next))} />
        </label>
        <label>
          fieldSort
          <Select aria-label="fieldSort" data={FIELD_SORTS} value={fieldSort ?? 'given'} onValueChange={(next) => next != null && setFieldSort(next === 'given' ? null : (next as 'asc' | 'desc'))} />
        </label>
        {check('addRuleToNewGroups', addRuleToNewGroups, setAddRuleToNewGroups)}
        {check('autoSelectField', autoSelectField, setAutoSelectField)}
        {check('autoSelectOperator', autoSelectOperator, setAutoSelectOperator)}
        {check('matchCase', matchCase, setMatchCase)}
        {check('readOnly', readOnly, setReadOnly)}
        {check('Depth in group headers', customHeader, setCustomHeader)}
        {check('Confirm removals', confirmRemovals, setConfirmRemovals)}
      </div>
      <QueryBuilder
        ref={api}
        aria-label="Orders"
        fields={fields}
        value={value}
        onValueChange={(next, d) => {
          setValue(next);
          push(`onValueChange ${d.action} ${d.nodeId ?? ''} (${d.source})`);
        }}
        onBeforeChange={(event) => {
          const removal = event.action === 'removeCondition' || event.action === 'removeGroup';
          if (confirmRemovals && removal) event.preventDefault();
          push(`onBeforeChange ${event.action} ${event.nodeId ?? ''}${confirmRemovals && removal ? ': cancelled' : ''}`);
        }}
        validation
        buttons={buttons}
        maxGroups={maxGroups}
        addRuleToNewGroups={addRuleToNewGroups}
        autoSelectField={autoSelectField}
        autoSelectOperator={autoSelectOperator}
        fieldSort={fieldSort}
        matchCase={matchCase}
        readOnly={readOnly}
        {...(customHeader ? { renderGroupHeader: header } : {})}
      />
      <div className="demo-toolbar" style={{ marginBlockEnd: 0 }}>
        <Button type="button" variant="outline" onClick={() => show('addRules', api.current?.addRules([{ field: 'country', operator: 'equal', value: 'Kenya' }]))}>
          api.addRules
        </Button>
        <Button
          type="button"
          variant="outline"
          onClick={() =>
            show(
              'addGroups',
              api.current?.addGroups([{ logic: 'or', filters: [{ field: 'amount', operator: 'lessThan', value: 10 }, { field: 'amount', operator: 'greaterThan', value: 1000 }] }]),
            )
          }
        >
          api.addGroups
        </Button>
        <Button
          type="button"
          variant="outline"
          onClick={() => {
            const last = api.current?.getValue().filters.at(-1);
            if (last?.id) api.current?.remove(last.id);
            show('remove', last?.id ?? null);
          }}
        >
          api.remove(last)
        </Button>
        <Button
          type="button"
          variant="outline"
          onClick={() => {
            const first = api.current?.getValue().filters[0];
            show('getNode', first?.id ? api.current?.getNode(first.id) : null);
          }}
        >
          api.getNode(first)
        </Button>
        <Button type="button" variant="outline" onClick={() => api.current?.setValue(PRESET)}>
          api.setValue(preset)
        </Button>
        <Button type="button" variant="outline" onClick={() => api.current?.reset()}>
          api.reset()
        </Button>
        <Button type="button" variant="outline" onClick={() => show('getValidValue', api.current?.getValidValue())}>
          api.getValidValue()
        </Button>
        <Button type="button" variant="outline" onClick={() => show('validate', api.current?.validate())}>
          api.validate()
        </Button>
      </div>
      {result ? <output style={{ overflowWrap: 'anywhere' }}>{result}</output> : null}
      <pre className="demo-log" style={{ maxBlockSize: 200, marginBlockStart: 0 }} tabIndex={0} aria-label="Current value">
        {JSON.stringify(value, null, 1)}
      </pre>
      <EventLog entries={log} label="Query builder events" />
    </div>
  );
}
```

| Prop | Type | Default |
| --- | --- | --- |
| `fields` | `QueryField[]` | required |
| `value`, `defaultValue` | `QueryGroup` | empty AND group |
| `onValueChange`, `onBeforeChange` | see above | |
| `operators` | `QueryOperator[]` (custom operators) | |
| `notCondition`, `summary`, `readOnly`, `disabled`, `reorderable`, `validation` | `boolean` | `false` |
| `buttons` | `QueryBuilderButtons` | remove and add-group on |
| `maxGroups` | `number` | `5` |
| `addRuleToNewGroups`, `autoSelectOperator` | `boolean` | `true` |
| `autoSelectField` | `boolean` | `false` |
| `fieldSort` | `'asc' \| 'desc' \| null` | `null` |
| `fieldPicker` | `'list' \| 'tree'` | `'list'` |
| `matchCase` | `boolean` | |
| `pathSeparator` | `string` | `'.'` |
| `renderRule`, `renderGroupHeader` | render functions | |
| `editorProps` | `{ field?, operator?, value? }` | |
| `onDragStart`, `onDrag`, `onDrop` | drag events | |
| `localeText`, `locale` | text overrides, BCP 47 | English, `'en-US'` |
| `name`, `form`, `id`, `className`, `style`, `aria-label`, `aria-labelledby`, `dir` | | |

## Custom operators

`operators: [{ name, label?, types?, valueless?, list?, evaluate? }]` adds
operators to the fields of matching types. `evaluate(cell, value,
{ matchCase, ignoreAccents })` serves `filterRows` (the Data Grid takes the
same function through `createFilterModule({ operators })`); `toSql` and
`toMongo` take an `operators` hook per name.

## filterRows

`filterRows(rows, value, fields?, { pathSeparator, matchCase,
ignoreAccents, operators }?)` returns the matching rows with the Data Grid
filter semantics (case and accent folding, blanks, calendar-day dates,
`like` / `wildcard` patterns); a unit test runs the same queries through
the core filter module.

## SQL and MongoDB

### Live demo: Query builder converters

Live demo: https://salmonui.dev/demos/inputs/query-builder-converters

The QueryBuilder value as parameterized SQL with toSql and as a MongoDB filter with toMongo.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { QueryBuilder, type QueryField, type QueryGroup } from '@salmonui/query-builder';
import { toMongo } from '@salmonui/query-builder/mongo';
import { toSql } from '@salmonui/query-builder/sql';

const fields: QueryField[] = [
  { field: 'product', label: 'Product' },
  { field: 'price', label: 'Price', type: 'number' },
  { field: 'stock', label: 'In stock', type: 'boolean' },
];

function convert(value: QueryGroup) {
  try {
    return { sql: toSql(value, { dialect: 'postgres' }), mongo: toMongo(value) };
  } catch {
    return null;
  }
}

// The value as parameterized SQL (postgres placeholders) and a MongoDB filter.
export default function QueryBuilderConvertersDemo() {
  const [value, setValue] = useState<QueryGroup>({
    logic: 'or',
    filters: [
      { field: 'product', operator: 'startsWith', value: "Chef's" },
      { field: 'price', operator: 'between', value: [10, 20] },
    ],
  });
  const out = convert(value);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr)', gap: 12 }}>
      <QueryBuilder aria-label="Products" fields={fields} value={value} onValueChange={setValue} validation />
      <pre className="demo-log" style={{ marginBlockStart: 0, maxBlockSize: 'none' }} tabIndex={0} aria-label="SQL and MongoDB output">
        {out ? `${out.sql.sql}\n${JSON.stringify(out.sql.params)}\n\n${JSON.stringify(out.mongo, null, 2)}` : 'Complete every condition to convert.'}
      </pre>
    </div>
  );
}
```

`@salmonui/query-builder/sql` and `/mongo` are server-safe: no
React, no component code, no package imports.

- `toSql(value, { named, inline, quoteIdentifier, dialect, operators,
  pathSeparator, paramPrefix })` returns `{ sql, params }`, parameterized
  by default (`?`; `$1` on postgres, `@p1` on mssql) so values never reach
  the SQL text; `named: true` uses `:p1` and a params record; `inline:
  true` writes escaped literals like `getSqlFromRules`.
  Text comparisons follow the database collation (`matchCase` is not
  translated); LIKE patterns escape the user's `%` and `_` with `ESCAPE
  '!'`.
- `fromSql(sql, { params, named, pathSeparator })` reads back the subset
  `toSql` writes (comparisons, `IN`, `BETWEEN`, `LIKE`, `IS [NOT] NULL`,
  `AND` / `OR` / `NOT` groups, quoted identifiers, every placeholder
  style); anything else throws a `SqlParseError` with the position, and
  nothing is evaluated.
- `toMongo(value, { operators, pathSeparator })` writes `$and` / `$or`,
  `$nor` for NOT groups, comparisons, `$in` / `$nin` and escaped `$regex`;
`fromMongo(query, { pathSeparator })` reads `$and`, `$or`,
  `$nor`, implicit equality, `$eq` ... `$lte`, `$in`, `$nin`, literal
  `$regex` (with `$options`, also under `$not`) and `$exists`, and throws
  a `TypeError` naming any other operator.

### Live demo: Query builder SQL and MongoDB import

Live demo: https://salmonui.dev/demos/inputs/query-builder-sql

Inline SQL from toSql, a custom operator evaluated by filterRows and serialized by the toSql and toMongo hooks, and queries loaded back with fromSql (literal, positional and named parameters) and fromMongo.

`Demo.tsx`:

```tsx
'use client';

import { useMemo, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { filterRows, QueryBuilder, type Json, type QueryField, type QueryGroup, type QueryOperator } from '@salmonui/query-builder';
import { fromMongo, toMongo, type MongoFilter, type MongoOperatorContext } from '@salmonui/query-builder/mongo';
import { fromSql, toSql, type SqlOperatorContext } from '@salmonui/query-builder/sql';
import { TextArea, TextField } from '@salmonui/inputs/text-field';

const fields: QueryField[] = [
  { field: 'product', label: 'Product' },
  { field: 'price', label: 'Price', type: 'number' },
  { field: 'qty', label: 'Pack size', type: 'number' },
  { field: 'stock', label: 'In stock', type: 'boolean' },
];

// A custom operator: offered on number fields, evaluated by filterRows, serialized by the converter hooks.
const operators: QueryOperator[] = [
  {
    name: 'multipleOf',
    label: 'Multiple of',
    types: ['number'],
    evaluate: (cell, value) => typeof cell === 'number' && typeof value === 'number' && value !== 0 && cell % value === 0,
  },
];
const sqlHooks = { multipleOf: (c: SqlOperatorContext) => `MOD(${c.field}, ${c.param(c.value ?? 1)}) = 0` };
const mongoHooks = { multipleOf: (c: MongoOperatorContext): MongoFilter => ({ [c.field]: { $mod: [c.value, 0] } }) };

const rows = [
  { product: 'Desk lamp', price: 39, qty: 1, stock: true },
  { product: "Chef's knife", price: 84, qty: 1, stock: false },
  { product: 'Candles', price: 12, qty: 6, stock: true },
  { product: 'Tea lights', price: 9, qty: 24, stock: true },
  { product: 'Glasses', price: 28, qty: 4, stock: false },
];

const message = (error: unknown) => (error instanceof Error ? `${error.name}: ${error.message}` : String(error));

export default function QueryBuilderSqlDemo() {
  const [value, setValue] = useState<QueryGroup>({
    logic: 'and',
    filters: [
      { field: 'qty', operator: 'multipleOf', value: 6 },
      { field: 'stock', operator: 'equal', value: true },
    ],
  });
  const [sqlText, setSqlText] = useState(`"price" > ? AND ("product" LIKE ? ESCAPE '!' OR "stock" = ?)`);
  const [paramsText, setParamsText] = useState('[10, "%lamp%", false]');
  const [named, setNamed] = useState(false);
  const [mongoText, setMongoText] = useState('{ "$or": [{ "price": { "$lt": 20 } }, { "product": { "$regex": "^Chef" } }] }');
  const [status, setStatus] = useState('');

  const out = useMemo(() => {
    try {
      return { sql: toSql(value, { inline: true, operators: sqlHooks }).sql, mongo: JSON.stringify(toMongo(value, { operators: mongoHooks })) };
    } catch {
      return null;
    }
  }, [value]);
  const matches = useMemo(() => filterRows(rows, value, fields, { operators }), [value]);

  const loadSql = () => {
    try {
      const params = paramsText.trim() ? (JSON.parse(paramsText) as Json[] | Record<string, Json>) : undefined;
      setValue(fromSql(sqlText, { named, ...(params === undefined ? {} : { params }) }));
      setStatus('Loaded from SQL');
    } catch (error) {
      setStatus(message(error));
    }
  };
  const loadMongo = () => {
    try {
      setValue(fromMongo(JSON.parse(mongoText) as MongoFilter));
      setStatus('Loaded from MongoDB');
    } catch (error) {
      setStatus(message(error));
    }
  };

  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <QueryBuilder aria-label="Products" fields={fields} operators={operators} value={value} onValueChange={setValue} />
      <output>Matches: {matches.map((r) => r.product).join(', ') || 'none'}</output>
      <pre className="demo-log" style={{ marginBlockStart: 0, whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }}>{out ? `toSql (inline): ${out.sql || '(empty)'}\ntoMongo: ${out.mongo}` : 'Complete every condition to convert.'}</pre>
      <div style={{ display: 'grid', gap: 6 }}>
        <TextArea label="SQL WHERE expression" rows={2} value={sqlText} onValueChange={setSqlText} />
        <TextField label="Parameters (JSON array, or an object for named parameters)" value={paramsText} onValueChange={setParamsText} />
        <div className="demo-toolbar">
          <Checkbox checked={named} onCheckedChange={(checked) => setNamed(checked)}>
            Named parameters
          </Checkbox>
          <Button type="button" variant="outline" onClick={loadSql}>
            Load SQL
          </Button>
        </div>
        <TextArea label="MongoDB filter (JSON)" rows={2} value={mongoText} onValueChange={setMongoText} />
        <div className="demo-toolbar">
          <Button type="button" variant="outline" onClick={loadMongo}>
            Load MongoDB
          </Button>
        </div>
        <output aria-live="polite">{status}</output>
      </div>
    </div>
  );
}
```

## Keyboard and accessibility

Every group is a `role="group"` named by its connector ("And group", the
root by `aria-label`); every rule is a group named by its position
("Condition 2"). Focus moves to a new rule's field after add and
clone, and to the group's add button after remove.

| Key | Action |
| --- | --- |
| Tab | Moves through the connector, NOT, buttons and editors |
| Arrow keys | Change the AND / OR connector (radio group) |
| Alt+ArrowUp / Alt+ArrowDown on a handle | Move the rule or group up or down; it enters an adjacent group and leaves its group at the ends; the new position is announced |
| Escape while dragging | Cancel the drag |

## Localization

`localeText` overrides every text. The operator labels
(`operatorContains`, ...), connector, NOT and button texts use the Data
Grid `localeText` keys and English defaults, so one localized bundle
serves both; `groupLabel` (`'{connector} group'`), `ruleLabel`,
`summaryRule` and `validation*` messages are QueryBuilder keys.

## Performance

A 200-rule builder mounts in about 8 ms (budget 50 ms) and a rule edit
re-renders only that rule (`tests/browser/query-builder-perf.spec.ts`).
Bundle rows: QueryBuilder's own code 10.60 KB gzip with the tree picker
chunk (cap 14 KB, the composed families excluded), own CSS rules 0.55 KB,
`toSql` 1.33 KB, `/sql` with `fromSql` 3.07 KB (over its 2.5 KB design
cap, gated at 3.2 KB), `/mongo` 1.98 KB.

### Live demo: Query builder with 200 rules

Live demo: https://salmonui.dev/demos/inputs/query-builder-large

A 200-rule QueryBuilder mounted on demand, with the mount time and a single-rule edit time measured and shown against the budgets.

`Demo.tsx`:

```tsx
'use client';

import { useLayoutEffect, useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { QueryBuilder, type QueryField, type QueryGroup, type QueryRule } from '@salmonui/query-builder';

const fields: QueryField[] = [
  { field: 'name', label: 'Name' },
  { field: 'age', label: 'Age', type: 'number' },
];

const NAMES = ['Ada', 'Grace', 'Linus', 'Hedy', 'Alan', 'Katherine', 'Edsger', 'Barbara', 'Dennis', 'Margaret'];

// 200 rules with stable ids (deterministic: SSR-safe).
const LARGE: QueryGroup = {
  logic: 'and',
  filters: Array.from({ length: 200 }, (_, i): QueryRule => ({
    id: `r${i}`,
    field: i % 2 ? 'age' : 'name',
    operator: i % 2 ? 'greaterThan' : 'contains',
    value: i % 2 ? 18 + (i % 50) : NAMES[(i / 2) % NAMES.length]!,
  })),
};

type Pending = { readonly kind: 'mount' | 'edit'; readonly start: number };

// mount and single-rule edit, click to commit, measured with performance.now().
export default function QueryBuilderLargeDemo() {
  const [shown, setShown] = useState(false);
  const [value, setValue] = useState<QueryGroup>(LARGE);
  const [result, setResult] = useState<{ mount?: number; edit?: number }>({});
  const pending = useRef<Pending | null>(null);

  useLayoutEffect(() => {
    const p = pending.current;
    if (!p) return;
    pending.current = null;
    const ms = performance.now() - p.start;
    setResult((r) => ({ ...r, [p.kind]: ms }));
  }, [shown, value]);

  const editRule = () => {
    pending.current = { kind: 'edit', start: performance.now() };
    setValue((v) => ({ ...v, filters: v.filters.map((f) => (f.id === 'r100' && !('filters' in f) ? { ...f, value: f.value === 'Ada' ? 'Grace' : 'Ada' } : f)) }));
  };

  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <div className="demo-toolbar">
        <Button
          type="button"
          variant="outline"
          onClick={() => {
            pending.current = shown ? null : { kind: 'mount', start: performance.now() };
            setShown((s) => !s);
          }}
        >
          {shown ? 'Unmount' : 'Mount 200 rules'}
        </Button>
        <Button type="button" variant="outline" disabled={!shown} onClick={editRule}>
          Edit rule 100
        </Button>
        <output aria-live="polite">
          {result.mount === undefined ? 'Not measured yet' : `Mount ${result.mount.toFixed(1)} ms (budget 50 ms)`}
          {result.edit === undefined ? '' : `; last edit ${result.edit.toFixed(1)} ms`}
        </output>
      </div>
      {shown ? (
        <div style={{ maxBlockSize: 420, overflow: 'auto' }}>
          <QueryBuilder aria-label="Large query" fields={fields} value={value} onValueChange={setValue} />
        </div>
      ) : null}
    </div>
  );
}
```

## Server rendering

The builder renders on the server with the same markup as the first client
render: nodes without an `id` get ids from their path, values are
formatted with the `locale` prop (default `'en-US'`), and the tree field
picker only replaces the list picker after hydration. `@salmonui/query-builder/sql`
and `/mongo` contain no React or DOM code, so route handlers and server
actions can convert or parse queries.

## Reference

Every exported symbol and type is listed in the reference:
[`@salmonui/query-builder`](https://salmonui.dev/docs/reference/query-builder),
[`@salmonui/query-builder/sql`](https://salmonui.dev/docs/reference/query-builder/sql)
and [`@salmonui/query-builder/mongo`](https://salmonui.dev/docs/reference/query-builder/mongo).

## Design notes

- fields are explicit; the builder does not infer them from sample
  records, because inferring field types from the first record is
  unreliable (nulls, numeric strings, dates as strings). Pass
  `fields={[{ field: 'age', label: 'Age', type: 'number' }]}`; a Data
  Grid's columns map to fields with one `map`.
- there is no layout-mode prop. Horizontal or vertical layout
  depends on the available width, so a container query stacks the editors
  in narrow containers. To force the vertical layout, constrain the
  container width.
- there is no built-in change delay. Debouncing is the
  application's policy (live grid filtering differs from saving a query),
  so wrap the `onValueChange` handler in a debounce.
- siblings in a group share one connector. Different connectors
  between siblings make precedence ambiguous (`a AND b OR c`); nested
  groups state it and map one to one to the filter model and SQL
  parentheses. Put each run of rules sharing a connector in its own group.
