<!--# if expr="$arg_server = /^(node|python|go|php|ruby|dotnet)$/" --><!--# set var="stack_server" value="$arg_server" --><!--# else --><!--# set var="stack_server" value="node" --><!--# endif --><!--# if expr="$arg_database = /^(postgresql|redshift|mysql|mssql|clickhouse|snowflake|bigquery|databricks)$/" --><!--# set var="stack_database" value="$arg_database" --><!--# else --><!--# set var="stack_database" value="postgresql" --><!--# endif --><!--# if expr="$arg_cache = /^(none|duckdb|redis)$/" --><!--# set var="stack_cache" value="$arg_cache" --><!--# else --><!--# set var="stack_cache" value="none" --><!--# endif --><!--# if expr="$arg_messaging = /^(resend|twilio|postmark)$/" --><!--# set var="stack_messaging" value="$arg_messaging" --><!--# else --><!--# set var="stack_messaging" value="resend" --><!--# endif -->
# Alerts

Minimal alert builder powered by useReport.

> The code on this page is for the stack in its URL's query, by default `?server=node&messaging=resend&database=postgresql&cache=none`. Server: `node`, `python`, `go`, `php`, `ruby`, `dotnet`. Messaging: `resend`, `twilio`, `postmark`. Database: `postgresql`, `redshift`, `mysql`, `mssql`, `clickhouse`, `snowflake`, `bigquery`, `databricks`. Cache: `none`, `duckdb` (`node` only), `redis`. A missing or unknown value is the default, the first listed.

