{
  "name": "query-builder",
  "type": "registry:ui",
  "dependencies": [
    "cn",
    "radix-ui"
  ],
  "registryDependencies": [
    "button",
    "input",
    "select",
    "@diceui/faceted"
  ],
  "files": [
    {
      "path": "ui/query-builder.tsx",
      "type": "registry:ui",
      "content": "\"use client\";\n\nimport { cn } from \"cn\";\nimport { Slot as SlotPrimitive } from \"radix-ui\";\nimport { useLayoutEffect } from \"radix-ui/internal\";\nimport * as React from \"react\";\n\nimport {\n  addQueryNode,\n  createQueryGroup,\n  createQueryRule,\n  getIsQueryGroup,\n  getIsQueryRuleMultiple,\n  getQueryOperatorLabel,\n  getQueryOperators,\n  type QueryCombinator,\n  type QueryField,\n  type QueryFieldOption,\n  type QueryGroup,\n  type QueryNode,\n  type QueryOperator,\n  type QueryRule,\n  type QueryValue,\n  removeQueryNode,\n  setQueryRuleField,\n  setQueryRuleOperator,\n  setQueryRuleValues,\n  updateQueryNode,\n} from \"@/registry/bases/radix/lib/query-builder\";\nimport { Button } from \"@/registry/bases/radix/ui/button\";\nimport {\n  Faceted,\n  FacetedBadge,\n  FacetedClear,\n  FacetedContent,\n  FacetedEmpty,\n  FacetedGroup,\n  FacetedInput,\n  FacetedItem,\n  FacetedItemIndicator,\n  FacetedList,\n  FacetedTrigger,\n  FacetedValue,\n} from \"@/registry/bases/radix/ui/faceted\";\nimport { Input } from \"@/registry/bases/radix/ui/input\";\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from \"@/registry/bases/radix/ui/select\";\nimport { IconPlaceholder } from \"@/registry/icons/icon-placeholder\";\n\nconst ROOT_NAME = \"QueryBuilder\";\nconst GROUP_NAME = \"QueryBuilderGroup\";\nconst GROUP_HEADER_NAME = \"QueryBuilderGroupHeader\";\nconst GROUP_TITLE_NAME = \"QueryBuilderGroupTitle\";\nconst GROUP_FOOTER_NAME = \"QueryBuilderGroupFooter\";\nconst GROUP_CONTENT_NAME = \"QueryBuilderGroupContent\";\nconst RULE_LIST_NAME = \"QueryBuilderRuleList\";\nconst RULE_NAME = \"QueryBuilderRule\";\nconst COMBINATOR_NAME = \"QueryBuilderCombinator\";\nconst CONNECTOR_NAME = \"QueryBuilderConnector\";\nconst NEGATE_NAME = \"QueryBuilderNegate\";\nconst FIELD_NAME = \"QueryBuilderField\";\nconst OPERATOR_NAME = \"QueryBuilderOperator\";\nconst VALUE_NAME = \"QueryBuilderValue\";\nconst ADD_RULE_NAME = \"QueryBuilderAddRule\";\nconst ADD_GROUP_NAME = \"QueryBuilderAddGroup\";\nconst REMOVE_NAME = \"QueryBuilderRemove\";\n\ninterface DivProps extends React.ComponentProps<\"div\"> {\n  asChild?: boolean;\n}\n\nconst DEFAULT_LABELS = {\n  where: \"Where\",\n  and: \"And\",\n  or: \"Or\",\n  all: \"All\",\n  any: \"Any\",\n  not: \"Not\",\n  combinator: \"Combinator\",\n  matchAll: \"All of the following are true…\",\n  matchAny: \"Any of the following are true…\",\n  matchNotAll: \"Not all of the following are true…\",\n  matchNone: \"None of the following are true…\",\n  field: \"Field\",\n  searchFields: \"Search fields\",\n  noFields: \"No fields found.\",\n  operator: \"Operator\",\n  operatorLabel: getQueryOperatorLabel,\n  searchOperators: \"Search operators\",\n  noOperators: \"No operators found.\",\n  enterValue: \"Enter a value\",\n  selectValue: \"Select a value\",\n  selectValues: \"Select values\",\n  searchValues: (field: string) => `Search ${field.toLowerCase()}`,\n  selected: (count: number) => `${count} selected`,\n  noValue: \"no value\",\n  noValues: \"No results.\",\n  between: \"and\",\n  from: \"from\",\n  to: \"to\",\n  true: \"True\",\n  false: \"False\",\n  addRule: \"Add rule\",\n  addGroup: \"Add group\",\n  removeRule: \"Remove rule\",\n  removeGroup: \"Remove group\",\n};\n\ntype QueryBuilderLabels = typeof DEFAULT_LABELS;\n\ninterface QueryBuilderContextValue {\n  fields: QueryField[];\n  labels: QueryBuilderLabels;\n  value: QueryGroup;\n  setValue: (updater: (value: QueryGroup) => QueryGroup) => void;\n  maxDepth: number;\n  disabled: boolean;\n}\n\nconst QueryBuilderContext =\n  React.createContext<QueryBuilderContextValue | null>(null);\n\nfunction useQueryBuilderContext(consumerName: string) {\n  const context = React.useContext(QueryBuilderContext);\n  if (!context) {\n    throw new Error(`\\`${consumerName}\\` must be used within \\`${ROOT_NAME}\\``);\n  }\n  return context;\n}\n\ninterface GroupContextValue {\n  group: QueryGroup;\n  depth: number;\n  isRoot: boolean;\n}\n\nconst GroupContext = React.createContext<GroupContextValue | null>(null);\n\nfunction useGroupContext(consumerName: string) {\n  const context = React.useContext(GroupContext);\n  if (!context) {\n    throw new Error(\n      `\\`${consumerName}\\` must be used within \\`${GROUP_NAME}\\``,\n    );\n  }\n  return context;\n}\n\nconst NestedGroupContext = React.createContext<QueryGroup | null>(null);\n\nconst GroupTemplateContext = React.createContext<QueryBuilderGroupProps | null>(\n  null,\n);\n\ninterface NodeContextValue {\n  index: number;\n  group: QueryGroup;\n}\n\nconst NodeContext = React.createContext<NodeContextValue | null>(null);\n\nconst RuleContext = React.createContext<QueryRule | null>(null);\n\nfunction useRuleContext(consumerName: string) {\n  const context = React.useContext(RuleContext);\n  if (!context) {\n    throw new Error(`\\`${consumerName}\\` must be used within \\`${RULE_NAME}\\``);\n  }\n  return context;\n}\n\nfunction useQueryActions(consumerName: string) {\n  const { setValue } = useQueryBuilderContext(consumerName);\n  return React.useMemo(\n    () => ({\n      update: (id: string, updater: (node: QueryNode) => QueryNode) =>\n        setValue((value) => updateQueryNode(value, id, updater)),\n      add: (groupId: string, node: QueryNode) =>\n        setValue((value) => addQueryNode(value, groupId, node)),\n      remove: (id: string) => setValue((value) => removeQueryNode(value, id)),\n    }),\n    [setValue],\n  );\n}\n\ninterface QueryBuilderProps extends Omit<DivProps, \"defaultValue\"> {\n  fields: QueryField[];\n  value?: QueryGroup;\n  defaultValue?: QueryGroup;\n  onValueChange?: (value: QueryGroup) => void;\n  maxDepth?: number;\n  labels?: Partial<QueryBuilderLabels>;\n  disabled?: boolean;\n}\n\nfunction QueryBuilder({\n  fields,\n  value: valueProp,\n  defaultValue,\n  onValueChange: onValueChangeProp,\n  maxDepth = 2,\n  labels: labelsProp,\n  disabled = false,\n  asChild,\n  className,\n  ...props\n}: QueryBuilderProps) {\n  const [uncontrolledValue, setUncontrolledValue] = React.useState(\n    () => defaultValue ?? createQueryGroup(),\n  );\n  const isControlled = valueProp !== undefined;\n  const value = valueProp ?? uncontrolledValue;\n\n  const valueRef = React.useRef(value);\n  useLayoutEffect(() => {\n    valueRef.current = value;\n  });\n\n  const setValue = React.useCallback(\n    (updater: (value: QueryGroup) => QueryGroup) => {\n      const next = updater(valueRef.current);\n      if (next === valueRef.current) return;\n      valueRef.current = next;\n      if (!isControlled) setUncontrolledValue(next);\n      onValueChangeProp?.(next);\n    },\n    [isControlled, onValueChangeProp],\n  );\n\n  const labels = React.useMemo<QueryBuilderLabels>(\n    () => ({\n      ...DEFAULT_LABELS,\n      ...Object.fromEntries(\n        Object.entries(labelsProp ?? {}).filter(\n          ([, label]) => label !== undefined,\n        ),\n      ),\n    }),\n    [labelsProp],\n  );\n\n  const contextValue = React.useMemo<QueryBuilderContextValue>(\n    () => ({ fields, labels, value, setValue, maxDepth, disabled }),\n    [fields, labels, value, setValue, maxDepth, disabled],\n  );\n\n  const RootPrimitive = asChild ? SlotPrimitive.Slot : \"div\";\n\n  return (\n    <QueryBuilderContext.Provider value={contextValue}>\n      <RootPrimitive\n        role=\"group\"\n        data-slot=\"query-builder\"\n        data-disabled={disabled ? \"\" : undefined}\n        {...props}\n        className={cn(\n          \"min-w-64 gap-3 @container/query-builder flex flex-col\",\n          className,\n        )}\n      />\n    </QueryBuilderContext.Provider>\n  );\n}\n\ninterface QueryBuilderGroupProps extends Omit<DivProps, \"children\"> {\n  children?: React.ReactNode | ((group: QueryGroup) => React.ReactNode);\n}\n\nfunction QueryBuilderGroup(groupProps: QueryBuilderGroupProps) {\n  const { value } = useQueryBuilderContext(GROUP_NAME);\n  const parent = React.useContext(GroupContext);\n  const nestedGroup = React.useContext(NestedGroupContext);\n  const template = React.useContext(GroupTemplateContext);\n\n  const { asChild, className, ref, id, children, ...props } =\n    parent && template\n      ? {\n          ...template,\n          ...groupProps,\n          className: cn(template.className, groupProps.className),\n        }\n      : groupProps;\n\n  const group = nestedGroup ?? value;\n  const depth = parent ? parent.depth + 1 : 0;\n\n  const groupContext = React.useMemo<GroupContextValue>(\n    () => ({ group, depth, isRoot: !parent }),\n    [group, depth, parent],\n  );\n\n  const GroupPrimitive = asChild ? SlotPrimitive.Slot : \"div\";\n\n  const element = (\n    <GroupContext.Provider value={groupContext}>\n      <NestedGroupContext.Provider value={null}>\n        <GroupPrimitive\n          ref={ref}\n          id={id}\n          role={parent ? \"listitem\" : \"group\"}\n          data-slot=\"query-builder-group\"\n          data-depth={depth}\n          data-combinator={group.combinator}\n          data-not={group.not ? \"\" : undefined}\n          {...props}\n          className={cn(\"items-start gap-2 @max-[28rem]/query-builder:gap-1.5 @max-[28rem]/query-builder:flex-col @max-[28rem]/query-builder:items-stretch flex\", className)}\n        >\n          {typeof children === \"function\" ? children(group) : children}\n        </GroupPrimitive>\n      </NestedGroupContext.Provider>\n    </GroupContext.Provider>\n  );\n\n  if (parent) return element;\n\n  return (\n    <GroupTemplateContext.Provider\n      value={{ asChild, className, children, ...props }}\n    >\n      {element}\n    </GroupTemplateContext.Provider>\n  );\n}\n\nfunction QueryBuilderGroupHeader({ asChild, className, ...props }: DivProps) {\n  const { depth } = useGroupContext(GROUP_HEADER_NAME);\n  const HeaderPrimitive = asChild ? SlotPrimitive.Slot : \"div\";\n\n  return (\n    <HeaderPrimitive\n      data-slot=\"query-builder-group-header\"\n      data-depth={depth}\n      {...props}\n      className={cn(\n        \"gap-1 ps-1.5 text-sm text-muted-foreground flex items-center\",\n        className,\n      )}\n    />\n  );\n}\n\nfunction QueryBuilderGroupTitle({\n  asChild,\n  className,\n  children,\n  ...props\n}: DivProps) {\n  const { labels } = useQueryBuilderContext(GROUP_TITLE_NAME);\n  const { group } = useGroupContext(GROUP_TITLE_NAME);\n  const title =\n    group.combinator === \"and\"\n      ? group.not\n        ? labels.matchNotAll\n        : labels.matchAll\n      : group.not\n        ? labels.matchNone\n        : labels.matchAny;\n\n  const TitlePrimitive = asChild ? SlotPrimitive.Slot : \"div\";\n\n  return (\n    <TitlePrimitive\n      data-slot=\"query-builder-group-title\"\n      dir=\"auto\"\n      {...props}\n      className={cn(\"flex-1 truncate\", className)}\n    >\n      {asChild ? (\n        <SlotPrimitive.Slottable child={children}>\n          {(content) => content ?? title}\n        </SlotPrimitive.Slottable>\n      ) : (\n        (children ?? title)\n      )}\n    </TitlePrimitive>\n  );\n}\n\nfunction QueryBuilderGroupFooter({ asChild, className, ...props }: DivProps) {\n  const { depth } = useGroupContext(GROUP_FOOTER_NAME);\n  const FooterPrimitive = asChild ? SlotPrimitive.Slot : \"div\";\n\n  return (\n    <FooterPrimitive\n      data-slot=\"query-builder-group-footer\"\n      data-depth={depth}\n      {...props}\n      className={cn(\n        \"gap-1 flex items-center\",\n        className,\n      )}\n    />\n  );\n}\n\nfunction QueryBuilderGroupContent({ asChild, className, ...props }: DivProps) {\n  const { depth } = useGroupContext(GROUP_CONTENT_NAME);\n  const ContentPrimitive = asChild ? SlotPrimitive.Slot : \"div\";\n\n  return (\n    <ContentPrimitive\n      data-slot=\"query-builder-group-content\"\n      data-depth={depth}\n      {...props}\n      className={cn(\n        \"min-w-0 flex-1 gap-2 not-data-[depth=0]:rounded-lg not-data-[depth=0]:border not-data-[depth=0]:bg-muted/20 not-data-[depth=0]:p-2 @container/query-builder flex flex-col\",\n        className,\n      )}\n    />\n  );\n}\n\ninterface QueryBuilderRuleListProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"children\"\n> {\n  children?: React.ReactNode | ((node: QueryNode) => React.ReactNode);\n}\n\nfunction QueryBuilderRuleList({\n  className,\n  children,\n  ...props\n}: QueryBuilderRuleListProps) {\n  const { group } = useGroupContext(RULE_LIST_NAME);\n\n  return (\n    <div\n      role=\"list\"\n      data-slot=\"query-builder-rule-list\"\n      {...props}\n      className={cn(\"gap-2 flex flex-col\", className)}\n    >\n      {group.rules.map((node, index) => (\n        <NodeContext.Provider key={node.id} value={{ index, group }}>\n          {getIsQueryGroup(node) ? (\n            <NestedGroupContext.Provider value={node}>\n              {typeof children === \"function\" ? (\n                children(node)\n              ) : (\n                <QueryBuilderGroup />\n              )}\n            </NestedGroupContext.Provider>\n          ) : (\n            <RuleContext.Provider value={node}>\n              {typeof children === \"function\" ? children(node) : children}\n            </RuleContext.Provider>\n          )}\n        </NodeContext.Provider>\n      ))}\n    </div>\n  );\n}\n\nfunction QueryBuilderRule({ asChild, className, ...props }: DivProps) {\n  const rule = useRuleContext(RULE_NAME);\n\n  const RulePrimitive = asChild ? SlotPrimitive.Slot : \"div\";\n\n  return (\n    <RulePrimitive\n      role=\"listitem\"\n      data-slot=\"query-builder-rule\"\n      data-operator={rule.operator}\n      {...props}\n      className={cn(\"gap-2 *:data-[slot=button-group]:min-w-0 @max-[28rem]/query-builder:gap-1.5 @max-[28rem]/query-builder:*:data-[slot=button-group]:flex-1 @max-[28rem]/query-builder:**:data-[slot=query-builder-select-icon]:hidden has-data-[operator=isBetween]:*:data-[slot=button-group]:flex-1 [&>[data-slot=button-group]>*:not(:first-child):focus-visible]:outline-1 [&>[data-slot=button-group]>*:not(:first-child):focus-visible]:outline-solid [&>[data-slot=button-group]>*:not(:first-child):focus-visible]:outline-ring [&>[data-slot=button-group]>*:not(:first-child):focus-visible]:-outline-offset-1 @max-[40rem]/query-builder:data-[operator=isBetween]:items-start @max-[40rem]/query-builder:data-[operator=isBetween]:*:data-[slot=button-group]:flex-wrap @max-[40rem]/query-builder:data-[operator=isBetween]:*:data-[slot=button-group]:gap-y-1 flex items-center\", className)}\n    />\n  );\n}\n\ninterface CombinatorSelectProps extends React.ComponentProps<\n  typeof SelectTrigger\n> {\n  group: QueryGroup;\n  items: Record<QueryCombinator, string>;\n}\n\nfunction CombinatorSelect({\n  group,\n  items,\n  disabled: disabledProp,\n  ...props\n}: CombinatorSelectProps) {\n  const { disabled, labels } = useQueryBuilderContext(COMBINATOR_NAME);\n  const isDisabled = disabled || disabledProp;\n  const { update } = useQueryActions(COMBINATOR_NAME);\n\n  return (\n    <Select\n      value={group.combinator}\n      onValueChange={(combinator) =>\n        update(group.id, (node) => ({\n          ...node,\n          combinator: combinator as QueryCombinator,\n        }))\n      }\n      disabled={isDisabled}\n    >\n      <SelectTrigger size=\"sm\" aria-label={labels.combinator} {...props}>\n        <SelectValue />\n      </SelectTrigger>\n      <SelectContent>\n        {([\"and\", \"or\"] as const).map((combinator) => (\n          <SelectItem key={combinator} value={combinator}>\n            {items[combinator]}\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  );\n}\n\nfunction QueryBuilderCombinator({\n  className,\n  ...props\n}: React.ComponentProps<typeof SelectTrigger>) {\n  const { labels } = useQueryBuilderContext(COMBINATOR_NAME);\n  const { group } = useGroupContext(COMBINATOR_NAME);\n\n  return (\n    <CombinatorSelect\n      group={group}\n      items={{ and: labels.all, or: labels.any }}\n      data-slot=\"query-builder-combinator\"\n      {...props}\n      className={cn(\"w-20\", className)}\n    />\n  );\n}\n\nfunction QueryBuilderConnector({\n  asChild,\n  className,\n  children,\n  ...props\n}: DivProps) {\n  const { labels } = useQueryBuilderContext(CONNECTOR_NAME);\n  const node = React.useContext(NodeContext);\n\n  if (!node) return null;\n\n  const { index, group } = node;\n  const target = group.rules[index];\n  const items = { and: labels.and, or: labels.or };\n\n  const ConnectorPrimitive = asChild ? SlotPrimitive.Slot : \"div\";\n\n  return (\n    <ConnectorPrimitive\n      data-slot=\"query-builder-connector\"\n      data-type={target && getIsQueryGroup(target) ? \"group\" : \"rule\"}\n      {...props}\n      className={cn(\"h-8 w-18 shrink-0 data-[type=group]:mt-2 @max-[28rem]/query-builder:w-15 @max-[28rem]/query-builder:data-[type=group]:mt-0 flex items-center\", className)}\n    >\n      {asChild && <SlotPrimitive.Slottable>{children}</SlotPrimitive.Slottable>}\n      {index === 1 ? (\n        <CombinatorSelect\n          group={group}\n          items={items}\n          className=\"w-full rounded-md data-[size=sm]:rounded-md @max-[28rem]/query-builder:gap-1 @max-[28rem]/query-builder:px-1.5 @max-[28rem]/query-builder:[&_svg]:hidden\"\n        />\n      ) : (\n        <span className=\"ps-2 text-sm text-muted-foreground @max-[28rem]/query-builder:ps-1\">\n          {index === 0 ? labels.where : items[group.combinator]}\n        </span>\n      )}\n    </ConnectorPrimitive>\n  );\n}\n\nfunction QueryBuilderNegate({\n  onClick,\n  children,\n  className,\n  disabled: disabledProp,\n  ...props\n}: React.ComponentProps<typeof Button>) {\n  const { disabled, labels } = useQueryBuilderContext(NEGATE_NAME);\n  const isDisabled = disabled || disabledProp;\n  const { group } = useGroupContext(NEGATE_NAME);\n  const { update } = useQueryActions(NEGATE_NAME);\n\n  return (\n    <Button\n      type=\"button\"\n      variant=\"ghost\"\n      size=\"sm\"\n      aria-pressed={!!group.not}\n      data-slot=\"query-builder-negate\"\n      data-state={group.not ? \"on\" : \"off\"}\n      disabled={isDisabled}\n      {...props}\n      onClick={(event) => {\n        onClick?.(event);\n        if (event.defaultPrevented) return;\n        update(group.id, (node) =>\n          getIsQueryGroup(node) ? { ...node, not: !node.not } : node,\n        );\n      }}\n      className={cn(\"text-muted-foreground aria-pressed:bg-muted aria-pressed:text-foreground\", className)}\n    >\n      {children ?? labels.not}\n    </Button>\n  );\n}\n\nfunction QueryBuilderField({\n  id,\n  \"aria-labelledby\": ariaLabelledBy,\n  className,\n  disabled: disabledProp,\n  ...props\n}: React.ComponentProps<typeof Button>) {\n  const { fields, labels, disabled } = useQueryBuilderContext(FIELD_NAME);\n  const isDisabled = disabled || disabledProp;\n  const generatedId = React.useId();\n  const triggerId = id ?? generatedId;\n  const rule = useRuleContext(FIELD_NAME);\n  const { update } = useQueryActions(FIELD_NAME);\n  const currentField = fields.find((field) => field.value === rule.field);\n\n  return (\n    <Faceted\n      items={fields}\n      value={rule.field}\n      onValueChange={(value) => {\n        const field = fields.find((item) => item.value === value);\n        if (!field) return;\n        update(rule.id, (node) =>\n          setQueryRuleField(node as QueryRule, currentField, field),\n        );\n      }}\n    >\n      <FacetedTrigger asChild>\n        <Button\n          variant=\"outline\"\n          size=\"sm\"\n          aria-label={\n            ariaLabelledBy\n              ? currentField\n                ? currentField.label\n                : labels.field\n              : currentField\n                ? `${labels.field}: ${currentField.label}`\n                : labels.field\n          }\n          aria-labelledby={\n            ariaLabelledBy ? `${ariaLabelledBy} ${triggerId}` : undefined\n          }\n          title={currentField?.label}\n          id={triggerId}\n          data-slot=\"query-builder-field\"\n          disabled={isDisabled}\n          {...props}\n          className={cn(\n            \"w-24 min-w-0 @max-[28rem]/query-builder:w-auto @max-[28rem]/query-builder:not-in-data-[operator=isBetween]:flex-1 @max-[40rem]/query-builder:in-data-[operator=isBetween]:basis-1/2 justify-between gap-1 font-normal transition-[color,background-color,border-color,box-shadow] has-data-[slot=query-builder-value-list]:pl-1\",\n            className,\n          )}\n        >\n          <FacetedValue>\n            {([item]) => (\n              <bdi\n                className={cn(\n                  \"min-w-0 truncate\",\n                  !item && \"text-muted-foreground\",\n                )}\n              >\n                {item ? item.label : labels.field}\n              </bdi>\n            )}\n          </FacetedValue>\n          <IconPlaceholder\n            lucide=\"ChevronDownIcon\"\n            tabler=\"IconChevronDown\"\n            hugeicons=\"ArrowDown01Icon\"\n            phosphor=\"CaretDownIcon\"\n            remixicon=\"RiArrowDownSLine\"\n            data-slot=\"query-builder-select-icon\"\n            className=\"size-4 shrink-0 opacity-50\"\n          />\n        </Button>\n      </FacetedTrigger>\n      <FacetedContent align=\"start\">\n        <FacetedInput placeholder={labels.searchFields} />\n        <FacetedList>\n          <FacetedEmpty>{labels.noFields}</FacetedEmpty>\n          <FacetedGroup>\n            {fields.map((field) => (\n              <FacetedItem key={field.value} value={field.value}>\n                <bdi className=\"flex-1 truncate\">{field.label}</bdi>\n                <FacetedItemIndicator />\n              </FacetedItem>\n            ))}\n          </FacetedGroup>\n        </FacetedList>\n      </FacetedContent>\n    </Faceted>\n  );\n}\n\nfunction QueryBuilderOperator({\n  id,\n  \"aria-labelledby\": ariaLabelledBy,\n  className,\n  disabled: disabledProp,\n  ...props\n}: React.ComponentProps<typeof Button>) {\n  const { fields, labels, disabled } = useQueryBuilderContext(OPERATOR_NAME);\n  const isDisabled = disabled || disabledProp;\n  const generatedId = React.useId();\n  const triggerId = id ?? generatedId;\n  const rule = useRuleContext(OPERATOR_NAME);\n  const { update } = useQueryActions(OPERATOR_NAME);\n  const field = fields.find((item) => item.value === rule.field);\n\n  if (!field) return null;\n\n  const operators = getQueryOperators(field).map((operator) => ({\n    label: labels.operatorLabel(operator, field.type),\n    value: operator,\n  }));\n\n  return (\n    <Faceted\n      items={operators}\n      value={rule.operator}\n      onValueChange={(next) => {\n        if (!next) return;\n        update(rule.id, (node) =>\n          setQueryRuleOperator(node as QueryRule, field, next as QueryOperator),\n        );\n      }}\n    >\n      <FacetedTrigger asChild>\n        <Button\n          variant=\"outline\"\n          size=\"sm\"\n          aria-label={\n            ariaLabelledBy\n              ? labels.operatorLabel(rule.operator, field.type)\n              : `${labels.operator}: ${labels.operatorLabel(rule.operator, field.type)}`\n          }\n          aria-labelledby={\n            ariaLabelledBy ? `${ariaLabelledBy} ${triggerId}` : undefined\n          }\n          title={labels.operatorLabel(rule.operator, field.type)}\n          id={triggerId}\n          data-slot=\"query-builder-operator\"\n          disabled={isDisabled}\n          {...props}\n          className={cn(\n            \"w-28 min-w-0 @max-[28rem]/query-builder:w-auto @max-[28rem]/query-builder:not-in-data-[operator=isBetween]:flex-1 @max-[40rem]/query-builder:in-data-[operator=isBetween]:basis-1/2 @max-[40rem]/query-builder:in-data-[operator=isBetween]:rounded-r-md! justify-between gap-1 font-normal transition-[color,background-color,border-color,box-shadow] has-data-[slot=query-builder-value-list]:pl-1\",\n            className,\n          )}\n        >\n          <FacetedValue>\n            {([item]) => (\n              <bdi className=\"min-w-0 truncate\">{item?.label}</bdi>\n            )}\n          </FacetedValue>\n          <IconPlaceholder\n            lucide=\"ChevronDownIcon\"\n            tabler=\"IconChevronDown\"\n            hugeicons=\"ArrowDown01Icon\"\n            phosphor=\"CaretDownIcon\"\n            remixicon=\"RiArrowDownSLine\"\n            data-slot=\"query-builder-select-icon\"\n            className=\"size-4 shrink-0 opacity-50\"\n          />\n        </Button>\n      </FacetedTrigger>\n      <FacetedContent align=\"start\">\n        <FacetedInput placeholder={labels.searchOperators} />\n        <FacetedList>\n          <FacetedEmpty>{labels.noOperators}</FacetedEmpty>\n          <FacetedGroup>\n            {operators.map((operator) => (\n              <FacetedItem key={operator.value} value={operator.value}>\n                <bdi className=\"flex-1 truncate\">{operator.label}</bdi>\n                <FacetedItemIndicator />\n              </FacetedItem>\n            ))}\n          </FacetedGroup>\n        </FacetedList>\n      </FacetedContent>\n    </Faceted>\n  );\n}\n\nfunction getSelectedValues(value: QueryValue | undefined) {\n  if (Array.isArray(value)) return value;\n  return value ? [value] : [];\n}\n\nfunction QueryBuilderValueList({ options }: { options: QueryFieldOption[] }) {\n  const listRef = React.useRef<HTMLSpanElement>(null);\n  const itemRefs = React.useRef<(HTMLSpanElement | null)[]>([]);\n  const labelRefs = React.useRef<(HTMLElement | null)[]>([]);\n  const countRef = React.useRef<HTMLSpanElement>(null);\n  const [visibleCount, setVisibleCount] = React.useState(options.length);\n\n  React.useLayoutEffect(() => {\n    const list = listRef.current;\n    if (!list) return;\n\n    function measure() {\n      if (!list) return;\n      const widths = options.map((_, index) => {\n        const item = itemRefs.current[index];\n        const label = labelRefs.current[index];\n        if (!item) return 0;\n        if (!label) return item.getBoundingClientRect().width;\n        return (\n          item.getBoundingClientRect().width -\n          label.getBoundingClientRect().width +\n          label.scrollWidth\n        );\n      });\n      const gap = Number.parseFloat(getComputedStyle(list).columnGap) || 0;\n      const available = list.getBoundingClientRect().width;\n      const total = widths.reduce((sum, width) => sum + width + gap, -gap);\n      if (total <= available) {\n        setVisibleCount(widths.length);\n        return;\n      }\n      let used = countRef.current?.getBoundingClientRect().width ?? 24;\n      let count = 0;\n      for (const width of widths) {\n        if (used + gap + width > available) break;\n        used += gap + width;\n        count++;\n      }\n      setVisibleCount(Math.max(1, count));\n    }\n\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(list);\n    return () => observer.disconnect();\n  });\n\n  const hiddenCount = Math.max(0, options.length - visibleCount);\n\n  return (\n    <span\n      ref={listRef}\n      data-slot=\"query-builder-value-list\"\n      className=\"relative flex min-w-0 flex-1 items-center gap-1 overflow-hidden\"\n    >\n      {options.map(({ label, value }, index) => (\n        <span\n          key={value}\n          ref={(node) => {\n            itemRefs.current[index] = node;\n          }}\n          data-slot=\"query-builder-value-item\"\n          data-hidden={index >= visibleCount ? \"\" : undefined}\n          className=\"flex min-w-0 shrink-0 items-center first:shrink data-hidden:invisible data-hidden:absolute\"\n        >\n          <FacetedBadge>\n            <bdi\n              ref={(node) => {\n                labelRefs.current[index] = node;\n              }}\n              className=\"truncate\"\n            >\n              {label}\n            </bdi>\n          </FacetedBadge>\n        </span>\n      ))}\n      {hiddenCount > 0 && (\n        <FacetedBadge ref={countRef} className=\"shrink-0\">\n          +{hiddenCount}\n        </FacetedBadge>\n      )}\n    </span>\n  );\n}\n\ninterface QueryBuilderValueProps extends Omit<\n  React.HTMLAttributes<HTMLElement>,\n  \"children\" | \"defaultValue\" | \"onChange\"\n> {\n  display?: \"list\" | \"summary\";\n  disabled?: boolean;\n}\n\nfunction QueryBuilderValue({\n  display = \"list\",\n  id,\n  \"aria-label\": ariaLabel,\n  \"aria-labelledby\": ariaLabelledBy,\n  className,\n  disabled: disabledProp,\n  ...props\n}: QueryBuilderValueProps) {\n  const { fields, labels, disabled } = useQueryBuilderContext(VALUE_NAME);\n  const isDisabled = disabled || disabledProp;\n  const rule = useRuleContext(VALUE_NAME);\n  const { update } = useQueryActions(VALUE_NAME);\n  const field = fields.find((item) => item.value === rule.field);\n\n  const generatedId = React.useId();\n\n  if (!field) return null;\n\n  const label = ariaLabel ?? field.label;\n\n  const onChange = (value: QueryValue) =>\n    update(rule.id, (node) => ({ ...node, value }));\n\n  const inputType =\n    field.type === \"number\"\n      ? \"number\"\n      : field.type === \"date\"\n        ? \"date\"\n        : \"text\";\n\n  const valueClassName = cn(\"cn-query-builder-value\", className);\n\n  if (rule.operator === \"isEmpty\" || rule.operator === \"isNotEmpty\") {\n    return (\n      <Input\n        aria-hidden=\"true\"\n        tabIndex={-1}\n        id={id}\n        {...props}\n        value=\"\"\n        readOnly\n        data-slot=\"query-builder-value\"\n        data-operator={rule.operator}\n        className={cn(\"pointer-events-none\", valueClassName)}\n      />\n    );\n  }\n\n  if (rule.operator === \"isBetween\") {\n    const [start = \"\", end = \"\"] = Array.isArray(rule.value) ? rule.value : [];\n    const fromId = id ?? `${generatedId}-from`;\n    const toId = `${generatedId}-to`;\n    return (\n      <>\n        <Input\n          type={inputType}\n          id={fromId}\n          placeholder={labels.from}\n          aria-label={ariaLabelledBy ? labels.from : `${label} ${labels.from}`}\n          aria-labelledby={\n            ariaLabelledBy ? `${ariaLabelledBy} ${fromId}` : undefined\n          }\n          {...props}\n          data-slot=\"query-builder-value\"\n          data-operator={rule.operator}\n          value={start}\n          onChange={(event) => onChange([event.target.value, end])}\n          disabled={isDisabled}\n          className={valueClassName}\n        />\n        <span className=\"flex h-8 items-center border-y border-e border-input bg-transparent dark:bg-input/30 px-2 text-sm text-muted-foreground @max-[40rem]/query-builder:hidden\">\n          {labels.between}\n        </span>\n        <Input\n          type={inputType}\n          id={toId}\n          placeholder={labels.to}\n          aria-label={ariaLabelledBy ? labels.to : `${label} ${labels.to}`}\n          aria-labelledby={\n            ariaLabelledBy ? `${ariaLabelledBy} ${toId}` : undefined\n          }\n          {...props}\n          data-slot=\"query-builder-value\"\n          data-operator={rule.operator}\n          value={end}\n          onChange={(event) => onChange([start, event.target.value])}\n          disabled={isDisabled}\n          className={valueClassName}\n        />\n      </>\n    );\n  }\n\n  if (\n    field.type === \"boolean\" ||\n    field.type === \"select\" ||\n    field.type === \"multiSelect\"\n  ) {\n    const options =\n      field.type === \"boolean\"\n        ? [\n            { label: labels.true, value: \"true\" },\n            { label: labels.false, value: \"false\" },\n          ]\n        : (field.options ?? []);\n    const multiple = getIsQueryRuleMultiple(rule, field);\n    const selected = getSelectedValues(rule.value).flatMap((value) =>\n      options.filter((option) => option.value === value),\n    );\n    const selectedLabels = selected.map((option) => option.label).join(\", \");\n\n    return (\n      <Faceted\n        items={options}\n        multiple={multiple}\n        value={multiple ? getSelectedValues(rule.value) : rule.value}\n        onValueChange={(next) =>\n          update(rule.id, (node) =>\n            setQueryRuleValues(\n              node as QueryRule,\n              field,\n              getSelectedValues(next),\n            ),\n          )\n        }\n      >\n        <FacetedTrigger asChild>\n          <Button\n            variant=\"outline\"\n            size=\"sm\"\n            aria-label={\n              ariaLabelledBy\n                ? selectedLabels || labels.noValue\n                : `${label}: ${selectedLabels || labels.noValue}`\n            }\n            aria-labelledby={\n              ariaLabelledBy\n                ? `${ariaLabelledBy} ${id ?? generatedId}`\n                : undefined\n            }\n            title={selectedLabels || undefined}\n            id={id ?? generatedId}\n            {...props}\n            data-slot=\"query-builder-value\"\n            data-operator={rule.operator}\n            disabled={isDisabled}\n            className={cn(\"justify-between gap-1 font-normal transition-[color,background-color,border-color,box-shadow] has-data-[slot=query-builder-value-list]:pl-1\", valueClassName)}\n          >\n            <FacetedValue>\n              {() => {\n                if (selected.length > 0 && display === \"summary\") {\n                  return (\n                    <bdi className=\"min-w-0 truncate\">\n                      {selected.length > 1\n                        ? labels.selected(selected.length)\n                        : selected[0]?.label}\n                    </bdi>\n                  );\n                }\n                if (selected.length > 0) {\n                  return <QueryBuilderValueList options={selected} />;\n                }\n                return (\n                  <bdi className=\"min-w-0 truncate text-muted-foreground\">\n                    {field.placeholder ??\n                      (multiple ? labels.selectValues : labels.selectValue)}\n                  </bdi>\n                );\n              }}\n            </FacetedValue>\n            <IconPlaceholder\n              lucide=\"ChevronDownIcon\"\n              tabler=\"IconChevronDown\"\n              hugeicons=\"ArrowDown01Icon\"\n              phosphor=\"CaretDownIcon\"\n              remixicon=\"RiArrowDownSLine\"\n              data-slot=\"query-builder-select-icon\"\n              className=\"size-4 shrink-0 opacity-50\"\n            />\n          </Button>\n        </FacetedTrigger>\n        <FacetedContent align=\"start\">\n          <FacetedInput placeholder={labels.searchValues(field.label)} />\n          <FacetedList>\n            <FacetedEmpty>{labels.noValues}</FacetedEmpty>\n            <FacetedGroup>\n              {options.map((option) => (\n                <FacetedItem key={option.value} value={option.value}>\n                  {option.icon && <option.icon aria-hidden=\"true\" />}\n                  <bdi className=\"flex-1 truncate\">{option.label}</bdi>\n                  <FacetedItemIndicator />\n                </FacetedItem>\n              ))}\n            </FacetedGroup>\n            {multiple && <FacetedClear />}\n          </FacetedList>\n        </FacetedContent>\n      </Faceted>\n    );\n  }\n\n  return (\n    <Input\n      type={inputType}\n      aria-label={label}\n      aria-labelledby={ariaLabelledBy}\n      placeholder={field.placeholder ?? labels.enterValue}\n      id={id}\n      {...props}\n      value={typeof rule.value === \"string\" ? rule.value : \"\"}\n      onChange={(event) => onChange(event.target.value)}\n      disabled={isDisabled}\n      data-slot=\"query-builder-value\"\n      data-operator={rule.operator}\n      className={valueClassName}\n    />\n  );\n}\n\nfunction getField(fields: QueryField[], value?: string) {\n  return value === undefined\n    ? fields[0]\n    : fields.find((field) => field.value === value);\n}\n\ninterface QueryBuilderAddRuleProps extends React.ComponentProps<typeof Button> {\n  field?: string;\n}\n\nfunction QueryBuilderAddRule({\n  field: fieldProp,\n  onClick,\n  children,\n  className,\n  disabled: disabledProp,\n  ...props\n}: QueryBuilderAddRuleProps) {\n  const { fields, labels, disabled } = useQueryBuilderContext(ADD_RULE_NAME);\n  const isDisabled = disabled || disabledProp;\n  const { group } = useGroupContext(ADD_RULE_NAME);\n  const { add } = useQueryActions(ADD_RULE_NAME);\n  const field = getField(fields, fieldProp);\n\n  return (\n    <Button\n      type=\"button\"\n      variant=\"ghost\"\n      size=\"sm\"\n      data-slot=\"query-builder-add-rule\"\n      disabled={isDisabled || !field}\n      {...props}\n      onClick={(event) => {\n        onClick?.(event);\n        if (event.defaultPrevented || !field) return;\n        add(group.id, createQueryRule(field));\n      }}\n      className={cn(\"text-muted-foreground\", className)}\n    >\n      {children ?? (\n        <>\n          <IconPlaceholder\n            lucide=\"PlusIcon\"\n            tabler=\"IconPlus\"\n            hugeicons=\"PlusSignIcon\"\n            phosphor=\"PlusIcon\"\n            remixicon=\"RiAddLine\"\n          />\n          {labels.addRule}\n        </>\n      )}\n    </Button>\n  );\n}\n\ninterface QueryBuilderAddGroupProps extends React.ComponentProps<\n  typeof Button\n> {\n  field?: string;\n}\n\nfunction QueryBuilderAddGroup({\n  field: fieldProp,\n  onClick,\n  children,\n  className,\n  disabled: disabledProp,\n  ...props\n}: QueryBuilderAddGroupProps) {\n  const { fields, labels, disabled, maxDepth } =\n    useQueryBuilderContext(ADD_GROUP_NAME);\n  const isDisabled = disabled || disabledProp;\n  const { group, depth } = useGroupContext(ADD_GROUP_NAME);\n  const { add } = useQueryActions(ADD_GROUP_NAME);\n  const field = getField(fields, fieldProp);\n\n  if (depth >= maxDepth) return null;\n\n  return (\n    <Button\n      type=\"button\"\n      variant=\"ghost\"\n      size=\"sm\"\n      data-slot=\"query-builder-add-group\"\n      disabled={isDisabled || !field}\n      {...props}\n      onClick={(event) => {\n        onClick?.(event);\n        if (event.defaultPrevented || !field) return;\n        add(\n          group.id,\n          createQueryGroup(group.combinator === \"and\" ? \"or\" : \"and\", [\n            createQueryRule(field),\n          ]),\n        );\n      }}\n      className={cn(\"text-muted-foreground\", className)}\n    >\n      {children ?? (\n        <>\n          <IconPlaceholder\n            lucide=\"ListPlusIcon\"\n            tabler=\"IconListDetails\"\n            hugeicons=\"LeftToRightListBulletIcon\"\n            phosphor=\"ListPlusIcon\"\n            remixicon=\"RiPlayListAddLine\"\n          />\n          {labels.addGroup}\n        </>\n      )}\n    </Button>\n  );\n}\n\nfunction QueryBuilderRemove({\n  onClick,\n  children,\n  className,\n  disabled: disabledProp,\n  ...props\n}: React.ComponentProps<typeof Button>) {\n  const { disabled, labels } = useQueryBuilderContext(REMOVE_NAME);\n  const isDisabled = disabled || disabledProp;\n  const rule = React.useContext(RuleContext);\n  const group = useGroupContext(REMOVE_NAME);\n  const { remove } = useQueryActions(REMOVE_NAME);\n\n  const id = rule?.id ?? (group.isRoot ? undefined : group.group.id);\n  if (!id) return null;\n\n  return (\n    <Button\n      type=\"button\"\n      variant=\"ghost\"\n      size=\"icon-sm\"\n      aria-label={rule ? labels.removeRule : labels.removeGroup}\n      data-slot=\"query-builder-remove\"\n      disabled={isDisabled}\n      {...props}\n      onClick={(event) => {\n        onClick?.(event);\n        if (event.defaultPrevented) return;\n        remove(id);\n      }}\n      className={cn(\"text-muted-foreground\", className)}\n    >\n      {children ?? (\n        <IconPlaceholder\n          lucide=\"Trash2Icon\"\n          tabler=\"IconTrash\"\n          hugeicons=\"Delete02Icon\"\n          phosphor=\"TrashIcon\"\n          remixicon=\"RiDeleteBinLine\"\n        />\n      )}\n    </Button>\n  );\n}\n\nexport {\n  QueryBuilder,\n  QueryBuilderAddGroup,\n  QueryBuilderAddRule,\n  QueryBuilderCombinator,\n  QueryBuilderConnector,\n  QueryBuilderField,\n  QueryBuilderGroup,\n  QueryBuilderGroupContent,\n  QueryBuilderGroupFooter,\n  QueryBuilderGroupHeader,\n  QueryBuilderGroupTitle,\n  QueryBuilderNegate,\n  QueryBuilderOperator,\n  QueryBuilderRemove,\n  QueryBuilderRule,\n  QueryBuilderRuleList,\n  QueryBuilderValue,\n};\n",
      "target": ""
    },
    {
      "path": "lib/query-builder.ts",
      "type": "registry:lib",
      "content": "import type * as React from \"react\";\n\nexport type QueryFieldType =\n  | \"text\"\n  | \"number\"\n  | \"date\"\n  | \"boolean\"\n  | \"select\"\n  | \"multiSelect\";\n\nexport type QueryOperator =\n  | \"iLike\"\n  | \"notILike\"\n  | \"eq\"\n  | \"ne\"\n  | \"lt\"\n  | \"lte\"\n  | \"gt\"\n  | \"gte\"\n  | \"isBetween\"\n  | \"inArray\"\n  | \"notInArray\"\n  | \"isEmpty\"\n  | \"isNotEmpty\";\n\nexport type QueryCombinator = \"and\" | \"or\";\n\nexport type QueryValue = string | string[];\n\nexport interface QueryFieldOption {\n  label: string;\n  value: string;\n  icon?: React.ComponentType<React.ComponentProps<\"svg\">>;\n}\n\nexport interface QueryField {\n  value: string;\n  label: string;\n  type: QueryFieldType;\n  column?: string;\n  operators?: QueryOperator[];\n  options?: QueryFieldOption[];\n  placeholder?: string;\n}\n\nexport interface QueryRule {\n  id: string;\n  field: string;\n  operator: QueryOperator;\n  value?: QueryValue;\n}\n\nexport interface QueryGroup {\n  id: string;\n  combinator: QueryCombinator;\n  not?: boolean;\n  rules: QueryNode[];\n}\n\nexport type QueryNode = QueryRule | QueryGroup;\n\nexport type QuerySelection = Record<string, string[]>;\n\nexport const QUERY_OPERATORS: Record<QueryFieldType, QueryOperator[]> = {\n  text: [\"iLike\", \"notILike\", \"eq\", \"ne\", \"isEmpty\", \"isNotEmpty\"],\n  number: [\n    \"eq\",\n    \"ne\",\n    \"lt\",\n    \"lte\",\n    \"gt\",\n    \"gte\",\n    \"isBetween\",\n    \"isEmpty\",\n    \"isNotEmpty\",\n  ],\n  date: [\n    \"eq\",\n    \"ne\",\n    \"lt\",\n    \"gt\",\n    \"lte\",\n    \"gte\",\n    \"isBetween\",\n    \"isEmpty\",\n    \"isNotEmpty\",\n  ],\n  boolean: [\"eq\", \"ne\"],\n  select: [\"eq\", \"ne\", \"inArray\", \"notInArray\", \"isEmpty\", \"isNotEmpty\"],\n  multiSelect: [\"inArray\", \"notInArray\", \"isEmpty\", \"isNotEmpty\"],\n};\n\nconst OPERATOR_LABELS: Record<QueryOperator, string> = {\n  iLike: \"contains\",\n  notILike: \"does not contain\",\n  eq: \"is\",\n  ne: \"is not\",\n  lt: \"is less than\",\n  lte: \"is at most\",\n  gt: \"is greater than\",\n  gte: \"is at least\",\n  isBetween: \"is between\",\n  inArray: \"is any of\",\n  notInArray: \"is none of\",\n  isEmpty: \"is empty\",\n  isNotEmpty: \"is not empty\",\n};\n\nconst DATE_OPERATOR_LABELS: Partial<Record<QueryOperator, string>> = {\n  lt: \"is before\",\n  lte: \"is on or before\",\n  gt: \"is after\",\n  gte: \"is on or after\",\n};\n\nexport function getQueryOperators(field: QueryField): QueryOperator[] {\n  return field.operators ?? QUERY_OPERATORS[field.type];\n}\n\nexport function getQueryOperatorLabel(\n  operator: QueryOperator,\n  type?: QueryFieldType,\n): string {\n  return (\n    (type === \"date\" ? DATE_OPERATOR_LABELS[operator] : undefined) ??\n    OPERATOR_LABELS[operator]\n  );\n}\n\nexport function getIsQueryGroup(node: QueryNode): node is QueryGroup {\n  return \"rules\" in node;\n}\n\nfunction createId() {\n  return typeof crypto !== \"undefined\" && \"randomUUID\" in crypto\n    ? crypto.randomUUID()\n    : Math.random().toString(36).slice(2);\n}\n\nexport function createQueryRule(field: QueryField): QueryRule {\n  const operator = getQueryOperators(field)[0] ?? \"eq\";\n  return {\n    id: createId(),\n    field: field.value,\n    operator,\n    value: getDefaultQueryValue(field, operator),\n  };\n}\n\nexport function createQueryGroup(\n  combinator: QueryCombinator = \"and\",\n  rules: QueryNode[] = [],\n): QueryGroup {\n  return { id: createId(), combinator, rules };\n}\n\nexport function getDefaultQueryValue(\n  field: QueryField,\n  operator: QueryOperator,\n): QueryValue | undefined {\n  if (operator === \"isEmpty\" || operator === \"isNotEmpty\") return undefined;\n  if (operator === \"isBetween\") return [\"\", \"\"];\n  if (operator === \"inArray\" || operator === \"notInArray\") return [];\n  if (field.type === \"boolean\") return \"true\";\n  return \"\";\n}\n\nfunction getIsListOperator(operator: QueryOperator) {\n  return operator === \"inArray\" || operator === \"notInArray\";\n}\n\nfunction getQueryValueForOperator(\n  rule: QueryRule,\n  operator: QueryOperator,\n): QueryValue | undefined {\n  const { value } = rule;\n  if (operator === \"isEmpty\" || operator === \"isNotEmpty\") return undefined;\n  if ((rule.operator === \"isBetween\") !== (operator === \"isBetween\")) {\n    return undefined;\n  }\n  if (getIsListOperator(operator)) {\n    if (Array.isArray(value)) return value;\n    return value ? [value] : undefined;\n  }\n  if (Array.isArray(value) && operator !== \"isBetween\") return value[0];\n  return value;\n}\n\nexport function setQueryRuleOperator(\n  rule: QueryRule,\n  field: QueryField,\n  operator: QueryOperator,\n): QueryRule {\n  return {\n    ...rule,\n    operator,\n    value:\n      getQueryValueForOperator(rule, operator) ??\n      getDefaultQueryValue(field, operator),\n  };\n}\n\nexport function setQueryRuleField(\n  rule: QueryRule,\n  from: QueryField | undefined,\n  to: QueryField,\n): QueryRule {\n  if (\n    !from ||\n    from.type !== to.type ||\n    !getQueryOperators(to).includes(rule.operator)\n  ) {\n    return { ...createQueryRule(to), id: rule.id };\n  }\n  if (to.type !== \"select\" && to.type !== \"multiSelect\") {\n    return { ...rule, field: to.value };\n  }\n  const options = new Set(to.options?.map((option) => option.value));\n  if (Array.isArray(rule.value)) {\n    return setQueryRuleValues(\n      { ...rule, field: to.value },\n      to,\n      rule.value.filter((item) => options.has(item)),\n    );\n  }\n  const value =\n    rule.value && options.has(rule.value)\n      ? rule.value\n      : getDefaultQueryValue(to, rule.operator);\n  return { ...rule, field: to.value, value };\n}\n\nconst OPERATOR_COUNTERPARTS: Partial<Record<QueryOperator, QueryOperator>> = {\n  eq: \"inArray\",\n  ne: \"notInArray\",\n  inArray: \"eq\",\n  notInArray: \"ne\",\n};\n\nfunction getOperatorCounterpart(operator: QueryOperator, field: QueryField) {\n  const counterpart = OPERATOR_COUNTERPARTS[operator];\n  return counterpart && getQueryOperators(field).includes(counterpart)\n    ? counterpart\n    : undefined;\n}\n\nexport function getIsQueryRuleMultiple(rule: QueryRule, field: QueryField) {\n  return (\n    getIsListOperator(rule.operator) ||\n    getOperatorCounterpart(rule.operator, field) !== undefined\n  );\n}\n\nexport function setQueryRuleValues(\n  rule: QueryRule,\n  field: QueryField,\n  values: string[],\n): QueryRule {\n  const counterpart = getOperatorCounterpart(rule.operator, field);\n  const operator =\n    counterpart &&\n    values.length > 0 &&\n    values.length > 1 !== getIsListOperator(rule.operator)\n      ? counterpart\n      : rule.operator;\n  return {\n    ...rule,\n    operator,\n    value: getIsListOperator(operator) ? values : (values[0] ?? \"\"),\n  };\n}\n\nfunction getRuleValues(rule: QueryRule) {\n  if (Array.isArray(rule.value)) return rule.value;\n  return rule.value ? [rule.value] : [];\n}\n\nfunction getIsSameValues(a: string[], b: string[]) {\n  return a.length === b.length && a.every((value, index) => value === b[index]);\n}\n\nexport function getQuerySelection(query: QueryGroup): QuerySelection {\n  const selection: QuerySelection = {};\n  for (const node of query.rules) {\n    if (getIsQueryGroup(node) || selection[node.field]) continue;\n    selection[node.field] = getRuleValues(node);\n  }\n  return selection;\n}\n\nexport function setQuerySelection(\n  query: QueryGroup,\n  fields: QueryField[],\n  selection: QuerySelection,\n): QueryGroup {\n  const current = getQuerySelection(query);\n  let rules = query.rules;\n  for (const field of fields) {\n    const values = selection[field.value] ?? [];\n    if (getIsSameValues(values, current[field.value] ?? [])) continue;\n    const rule = rules.find(\n      (node): node is QueryRule =>\n        !getIsQueryGroup(node) && node.field === field.value,\n    );\n    if (values.length === 0) {\n      rules = rules.filter((node) => node !== rule);\n    } else if (rule) {\n      rules = rules.map((node) =>\n        node === rule ? setQueryRuleValues(rule, field, values) : node,\n      );\n    } else {\n      rules = [\n        ...rules,\n        setQueryRuleValues(createQueryRule(field), field, values),\n      ];\n    }\n  }\n  return rules === query.rules ? query : { ...query, rules };\n}\n\nexport function updateQueryNode(\n  root: QueryGroup,\n  id: string,\n  updater: (node: QueryNode) => QueryNode,\n): QueryGroup {\n  if (root.id === id) {\n    const next = updater(root);\n    return getIsQueryGroup(next) ? next : root;\n  }\n  let changed = false;\n  const rules = root.rules.map((node) => {\n    const next = getIsQueryGroup(node)\n      ? updateQueryNode(node, id, updater)\n      : node.id === id\n        ? updater(node)\n        : node;\n    if (next !== node) changed = true;\n    return next;\n  });\n  return changed ? { ...root, rules } : root;\n}\n\nexport function removeQueryNode(root: QueryGroup, id: string): QueryGroup {\n  let changed = false;\n  const rules: QueryNode[] = [];\n  for (const node of root.rules) {\n    if (node.id === id) {\n      changed = true;\n      continue;\n    }\n    const next = getIsQueryGroup(node) ? removeQueryNode(node, id) : node;\n    if (next !== node) changed = true;\n    rules.push(next);\n  }\n  return changed ? { ...root, rules } : root;\n}\n\nexport function addQueryNode(\n  root: QueryGroup,\n  groupId: string,\n  node: QueryNode,\n): QueryGroup {\n  return updateQueryNode(root, groupId, (group) =>\n    getIsQueryGroup(group)\n      ? { ...group, rules: [...group.rules, node] }\n      : group,\n  );\n}\n\nexport function findQueryNode(\n  root: QueryGroup,\n  id: string,\n): QueryNode | undefined {\n  if (root.id === id) return root;\n  for (const node of root.rules) {\n    if (node.id === id) return node;\n    if (getIsQueryGroup(node)) {\n      const found = findQueryNode(node, id);\n      if (found) return found;\n    }\n  }\n  return undefined;\n}\n\nexport function moveQueryNode(\n  root: QueryGroup,\n  id: string,\n  groupId: string,\n  index: number,\n): QueryGroup {\n  const node = findQueryNode(root, id);\n  if (!node || node === root) return root;\n  if (getIsQueryGroup(node) && findQueryNode(node, groupId)) return root;\n  const group = findQueryNode(root, groupId);\n  if (!group || !getIsQueryGroup(group)) return root;\n  return updateQueryNode(removeQueryNode(root, id), groupId, (group) => {\n    if (!getIsQueryGroup(group)) return group;\n    const rules = [...group.rules];\n    rules.splice(index, 0, node);\n    return { ...group, rules };\n  });\n}\n\nfunction getField(fields: QueryField[], value: string) {\n  return fields.find((field) => field.value === value);\n}\n\nfunction getIsFilled(value: unknown) {\n  return typeof value === \"string\" && value.trim() !== \"\";\n}\n\nexport function getIsQueryRuleActive(rule: QueryRule, field?: QueryField) {\n  if (!field || !getQueryOperators(field).includes(rule.operator)) {\n    return false;\n  }\n  const { operator, value } = rule;\n  if (operator === \"isEmpty\" || operator === \"isNotEmpty\") return true;\n  if (operator === \"isBetween\") {\n    return (\n      Array.isArray(value) && (getIsFilled(value[0]) || getIsFilled(value[1]))\n    );\n  }\n  if (operator === \"inArray\" || operator === \"notInArray\") {\n    return Array.isArray(value) && value.length > 0;\n  }\n  if (field.type === \"number\" && typeof value === \"string\") {\n    return getIsFilled(value) && Number.isFinite(Number(value));\n  }\n  return getIsFilled(value);\n}\n\nfunction getDateKey(value: unknown): string | undefined {\n  if (value instanceof Date) {\n    if (Number.isNaN(value.getTime())) return undefined;\n    const month = String(value.getMonth() + 1).padStart(2, \"0\");\n    const day = String(value.getDate()).padStart(2, \"0\");\n    return `${value.getFullYear()}-${month}-${day}`;\n  }\n  if (typeof value === \"number\") return getDateKey(new Date(value));\n  if (typeof value === \"string\") {\n    const match = value.match(/^\\d{4}-\\d{2}-\\d{2}/);\n    return match ? match[0] : getDateKey(new Date(value));\n  }\n  return undefined;\n}\n\nfunction getNextDateKey(key: string) {\n  const date = new Date(`${key}T00:00:00Z`);\n  date.setUTCDate(date.getUTCDate() + 1);\n  return date.toISOString().slice(0, 10);\n}\n\nfunction getCellText(value: unknown): string {\n  if (value === null || value === undefined) return \"\";\n  if (value instanceof Date) return value.toISOString();\n  if (typeof value === \"object\") return JSON.stringify(value);\n  if (typeof value === \"string\") return value;\n  if (\n    typeof value === \"number\" ||\n    typeof value === \"boolean\" ||\n    typeof value === \"bigint\"\n  ) {\n    return value.toString();\n  }\n  return \"\";\n}\n\nfunction getIsEmptyCell(value: unknown) {\n  return (\n    value === null ||\n    value === undefined ||\n    (typeof value === \"string\" && value.trim() === \"\") ||\n    (Array.isArray(value) && value.length === 0)\n  );\n}\n\nfunction compare<T>(left: T, operator: QueryOperator, right: T) {\n  switch (operator) {\n    case \"eq\":\n      return left === right;\n    case \"ne\":\n      return left !== right;\n    case \"lt\":\n      return left < right;\n    case \"lte\":\n      return left <= right;\n    case \"gt\":\n      return left > right;\n    case \"gte\":\n      return left >= right;\n    default:\n      return false;\n  }\n}\n\nfunction matchesRule(cell: unknown, rule: QueryRule, field: QueryField) {\n  const { operator, value } = rule;\n\n  if (operator === \"isEmpty\") return getIsEmptyCell(cell);\n  if (operator === \"isNotEmpty\") return !getIsEmptyCell(cell);\n\n  if (operator === \"inArray\" || operator === \"notInArray\") {\n    const values = Array.isArray(value) ? value : [];\n    const cells = Array.isArray(cell)\n      ? cell.map(getCellText)\n      : [getCellText(cell)];\n    const hasAny = cells.some((item) => values.includes(item));\n    return operator === \"inArray\" ? hasAny : !hasAny;\n  }\n\n  if (field.type === \"number\") {\n    const number = typeof cell === \"number\" ? cell : Number(cell);\n    if (getIsEmptyCell(cell) || Number.isNaN(number)) return false;\n    if (operator === \"isBetween\" && Array.isArray(value)) {\n      const [min, max] = value;\n      return (\n        (!getIsFilled(min) || number >= Number(min)) &&\n        (!getIsFilled(max) || number <= Number(max))\n      );\n    }\n    return compare(number, operator, Number(value));\n  }\n\n  if (field.type === \"date\") {\n    const key = getDateKey(cell);\n    if (!key) return false;\n    if (operator === \"isBetween\" && Array.isArray(value)) {\n      const [start, end] = value;\n      return (\n        (!getIsFilled(start) || key >= (start as string)) &&\n        (!getIsFilled(end) || key <= (end as string))\n      );\n    }\n    return compare(key, operator, String(value));\n  }\n\n  const text = getCellText(cell);\n  if (operator === \"iLike\" || operator === \"notILike\") {\n    const contains = text.toLowerCase().includes(String(value).toLowerCase());\n    return operator === \"iLike\" ? contains : !contains;\n  }\n  return compare(text, operator, String(value));\n}\n\nfunction matchesGroup(\n  row: Record<string, unknown>,\n  group: QueryGroup,\n  fields: QueryField[],\n): boolean | undefined {\n  const results: boolean[] = [];\n  for (const node of group.rules) {\n    if (getIsQueryGroup(node)) {\n      const result = matchesGroup(row, node, fields);\n      if (result !== undefined) results.push(result);\n      continue;\n    }\n    const field = getField(fields, node.field);\n    if (!field || !getIsQueryRuleActive(node, field)) continue;\n    results.push(matchesRule(row[field.value], node, field));\n  }\n  if (results.length === 0) return undefined;\n  const matches =\n    group.combinator === \"and\" ? results.every(Boolean) : results.some(Boolean);\n  return group.not ? !matches : matches;\n}\n\nexport function matchesQuery(\n  row: Record<string, unknown>,\n  query: QueryGroup,\n  fields: QueryField[],\n): boolean {\n  return matchesGroup(row, query, fields) ?? true;\n}\n\nexport type SqlDialect = \"postgres\" | \"mysql\" | \"sqlite\";\n\nexport interface FormatQueryOptions {\n  dialect?: SqlDialect;\n}\n\nexport interface FormattedQuery {\n  sql: string;\n  params: unknown[];\n}\n\nfunction quoteIdentifier(identifier: string, dialect: SqlDialect) {\n  const quote = dialect === \"mysql\" ? \"`\" : '\"';\n  return identifier\n    .split(\".\")\n    .map((part) => `${quote}${part.replaceAll(quote, quote + quote)}${quote}`)\n    .join(\".\");\n}\n\nfunction escapeLike(value: string) {\n  return value.replace(/[!%_]/g, \"!$&\");\n}\n\nfunction formatRule(\n  rule: QueryRule,\n  field: QueryField,\n  dialect: SqlDialect,\n  addParam: (value: unknown) => string,\n): string | undefined {\n  const column = quoteIdentifier(field.column ?? field.value, dialect);\n  const { operator, value } = rule;\n\n  if (operator === \"isEmpty\" || operator === \"isNotEmpty\") {\n    const isText = field.type === \"text\" || field.type === \"select\";\n    if (operator === \"isEmpty\") {\n      return isText\n        ? `(${column} IS NULL OR ${column} = '')`\n        : `${column} IS NULL`;\n    }\n    return isText\n      ? `(${column} IS NOT NULL AND ${column} <> '')`\n      : `${column} IS NOT NULL`;\n  }\n\n  if (operator === \"inArray\" || operator === \"notInArray\") {\n    const values = Array.isArray(value) ? value : [];\n    const list = values.map((item) => addParam(item)).join(\", \");\n    return `${column} ${operator === \"inArray\" ? \"IN\" : \"NOT IN\"} (${list})`;\n  }\n\n  if (operator === \"iLike\" || operator === \"notILike\") {\n    const pattern = addParam(`%${escapeLike(String(value))}%`);\n    const negate = operator === \"notILike\" ? \"NOT \" : \"\";\n    return dialect === \"postgres\"\n      ? `${column} ${negate}ILIKE ${pattern} ESCAPE '!'`\n      : `LOWER(${column}) ${negate}LIKE LOWER(${pattern}) ESCAPE '!'`;\n  }\n\n  if (field.type === \"date\") {\n    if (operator === \"isBetween\" && Array.isArray(value)) {\n      const [start, end] = value;\n      const parts = [\n        getIsFilled(start) ? `${column} >= ${addParam(start)}` : undefined,\n        getIsFilled(end)\n          ? `${column} < ${addParam(getNextDateKey(end as string))}`\n          : undefined,\n      ].filter(Boolean);\n      return parts.length > 1 ? `(${parts.join(\" AND \")})` : parts[0];\n    }\n    const day = String(value);\n    const nextDay = getNextDateKey(day);\n    switch (operator) {\n      case \"eq\":\n        return `(${column} >= ${addParam(day)} AND ${column} < ${addParam(nextDay)})`;\n      case \"ne\":\n        return `(${column} < ${addParam(day)} OR ${column} >= ${addParam(nextDay)})`;\n      case \"lt\":\n        return `${column} < ${addParam(day)}`;\n      case \"lte\":\n        return `${column} < ${addParam(nextDay)}`;\n      case \"gt\":\n        return `${column} >= ${addParam(nextDay)}`;\n      case \"gte\":\n        return `${column} >= ${addParam(day)}`;\n      default:\n        return undefined;\n    }\n  }\n\n  const toParam = (input: unknown) => {\n    if (field.type === \"number\") return Number(input);\n    if (field.type === \"boolean\") return input === \"true\";\n    return input;\n  };\n\n  if (operator === \"isBetween\" && Array.isArray(value)) {\n    const [min, max] = value;\n    const parts = [\n      getIsFilled(min) ? `${column} >= ${addParam(toParam(min))}` : undefined,\n      getIsFilled(max) ? `${column} <= ${addParam(toParam(max))}` : undefined,\n    ].filter(Boolean);\n    return parts.length > 1 ? `(${parts.join(\" AND \")})` : parts[0];\n  }\n\n  const symbols: Partial<Record<QueryOperator, string>> = {\n    eq: \"=\",\n    ne: \"<>\",\n    lt: \"<\",\n    lte: \"<=\",\n    gt: \">\",\n    gte: \">=\",\n  };\n  const symbol = symbols[operator];\n  return symbol ? `${column} ${symbol} ${addParam(toParam(value))}` : undefined;\n}\n\nfunction formatGroup(\n  group: QueryGroup,\n  fields: QueryField[],\n  dialect: SqlDialect,\n  addParam: (value: unknown) => string,\n): string | undefined {\n  const parts: string[] = [];\n  for (const node of group.rules) {\n    if (getIsQueryGroup(node)) {\n      const part = formatGroup(node, fields, dialect, addParam);\n      if (part) parts.push(`(${part})`);\n      continue;\n    }\n    const field = getField(fields, node.field);\n    if (!field || !getIsQueryRuleActive(node, field)) continue;\n    const part = formatRule(node, field, dialect, addParam);\n    if (part) parts.push(part);\n  }\n  if (parts.length === 0) return undefined;\n  const sql = parts.join(group.combinator === \"and\" ? \" AND \" : \" OR \");\n  return group.not ? `NOT (${sql})` : sql;\n}\n\nexport function formatQuery(\n  query: QueryGroup,\n  fields: QueryField[],\n  options: FormatQueryOptions = {},\n): FormattedQuery {\n  const { dialect = \"postgres\" } = options;\n  const params: unknown[] = [];\n  const addParam = (value: unknown) => {\n    params.push(value);\n    return dialect === \"postgres\" ? `$${params.length}` : \"?\";\n  };\n  const sql = formatGroup(query, fields, dialect, addParam) ?? \"\";\n  return { sql, params };\n}\n",
      "target": ""
    }
  ]
}