[Open the demo](https://quill.co/docs-demo/blocks/#/alert-builder-2)

`AlertBuilder.tsx`

```tsx
import { useEffect, useState } from 'react';
import { useReport, useReportQueryBuilder } from '@quillsql/react';
import { Button } from '../components/button/button';
import { MultiSelect, FilterBuilder } from '../components/filter-builder/filter-builder';
import { InlineEdit } from '../components/inline-edit/inline-edit';
import styles from './AlertBuilderBlock.module.css';

/** The report the alert is on: Visitors on the Tabbed dashboard, the sum of web_traffic_daily's visitors. */
const ALERT_REPORT_ID = '6af337ed802380dce4bb37fb';
const T = 'web_traffic_daily';
/**
 * The alert the example opens on: over the last week on phones and tablets, signups fell or bounces rose. A rule on a
 * measure names it `<field>_sum`.
 */
const ALERT = {
  name: 'Mobile signup slowdown',
  aggregations: [`sum:${T}::signups`, `sum:${T}::bounced_visitors`],
  rules: {
    combinator: 'and' as const,
    rules: [
      { field: `${T}.day`, operator: 'inTheLast', value: [7, 'day'] },
      { field: `${T}.device`, operator: 'in', value: ['Mobile', 'Tablet'] },
      { combinator: 'or' as const, rules: [
        { field: 'signups_sum', operator: '<', value: 120 },
        { field: 'bounced_visitors_sum', operator: '>', value: 2200 },
      ] },
    ],
  },
};

/**
 * An alert on a report: its measures, and the rules that say when it fires, edited with Quill's filter editor on
 * `alert` / `setAlert`. Quill keeps no alert with this report, so the example sets its own once the report loads.
 */
export function AlertBuilder() {
  const report = useReport(ALERT_REPORT_ID, { destinationDashboardName: 'Tabbed dashboard', showTableNames: false });
  const { reportId, chartLoading, setReport, setAlert } = report;
  const queryBuilder = useReportQueryBuilder({ reportId, filters: report.alert, queryBuilderProps: report.alertQueryBuilderProps, onApply: setAlert });
  const [seeded, setSeeded] = useState(false);
  const busy = chartLoading || !seeded;

  useEffect(() => {
    if (seeded || !report.aggregationOptions.length) return;
    setSeeded(true);
    setReport({ name: ALERT.name, aggregations: ALERT.aggregations });
    setAlert(ALERT.rules);
  });

  return (
    <section className={`${styles.root} ${styles.card}`} aria-label="Alert builder">
      <header className={styles.head}>
        <InlineEdit as="h2" className={styles.name} label="Alert name" placeholder="Untitled alert" value={report.name} onSave={(name) => setReport({ name })} />
        <Button size="sm" disabled={busy || report.loading}>Create alert</Button>
      </header>

      <div className={styles.controls}>
        <MultiSelect className={`${styles.group} ${styles.sourcesPicker}`} label="Datasources" placeholder="Select tables"
          value={report.datasources} options={report.datasourceOptions} disabled={!report.datasourceOptions.length} onChange={(datasources) => setReport({ datasources })} />
        <MultiSelect className={`${styles.group} ${styles.measuresPicker}`} label="Aggregations" placeholder="Select measures"
          value={report.aggregations} options={report.aggregationOptions} disabled={busy} onChange={(aggregations) => setReport({ aggregations })} />
      </div>

      <div className={styles.rules}>
        <FilterBuilder label={null} layout="field" loading={busy} queryBuilder={queryBuilder} filterUniqueValuesLoading={report.filterUniqueValuesLoading}
          onFiltersChange={setAlert} empty="No rules yet. Add a rule to say when this alert fires." />
      </div>
    </section>
  );
}
```

`filter-builder.tsx`

```tsx
import {
  createContext,
  Fragment,
  useCallback,
  useContext,
  useId,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type ComponentProps,
  type KeyboardEvent,
  type MouseEvent,
  type ReactNode,
  type RefObject,
} from 'react';
import {
  DndContext,
  PointerSensor,
  closestCenter,
  useDndMonitor,
  useSensor,
  useSensors,
  type Active,
  type CollisionDetection,
  type DndMonitorListener,
  type DragEndEvent,
  type DragMoveEvent,
  type Over,
} from '@dnd-kit/core';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import {
  SortableContext,
  useSortable,
  verticalListSortingStrategy,
  type SortableData,
  type SortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import {
  QueryBuilder,
  RuleComponents,
  RuleGroupBodyComponents,
  findPath,
  getParentPath,
  getPathOfID,
  isRuleGroup,
  remove,
  toFlatOptionArray,
  useRule,
  useRuleGroup,
  useStopEventPropagation,
  useValueEditor,
  type ActionProps,
  type FullOption,
  type OperatorSelectorProps,
  type Path,
  type QueryActions,
  type RuleGroupProps,
  type RuleGroupType,
  type RuleGroupTypeAny,
  type RuleProps,
  type RuleType,
  type UseRuleGroup,
  type ValidationMap,
  type ValueEditorProps,
  type VersatileSelectorProps,
} from 'react-querybuilder';
import type { ReportFilters, SetFiltersInput, UseReportQueryBuilder } from '@quillsql/react';
import { Folder, GitBranch, Plus, X } from 'lucide-react';
import { Button } from '../button/button';
import { Input } from '../input/input';
import { MultiSelect as BaseMultiSelect } from '../multi-select/multi-select';
import { Popover, PopoverContent, PopoverTrigger } from '../popover/popover';
import { Select as BaseSelect } from '../select/select';
import styles from './filter-builder.module.css';

/**
 * A port of the Quill report builder's filter editor (packages/admin FilterBuilder) onto the app's popover, button, select,
 * multi-select and input, sized and colored to match it. Icons are Lucide at a 1.75 stroke.
 */
const STROKE = 1.75;
const XIcon = ({ size }: { size: number }) => <X size={size} strokeWidth={STROKE} aria-hidden="true" />;
const PlusIcon = ({ size }: { size: number }) => <Plus size={size} strokeWidth={STROKE} aria-hidden="true" />;
const FolderIcon = ({ size }: { size: number }) => <Folder size={size} strokeWidth={STROKE} aria-hidden="true" />;
const GitBranchIcon = ({ size }: { size: number }) => <GitBranch size={size} strokeWidth={STROKE} aria-hidden="true" />;
/** A trunk with two branches ending in nodes: adding a condition to a group. */
const BranchNodesIcon = ({ size }: { size: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={STROKE} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M4 4v12a2 2 0 0 0 2 2h9" />
    <path d="M4 9h11" />
    <circle cx="18" cy="9" r="2.5" />
    <circle cx="18" cy="18" r="2.5" />
  </svg>
);
const DragHandleIcon = () => (
  <svg width={9} height={15} viewBox="0 0 9 15" fill="currentColor" aria-hidden="true">
    {[0, 6, 12].flatMap((y) => [0, 6].map((x) => <rect key={`${x}-${y}`} x={x} y={y} width={3} height={3} rx={1.5} />))}
  </svg>
);

const VALUELESS_OPERATORS = new Set(['null', 'notNull']);
const RANGE_OPERATORS = new Set(['between', 'notBetween']);
const RELATIVE_DATE_OPERATOR_KEYS = new Set([
  'inTheLast',
  'inThePrevious',
  'inTheCurrent',
]);
const RELATIVE_DATE_UNITS = [
  'hour',
  'day',
  'week',
  'month',
  'quarter',
  'year',
] as const;
const COMBINATORS: FullOption[] = [
  { name: 'and', value: 'and', label: 'and' },
  { name: 'or', value: 'or', label: 'or' },
];
const TRANSLATIONS = {
  addRule: { label: 'Add rule', title: 'Add rule' },
  addGroup: { label: 'Add group', title: 'Add a group of conditions' },
  removeRule: { label: '', title: 'Remove rule' },
  removeGroup: { label: '', title: 'Remove group' },
};

// A rule reads "Field is Operator Value", so the report's SQL operators are
// labelled to follow the "is" that sits between the field and operator.
const OPERATOR_LABELS: Record<string, Record<string, string>> = {
  string: {
    in: 'Any of',
    notIn: 'None of',
    '=': 'Equal to',
    '!=': 'Not equal to',
    contains: 'Contains',
  },
  number: {
    '=': 'Equal to',
    '!=': 'Not equal to',
    '>': 'Greater than',
    '<': 'Less than',
    '>=': 'At least',
    '<=': 'At most',
  },
  date: {
    '=': 'On',
    '!=': 'Not on',
    '>': 'After',
    '<': 'Before',
    '>=': 'On or after',
    '<=': 'On or before',
    inTheLast: 'In the last',
    inThePrevious: 'In the previous',
    inTheCurrent: 'In the current',
  },
  boolean: { '=': 'Equal to', '!=': 'Not equal to' },
};
const SHARED_OPERATOR_LABELS: Record<string, string> = {
  null: 'Empty',
  notNull: 'Not empty',
  between: 'Between',
  notBetween: 'Not between',
};
/** Operators that read as a verb on their own, without "is" before them. */
const VERB_OPERATORS = new Set(['contains']);

type FilterBuilderContext = { valuesLoading?: boolean; empty?: string };
type SelectOption = { value: string; label: string };

function fieldTypeOf(fieldData: unknown): string {
  return String(
    (fieldData as { quillFieldType?: unknown } | undefined)?.quillFieldType ??
      'string',
  );
}

function operatorLabel(
  operator: { name: string; label?: string } | undefined,
  fieldType: string,
  fallback: string,
): string {
  if (!operator) return fallback;
  const label =
    OPERATOR_LABELS[fieldType]?.[operator.name] ??
    SHARED_OPERATOR_LABELS[operator.name] ??
    operator.label ??
    fallback;
  return label.charAt(0).toUpperCase() + label.slice(1);
}

/** The operator as it reads in a sentence: "is any of", "contains". */
function operatorPhrase(operatorName: string, label: string): string {
  const lower = label.toLowerCase();
  return VERB_OPERATORS.has(operatorName) ? lower : `is ${lower}`;
}

function toSelectOptions(
  options: Parameters<typeof toFlatOptionArray>[0],
): SelectOption[] {
  return toFlatOptionArray(options).map((option) => ({
    value: String(option.name),
    label: String(option.label),
  }));
}

function toRuleValueArray(value: unknown): string[] {
  if (Array.isArray(value)) return value.map(String).filter(Boolean);
  if (typeof value === 'string') {
    return value
      .split(',')
      .map((entry) => entry.trim())
      .filter(Boolean);
  }
  return value == null || value === '' ? [] : [String(value)];
}

function toRelativeDateUnit(rawUnit: unknown): string {
  const candidate = String(rawUnit ?? '')
    .trim()
    .toLowerCase();
  return RELATIVE_DATE_UNITS.includes(
    candidate as (typeof RELATIVE_DATE_UNITS)[number],
  )
    ? candidate
    : 'day';
}

/** Exported for unit tests. */
export function toRelativeDateTuple(value: unknown): [unknown, string] {
  if (Array.isArray(value) && value.length >= 2) {
    return [value[0], toRelativeDateUnit(value[1])];
  }
  if (value && typeof value === 'object') {
    const objectValue = value as { value?: unknown; unit?: unknown };
    if (objectValue.value !== undefined || objectValue.unit !== undefined) {
      return [objectValue.value ?? '', toRelativeDateUnit(objectValue.unit)];
    }
  }
  return ['', 'day'];
}

/** A rule is complete once every value its operator needs is filled in. */
function isRuleComplete(rule: RuleType): boolean {
  if (VALUELESS_OPERATORS.has(rule.operator)) return true;
  if (RELATIVE_DATE_OPERATOR_KEYS.has(rule.operator)) {
    if (rule.operator !== 'inTheLast') return true;
    const amount = Number(toRelativeDateTuple(rule.value)[0]);
    return Number.isFinite(amount) && amount > 0;
  }
  if (RANGE_OPERATORS.has(rule.operator)) {
    const [low, high] = Array.isArray(rule.value)
      ? rule.value
      : String(rule.value ?? '').split(',');
    return String(low ?? '').trim() !== '' && String(high ?? '').trim() !== '';
  }
  return toRuleValueArray(rule.value).length > 0;
}

function countIncompleteRules(group: RuleGroupTypeAny): number {
  return group.rules.reduce<number>((count, rule) => {
    if (typeof rule === 'string') return count;
    if ('rules' in rule) return count + countIncompleteRules(rule);
    return count + (isRuleComplete(rule) ? 0 : 1);
  }, 0);
}

/**
 * react-querybuilder's validator: incomplete rules get its invalid class, which
 * outlines their empty value fields.
 */
function validateRules(query: RuleGroupTypeAny): ValidationMap {
  const validation: ValidationMap = {};
  const visit = (group: RuleGroupTypeAny) => {
    for (const rule of group.rules) {
      if (typeof rule === 'string') continue;
      if ('rules' in rule) visit(rule);
      else if (rule.id) validation[rule.id] = isRuleComplete(rule);
    }
  };
  visit(query);
  return validation;
}

/** Exported for unit tests. */
export function formatAppliedFilterValue(
  rule: RuleType,
  valueOptions: Array<{ value?: unknown; name?: unknown; label?: unknown }>,
): string {
  const valueLabel = (rawValue: unknown) => {
    const match = valueOptions.find(
      (option) =>
        String(option.value ?? option.name) === String(rawValue ?? ''),
    );
    return String(match?.label ?? rawValue ?? '');
  };

  if (RELATIVE_DATE_OPERATOR_KEYS.has(rule.operator)) {
    const [amount, unit] = toRelativeDateTuple(rule.value);
    return rule.operator === 'inTheLast'
      ? `${amount} ${unit}${Number(amount) === 1 ? '' : 's'}`
      : unit;
  }
  if (RANGE_OPERATORS.has(rule.operator)) {
    const [low, high] = toRuleValueArray(rule.value);
    return [low, high].filter(Boolean).map(valueLabel).join(' – ');
  }
  if (!VALUELESS_OPERATORS.has(rule.operator)) {
    return toRuleValueArray(rule.value).map(valueLabel).join(', ');
  }
  return '';
}

function describeRule(queryBuilder: UseReportQueryBuilder, rule: RuleType) {
  const field = queryBuilder.props.fields.find(
    (option) => option.name === rule.field,
  );
  const misc = { fieldData: field };
  const operator = queryBuilder.props
    .getOperators(rule.field, misc)
    .find((option) => option.name === rule.operator);
  return {
    field: field?.label ?? rule.field,
    operator: operatorPhrase(
      rule.operator,
      operatorLabel(operator, fieldTypeOf(field), rule.operator),
    ),
    value: formatAppliedFilterValue(
      rule,
      queryBuilder.props.getValues(rule.field, rule.operator, misc),
    ),
  };
}

function describeGroup(
  queryBuilder: UseReportQueryBuilder,
  group: ReportFilters,
): string {
  return group.rules
    .filter((rule) => typeof rule !== 'string')
    .map((rule) => {
      if ('rules' in rule) return `(${describeGroup(queryBuilder, rule)})`;
      const { field, operator, value } = describeRule(queryBuilder, rule);
      return [field, operator, value].filter(Boolean).join(' ');
    })
    .join(group.combinator === 'or' ? ' or ' : ', ');
}

/** Filter-toolbar chip: the field and operator in secondary text, the value emphasized. */
function AppliedFilterChip({
  disabled,
  field,
  value,
  onEdit,
  onRemove,
}: {
  disabled?: boolean;
  field: string;
  value: string;
  onEdit: () => void;
  onRemove?: () => void;
}) {
  const summary = [field, value].filter(Boolean).join(' ');
  return (
    <span className={styles.chip} data-testid="applied-filter-rule">
      <button
        type="button"
        className={styles.chipBody}
        title={summary}
        disabled={disabled}
        onClick={onEdit}
      >
        <span className={styles.chipField}>{field}</span>
        {value ? <span className={styles.chipValue}>{value}</span> : null}
      </button>
      {onRemove ? (
        <button
          type="button"
          className={styles.chipRemove}
          aria-label={`Remove filter: ${summary}`}
          disabled={disabled}
          onClick={onRemove}
        >
          <XIcon size={13} />
        </button>
      ) : null}
    </span>
  );
}

/** The nearest group: its id, and how many rules and groups it holds. */
const GroupContext = createContext<{ id: string; count: number }>({
  id: '',
  count: 0,
});

/**
 * Where a drag in progress would drop. "sort" reorders within the rule's own
 * group, shown by its neighbors sliding; "insert" moves it into another group,
 * or beside a group, at `index` counted before removal, shown by a drop line.
 */
type DropTarget = { groupId: string; index: number; mode: 'sort' | 'insert' };
const DropTargetContext = createContext<DropTarget | null>(null);

type DragData = { kind: 'rule' | 'group'; parentId: string };

/** Bands at a group card's top and bottom that drop beside it, not into it. */
const GROUP_EDGE = 16;
const noShiftStrategy: SortingStrategy = () => null;

/** A list's rule and group elements, leaving out the drop line. */
function listItems(list: Element | null | undefined) {
  return Array.from(list?.children ?? []).filter((child) =>
    child.classList.contains(styles.item),
  ) as HTMLElement[];
}

function itemIdOf(element: HTMLElement) {
  return element.dataset.ruleId ?? element.dataset.ruleGroupId ?? '';
}

function groupListOf(scope: HTMLElement, groupId: string) {
  return scope.querySelector<HTMLElement>(
    `[data-rule-group-id="${groupId}"] > .${styles.tree} > .${styles.list}`,
  );
}

/**
 * The index a pointer at `y` inserts at among a group's items, counted before
 * the dragged rule leaves its place, as react-querybuilder's move expects.
 */
function insertionIndex(
  scope: HTMLElement,
  groupId: string,
  activeId: string,
  y: number,
) {
  const items = listItems(groupListOf(scope, groupId));
  const activeIndex = items.findIndex((item) => itemIdOf(item) === activeId);
  const others = items.filter((_, index) => index !== activeIndex);
  const before = others.findIndex((item) => {
    const rect = item.getBoundingClientRect();
    return y < rect.top + rect.height / 2;
  });
  const index = before < 0 ? others.length : before;
  return activeIndex >= 0 && index >= activeIndex ? index + 1 : index;
}

/**
 * The group card under the pointer, outside its edge bands, or none for the top
 * level. Measured from dnd-kit's rects, which leave out the sliding transforms,
 * so a neighbor sliding under the pointer never flips the target back.
 */
function groupUnderPointer(
  args: Parameters<CollisionDetection>[0],
  pointer: { x: number; y: number },
) {
  const group = args.droppableContainers.find((container) => {
    if ((container.data.current as DragData | undefined)?.kind !== 'group') {
      return false;
    }
    const rect = args.droppableRects.get(container.id);
    return (
      !!rect &&
      pointer.x >= rect.left &&
      pointer.x <= rect.right &&
      pointer.y >= rect.top + GROUP_EDGE &&
      pointer.y <= rect.bottom - GROUP_EDGE
    );
  });
  return group ? String(group.id) : null;
}

/**
 * In its own group a rule sorts, and its neighbors slide to show where it
 * lands. Into any other group, or beside one, it inserts where the pointer is.
 */
function resolveDropTarget(
  scope: HTMLElement | null,
  groupId: string,
  active: Active,
  over: Over | null,
  y: number | undefined,
): DropTarget | null {
  const activeData = active.data.current as DragData | undefined;
  if (!scope || !activeData || y === undefined) return null;
  if (groupId === activeData.parentId) {
    const sortable = (over?.data.current as Partial<SortableData> | undefined)
      ?.sortable;
    return sortable ? { groupId, index: sortable.index, mode: 'sort' } : null;
  }
  return {
    groupId,
    index: insertionIndex(scope, groupId, String(active.id), y),
    mode: 'insert',
  };
}

function sameDropTarget(a: DropTarget | null, b: DropTarget | null) {
  return (
    a === b ||
    (!!a &&
      !!b &&
      a.groupId === b.groupId &&
      a.index === b.index &&
      a.mode === b.mode)
  );
}

/**
 * A drag that takes a group's last rule out leaves the group empty, so the
 * group goes with the move. Exported for unit tests.
 */
export function withoutEmptiedGroup<Q extends RuleGroupTypeAny>(
  query: Q,
  nextQuery: Q,
  fromPath: Path,
): Q {
  if (fromPath.length < 2) return nextQuery;
  const sourceId = findPath(getParentPath(fromPath), query)?.id;
  const sourcePath = sourceId ? getPathOfID(sourceId, nextQuery) : null;
  if (!sourcePath || sourcePath.length === 0) return nextQuery;
  const source = findPath(sourcePath, nextQuery);
  return source && isRuleGroup(source) && source.rules.length === 0
    ? remove(nextQuery, sourcePath)
    : nextQuery;
}

/**
 * Moves the rule or group at `path` to `toIndex` among its siblings.
 * react-querybuilder inserts before the item at the target path, counted
 * before removal, so a move down targets the slot past `toIndex`.
 */
function moveWithinGroup(
  moveRule: QueryActions['moveRule'],
  path: Path,
  toIndex: number,
) {
  const fromIndex = path[path.length - 1] ?? 0;
  if (toIndex === fromIndex) return;
  moveRule(path, [
    ...path.slice(0, -1),
    toIndex > fromIndex ? toIndex + 1 : toIndex,
  ]);
}

function sortableStyle(
  transform: Parameters<typeof CSS.Translate.toString>[0],
  transition: string | undefined,
) {
  return { transform: CSS.Translate.toString(transform), transition };
}

/**
 * Draws the group's bracket from the middle of its first item to the middle of
 * its last, with the combinator centered on it. Items tick into the bracket
 * through CSS; their middles are measured here.
 */
function useBracket(
  treeRef: RefObject<HTMLDivElement | null>,
  listRef: RefObject<HTMLDivElement | null>,
  itemsSignature: string,
) {
  useLayoutEffect(() => {
    const tree = treeRef.current;
    const list = listRef.current;
    if (!tree || !list) return;
    const measure = () => {
      const items = listItems(list);
      const first = items[0];
      const last = items[items.length - 1];
      if (!first || !last || first === last) return;
      const top = first.offsetTop + first.offsetHeight / 2;
      const bottom = last.offsetTop + last.offsetHeight / 2;
      tree.style.setProperty('--fb-bracket-top', `${top}px`);
      tree.style.setProperty('--fb-bracket-height', `${bottom - top}px`);
    };
    measure();
    if (typeof ResizeObserver === 'undefined') return;
    const observer = new ResizeObserver(measure);
    observer.observe(list);
    for (const item of listItems(list)) observer.observe(item);
    return () => observer.disconnect();
  }, [treeRef, listRef, itemsSignature]);
}

/** Where the drop line sits in a list for an insert at `index`. */
function dropLineTop(list: HTMLElement | null, index: number) {
  const items = listItems(list);
  const gap = 12;
  const item = items[index];
  if (item) return item.offsetTop - gap / 2;
  const last = items[items.length - 1];
  return last ? last.offsetTop + last.offsetHeight + gap / 2 : 0;
}

/**
 * A group's items in a sortable list, joined by a bracket that carries the
 * group's one combinator as a toggle. Every group's list shares the root's
 * drag context, so rules move between groups.
 */
function GroupItems({ rg }: { rg: UseRuleGroup }) {
  const treeRef = useRef<HTMLDivElement>(null);
  const listRef = useRef<HTMLDivElement>(null);
  const groupId = String(rg.id ?? '');
  const ids = rg.ruleGroup.rules.flatMap((rule) =>
    typeof rule === 'string' ? [] : [String(rule.id ?? '')],
  );
  useBracket(treeRef, listRef, ids.join('|'));
  const dropTarget = useContext(DropTargetContext);
  const inserting = dropTarget?.mode === 'insert';
  const insertingHere = inserting && dropTarget.groupId === groupId;
  const joined = ids.length > 1;
  const isOr = rg.combinator === 'or';

  return (
    <GroupContext.Provider value={{ id: groupId, count: ids.length }}>
      <div
        ref={treeRef}
        className={styles.tree}
        data-joined={joined || undefined}
      >
        {joined ? (
          <>
            <span className={styles.bracket} aria-hidden="true" />
            <button
              type="button"
              className={styles.combinator}
              disabled={rg.disabled}
              aria-label={`Conditions joined by ${isOr ? 'or' : 'and'}. Switch to ${isOr ? 'and' : 'or'}`}
              title={`Switch to ${isOr ? 'and' : 'or'}`}
              onClick={() => rg.onCombinatorChange(isOr ? 'and' : 'or')}
            >
              {isOr ? 'Or' : 'And'}
            </button>
          </>
        ) : null}
        <SortableContext
          id={groupId}
          items={ids}
          strategy={inserting ? noShiftStrategy : verticalListSortingStrategy}
        >
          <div ref={listRef} className={styles.list}>
            <RuleGroupBodyComponents {...rg} />
            {insertingHere ? (
              <span
                className={styles.dropLine}
                style={{ top: dropLineTop(listRef.current, dropTarget.index) }}
                aria-hidden="true"
              />
            ) : null}
          </div>
        </SortableContext>
      </div>
    </GroupContext.Provider>
  );
}

function GroupAction({
  disabled,
  icon,
  label,
  onClick,
}: {
  disabled?: boolean;
  icon: ReactNode;
  label: ReactNode;
  onClick: (event: MouseEvent<HTMLButtonElement>) => void;
}) {
  return (
    <Button
      type="button"
      variant="secondary"
      size="sm"
      className={styles.groupAction}
      disabled={disabled}
      onClick={onClick}
    >
      {icon}
      {label}
    </Button>
  );
}

/**
 * The top level: "When", its rules and groups, then Add rule and Add group.
 * It owns the one drag context: a rule drops among its own group's rules, into
 * another group, or beside a group at the top level.
 */
function RootGroup({ rg }: { rg: UseRuleGroup }) {
  const addRule = useStopEventPropagation(rg.addRule);
  const addGroup = useStopEventPropagation(rg.addGroup);
  const rootRef = useRef<HTMLDivElement>(null);
  const rootId = String(rg.id ?? '');
  const itemCount = rg.ruleGroup.rules.filter(
    (rule) => typeof rule !== 'string',
  ).length;
  const hasItems = itemCount > 0;

  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
  );
  const pointerRef = useRef<{ x: number; y: number } | null>(null);
  const targetGroupRef = useRef(rootId);
  // The pointer picks the group; the item over is the closest one in that
  // group, so within its own group a rule keeps sorting against its siblings.
  const collisionDetection = useCallback<CollisionDetection>(
    (args) => {
      const pointer = args.pointerCoordinates;
      pointerRef.current = pointer;
      const groupId = (pointer && groupUnderPointer(args, pointer)) ?? rootId;
      targetGroupRef.current = groupId;
      const items = args.droppableContainers.filter(
        (container) =>
          (container.data.current as DragData | undefined)?.parentId ===
          groupId,
      );
      return items.length > 0
        ? closestCenter({ ...args, droppableContainers: items })
        : [];
    },
    [rootId],
  );
  const [dropTarget, setDropTarget] = useState<DropTarget | null>(null);
  const resolve = ({ active, over }: DragMoveEvent | DragEndEvent) =>
    resolveDropTarget(
      rootRef.current,
      targetGroupRef.current,
      active,
      over,
      pointerRef.current?.y,
    );
  const onDragMove = (event: DragMoveEvent) => {
    const next = resolve(event);
    setDropTarget((prev) => (sameDropTarget(prev, next) ? prev : next));
  };
  const onDragEnd = (event: DragEndEvent) => {
    const target = resolve(event);
    setDropTarget(null);
    const fromPath = getPathOfID(String(event.active.id), rg.ruleGroup);
    if (!target || !fromPath) return;
    if (target.mode === 'sort') {
      moveWithinGroup(rg.actions.moveRule, fromPath, target.index);
      return;
    }
    const groupPath =
      target.groupId === rootId
        ? []
        : getPathOfID(target.groupId, rg.ruleGroup);
    if (groupPath) rg.actions.moveRule(fromPath, [...groupPath, target.index]);
  };

  return (
    <div
      ref={rootRef}
      className={`${rg.outerClassName} ${styles.root}`}
      data-testid="rule-group"
      data-rule-group-id={rg.id}
      data-level={0}
      data-joined={itemCount > 1 || undefined}
    >
      <span className={styles.when}>When</span>
      {hasItems ? (
        <DndContext
          sensors={sensors}
          collisionDetection={collisionDetection}
          modifiers={[restrictToVerticalAxis]}
          onDragMove={onDragMove}
          onDragEnd={onDragEnd}
          onDragCancel={() => setDropTarget(null)}
        >
          <DropTargetContext.Provider value={dropTarget}>
            <GroupItems rg={rg} />
          </DropTargetContext.Provider>
        </DndContext>
      ) : (
        <p className={styles.empty}>
          {(rg.context as FilterBuilderContext | undefined)?.empty ??
            'No filters yet. Add a rule to narrow this report.'}
        </p>
      )}
      <div className={styles.groupActions}>
        <GroupAction
          disabled={rg.disabled}
          icon={<GitBranchIcon size={15} />}
          label={rg.translations.addRule.label}
          onClick={(event) => addRule(event)}
        />
        <GroupAction
          disabled={rg.disabled}
          icon={<FolderIcon size={15} />}
          label={rg.translations.addGroup.label}
          onClick={(event) => addGroup(event)}
        />
      </div>
    </div>
  );
}

/**
 * A nested group: a card with its condition count, its own bracketed rules,
 * and Add condition. Groups nest one level deep, never a group of groups.
 */
function NestedGroup({ rg }: { rg: UseRuleGroup }) {
  const addRule = useStopEventPropagation(rg.addRule);
  const removeGroup = useStopEventPropagation(rg.removeGroup);
  const parent = useContext(GroupContext);
  const dropTarget = useContext(DropTargetContext);
  const groupId = String(rg.id ?? '');
  // Groups have no grip; they sort as their neighbors move and take drops.
  const { setNodeRef, transform, transition } = useSortable({
    id: groupId,
    data: { kind: 'group', parentId: parent.id } satisfies DragData,
    disabled: rg.disabled,
  });
  const count = rg.ruleGroup.rules.filter(
    (rule) => typeof rule !== 'string',
  ).length;
  const isDropTarget =
    dropTarget?.mode === 'insert' && dropTarget.groupId === groupId;
  return (
    <div
      ref={setNodeRef}
      style={sortableStyle(transform, transition)}
      className={`${rg.outerClassName} ${styles.item} ${styles.group}`}
      data-testid="rule-group"
      data-rule-group-id={rg.id}
      data-level={rg.path.length}
      data-drop-target={isDropTarget || undefined}
    >
      <div className={styles.groupHead}>
        <span className={styles.groupTitle}>
          <span className={styles.groupName}>Group</span>
          {` · ${count === 0 ? 'No conditions' : `${count} condition${count === 1 ? '' : 's'}`}`}
        </span>
        <Button
          type="button"
          variant="ghost"
          size="sm"
          className={styles.remove}
          aria-label={rg.translations.removeGroup.title}
          title={rg.translations.removeGroup.title}
          disabled={rg.disabled}
          onClick={(event) => removeGroup(event)}
        >
          <XIcon size={15} />
        </Button>
      </div>
      {count > 0 ? <GroupItems rg={rg} /> : null}
      <div className={styles.groupActions}>
        <GroupAction
          disabled={rg.disabled}
          icon={<BranchNodesIcon size={15} />}
          label="Add condition"
          onClick={(event) => addRule(event)}
        />
      </div>
    </div>
  );
}

function FilterRuleGroup(props: RuleGroupProps) {
  const rg = useRuleGroup(props);
  return rg.path.length === 0 ? <RootGroup rg={rg} /> : <NestedGroup rg={rg} />;
}

/**
 * dnd-kit only moves a dragged row while it is over its own group's list; over
 * another list it drops the row's transform and the row snaps back to its slot.
 * This keeps the drag's offset so the row stays under the pointer.
 */
function useDragOffset(id: string) {
  const [offset, setOffset] = useState<number | null>(null);
  const listener = useMemo<DndMonitorListener>(
    () => ({
      onDragMove: ({ active, delta }) => {
        if (String(active.id) === id) setOffset(delta.y);
      },
      onDragEnd: () => setOffset(null),
      onDragCancel: () => setOffset(null),
    }),
    [id],
  );
  useDndMonitor(listener);
  return offset;
}

/**
 * One rule as a row card: a grip to reorder it, then the field, operator, and
 * value controls, and a remove button. The grip drags the rule anywhere in the
 * tree, into or out of groups, or moves it within its group with the arrow
 * keys.
 */
function FilterRule(props: RuleProps) {
  const r = useRule(props);
  const group = useContext(GroupContext);
  const siblingCount = group.count;
  const index = r.path[r.path.length - 1] ?? 0;
  // A lone top-level rule has nowhere to go; a rule in a group can always leave it.
  const canDrag = !r.disabled && (siblingCount > 1 || r.path.length > 1);
  const gripRef = useRef<HTMLButtonElement | null>(null);
  const {
    listeners,
    setActivatorNodeRef,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({
    id: String(r.id ?? ''),
    data: { kind: 'rule', parentId: group.id } satisfies DragData,
    disabled: !canDrag,
  });
  const dragOffset = useDragOffset(String(r.id ?? ''));
  const rowTransform =
    isDragging && !transform && dragOffset !== null
      ? { x: 0, y: dragOffset, scaleX: 1, scaleY: 1 }
      : transform;
  const removeRule = useStopEventPropagation(r.removeRule);
  const onGripKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {
    const step =
      event.key === 'ArrowUp' ? -1 : event.key === 'ArrowDown' ? 1 : 0;
    if (!step) return;
    event.preventDefault();
    const toIndex = index + step;
    if (toIndex < 0 || toIndex >= siblingCount) return;
    moveWithinGroup(r.actions.moveRule, r.path, toIndex);
    // The row's node may be re-inserted on reorder, which drops focus.
    requestAnimationFrame(() => gripRef.current?.focus());
  };

  return (
    <div
      ref={setNodeRef}
      style={sortableStyle(rowTransform, transition)}
      className={`${r.outerClassName} ${styles.item}`}
      data-testid="rule"
      data-rule-id={r.id}
      data-level={r.path.length}
      data-dragging={isDragging || undefined}
    >
      <button
        type="button"
        ref={(node) => {
          gripRef.current = node;
          setActivatorNodeRef(node);
        }}
        className={styles.grip}
        aria-label={`Reorder rule ${index + 1} of ${siblingCount}. Use the arrow keys.`}
        title="Drag to reorder or move into a group"
        disabled={!canDrag}
        {...listeners}
        onKeyDown={onGripKeyDown}
      >
        <DragHandleIcon />
      </button>
      <RuleComponents {...r} removeRule={removeRule} />
    </div>
  );
}

function RemoveRuleAction({
  className,
  disabled,
  handleOnClick,
  title,
}: ActionProps) {
  return (
    <Button
      type="button"
      variant="ghost"
      size="sm"
      className={`${styles.remove} ${className ?? ''}`}
      aria-label={title}
      title={title}
      disabled={disabled}
      onClick={(event) => handleOnClick(event)}
    >
      <XIcon size={15} />
    </Button>
  );
}

/** The select at the builder's small size; its label is for assistive tech only. */
export function Select({
  className,
  disabled,
  hideLabel,
  label,
  onChange,
  options,
  placeholder,
  value,
}: {
  className?: string;
  disabled?: boolean;
  /** Keeps the label for assistive tech only, for a value that names itself (By month, Last 90 days). */
  hideLabel?: boolean;
  label: string;
  onChange: (value: string) => void;
  options: SelectOption[];
  /** Shown when the value is empty. Defaults to the label of the option whose value is `''` (None, Dynamic). */
  placeholder?: string;
  value: unknown;
}) {
  return (
    <div className={`${className ?? ''} ${styles.select} ${hideLabel ? styles.hiddenLabel : ''}`}>
      <BaseSelect
        label={label}
        className={styles.selectTrigger}
        contentClassName={styles.menu}
        value={value == null ? '' : String(value)}
        options={options}
        placeholder={placeholder ?? options.find((option) => option.value === '')?.label}
        disabled={disabled}
        onValueChange={onChange}
      />
    </div>
  );
}

function ValueSelector({
  className,
  disabled,
  handleOnChange,
  options,
  title,
  value,
}: VersatileSelectorProps) {
  return (
    <Select
      className={className}
      disabled={disabled}
      label={title || 'Field'}
      options={toSelectOptions(options)}
      value={value}
      onChange={handleOnChange}
    />
  );
}

/**
 * Operators are labelled for the rule's field type and follow an "is" between
 * the field and operator, except verbs such as "Contains".
 */
function OperatorSelector({
  className,
  disabled,
  fieldData,
  handleOnChange,
  options,
  value,
}: OperatorSelectorProps) {
  const fieldType = fieldTypeOf(fieldData);
  return (
    <div className={`${className ?? ''} ${styles.operator}`}>
      {VERB_OPERATORS.has(String(value)) ? null : (
        <span className={styles.is}>is</span>
      )}
      <Select
        disabled={disabled}
        label="Operator"
        options={toSelectOptions(options).map((option) => ({
          ...option,
          label: operatorLabel(
            { name: option.value, label: option.label },
            fieldType,
            option.label,
          ),
        }))}
        value={value}
        onChange={handleOnChange}
      />
    </div>
  );
}

/**
 * The multi-select at the builder's small size: picked values as removable tags
 * inside the field, as in the base multi-select; the menu adds and removes them too,
 * so the tags' remove marks are a pointer shortcut and stay out of the
 * accessibility tree.
 */
export function MultiSelect({
  className,
  disabled,
  hideLabel,
  label,
  onChange,
  options,
  placeholder,
  value,
}: {
  className?: string;
  disabled?: boolean;
  /** Keeps the label for assistive tech only. */
  hideLabel?: boolean;
  label: string;
  onChange: (values: string[]) => void;
  options: SelectOption[];
  placeholder?: string;
  value: string[];
}) {
  return (
    <div className={`${className ?? ''} ${styles.tagsField} ${hideLabel ? styles.hiddenLabel : ''}`}>
      <BaseMultiSelect
        label={label}
        className={styles.tags}
        value={value}
        options={options}
        disabled={disabled}
        placeholder={placeholder}
        maxVisible={Number.POSITIVE_INFINITY}
        removableChips
        onValueChange={onChange}
      />
    </div>
  );
}

/** A rule's values as tags. */
function ValueTagsSelect({
  className,
  disabled,
  isLoading,
  onChange,
  options,
  value,
}: {
  className?: string;
  disabled?: boolean;
  isLoading?: boolean;
  onChange: (values: string[]) => void;
  options: SelectOption[];
  value: string[];
}) {
  return (
    <MultiSelect className={className} hideLabel label="Values" value={value} options={options} disabled={disabled}
      placeholder={isLoading ? 'Loading values' : 'Select values'} onChange={onChange} />
  );
}

/**
 * Between and not between: react-querybuilder's own list handling, so each
 * end updates on its own. The hook lives here alone because its effect
 * collapses any other array value, such as a relative date's [amount, unit],
 * to its first element on every change.
 */
function RangeEditor(props: ValueEditorProps) {
  const { className, disabled, inputType } = props;
  const { valueAsArray, multiValueHandler } = useValueEditor(props);
  const htmlType = inputType || 'text';
  const isDate = htmlType === 'date';
  return (
    <div className={className}>
      <div className={styles.pair}>
        <Input
          className={styles.input}
          type={htmlType}
          label={isDate ? 'Start' : 'Minimum'}
          placeholder={isDate ? 'Start' : 'Min'}
          value={String(valueAsArray[0] ?? '')}
          disabled={disabled}
          onChange={(event) => multiValueHandler(event.target.value, 0)}
        />
        <span className={styles.pairJoin}>and</span>
        <Input
          className={styles.input}
          type={htmlType}
          label={isDate ? 'End' : 'Maximum'}
          placeholder={isDate ? 'End' : 'Max'}
          value={String(valueAsArray[1] ?? '')}
          disabled={disabled}
          onChange={(event) => multiValueHandler(event.target.value, 1)}
        />
      </div>
    </div>
  );
}

function ValueEditor(props: ValueEditorProps) {
  const {
    className,
    context,
    disabled,
    handleOnChange,
    inputType,
    listsAsArrays = true,
    operator,
    type,
    value,
    values,
  } = props;
  const valuesLoading = Boolean(
    (context as FilterBuilderContext | undefined)?.valuesLoading,
  );

  if (VALUELESS_OPERATORS.has(operator)) return null;

  if (RELATIVE_DATE_OPERATOR_KEYS.has(operator)) {
    const [amount, unit] = toRelativeDateTuple(value);
    const showAmount = operator === 'inTheLast';
    const plural = showAmount && Number(amount) !== 1;
    const commit = (nextAmount: unknown, nextUnit: string) =>
      handleOnChange(
        listsAsArrays ? [nextAmount, nextUnit] : `${nextAmount},${nextUnit}`,
      );
    return (
      <div className={className}>
        <div className={styles.pair}>
          {showAmount ? (
            <Input
              className={`${styles.input} ${styles.amount}`}
              type="number"
              min={1}
              inputMode="numeric"
              label="Amount"
              placeholder="0"
              value={String(amount ?? '')}
              disabled={disabled}
              onChange={(event) => {
                const parsed = Number(event.target.value);
                commit(
                  event.target.value === '' || !Number.isFinite(parsed)
                    ? event.target.value
                    : parsed,
                  unit,
                );
              }}
            />
          ) : null}
          <Select
            disabled={disabled}
            label="Unit"
            value={unit}
            options={RELATIVE_DATE_UNITS.map((unitOption) => ({
              value: unitOption,
              label: plural ? `${unitOption}s` : unitOption,
            }))}
            onChange={(nextUnit) => commit(showAmount ? amount : 1, nextUnit)}
          />
        </div>
      </div>
    );
  }

  const options = toSelectOptions(values ?? []);
  const isMultiSelect =
    type === 'multiselect' || operator === 'in' || operator === 'notIn';

  if (isMultiSelect && (options.length > 0 || valuesLoading)) {
    return (
      <ValueTagsSelect
        className={className}
        value={toRuleValueArray(value)}
        options={options}
        disabled={disabled}
        isLoading={valuesLoading && options.length === 0}
        onChange={(nextValues) =>
          handleOnChange(listsAsArrays ? nextValues : nextValues.join(','))
        }
      />
    );
  }

  if ((type === 'select' || type === 'radio') && options.length > 0) {
    return (
      <Select
        className={className}
        disabled={disabled}
        label="Value"
        options={options}
        value={value}
        onChange={handleOnChange}
      />
    );
  }

  const htmlType = inputType || 'text';
  if (RANGE_OPERATORS.has(operator)) return <RangeEditor {...props} />;

  return (
    <div className={className}>
      <Input
        className={styles.input}
        type={htmlType}
        label="Value"
        placeholder={htmlType === 'number' ? '0' : 'Value'}
        value={value == null ? '' : String(value)}
        disabled={disabled}
        onChange={(event) => handleOnChange(event.target.value)}
      />
    </div>
  );
}

const CONTROL_ELEMENTS = {
  ruleGroup: FilterRuleGroup,
  rule: FilterRule,
  removeRuleAction: RemoveRuleAction,
  fieldSelector: ValueSelector,
  operatorSelector: OperatorSelector,
  valueSelector: ValueSelector,
  valueEditor: ValueEditor,
};

/**
 * The report builder's filters, edited in react-querybuilder with the app's
 * controls, laid out as a "When" tree of rule rows and group cards joined by
 * brackets: shown as filter-toolbar chips that open the editor in a
 * popover, or as the editor itself, open in place. Edits stay a draft until
 * Apply; Cancel, or closing the popover any other way, discards them.
 */
export function FilterBuilder({
  disabled: disabledProp,
  loading = false,
  filters,
  queryBuilder,
  filterUniqueValuesLoading,
  onFiltersChange,
  label = 'Filters',
  align = 'start',
  layout = 'chips',
  empty,
}: {
  disabled?: boolean;
  /** The rules are loading: empty rule rows in place of the editor until the first time it's false; later loads only disable it. */
  loading?: boolean;
  filters?: ReportFilters | null;
  queryBuilder: UseReportQueryBuilder;
  filterUniqueValuesLoading?: boolean;
  /** Commits filters directly, for removing a chip. */
  onFiltersChange?: (next: SetFiltersInput) => void;
  /** The field's visible label; null leaves it out, for a toolbar that already says what it is. */
  label?: string | null;
  /** Which edge of the trigger the editor lines up with. */
  align?: 'start' | 'end';
  /**
   * chips: the chips, then Edit filters. editor: the editor, with Cancel and Apply once edited. field: the editor alone,
   * applied by the form's own button (`queryBuilder.apply`).
   */
  layout?: 'chips' | 'editor' | 'field';
  /** What the editor says with no rules yet. */
  empty?: string;
}) {
  const disabled = disabledProp || loading;
  const [loaded, setLoaded] = useState(!loading);
  if (!loading && !loaded) setLoaded(true);
  const titleId = useId();
  const triggerRef = useRef<HTMLButtonElement>(null);
  const [open, setOpen] = useState(false);
  const triggerDisabled = disabled || filterUniqueValuesLoading;
  const adaptedQueryBuilderProps = queryBuilder.props as ComponentProps<
    typeof QueryBuilder
  >;
  const appliedRules =
    filters && Array.isArray(filters.rules) ? filters.rules : [];
  // The editor's latest draft, so Apply can wait for every rule to be complete.
  const [draft, setDraft] = useState<RuleGroupType | null>(null);
  const forwardQueryChange = queryBuilder.props.onQueryChange;
  const handleQueryChange = useCallback(
    (next: RuleGroupType) => {
      setDraft(next);
      forwardQueryChange?.(next);
    },
    [forwardQueryChange],
  );
  const incompleteCount = draft ? countIncompleteRules(draft) : 0;
  // Apply tracks whether the filters are valid, not whether they changed:
  // undoing an edit by hand still applies, it just closes without a re-query.
  const canApply = incompleteCount === 0;

  const close = () => {
    if (queryBuilder.hasUnappliedChanges) queryBuilder.discard();
    setDraft(null);
    setOpen(false);
  };
  // Chips index the committed tree, which is also what the updater receives.
  const removeAt = (index: number) =>
    onFiltersChange?.((committed) => ({
      ...committed,
      rules: committed.rules.filter((_, ruleIndex) => ruleIndex !== index),
    }));

  const builder = (
    <QueryBuilder
      key={queryBuilder.key}
      {...adaptedQueryBuilderProps}
      onQueryChange={handleQueryChange}
      disabled={disabled}
      resetOnOperatorChange
      onMoveRule={(_rule, fromPath, _toPath, query, nextQuery) =>
        withoutEmptiedGroup(query, nextQuery, fromPath)
      }
      combinators={COMBINATORS}
      context={{ valuesLoading: filterUniqueValuesLoading, empty }}
      controlElements={CONTROL_ELEMENTS}
      controlClassnames={{ queryBuilder: styles.qb }}
      validator={validateRules}
      translations={TRANSLATIONS}
    />
  );
  const foot = (
    <div className={styles.panelFoot}>
      {incompleteCount ? (
        <p className={styles.panelError} role="status">
          {incompleteCount === 1
            ? '1 filter is incomplete. Finish or remove it to apply.'
            : `${incompleteCount} filters are incomplete. Finish or remove them to apply.`}
        </p>
      ) : null}
      <Button
        type="button"
        variant="secondary"
        size="sm"
        className={styles.footButton}
        onClick={() => {
          close();
          triggerRef.current?.focus();
        }}
      >
        Cancel
      </Button>
      <Button
        type="button"
        variant="primary"
        size="sm"
        className={`${styles.footButton} ${styles.apply}`}
        disabled={disabled || filterUniqueValuesLoading || !canApply}
        onClick={() => {
          if (queryBuilder.hasUnappliedChanges) queryBuilder.apply();
          setDraft(null);
          setOpen(false);
          triggerRef.current?.focus();
        }}
      >
        Apply
      </Button>
    </div>
  );

  if (layout !== 'chips') {
    return (
      <div className={styles.field} data-layout={layout} aria-busy={!loaded || undefined}>
        {label ? <span className={styles.label}>{label}</span> : null}
        {loaded ? builder : (
          <div className={styles.skeleton}>
            <span className={styles.when}>When</span>
            <span /><span /><span />
          </div>
        )}
        {layout === 'editor' && queryBuilder.hasUnappliedChanges ? foot : null}
      </div>
    );
  }

  return (
    <div className={styles.field} data-layout={layout}>
      {label ? <span className={styles.label}>{label}</span> : null}
      {appliedRules.length ? (
        <div
          className={styles.chips}
          role="group"
          aria-label="Applied filters"
          data-testid="applied-filter-group"
        >
          {appliedRules.map((rule, index) => {
            if (typeof rule === 'string') return null;
            const chip =
              'rules' in rule
                ? {
                    field: rule.combinator === 'or' ? 'Any of' : 'All of',
                    value: describeGroup(queryBuilder, rule),
                  }
                : (() => {
                    const { field, operator, value } = describeRule(
                      queryBuilder,
                      rule,
                    );
                    return { field: `${field} ${operator}`, value };
                  })();
            return (
              <Fragment key={index}>
                {index > 0 && filters?.combinator === 'or' ? (
                  <span className={styles.joiner}>or</span>
                ) : null}
                <AppliedFilterChip
                  disabled={triggerDisabled}
                  field={chip.field}
                  value={chip.value}
                  onEdit={() => setOpen(true)}
                  onRemove={onFiltersChange ? () => removeAt(index) : undefined}
                />
              </Fragment>
            );
          })}
        </div>
      ) : null}
      <Popover
        open={open}
        onOpenChange={(next) => (next ? setOpen(true) : close())}
      >
        <PopoverTrigger asChild>
          <Button
            ref={triggerRef}
            type="button"
            variant="secondary"
            size="sm"
            className={styles.trigger}
            data-open={open || undefined}
            disabled={triggerDisabled}
          >
            {appliedRules.length ? (
              'Edit filters'
            ) : (
              <>
                <PlusIcon size={14} />
                Add filter
              </>
            )}
          </Button>
        </PopoverTrigger>
        <PopoverContent
          aria-labelledby={titleId}
          className={styles.panel}
          side="bottom"
          align={align}
        >
          <div className={styles.panelHead}>
            <h3 id={titleId} className={styles.panelTitle}>
              Filters
            </h3>
          </div>
          <div className={styles.panelBody}>
            {/* Unmount as soon as the panel starts closing: `close()` discards
                the draft, which remounts the builder, and a remount inside the
                popover's exit animation would seed a blank rule and mark the
                draft dirty again after it is gone. */}
            {open ? builder : null}
          </div>
          {foot}
        </PopoverContent>
      </Popover>
    </div>
  );
}
```

<!--# include virtual="/docs-md/code/server-file/$stack_server/$stack_database/$stack_cache.md" -->

<!--# include virtual="/docs-md/page/use-cases/alerts/1/$stack_messaging.md" -->
