@middag-io/react 0.45.0 → 0.45.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (321) hide show
  1. package/README.md +4 -3
  2. package/docs/public/schemas/ai-contract-manifest.json +1820 -0
  3. package/docs/public/schemas/blocks.json +445 -0
  4. package/docs/public/schemas/components.json +166 -0
  5. package/docs/public/schemas/connectors.json +97 -0
  6. package/docs/public/schemas/fragment.json +2329 -0
  7. package/docs/public/schemas/manifest.json +119 -0
  8. package/docs/public/schemas/navigation.json +72 -0
  9. package/docs/public/schemas/page-contract.json +2329 -0
  10. package/docs/public/schemas/shared-props.json +118 -0
  11. package/docs/public/schemas/theme-defaults.json +253 -0
  12. package/docs/public/schemas/theme.json +401 -0
  13. package/package.json +109 -3
  14. package/src/assets/lottie/calendar/schedule-1.json +1 -0
  15. package/src/assets/lottie/calendar/schedule-2.json +1 -0
  16. package/src/assets/lottie/celebration/confetti-1.json +1 -0
  17. package/src/assets/lottie/celebration/confetti-2.json +1 -0
  18. package/src/assets/lottie/celebration/confetti-3.json +1 -0
  19. package/src/assets/lottie/cloud/cloud-1.json +1 -0
  20. package/src/assets/lottie/cloud/cloud-2.json +1 -0
  21. package/src/assets/lottie/connection/network-1.json +1 -0
  22. package/src/assets/lottie/connection/network-2.json +1 -0
  23. package/src/assets/lottie/connection/network-3.json +1 -0
  24. package/src/assets/lottie/dashboard/analytics-1.json +1 -0
  25. package/src/assets/lottie/dashboard/analytics-2.json +1 -0
  26. package/src/assets/lottie/dashboard/analytics-3.json +1 -0
  27. package/src/assets/lottie/email/mail-1.json +1 -0
  28. package/src/assets/lottie/email/mail-2.json +1 -0
  29. package/src/assets/lottie/email/mail-3.json +1 -0
  30. package/src/assets/lottie/empty-state/empty-1.json +1 -0
  31. package/src/assets/lottie/empty-state/empty-2.json +1 -0
  32. package/src/assets/lottie/empty-state/empty-3.json +1 -0
  33. package/src/assets/lottie/error/warning-1.json +1 -0
  34. package/src/assets/lottie/error/warning-2.json +1 -0
  35. package/src/assets/lottie/error/warning-3.json +1 -0
  36. package/src/assets/lottie/index.ts +49 -0
  37. package/src/assets/lottie/loading/spinner-1.json +1 -0
  38. package/src/assets/lottie/loading/spinner-2.json +1 -0
  39. package/src/assets/lottie/loading/spinner-3.json +1 -0
  40. package/src/assets/lottie/maintenance/construction-1.json +1 -0
  41. package/src/assets/lottie/maintenance/construction-2.json +1 -0
  42. package/src/assets/lottie/maintenance/construction-3.json +1 -0
  43. package/src/assets/lottie/not-found/404-1.json +1 -0
  44. package/src/assets/lottie/not-found/404-2.json +1 -0
  45. package/src/assets/lottie/not-found/404-3.json +1 -0
  46. package/src/assets/lottie/notification/bell-1.json +1 -0
  47. package/src/assets/lottie/notification/bell-2.json +1 -0
  48. package/src/assets/lottie/notification/bell-3.json +1 -0
  49. package/src/assets/lottie/onboarding/welcome-1.json +1 -0
  50. package/src/assets/lottie/onboarding/welcome-2.json +1 -0
  51. package/src/assets/lottie/onboarding/welcome-3.json +1 -0
  52. package/src/assets/lottie/payment/wallet-1.json +1 -0
  53. package/src/assets/lottie/payment/wallet-2.json +1 -0
  54. package/src/assets/lottie/payment/wallet-3.json +1 -0
  55. package/src/assets/lottie/search/search-1.json +1 -0
  56. package/src/assets/lottie/search/search-2.json +1 -0
  57. package/src/assets/lottie/search/search-3.json +1 -0
  58. package/src/assets/lottie/security/lock-1.json +1 -0
  59. package/src/assets/lottie/security/lock-2.json +1 -0
  60. package/src/assets/lottie/security/lock-3.json +1 -0
  61. package/src/assets/lottie/settings/gear-1.json +1 -0
  62. package/src/assets/lottie/settings/gear-2.json +1 -0
  63. package/src/assets/lottie/settings/gear-3.json +1 -0
  64. package/src/assets/lottie/success/check-1.json +1 -0
  65. package/src/assets/lottie/success/check-2.json +1 -0
  66. package/src/assets/lottie/success/check-3.json +1 -0
  67. package/src/assets/lottie/upload/upload-1.json +1 -0
  68. package/src/assets/lottie/upload/upload-2.json +1 -0
  69. package/src/assets/lottie/upload/upload-3.json +1 -0
  70. package/src/assets/lottie/user/profile-1.json +1 -0
  71. package/src/assets/lottie/user/profile-2.json +1 -0
  72. package/src/assets/lottie/user/profile-3.json +1 -0
  73. package/src/base/blocks/ActionGridBlock.tsx +151 -0
  74. package/src/base/blocks/ActivityTimelineBlock.tsx +180 -0
  75. package/src/base/blocks/CardGridBlock.tsx +384 -0
  76. package/src/base/blocks/ChartBlock.tsx +81 -0
  77. package/src/base/blocks/DenseTableBlock.tsx +403 -0
  78. package/src/base/blocks/DetailPanelBlock.tsx +189 -0
  79. package/src/base/blocks/EmptyStateBlock.tsx +46 -0
  80. package/src/base/blocks/FormPanelBlock.lazy.tsx +38 -0
  81. package/src/base/blocks/FormPanelBlock.tsx +480 -0
  82. package/src/base/blocks/LinkListBlock.tsx +94 -0
  83. package/src/base/blocks/MarkdownPanelBlock.tsx +60 -0
  84. package/src/base/blocks/MetricCardBlock.tsx +128 -0
  85. package/src/base/blocks/StatusStripBlock.tsx +43 -0
  86. package/src/base/blocks/TabsBlock.tsx +94 -0
  87. package/src/base/form/FormField.tsx +607 -0
  88. package/src/base/form/fields/CheckboxField.tsx +56 -0
  89. package/src/base/form/fields/ColorField.tsx +76 -0
  90. package/src/base/form/fields/CurrencyField.tsx +126 -0
  91. package/src/base/form/fields/DateField.tsx +168 -0
  92. package/src/base/form/fields/DateRangeField.tsx +66 -0
  93. package/src/base/form/fields/DocumentField.tsx +222 -0
  94. package/src/base/form/fields/EntityPickerField.tsx +244 -0
  95. package/src/base/form/fields/FileUploadField.tsx +253 -0
  96. package/src/base/form/fields/MultiSelectField.tsx +286 -0
  97. package/src/base/form/fields/NativeSelectField.tsx +67 -0
  98. package/src/base/form/fields/NumberField.tsx +67 -0
  99. package/src/base/form/fields/OtpField.tsx +88 -0
  100. package/src/base/form/fields/PasswordField.tsx +69 -0
  101. package/src/base/form/fields/PhoneField.tsx +64 -0
  102. package/src/base/form/fields/RadioField.tsx +66 -0
  103. package/src/base/form/fields/RatingField.tsx +52 -0
  104. package/src/base/form/fields/SelectField.tsx +76 -0
  105. package/src/base/form/fields/SliderField.tsx +77 -0
  106. package/src/base/form/fields/SlugField.tsx +114 -0
  107. package/src/base/form/fields/StaticField.tsx +25 -0
  108. package/src/base/form/fields/SwitchField.tsx +56 -0
  109. package/src/base/form/fields/TagsField.tsx +128 -0
  110. package/src/base/form/fields/TextField.tsx +55 -0
  111. package/src/base/form/fields/TextareaField.tsx +55 -0
  112. package/src/base/form/fields/document-validation.ts +126 -0
  113. package/src/base/form/fields/field-registry.ts +53 -0
  114. package/src/base/form/fields/register-default-fields.ts +86 -0
  115. package/src/base/form/form-schema-builder.ts +192 -0
  116. package/src/base/form/form-utils.ts +71 -0
  117. package/src/base/hooks/useIsDark.ts +50 -0
  118. package/src/base/hooks/useLazyTabs.ts +98 -0
  119. package/src/base/hooks/usePolling.ts +43 -0
  120. package/src/base/hooks/useRemember.ts +58 -0
  121. package/src/base/hooks/useToast.ts +27 -0
  122. package/src/base/layout/BlockRegion.tsx +39 -0
  123. package/src/base/layout/DashboardLayout.tsx +110 -0
  124. package/src/base/layout/SidebarLayout.tsx +38 -0
  125. package/src/base/layout/StackLayout.tsx +32 -0
  126. package/src/base/layout/WizardLayout.tsx +49 -0
  127. package/src/base/partials/ActionBar/index.tsx +115 -0
  128. package/src/base/partials/ConfirmationDialog/index.tsx +128 -0
  129. package/src/base/partials/DataTable/cell-registry.ts +50 -0
  130. package/src/base/partials/DataTable/cell-renderers.tsx +372 -0
  131. package/src/base/partials/DataTable/index.tsx +1282 -0
  132. package/src/base/partials/DataTable/register-default-cells.ts +37 -0
  133. package/src/base/partials/DataTable/sanitize-html.ts +45 -0
  134. package/src/base/partials/DataTable/types.ts +229 -0
  135. package/src/base/partials/DetailSection/index.tsx +316 -0
  136. package/src/base/partials/EmptyPlaceholder/index.tsx +162 -0
  137. package/src/base/partials/EntityItem/index.tsx +154 -0
  138. package/src/base/partials/FilterBar/index.tsx +256 -0
  139. package/src/base/partials/FormSection/index.tsx +87 -0
  140. package/src/base/partials/LogViewer/JsonBlock.tsx +39 -0
  141. package/src/base/partials/LogViewer/LogEntry.tsx +68 -0
  142. package/src/base/partials/LogViewer/LogViewerToolbar.tsx +71 -0
  143. package/src/base/partials/LogViewer/index.tsx +110 -0
  144. package/src/base/partials/LogViewer/types.ts +28 -0
  145. package/src/base/partials/MarkdownContent/index.tsx +307 -0
  146. package/src/base/partials/MenuBar/index.tsx +80 -0
  147. package/src/base/partials/QuickRecordSheet/index.tsx +59 -0
  148. package/src/base/partials/ResizableSidebar/index.tsx +70 -0
  149. package/src/base/partials/StatRow/index.tsx +28 -0
  150. package/src/base/partials/StatusBar/index.tsx +126 -0
  151. package/src/base/partials/StatusIndicator/index.tsx +61 -0
  152. package/src/base/partials/StepIndicator/index.tsx +63 -0
  153. package/src/base/partials/TableOfContents/index.tsx +78 -0
  154. package/src/base/partials/TimelineList/index.tsx +273 -0
  155. package/src/base/partials/ToggleGroupControl/index.tsx +100 -0
  156. package/src/base/partials/TreeView/index.tsx +75 -0
  157. package/src/base/partials/index.ts +23 -0
  158. package/src/base/shell/AuthShell.tsx +54 -0
  159. package/src/base/shell/BasicShell.tsx +286 -0
  160. package/src/base/shell/ImmersiveShell.tsx +85 -0
  161. package/src/base/shell/partials/EditablePanelContext.tsx +82 -0
  162. package/src/base/shell/partials/EditablePanelProvider.tsx +122 -0
  163. package/src/base/shell/partials/InlineEditablePanel.tsx +239 -0
  164. package/src/base/shell/partials/InspectorContext.tsx +173 -0
  165. package/src/base/shell/partials/InspectorPanel.tsx +65 -0
  166. package/src/base/shell/partials/NavErrorBoundary.tsx +82 -0
  167. package/src/base/shell/partials/OverlayScreen.tsx +67 -0
  168. package/src/base/shell/partials/PageActionButton.tsx +203 -0
  169. package/src/base/theme/appearance.ts +133 -0
  170. package/src/base/theme/host-layout-detector.ts +119 -0
  171. package/src/base/theme/host-theme-detector.ts +146 -0
  172. package/src/base/theme/sidebar-safelist.txt +20 -0
  173. package/src/base/theme/tailwind-theme.css +136 -0
  174. package/src/base/theme/theme-bridge.css +164 -0
  175. package/src/base/theme/theme-context.tsx +142 -0
  176. package/src/base/theme/themes/classic.css +174 -0
  177. package/src/base/theme/tokens.css +290 -0
  178. package/src/base/theme/useHostTheme.ts +95 -0
  179. package/src/base/utils/clipboard.ts +39 -0
  180. package/src/base/utils/conditions.ts +27 -0
  181. package/src/base/utils/icon-registry.ts +78 -0
  182. package/src/base/utils/icons.ts +31 -0
  183. package/src/base/utils/interpolate.ts +9 -0
  184. package/src/base/utils/register-default-icons.ts +163 -0
  185. package/src/base/utils/storage.ts +65 -0
  186. package/src/base/utils/time.ts +139 -0
  187. package/src/contracts/block-data/actions.ts +73 -0
  188. package/src/contracts/block-data/data-display.ts +343 -0
  189. package/src/contracts/block-data/form.ts +164 -0
  190. package/src/contracts/block-data/index.ts +15 -0
  191. package/src/contracts/block-data/interactive.ts +34 -0
  192. package/src/contracts/block-data/shared.ts +44 -0
  193. package/src/contracts/connectors.ts +60 -0
  194. package/src/contracts/generated/contract-schema.ts +1237 -0
  195. package/src/contracts/generated/contract-types.ts +675 -0
  196. package/src/contracts/generated/index.ts +15 -0
  197. package/src/contracts/navigation.ts +59 -0
  198. package/src/contracts/page-contract-schema.ts +40 -0
  199. package/src/contracts/page-contract.ts +79 -0
  200. package/src/contracts/shared-props.ts +92 -0
  201. package/src/engine/ContractPage.tsx +178 -0
  202. package/src/engine/EntityRoutes.tsx +72 -0
  203. package/src/engine/HostSlot.tsx +126 -0
  204. package/src/engine/LazyBlock.tsx +92 -0
  205. package/src/engine/bootstrap.tsx +20 -0
  206. package/src/engine/providers/auth.tsx +87 -0
  207. package/src/engine/providers/error-reporter.tsx +89 -0
  208. package/src/engine/providers/flash.tsx +44 -0
  209. package/src/engine/providers/index.ts +18 -0
  210. package/src/engine/providers/inertia-error-reporter.tsx +61 -0
  211. package/src/engine/providers/progress.tsx +56 -0
  212. package/src/engine/providers/scope.tsx +51 -0
  213. package/src/engine/register-defaults.ts +88 -0
  214. package/src/engine/registries.ts +96 -0
  215. package/src/i18n/I18nProvider.tsx +53 -0
  216. package/src/i18n/MANIFEST.md +101 -0
  217. package/src/i18n/host-resolver.ts +18 -0
  218. package/src/i18n/instance.ts +69 -0
  219. package/src/i18n/locales/en/ui.json +277 -0
  220. package/src/i18n/locales/en/validators.json +13 -0
  221. package/src/i18n/locales/pt-BR/ui.json +277 -0
  222. package/src/i18n/locales/pt-BR/validators.json +13 -0
  223. package/src/i18n/register-strings.ts +10 -0
  224. package/src/i18n/render-label.ts +33 -0
  225. package/src/i18n/resolve-field-error.ts +29 -0
  226. package/src/i18n/useHostString.ts +50 -0
  227. package/src/i18n/useTranslation.ts +83 -0
  228. package/src/lib/actions/resolve-action-target.ts +151 -0
  229. package/src/lib/hooks/use-copy-to-clipboard.ts +37 -0
  230. package/src/lib/hooks/use-file-upload.ts +406 -0
  231. package/src/lib/hooks/use-mobile.ts +21 -0
  232. package/src/lib/host-pending.ts +76 -0
  233. package/src/lib/portal-container.ts +16 -0
  234. package/src/lib/test-ids.ts +40 -0
  235. package/src/lib/utils.ts +6 -0
  236. package/src/primitives/reui/MANIFEST.md +97 -0
  237. package/src/primitives/reui/accordion.tsx +64 -0
  238. package/src/primitives/reui/alert-dialog.tsx +196 -0
  239. package/src/primitives/reui/alert.tsx +92 -0
  240. package/src/primitives/reui/aspect-ratio.tsx +9 -0
  241. package/src/primitives/reui/autocomplete.tsx +343 -0
  242. package/src/primitives/reui/avatar.tsx +109 -0
  243. package/src/primitives/reui/badge.tsx +94 -0
  244. package/src/primitives/reui/breadcrumb.tsx +109 -0
  245. package/src/primitives/reui/button-group.tsx +83 -0
  246. package/src/primitives/reui/button.tsx +64 -0
  247. package/src/primitives/reui/calendar.tsx +220 -0
  248. package/src/primitives/reui/card.tsx +92 -0
  249. package/src/primitives/reui/carousel.tsx +239 -0
  250. package/src/primitives/reui/chart.tsx +388 -0
  251. package/src/primitives/reui/checkbox.tsx +30 -0
  252. package/src/primitives/reui/collapsible.tsx +31 -0
  253. package/src/primitives/reui/combobox.tsx +308 -0
  254. package/src/primitives/reui/command.tsx +182 -0
  255. package/src/primitives/reui/context-menu.tsx +250 -0
  256. package/src/primitives/reui/data-grid/data-grid-column-filter.tsx +172 -0
  257. package/src/primitives/reui/data-grid/data-grid-column-header.tsx +420 -0
  258. package/src/primitives/reui/data-grid/data-grid-column-visibility.tsx +51 -0
  259. package/src/primitives/reui/data-grid/data-grid-pagination.tsx +235 -0
  260. package/src/primitives/reui/data-grid/data-grid-scroll-area.tsx +427 -0
  261. package/src/primitives/reui/data-grid/data-grid-table-dnd-rows.tsx +308 -0
  262. package/src/primitives/reui/data-grid/data-grid-table-dnd.tsx +318 -0
  263. package/src/primitives/reui/data-grid/data-grid-table-virtual.tsx +491 -0
  264. package/src/primitives/reui/data-grid/data-grid-table.tsx +1430 -0
  265. package/src/primitives/reui/data-grid/data-grid.tsx +269 -0
  266. package/src/primitives/reui/data-grid-pagination.tsx +235 -0
  267. package/src/primitives/reui/date-selector.tsx +1353 -0
  268. package/src/primitives/reui/dialog.tsx +158 -0
  269. package/src/primitives/reui/drawer.tsx +133 -0
  270. package/src/primitives/reui/dropdown-menu.tsx +257 -0
  271. package/src/primitives/reui/empty.tsx +104 -0
  272. package/src/primitives/reui/field.tsx +246 -0
  273. package/src/primitives/reui/filters.tsx +1891 -0
  274. package/src/primitives/reui/frame.tsx +170 -0
  275. package/src/primitives/reui/hover-card.tsx +42 -0
  276. package/src/primitives/reui/icon-placeholder.tsx +39 -0
  277. package/src/primitives/reui/index.ts +98 -0
  278. package/src/primitives/reui/input-group.tsx +170 -0
  279. package/src/primitives/reui/input-otp.tsx +75 -0
  280. package/src/primitives/reui/input.tsx +21 -0
  281. package/src/primitives/reui/item.tsx +193 -0
  282. package/src/primitives/reui/kanban.tsx +743 -0
  283. package/src/primitives/reui/kbd.tsx +28 -0
  284. package/src/primitives/reui/label.tsx +22 -0
  285. package/src/primitives/reui/menubar.tsx +274 -0
  286. package/src/primitives/reui/native-select.tsx +62 -0
  287. package/src/primitives/reui/navigation-menu.tsx +168 -0
  288. package/src/primitives/reui/number-field.tsx +250 -0
  289. package/src/primitives/reui/pagination.tsx +127 -0
  290. package/src/primitives/reui/phone-input.tsx +231 -0
  291. package/src/primitives/reui/popover.tsx +87 -0
  292. package/src/primitives/reui/progress.tsx +31 -0
  293. package/src/primitives/reui/radio-group.tsx +43 -0
  294. package/src/primitives/reui/rating.tsx +177 -0
  295. package/src/primitives/reui/resizable.tsx +51 -0
  296. package/src/primitives/reui/scroll-area.tsx +58 -0
  297. package/src/primitives/reui/scrollspy.tsx +240 -0
  298. package/src/primitives/reui/select.tsx +188 -0
  299. package/src/primitives/reui/separator.tsx +28 -0
  300. package/src/primitives/reui/sheet.tsx +141 -0
  301. package/src/primitives/reui/sidebar.tsx +732 -0
  302. package/src/primitives/reui/skeleton.tsx +13 -0
  303. package/src/primitives/reui/slider.tsx +61 -0
  304. package/src/primitives/reui/sonner.tsx +47 -0
  305. package/src/primitives/reui/sortable.tsx +414 -0
  306. package/src/primitives/reui/spinner.tsx +16 -0
  307. package/src/primitives/reui/stepper.tsx +484 -0
  308. package/src/primitives/reui/svgs/claudeAiIcon.tsx +12 -0
  309. package/src/primitives/reui/svgs/gemini.tsx +171 -0
  310. package/src/primitives/reui/svgs/openai.tsx +9 -0
  311. package/src/primitives/reui/svgs/openaiDark.tsx +12 -0
  312. package/src/primitives/reui/switch.tsx +33 -0
  313. package/src/primitives/reui/table.tsx +114 -0
  314. package/src/primitives/reui/tabs.tsx +91 -0
  315. package/src/primitives/reui/textarea.tsx +18 -0
  316. package/src/primitives/reui/timeline.tsx +219 -0
  317. package/src/primitives/reui/toggle-group.tsx +83 -0
  318. package/src/primitives/reui/toggle.tsx +45 -0
  319. package/src/primitives/reui/tooltip.tsx +55 -0
  320. package/src/primitives/reui/tree.tsx +247 -0
  321. package/src/theme.css +71 -0
@@ -0,0 +1,1891 @@
1
+ import type React from "react";
2
+ import {
3
+ createContext,
4
+ useCallback,
5
+ useContext,
6
+ useEffect,
7
+ useId,
8
+ useMemo,
9
+ useRef,
10
+ useState,
11
+ } from "react";
12
+ import { cva } from "class-variance-authority";
13
+
14
+ import { cn } from "@/lib/utils";
15
+ import { Button } from "@/primitives/reui/button";
16
+ import { ButtonGroup, ButtonGroupText } from "@/primitives/reui/button-group";
17
+ import {
18
+ DropdownMenu,
19
+ DropdownMenuCheckboxItem,
20
+ DropdownMenuContent,
21
+ DropdownMenuGroup,
22
+ DropdownMenuItem,
23
+ DropdownMenuSeparator,
24
+ DropdownMenuSub,
25
+ DropdownMenuSubContent,
26
+ DropdownMenuSubTrigger,
27
+ DropdownMenuTrigger,
28
+ } from "@/primitives/reui/dropdown-menu";
29
+ import { Input } from "@/primitives/reui/input";
30
+ import {
31
+ InputGroup,
32
+ InputGroupAddon,
33
+ InputGroupButton,
34
+ InputGroupInput,
35
+ InputGroupText,
36
+ } from "@/primitives/reui/input-group";
37
+ import { Kbd } from "@/primitives/reui/kbd";
38
+ import { ScrollArea } from "@/primitives/reui/scroll-area";
39
+ import {
40
+ Tooltip,
41
+ TooltipContent,
42
+ TooltipProvider,
43
+ TooltipTrigger,
44
+ } from "@/primitives/reui/tooltip";
45
+ import { HugeiconsIcon } from "@hugeicons/react";
46
+ import {
47
+ AlertCircleIcon,
48
+ Cancel01Icon,
49
+ Tick02Icon,
50
+ Plus01Icon,
51
+ } from "@hugeicons/core-free-icons";
52
+
53
+ // i18n Configuration Interface
54
+ export interface FilterI18nConfig {
55
+ // UI Labels
56
+ addFilter: string;
57
+ searchFields: string;
58
+ noFieldsFound: string;
59
+ noResultsFound: string;
60
+ select: string;
61
+ true: string;
62
+ false: string;
63
+ min: string;
64
+ max: string;
65
+ to: string;
66
+ typeAndPressEnter: string;
67
+ selected: string;
68
+ selectedCount: string;
69
+ percent: string;
70
+ defaultCurrency: string;
71
+ defaultColor: string;
72
+ addFilterTitle: string;
73
+
74
+ // Operators
75
+ operators: {
76
+ is: string;
77
+ isNot: string;
78
+ isAnyOf: string;
79
+ isNotAnyOf: string;
80
+ includesAll: string;
81
+ excludesAll: string;
82
+ before: string;
83
+ after: string;
84
+ between: string;
85
+ notBetween: string;
86
+ contains: string;
87
+ notContains: string;
88
+ startsWith: string;
89
+ endsWith: string;
90
+ isExactly: string;
91
+ equals: string;
92
+ notEquals: string;
93
+ greaterThan: string;
94
+ lessThan: string;
95
+ overlaps: string;
96
+ includes: string;
97
+ excludes: string;
98
+ includesAllOf: string;
99
+ includesAnyOf: string;
100
+ empty: string;
101
+ notEmpty: string;
102
+ };
103
+
104
+ // Placeholders
105
+ placeholders: {
106
+ enterField: (fieldType: string) => string;
107
+ selectField: string;
108
+ searchField: (fieldName: string) => string;
109
+ enterKey: string;
110
+ enterValue: string;
111
+ };
112
+
113
+ // Helper functions
114
+ helpers: {
115
+ formatOperator: (operator: string) => string;
116
+ };
117
+
118
+ // Validation
119
+ validation: {
120
+ invalidEmail: string;
121
+ invalidUrl: string;
122
+ invalidTel: string;
123
+ invalid: string;
124
+ };
125
+ }
126
+
127
+ // Default English i18n configuration
128
+ export const DEFAULT_I18N: FilterI18nConfig = {
129
+ // UI Labels
130
+ addFilter: "Filter",
131
+ searchFields: "Filter...",
132
+ noFieldsFound: "No filters found.",
133
+ noResultsFound: "No results found.",
134
+ select: "Select...",
135
+ true: "True",
136
+ false: "False",
137
+ min: "Min",
138
+ max: "Max",
139
+ to: "to",
140
+ typeAndPressEnter: "Type and press Enter to add tag",
141
+ selected: "selected",
142
+ selectedCount: "selected",
143
+ percent: "%",
144
+ defaultCurrency: "$",
145
+ defaultColor: "#000000",
146
+ addFilterTitle: "Add filter",
147
+
148
+ // Operators
149
+ operators: {
150
+ is: "is",
151
+ isNot: "is not",
152
+ isAnyOf: "is any of",
153
+ isNotAnyOf: "is not any of",
154
+ includesAll: "includes all",
155
+ excludesAll: "excludes all",
156
+ before: "before",
157
+ after: "after",
158
+ between: "between",
159
+ notBetween: "not between",
160
+ contains: "contains",
161
+ notContains: "does not contain",
162
+ startsWith: "starts with",
163
+ endsWith: "ends with",
164
+ isExactly: "is exactly",
165
+ equals: "equals",
166
+ notEquals: "not equals",
167
+ greaterThan: "greater than",
168
+ lessThan: "less than",
169
+ overlaps: "overlaps",
170
+ includes: "includes",
171
+ excludes: "excludes",
172
+ includesAllOf: "includes all of",
173
+ includesAnyOf: "includes any of",
174
+ empty: "is empty",
175
+ notEmpty: "is not empty",
176
+ },
177
+
178
+ // Placeholders
179
+ placeholders: {
180
+ enterField: (fieldType: string) => `Enter ${fieldType}...`,
181
+ selectField: "Select...",
182
+ searchField: (fieldName: string) => `Search ${fieldName.toLowerCase()}...`,
183
+ enterKey: "Enter key...",
184
+ enterValue: "Enter value...",
185
+ },
186
+
187
+ // Helper functions
188
+ helpers: {
189
+ formatOperator: (operator: string) => operator.replace(/_/g, " "),
190
+ },
191
+
192
+ // Validation
193
+ validation: {
194
+ invalidEmail: "Invalid email format",
195
+ invalidUrl: "Invalid URL format",
196
+ invalidTel: "Invalid phone format",
197
+ invalid: "Invalid input format",
198
+ },
199
+ };
200
+
201
+ // Context for all Filter component props
202
+ interface FilterContextValue {
203
+ variant: "solid" | "default";
204
+ size: "sm" | "default" | "lg";
205
+ radius: "default" | "full";
206
+ i18n: FilterI18nConfig;
207
+ className?: string;
208
+ showSearchInput?: boolean;
209
+ trigger?: React.ReactNode;
210
+ allowMultiple?: boolean;
211
+ }
212
+
213
+ const FilterContext = createContext<FilterContextValue>({
214
+ variant: "default",
215
+ size: "default",
216
+ radius: "default",
217
+ i18n: DEFAULT_I18N,
218
+ className: undefined,
219
+ showSearchInput: true,
220
+ trigger: undefined,
221
+ allowMultiple: true,
222
+ });
223
+
224
+ const useFilterContext = () => useContext(FilterContext);
225
+
226
+ // Container variant for filters wrapper
227
+ const filtersContainerVariants = cva("flex flex-wrap items-center", {
228
+ variants: {
229
+ variant: {
230
+ solid: "gap-2",
231
+ default: "",
232
+ },
233
+ size: {
234
+ sm: "gap-1.5",
235
+ default: "gap-2.5",
236
+ lg: "gap-3.5",
237
+ },
238
+ },
239
+ defaultVariants: {
240
+ variant: "default",
241
+ size: "default",
242
+ },
243
+ });
244
+
245
+ function FilterInput<T = unknown>({
246
+ field,
247
+ onBlur,
248
+ onKeyDown,
249
+ className,
250
+ ...props
251
+ }: React.InputHTMLAttributes<HTMLInputElement> & {
252
+ className?: string;
253
+ field?: FilterFieldConfig<T>;
254
+ }) {
255
+ const context = useFilterContext();
256
+ const [isValid, setIsValid] = useState(true);
257
+ const [validationMessage, setValidationMessage] = useState("");
258
+ const inputRef = useRef<HTMLInputElement>(null);
259
+
260
+ useEffect(() => {
261
+ if (props.autoFocus) {
262
+ const timer = setTimeout(() => {
263
+ inputRef.current?.focus();
264
+ }, 300);
265
+ return () => clearTimeout(timer);
266
+ }
267
+ }, [props.autoFocus]);
268
+
269
+ // Validation function to check if input matches pattern
270
+ const validateInput = (value: string, pattern?: string): boolean => {
271
+ if (!pattern || !value) return true;
272
+ const regex = new RegExp(pattern);
273
+ return regex.test(value);
274
+ };
275
+
276
+ // Get validation message for field type
277
+ const getValidationMessage = (): string => {
278
+ return context.i18n.validation.invalid;
279
+ };
280
+
281
+ // Handle blur event - validate when user leaves input
282
+ const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
283
+ const value = e.target.value;
284
+ const pattern = field?.pattern || props.pattern;
285
+
286
+ // Only validate if there's a value and (pattern or validation function)
287
+ if (value && (pattern || field?.validation)) {
288
+ let valid = true;
289
+ let customMessage = "";
290
+
291
+ // If there's a custom validation function, use it
292
+ if (field?.validation) {
293
+ const result = field.validation(value);
294
+ // Handle both boolean and object return types
295
+ if (typeof result === "boolean") {
296
+ valid = result;
297
+ } else {
298
+ valid = result.valid;
299
+ customMessage = result.message || "";
300
+ }
301
+ } else if (pattern) {
302
+ // Use pattern validation
303
+ valid = validateInput(value, pattern);
304
+ }
305
+
306
+ setIsValid(valid);
307
+ setValidationMessage(
308
+ valid ? "" : customMessage || getValidationMessage(),
309
+ );
310
+ } else {
311
+ // Reset validation state for empty values or no validation
312
+ setIsValid(true);
313
+ setValidationMessage("");
314
+ }
315
+
316
+ // Call the original onBlur if provided
317
+ onBlur?.(e);
318
+ };
319
+
320
+ // Handle keydown event - hide validation error when user starts typing
321
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
322
+ // Hide validation error when user starts typing (any key except special keys)
323
+ if (
324
+ !isValid &&
325
+ ![
326
+ "Tab",
327
+ "Escape",
328
+ "Enter",
329
+ "ArrowUp",
330
+ "ArrowDown",
331
+ "ArrowLeft",
332
+ "ArrowRight",
333
+ ].includes(e.key)
334
+ ) {
335
+ setIsValid(true);
336
+ setValidationMessage("");
337
+ }
338
+
339
+ // Call the original onKeyDown if provided
340
+ onKeyDown?.(e);
341
+ };
342
+
343
+ return (
344
+ <InputGroup
345
+ className={cn(
346
+ "w-36",
347
+ context.size == "sm" && "h-8!",
348
+ context.size == "default" && "h-9!",
349
+ context.size == "lg" && "h-10!",
350
+ className,
351
+ )}
352
+ >
353
+ {field?.prefix && (
354
+ <InputGroupAddon>
355
+ <InputGroupText>{field.prefix}</InputGroupText>
356
+ </InputGroupAddon>
357
+ )}
358
+ <InputGroupInput
359
+ ref={inputRef}
360
+ aria-invalid={!isValid}
361
+ aria-describedby={
362
+ !isValid && validationMessage
363
+ ? `${field?.key || "input"}-error`
364
+ : undefined
365
+ }
366
+ onBlur={handleBlur}
367
+ onKeyDown={handleKeyDown}
368
+ className={cn(
369
+ context.size == "sm" && "h-8! text-xs",
370
+ context.size == "default" && "h-9!",
371
+ context.size == "lg" && "h-10!",
372
+ )}
373
+ {...props}
374
+ />
375
+ {!isValid && validationMessage && (
376
+ <InputGroupAddon align="inline-end">
377
+ <TooltipProvider>
378
+ <Tooltip>
379
+ <TooltipTrigger asChild>
380
+ <InputGroupButton size="icon-xs">
381
+ <HugeiconsIcon
382
+ icon={AlertCircleIcon}
383
+ strokeWidth={2}
384
+ className="text-destructive size-3.5"
385
+ />
386
+ </InputGroupButton>
387
+ </TooltipTrigger>
388
+ <TooltipContent>
389
+ <p className="text-sm">{validationMessage}</p>
390
+ </TooltipContent>
391
+ </Tooltip>
392
+ </TooltipProvider>
393
+ </InputGroupAddon>
394
+ )}
395
+
396
+ {field?.suffix && (
397
+ <InputGroupAddon align="inline-end">
398
+ <InputGroupText>{field.suffix}</InputGroupText>
399
+ </InputGroupAddon>
400
+ )}
401
+ </InputGroup>
402
+ );
403
+ }
404
+
405
+ interface FilterRemoveButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
406
+ icon?: React.ReactNode;
407
+ }
408
+
409
+ function FilterRemoveButton({
410
+ className,
411
+ icon = <HugeiconsIcon icon={Cancel01Icon} strokeWidth={2} />,
412
+ ...props
413
+ }: FilterRemoveButtonProps) {
414
+ const context = useFilterContext();
415
+
416
+ const sizeMap = {
417
+ sm: "sm" as const,
418
+ default: "sm" as const,
419
+ lg: "default" as const,
420
+ };
421
+
422
+ return (
423
+ <Button
424
+ variant="outline"
425
+ size={
426
+ context.size === "sm"
427
+ ? "icon-sm"
428
+ : context.size === "lg"
429
+ ? "icon-lg"
430
+ : "icon"
431
+ }
432
+ {...props}
433
+ >
434
+ {icon}
435
+ </Button>
436
+ );
437
+ }
438
+
439
+ // Generic types for flexible filter system
440
+ export interface FilterOption<T = unknown> {
441
+ value: T;
442
+ label: string;
443
+ icon?: React.ReactNode;
444
+ metadata?: Record<string, unknown>;
445
+ className?: string;
446
+ }
447
+
448
+ export interface FilterOperator {
449
+ value: string;
450
+ label: string;
451
+ supportsMultiple?: boolean;
452
+ }
453
+
454
+ // Custom renderer props interface
455
+ export interface CustomRendererProps<T = unknown> {
456
+ field: FilterFieldConfig<T>;
457
+ values: T[];
458
+ onChange: (values: T[]) => void;
459
+ operator: string;
460
+ }
461
+
462
+ // Grouped field configuration interface
463
+ export interface FilterFieldGroup<T = unknown> {
464
+ group?: string;
465
+ fields: FilterFieldConfig<T>[];
466
+ }
467
+
468
+ // Union type for both flat and grouped field configurations
469
+ export type FilterFieldsConfig<T = unknown> =
470
+ | FilterFieldConfig<T>[]
471
+ | FilterFieldGroup<T>[];
472
+
473
+ export interface FilterFieldConfig<T = unknown> {
474
+ key?: string;
475
+ label?: string;
476
+ icon?: React.ReactNode;
477
+ type?: "select" | "multiselect" | "text" | "custom" | "separator";
478
+ // Group-level configuration
479
+ group?: string;
480
+ fields?: FilterFieldConfig<T>[];
481
+ // Field-specific options
482
+ options?: FilterOption<T>[];
483
+ operators?: FilterOperator[];
484
+ customRenderer?: (props: CustomRendererProps<T>) => React.ReactNode;
485
+ customValueRenderer?: (
486
+ values: T[],
487
+ options: FilterOption<T>[],
488
+ ) => React.ReactNode;
489
+ placeholder?: string;
490
+ searchable?: boolean;
491
+ maxSelections?: number;
492
+ min?: number;
493
+ max?: number;
494
+ step?: number;
495
+ prefix?: string | React.ReactNode;
496
+ suffix?: string | React.ReactNode;
497
+ pattern?: string;
498
+ validation?: (
499
+ value: unknown,
500
+ ) => boolean | { valid: boolean; message?: string };
501
+ allowCustomValues?: boolean;
502
+ className?: string;
503
+ menuPopupClassName?: string;
504
+ // Grouping options (legacy support)
505
+ groupLabel?: string;
506
+ // Boolean field options
507
+ onLabel?: string;
508
+ offLabel?: string;
509
+ // Input event handlers
510
+ onInputChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
511
+ // Default operator to use when creating a filter for this field
512
+ defaultOperator?: string;
513
+ // Controlled values support for this field
514
+ value?: T[];
515
+ onValueChange?: (values: T[]) => void;
516
+ }
517
+
518
+ // Helper functions to handle both flat and grouped field configurations
519
+ const isFieldGroup = <T = unknown,>(
520
+ item: FilterFieldConfig<T> | FilterFieldGroup<T>,
521
+ ): item is FilterFieldGroup<T> => {
522
+ return "fields" in item && Array.isArray(item.fields);
523
+ };
524
+
525
+ // Helper function to check if a FilterFieldConfig is a group-level configuration
526
+ const isGroupLevelField = <T = unknown,>(
527
+ field: FilterFieldConfig<T>,
528
+ ): boolean => {
529
+ return Boolean(field.group && field.fields);
530
+ };
531
+
532
+ const flattenFields = <T = unknown,>(
533
+ fields: FilterFieldsConfig<T>,
534
+ ): FilterFieldConfig<T>[] => {
535
+ return fields.reduce<FilterFieldConfig<T>[]>((acc, item) => {
536
+ if (isFieldGroup(item)) {
537
+ return [...acc, ...item.fields];
538
+ }
539
+ // Handle group-level fields (new structure)
540
+ if (isGroupLevelField(item)) {
541
+ return [...acc, ...item.fields!];
542
+ }
543
+ return [...acc, item];
544
+ }, []);
545
+ };
546
+
547
+ const getFieldsMap = <T = unknown,>(
548
+ fields: FilterFieldsConfig<T>,
549
+ ): Record<string, FilterFieldConfig<T>> => {
550
+ const flatFields = flattenFields(fields);
551
+ return flatFields.reduce(
552
+ (acc, field) => {
553
+ // Only add fields that have a key (skip group-level configurations)
554
+ if (field.key) {
555
+ acc[field.key] = field;
556
+ }
557
+ return acc;
558
+ },
559
+ {} as Record<string, FilterFieldConfig<T>>,
560
+ );
561
+ };
562
+
563
+ // Helper function to create operators from i18n config
564
+ const createOperatorsFromI18n = (
565
+ i18n: FilterI18nConfig,
566
+ ): Record<string, FilterOperator[]> => ({
567
+ select: [
568
+ { value: "is", label: i18n.operators.is },
569
+ { value: "is_not", label: i18n.operators.isNot },
570
+ { value: "empty", label: i18n.operators.empty },
571
+ { value: "not_empty", label: i18n.operators.notEmpty },
572
+ ],
573
+ multiselect: [
574
+ { value: "is_any_of", label: i18n.operators.isAnyOf },
575
+ { value: "is_not_any_of", label: i18n.operators.isNotAnyOf },
576
+ { value: "includes_all", label: i18n.operators.includesAll },
577
+ { value: "excludes_all", label: i18n.operators.excludesAll },
578
+ { value: "empty", label: i18n.operators.empty },
579
+ { value: "not_empty", label: i18n.operators.notEmpty },
580
+ ],
581
+ text: [
582
+ { value: "contains", label: i18n.operators.contains },
583
+ { value: "not_contains", label: i18n.operators.notContains },
584
+ { value: "starts_with", label: i18n.operators.startsWith },
585
+ { value: "ends_with", label: i18n.operators.endsWith },
586
+ { value: "is", label: i18n.operators.isExactly },
587
+ { value: "empty", label: i18n.operators.empty },
588
+ { value: "not_empty", label: i18n.operators.notEmpty },
589
+ ],
590
+ custom: [
591
+ { value: "is", label: i18n.operators.is },
592
+ { value: "after", label: i18n.operators.after },
593
+ { value: "is", label: i18n.operators.is },
594
+ { value: "between", label: i18n.operators.between },
595
+ { value: "empty", label: i18n.operators.empty },
596
+ { value: "not_empty", label: i18n.operators.notEmpty },
597
+ ],
598
+ });
599
+
600
+ // Default operators for different field types (using default i18n)
601
+ export const DEFAULT_OPERATORS: Record<string, FilterOperator[]> =
602
+ createOperatorsFromI18n(DEFAULT_I18N);
603
+
604
+ // Helper function to get operators for a field
605
+ const getOperatorsForField = <T = unknown,>(
606
+ field: FilterFieldConfig<T>,
607
+ values: T[],
608
+ i18n: FilterI18nConfig,
609
+ ): FilterOperator[] => {
610
+ if (field.operators) return field.operators;
611
+
612
+ const operators = createOperatorsFromI18n(i18n);
613
+
614
+ // Determine field type for operator selection
615
+ let fieldType = field.type || "select";
616
+
617
+ // If it's a select field but has multiple values, treat as multiselect
618
+ if (fieldType === "select" && values.length > 1) {
619
+ fieldType = "multiselect";
620
+ }
621
+
622
+ // If it's a multiselect field or has multiselect operators, use multiselect operators
623
+ if (fieldType === "multiselect" || field.type === "multiselect") {
624
+ return operators.multiselect;
625
+ }
626
+
627
+ return operators[fieldType] || operators.select;
628
+ };
629
+
630
+ interface FilterOperatorDropdownProps<T = unknown> {
631
+ field: FilterFieldConfig<T>;
632
+ operator: string;
633
+ values: T[];
634
+ onChange: (operator: string) => void;
635
+ }
636
+
637
+ function FilterOperatorDropdown<T = unknown>({
638
+ field,
639
+ operator,
640
+ values,
641
+ onChange,
642
+ }: FilterOperatorDropdownProps<T>) {
643
+ const context = useFilterContext();
644
+ const operators = getOperatorsForField(field, values, context.i18n);
645
+
646
+ // Find the operator label, with fallback to formatted operator name
647
+ const operatorLabel =
648
+ operators.find((op) => op.value === operator)?.label ||
649
+ context.i18n.helpers.formatOperator(operator);
650
+
651
+ return (
652
+ <DropdownMenu>
653
+ <DropdownMenuTrigger asChild>
654
+ <Button
655
+ variant="outline"
656
+ size={context.size}
657
+ className="text-muted-foreground hover:text-foreground"
658
+ >
659
+ {operatorLabel}
660
+ </Button>
661
+ </DropdownMenuTrigger>
662
+ <DropdownMenuContent align="start" className="w-fit min-w-fit">
663
+ {operators.map((op) => (
664
+ <DropdownMenuItem
665
+ key={op.value}
666
+ onClick={() => onChange(op.value)}
667
+ className={cn(
668
+ "data-highlighted:bg-accent data-highlighted:text-accent-foreground flex items-center justify-between",
669
+ )}
670
+ >
671
+ <span>{op.label}</span>
672
+ <HugeiconsIcon
673
+ icon={Tick02Icon}
674
+ strokeWidth={2}
675
+ className={cn(
676
+ "text-primary ms-auto",
677
+ op.value === operator ? "opacity-100" : "opacity-0",
678
+ )}
679
+ />
680
+ </DropdownMenuItem>
681
+ ))}
682
+ </DropdownMenuContent>
683
+ </DropdownMenu>
684
+ );
685
+ }
686
+
687
+ interface FilterValueSelectorProps<T = unknown> {
688
+ field: FilterFieldConfig<T>;
689
+ values: T[];
690
+ onChange: (values: T[]) => void;
691
+ operator: string;
692
+ autoFocus?: boolean;
693
+ }
694
+
695
+ interface SelectOptionsPopoverProps<T = unknown> {
696
+ field: FilterFieldConfig<T>;
697
+ values: T[];
698
+ onChange: (values: T[]) => void;
699
+ onClose?: () => void;
700
+ inline?: boolean;
701
+ }
702
+
703
+ function SelectOptionsPopover<T = unknown>({
704
+ field,
705
+ values,
706
+ onChange,
707
+ onClose,
708
+ inline = false,
709
+ }: SelectOptionsPopoverProps<T>) {
710
+ const [open, setOpen] = useState(false);
711
+ const [searchInput, setSearchInput] = useState("");
712
+ const [highlightedIndex, setHighlightedIndex] = useState(-1);
713
+ const inputRef = useRef<HTMLInputElement>(null);
714
+ const context = useFilterContext();
715
+ const baseId = useId();
716
+
717
+ useEffect(() => {
718
+ setHighlightedIndex(-1);
719
+ }, [searchInput, open]);
720
+
721
+ useEffect(() => {
722
+ if (highlightedIndex >= 0 && open) {
723
+ const element = document.getElementById(
724
+ `${baseId}-item-${highlightedIndex}`,
725
+ );
726
+ element?.scrollIntoView({ block: "nearest" });
727
+ }
728
+ }, [highlightedIndex, open, baseId]);
729
+
730
+ const isMultiSelect = field.type === "multiselect" || values.length > 1;
731
+ const effectiveValues =
732
+ (field.value !== undefined ? (field.value as T[]) : values) || [];
733
+
734
+ const selectedOptions =
735
+ field.options?.filter((opt) => effectiveValues.includes(opt.value)) || [];
736
+ const unselectedOptions =
737
+ field.options?.filter((opt) => !effectiveValues.includes(opt.value)) || [];
738
+
739
+ // Filter options based on search input
740
+ const filteredSelectedOptions = selectedOptions; // Keep all selected visible
741
+ const filteredUnselectedOptions = unselectedOptions.filter((opt) =>
742
+ opt.label.toLowerCase().includes(searchInput.toLowerCase()),
743
+ );
744
+
745
+ const allFilteredOptions = useMemo(
746
+ () => [...filteredSelectedOptions, ...filteredUnselectedOptions],
747
+ [filteredSelectedOptions, filteredUnselectedOptions],
748
+ );
749
+
750
+ const handleClose = () => {
751
+ setOpen(false);
752
+ onClose?.();
753
+ };
754
+
755
+ const renderMenuContent = () => (
756
+ <>
757
+ {field.searchable !== false && (
758
+ <>
759
+ <Input
760
+ ref={inputRef}
761
+ role="combobox"
762
+ aria-autocomplete="list"
763
+ aria-expanded={true}
764
+ aria-haspopup="listbox"
765
+ aria-controls={`${baseId}-listbox`}
766
+ aria-activedescendant={
767
+ highlightedIndex >= 0
768
+ ? `${baseId}-item-${highlightedIndex}`
769
+ : undefined
770
+ }
771
+ placeholder={context.i18n.placeholders.searchField(
772
+ field.label || "",
773
+ )}
774
+ className={cn(
775
+ "border-input h-8 rounded-none border-0 bg-transparent! px-2 text-sm shadow-none",
776
+ "focus-visible:border-border focus-visible:ring-0 focus-visible:ring-offset-0",
777
+ )}
778
+ value={searchInput}
779
+ onChange={(e) => setSearchInput(e.target.value)}
780
+ onClick={(e) => e.stopPropagation()}
781
+ onKeyDown={(e) => {
782
+ if (e.key === "ArrowDown") {
783
+ e.preventDefault();
784
+ if (allFilteredOptions.length > 0) {
785
+ setHighlightedIndex((prev) =>
786
+ prev < allFilteredOptions.length - 1 ? prev + 1 : 0,
787
+ );
788
+ }
789
+ } else if (e.key === "ArrowUp") {
790
+ e.preventDefault();
791
+ if (allFilteredOptions.length > 0) {
792
+ setHighlightedIndex((prev) =>
793
+ prev > 0 ? prev - 1 : allFilteredOptions.length - 1,
794
+ );
795
+ }
796
+ } else if (e.key === "ArrowLeft") {
797
+ e.preventDefault();
798
+ setOpen(false);
799
+ } else if (e.key === "Enter" && highlightedIndex >= 0) {
800
+ e.preventDefault();
801
+ const option = allFilteredOptions[highlightedIndex];
802
+ if (option) {
803
+ const isSelected = effectiveValues.includes(
804
+ option.value as T,
805
+ );
806
+ const next = isSelected
807
+ ? (effectiveValues.filter((v) => v !== option.value) as T[])
808
+ : isMultiSelect
809
+ ? ([...effectiveValues, option.value] as T[])
810
+ : ([option.value] as T[]);
811
+
812
+ if (
813
+ !isSelected &&
814
+ isMultiSelect &&
815
+ field.maxSelections &&
816
+ next.length > field.maxSelections
817
+ ) {
818
+ return;
819
+ }
820
+
821
+ if (field.onValueChange) {
822
+ field.onValueChange(next);
823
+ } else {
824
+ onChange(next);
825
+ }
826
+ if (!isMultiSelect) handleClose();
827
+ }
828
+ }
829
+ e.stopPropagation();
830
+ }}
831
+ />
832
+ <DropdownMenuSeparator />
833
+ </>
834
+ )}
835
+ <div className="relative flex max-h-full">
836
+ <div
837
+ className="flex max-h-[min(var(--radix-dropdown-menu-content-available-height),24rem)] w-full scroll-pt-2 scroll-pb-2 flex-col overscroll-contain"
838
+ role="listbox"
839
+ id={`${baseId}-listbox`}
840
+ >
841
+ <ScrollArea className="size-full min-h-0 **:data-[slot=scroll-area-scrollbar]:m-0 **:data-[slot=scroll-area-viewport]:h-full **:data-[slot=scroll-area-viewport]:overscroll-contain">
842
+ {allFilteredOptions.length === 0 && (
843
+ <div className="text-muted-foreground py-2 text-center text-sm">
844
+ {context.i18n.noResultsFound}
845
+ </div>
846
+ )}
847
+
848
+ {/* Selected items */}
849
+ {filteredSelectedOptions.length > 0 && (
850
+ <DropdownMenuGroup className="px-1">
851
+ {filteredSelectedOptions.map((option, index) => {
852
+ const isHighlighted = highlightedIndex === index;
853
+ const itemId = `${baseId}-item-${index}`;
854
+
855
+ return (
856
+ <DropdownMenuCheckboxItem
857
+ key={String(option.value)}
858
+ id={itemId}
859
+ role="option"
860
+ aria-selected={isHighlighted}
861
+ data-highlighted={isHighlighted || undefined}
862
+ onMouseEnter={() => setHighlightedIndex(index)}
863
+ checked={true}
864
+ className={cn(
865
+ "data-highlighted:bg-accent data-highlighted:text-accent-foreground",
866
+ option.className,
867
+ )}
868
+ onSelect={(e) => {
869
+ if (isMultiSelect) e.preventDefault();
870
+ }}
871
+ onCheckedChange={() => {
872
+ const next = effectiveValues.filter(
873
+ (v) => v !== option.value,
874
+ ) as T[];
875
+ if (field.onValueChange) {
876
+ field.onValueChange(next);
877
+ } else {
878
+ onChange(next);
879
+ }
880
+ if (!isMultiSelect) handleClose();
881
+ }}
882
+ >
883
+ {option.icon && option.icon}
884
+ <span className="truncate">{option.label}</span>
885
+ </DropdownMenuCheckboxItem>
886
+ );
887
+ })}
888
+ </DropdownMenuGroup>
889
+ )}
890
+
891
+ {/* Separator */}
892
+ {filteredSelectedOptions.length > 0 &&
893
+ filteredUnselectedOptions.length > 0 && (
894
+ <DropdownMenuSeparator className="mx-0" />
895
+ )}
896
+
897
+ {/* Available items */}
898
+ {filteredUnselectedOptions.length > 0 && (
899
+ <DropdownMenuGroup className="px-1">
900
+ {filteredUnselectedOptions.map((option, index) => {
901
+ const overallIndex = index + filteredSelectedOptions.length;
902
+ const isHighlighted = highlightedIndex === overallIndex;
903
+ const itemId = `${baseId}-item-${overallIndex}`;
904
+
905
+ return (
906
+ <DropdownMenuCheckboxItem
907
+ key={String(option.value)}
908
+ id={itemId}
909
+ role="option"
910
+ aria-selected={isHighlighted}
911
+ data-highlighted={isHighlighted || undefined}
912
+ onMouseEnter={() => setHighlightedIndex(overallIndex)}
913
+ checked={false}
914
+ className={cn(
915
+ "data-highlighted:bg-accent data-highlighted:text-accent-foreground",
916
+ option.className,
917
+ )}
918
+ onSelect={(e) => {
919
+ if (isMultiSelect) e.preventDefault();
920
+ }}
921
+ onCheckedChange={() => {
922
+ const next = isMultiSelect
923
+ ? ([...effectiveValues, option.value] as T[])
924
+ : ([option.value] as T[]);
925
+
926
+ if (
927
+ isMultiSelect &&
928
+ field.maxSelections &&
929
+ next.length > field.maxSelections
930
+ ) {
931
+ return;
932
+ }
933
+
934
+ if (field.onValueChange) {
935
+ field.onValueChange(next);
936
+ } else {
937
+ onChange(next);
938
+ }
939
+ if (!isMultiSelect) handleClose();
940
+ }}
941
+ >
942
+ {option.icon && option.icon}
943
+ <span className="truncate">{option.label}</span>
944
+ </DropdownMenuCheckboxItem>
945
+ );
946
+ })}
947
+ </DropdownMenuGroup>
948
+ )}
949
+ </ScrollArea>
950
+ </div>
951
+ </div>
952
+ </>
953
+ );
954
+
955
+ if (inline) {
956
+ return <div className="w-full">{renderMenuContent()}</div>;
957
+ }
958
+
959
+ return (
960
+ <DropdownMenu
961
+ open={open}
962
+ onOpenChange={(open) => {
963
+ setOpen(open);
964
+ if (!open) {
965
+ setTimeout(() => setSearchInput(""), 200);
966
+ }
967
+ }}
968
+ >
969
+ <DropdownMenuTrigger asChild>
970
+ <Button variant="outline" size={context.size}>
971
+ <div className="flex items-center gap-1.5">
972
+ {field.customValueRenderer ? (
973
+ field.customValueRenderer(values, field.options || [])
974
+ ) : (
975
+ <>
976
+ {selectedOptions.length > 0 && (
977
+ <div className="flex items-center -space-x-1.5">
978
+ {selectedOptions.slice(0, 3).map((option) => (
979
+ <div key={String(option.value)}>{option.icon}</div>
980
+ ))}
981
+ </div>
982
+ )}
983
+ {selectedOptions.length === 1
984
+ ? selectedOptions[0].label
985
+ : selectedOptions.length > 1
986
+ ? `${selectedOptions.length} ${context.i18n.selectedCount}`
987
+ : context.i18n.select}
988
+ </>
989
+ )}
990
+ </div>
991
+ </Button>
992
+ </DropdownMenuTrigger>
993
+ <DropdownMenuContent
994
+ align="start"
995
+ className={cn("w-[200px] px-0", field.className)}
996
+ >
997
+ {renderMenuContent()}
998
+ </DropdownMenuContent>
999
+ </DropdownMenu>
1000
+ );
1001
+ }
1002
+
1003
+ function FilterValueSelector<T = unknown>({
1004
+ field,
1005
+ values,
1006
+ onChange,
1007
+ operator,
1008
+ autoFocus,
1009
+ }: FilterValueSelectorProps<T>) {
1010
+ const context = useFilterContext();
1011
+
1012
+ if (operator === "empty" || operator === "not_empty") {
1013
+ return null;
1014
+ }
1015
+
1016
+ if (field.customRenderer) {
1017
+ return (
1018
+ <ButtonGroupText className="hover:bg-accent aria-expanded:bg-accent text-start whitespace-nowrap outline-hidden">
1019
+ {field.customRenderer({ field, values, onChange, operator })}
1020
+ </ButtonGroupText>
1021
+ );
1022
+ }
1023
+
1024
+ if (field.type === "text") {
1025
+ return (
1026
+ <FilterInput
1027
+ type="text"
1028
+ value={(values[0] as string) || ""}
1029
+ onChange={(e) => onChange([e.target.value] as T[])}
1030
+ placeholder={field.placeholder}
1031
+ pattern={field.pattern}
1032
+ field={field}
1033
+ className={cn("w-36", field.className)}
1034
+ autoFocus={autoFocus}
1035
+ />
1036
+ );
1037
+ }
1038
+
1039
+ if (field.type === "select" || field.type === "multiselect") {
1040
+ return (
1041
+ <SelectOptionsPopover field={field} values={values} onChange={onChange} />
1042
+ );
1043
+ }
1044
+
1045
+ return (
1046
+ <SelectOptionsPopover field={field} values={values} onChange={onChange} />
1047
+ );
1048
+ }
1049
+ export interface Filter<T = unknown> {
1050
+ id: string;
1051
+ field: string;
1052
+ operator: string;
1053
+ values: T[];
1054
+ }
1055
+
1056
+ export interface FilterGroup<T = unknown> {
1057
+ id: string;
1058
+ label?: string;
1059
+ filters: Filter<T>[];
1060
+ fields: FilterFieldConfig<T>[];
1061
+ }
1062
+
1063
+ interface FiltersContentProps<T = unknown> {
1064
+ filters: Filter<T>[];
1065
+ fields: FilterFieldsConfig<T>;
1066
+ onChange: (filters: Filter<T>[]) => void;
1067
+ }
1068
+
1069
+ export const FiltersContent = <T = unknown,>({
1070
+ filters,
1071
+ fields,
1072
+ onChange,
1073
+ }: FiltersContentProps<T>) => {
1074
+ const context = useFilterContext();
1075
+ const fieldsMap = useMemo(() => getFieldsMap(fields), [fields]);
1076
+
1077
+ const updateFilter = useCallback(
1078
+ (filterId: string, updates: Partial<Filter<T>>) => {
1079
+ onChange(
1080
+ filters.map((filter) => {
1081
+ if (filter.id === filterId) {
1082
+ const updatedFilter = { ...filter, ...updates };
1083
+ if (
1084
+ updates.operator === "empty" ||
1085
+ updates.operator === "not_empty"
1086
+ ) {
1087
+ updatedFilter.values = [] as T[];
1088
+ }
1089
+ return updatedFilter;
1090
+ }
1091
+ return filter;
1092
+ }),
1093
+ );
1094
+ },
1095
+ [filters, onChange],
1096
+ );
1097
+
1098
+ const removeFilter = useCallback(
1099
+ (filterId: string) => {
1100
+ onChange(filters.filter((filter) => filter.id !== filterId));
1101
+ },
1102
+ [filters, onChange],
1103
+ );
1104
+
1105
+ return (
1106
+ <div
1107
+ className={cn(
1108
+ filtersContainerVariants({
1109
+ variant: context.variant,
1110
+ size: context.size,
1111
+ }),
1112
+ context.className,
1113
+ )}
1114
+ >
1115
+ {filters.map((filter) => {
1116
+ const field = fieldsMap[filter.field];
1117
+ if (!field) return null;
1118
+
1119
+ return (
1120
+ <ButtonGroup key={filter.id}>
1121
+ <ButtonGroupText>
1122
+ {field.icon && field.icon}
1123
+ {field.label}
1124
+ </ButtonGroupText>
1125
+
1126
+ <FilterOperatorDropdown<T>
1127
+ field={field}
1128
+ operator={filter.operator}
1129
+ values={filter.values}
1130
+ onChange={(operator) => updateFilter(filter.id, { operator })}
1131
+ />
1132
+
1133
+ <FilterValueSelector<T>
1134
+ field={field}
1135
+ values={filter.values}
1136
+ onChange={(values) => updateFilter(filter.id, { values })}
1137
+ operator={filter.operator}
1138
+ autoFocus={false}
1139
+ />
1140
+
1141
+ <FilterRemoveButton onClick={() => removeFilter(filter.id)} />
1142
+ </ButtonGroup>
1143
+ );
1144
+ })}
1145
+ </div>
1146
+ );
1147
+ };
1148
+
1149
+ interface FiltersProps<T = unknown> {
1150
+ filters: Filter<T>[];
1151
+ fields: FilterFieldsConfig<T>;
1152
+ onChange: (filters: Filter<T>[]) => void;
1153
+ className?: string;
1154
+ variant?: "solid" | "default";
1155
+ size?: "sm" | "default" | "lg";
1156
+ radius?: "default" | "full";
1157
+ i18n?: Partial<FilterI18nConfig>;
1158
+ showSearchInput?: boolean;
1159
+ trigger?: React.ReactNode;
1160
+ allowMultiple?: boolean;
1161
+ menuPopupClassName?: string;
1162
+ collapseAddButton?: boolean;
1163
+ enableShortcut?: boolean;
1164
+ shortcutKey?: string;
1165
+ shortcutLabel?: string;
1166
+ }
1167
+
1168
+ interface FilterSubmenuContentProps<T = unknown> {
1169
+ field: FilterFieldConfig<T>;
1170
+ currentValues: T[];
1171
+ isMultiSelect: boolean;
1172
+ onToggle: (value: T, isSelected: boolean) => void;
1173
+ i18n: FilterI18nConfig;
1174
+ isActive?: boolean;
1175
+ onActive?: () => void;
1176
+ onBack?: () => void;
1177
+ onClose?: () => void;
1178
+ }
1179
+
1180
+ function FilterSubmenuContent<T = unknown>({
1181
+ field,
1182
+ currentValues,
1183
+ isMultiSelect,
1184
+ onToggle,
1185
+ i18n,
1186
+ isActive,
1187
+ onActive,
1188
+ onBack,
1189
+ onClose,
1190
+ }: FilterSubmenuContentProps<T>) {
1191
+ const [searchInput, setSearchInput] = useState("");
1192
+ const [highlightedIndex, setHighlightedIndex] = useState(-1);
1193
+ const inputRef = useRef<HTMLInputElement>(null);
1194
+ const baseId = useId();
1195
+
1196
+ useEffect(() => {
1197
+ setHighlightedIndex(-1);
1198
+ }, [searchInput]);
1199
+
1200
+ useEffect(() => {
1201
+ if (highlightedIndex >= 0 && isActive) {
1202
+ const element = document.getElementById(
1203
+ `${baseId}-item-${highlightedIndex}`,
1204
+ );
1205
+ element?.scrollIntoView({ block: "nearest" });
1206
+ }
1207
+ }, [highlightedIndex, isActive, baseId]);
1208
+
1209
+ const filteredOptions = useMemo(() => {
1210
+ return (
1211
+ field.options?.filter((option) => {
1212
+ const isSelected = currentValues.includes(option.value);
1213
+ if (isSelected) return true;
1214
+ if (!searchInput) return true;
1215
+ return option.label.toLowerCase().includes(searchInput.toLowerCase());
1216
+ }) || []
1217
+ );
1218
+ }, [field.options, searchInput, currentValues]);
1219
+
1220
+ useEffect(() => {
1221
+ if (isActive && filteredOptions.length > 0) {
1222
+ setHighlightedIndex(0);
1223
+ }
1224
+ }, [isActive, filteredOptions.length]);
1225
+
1226
+ return (
1227
+ <div className="flex flex-col" onMouseEnter={onActive}>
1228
+ {field.searchable !== false && (
1229
+ <>
1230
+ <Input
1231
+ ref={inputRef}
1232
+ role="combobox"
1233
+ aria-autocomplete="list"
1234
+ aria-expanded={true}
1235
+ aria-haspopup="listbox"
1236
+ aria-controls={`${baseId}-listbox`}
1237
+ aria-activedescendant={
1238
+ highlightedIndex >= 0
1239
+ ? `${baseId}-item-${highlightedIndex}`
1240
+ : undefined
1241
+ }
1242
+ placeholder={i18n.placeholders.searchField(field.label || "")}
1243
+ className={cn(
1244
+ "h-8 rounded-none border-0 bg-transparent! px-2 text-sm shadow-none",
1245
+ "focus-visible:border-border focus-visible:ring-0 focus-visible:ring-offset-0",
1246
+ )}
1247
+ value={searchInput}
1248
+ onChange={(e) => setSearchInput(e.target.value)}
1249
+ onClick={(e) => e.stopPropagation()}
1250
+ onKeyDown={(e) => {
1251
+ if (e.key === "ArrowDown") {
1252
+ e.preventDefault();
1253
+ if (filteredOptions.length > 0) {
1254
+ setHighlightedIndex((prev) =>
1255
+ prev < filteredOptions.length - 1 ? prev + 1 : 0,
1256
+ );
1257
+ }
1258
+ } else if (e.key === "ArrowUp") {
1259
+ e.preventDefault();
1260
+ if (filteredOptions.length > 0) {
1261
+ setHighlightedIndex((prev) =>
1262
+ prev > 0 ? prev - 1 : filteredOptions.length - 1,
1263
+ );
1264
+ }
1265
+ } else if (e.key === "ArrowLeft") {
1266
+ e.preventDefault();
1267
+ onBack?.();
1268
+ } else if (e.key === "Enter" && highlightedIndex >= 0) {
1269
+ e.preventDefault();
1270
+ const option = filteredOptions[highlightedIndex];
1271
+ if (option) {
1272
+ onToggle(
1273
+ option.value as T,
1274
+ currentValues.includes(option.value),
1275
+ );
1276
+ if (!isMultiSelect) {
1277
+ onBack?.();
1278
+ }
1279
+ }
1280
+ } else if (e.key === "Escape") {
1281
+ e.preventDefault();
1282
+ onClose?.();
1283
+ }
1284
+ e.stopPropagation();
1285
+ }}
1286
+ />
1287
+ <DropdownMenuSeparator />
1288
+ </>
1289
+ )}
1290
+ <div className="relative flex max-h-full">
1291
+ <div
1292
+ className="flex max-h-[min(var(--radix-dropdown-menu-content-available-height),24rem)] w-full scroll-pt-2 scroll-pb-2 flex-col overscroll-contain outline-hidden"
1293
+ role="listbox"
1294
+ id={`${baseId}-listbox`}
1295
+ tabIndex={field.searchable === false ? 0 : -1}
1296
+ onKeyDown={(e) => {
1297
+ if (field.searchable === false) {
1298
+ if (e.key === "ArrowDown") {
1299
+ e.preventDefault();
1300
+ if (filteredOptions.length > 0) {
1301
+ setHighlightedIndex((prev) =>
1302
+ prev < filteredOptions.length - 1 ? prev + 1 : 0,
1303
+ );
1304
+ }
1305
+ } else if (e.key === "ArrowUp") {
1306
+ e.preventDefault();
1307
+ if (filteredOptions.length > 0) {
1308
+ setHighlightedIndex((prev) =>
1309
+ prev > 0 ? prev - 1 : filteredOptions.length - 1,
1310
+ );
1311
+ }
1312
+ } else if (e.key === "ArrowLeft") {
1313
+ e.preventDefault();
1314
+ onBack?.();
1315
+ } else if (e.key === "Enter" && highlightedIndex >= 0) {
1316
+ e.preventDefault();
1317
+ const option = filteredOptions[highlightedIndex];
1318
+ if (option) {
1319
+ onToggle(
1320
+ option.value as T,
1321
+ currentValues.includes(option.value),
1322
+ );
1323
+ if (!isMultiSelect) {
1324
+ onBack?.();
1325
+ }
1326
+ }
1327
+ } else if (e.key === "Escape") {
1328
+ e.preventDefault();
1329
+ onClose?.();
1330
+ }
1331
+ e.stopPropagation();
1332
+ }
1333
+ }}
1334
+ >
1335
+ <ScrollArea className="size-full min-h-0 **:data-[slot=scroll-area-scrollbar]:m-0 **:data-[slot=scroll-area-viewport]:h-full **:data-[slot=scroll-area-viewport]:overscroll-contain">
1336
+ {filteredOptions.length === 0 ? (
1337
+ <div className="text-muted-foreground py-2 text-center text-sm">
1338
+ {i18n.noResultsFound}
1339
+ </div>
1340
+ ) : (
1341
+ <DropdownMenuGroup>
1342
+ {filteredOptions.map((option, index) => {
1343
+ const isSelected = currentValues.includes(option.value);
1344
+ const isHighlighted = highlightedIndex === index;
1345
+ const itemId = `${baseId}-item-${index}`;
1346
+
1347
+ return (
1348
+ <DropdownMenuCheckboxItem
1349
+ key={String(option.value)}
1350
+ id={itemId}
1351
+ role="option"
1352
+ aria-selected={isHighlighted}
1353
+ data-highlighted={isHighlighted || undefined}
1354
+ onMouseEnter={() => setHighlightedIndex(index)}
1355
+ checked={isSelected}
1356
+ className={cn(
1357
+ "data-highlighted:bg-accent data-highlighted:text-accent-foreground",
1358
+ option.className,
1359
+ )}
1360
+ onSelect={(e) => {
1361
+ if (isMultiSelect) e.preventDefault();
1362
+ }}
1363
+ onCheckedChange={() =>
1364
+ onToggle(option.value as T, isSelected)
1365
+ }
1366
+ >
1367
+ {option.icon && option.icon}
1368
+ <span className="truncate">{option.label}</span>
1369
+ </DropdownMenuCheckboxItem>
1370
+ );
1371
+ })}
1372
+ </DropdownMenuGroup>
1373
+ )}
1374
+ </ScrollArea>
1375
+ </div>
1376
+ </div>
1377
+ </div>
1378
+ );
1379
+ }
1380
+
1381
+ export function Filters<T = unknown>({
1382
+ filters,
1383
+ fields,
1384
+ onChange,
1385
+ className,
1386
+ variant = "default",
1387
+ size = "default",
1388
+ radius = "default",
1389
+ i18n,
1390
+ showSearchInput = true,
1391
+ trigger,
1392
+ allowMultiple = true,
1393
+ menuPopupClassName,
1394
+ enableShortcut = false,
1395
+ shortcutKey = "f",
1396
+ shortcutLabel = "F",
1397
+ }: FiltersProps<T>) {
1398
+ const [addFilterOpen, setAddFilterOpen] = useState(false);
1399
+ const [menuSearchInput, setMenuSearchInput] = useState("");
1400
+ const [activeMenu, setActiveMenu] = useState<string>("root");
1401
+ const [openSubMenu, setOpenSubMenu] = useState<string | null>(null);
1402
+ const [highlightedIndex, setHighlightedIndex] = useState(-1);
1403
+ const [lastAddedFilterId, setLastAddedFilterId] = useState<string | null>(
1404
+ null,
1405
+ );
1406
+ const rootInputRef = useRef<HTMLInputElement>(null);
1407
+ const rootId = useId();
1408
+
1409
+ useEffect(() => {
1410
+ if (!enableShortcut) return;
1411
+
1412
+ const handleKeyDown = (e: KeyboardEvent) => {
1413
+ if (
1414
+ e.key.toLowerCase() === shortcutKey.toLowerCase() &&
1415
+ !addFilterOpen &&
1416
+ !(
1417
+ document.activeElement instanceof HTMLInputElement ||
1418
+ document.activeElement instanceof HTMLTextAreaElement
1419
+ )
1420
+ ) {
1421
+ e.preventDefault();
1422
+ setAddFilterOpen(true);
1423
+ }
1424
+ };
1425
+
1426
+ window.addEventListener("keydown", handleKeyDown);
1427
+ return () => window.removeEventListener("keydown", handleKeyDown);
1428
+ }, [enableShortcut, shortcutKey, addFilterOpen]);
1429
+
1430
+ useEffect(() => {
1431
+ setHighlightedIndex(-1);
1432
+ }, [menuSearchInput]);
1433
+
1434
+ useEffect(() => {
1435
+ if (highlightedIndex >= 0 && addFilterOpen) {
1436
+ const element = document.getElementById(
1437
+ `${rootId}-item-${highlightedIndex}`,
1438
+ );
1439
+ element?.scrollIntoView({ block: "nearest" });
1440
+ }
1441
+ }, [highlightedIndex, addFilterOpen, rootId]);
1442
+
1443
+ useEffect(() => {
1444
+ if (!addFilterOpen) {
1445
+ setOpenSubMenu(null);
1446
+ }
1447
+ }, [addFilterOpen]);
1448
+
1449
+ // Track which filter instance is being built in the current Add Filter menu session
1450
+ // Maps fieldKey -> unique filterId created during this open session
1451
+ const [sessionFilterIds, setSessionFilterIds] = useState<
1452
+ Record<string, string>
1453
+ >({});
1454
+
1455
+ useEffect(() => {
1456
+ if (lastAddedFilterId) {
1457
+ const timer = setTimeout(() => {
1458
+ setLastAddedFilterId(null);
1459
+ }, 1000);
1460
+ return () => clearTimeout(timer);
1461
+ }
1462
+ }, [lastAddedFilterId]);
1463
+
1464
+ const mergedI18n: FilterI18nConfig = {
1465
+ ...DEFAULT_I18N,
1466
+ ...i18n,
1467
+ operators: { ...DEFAULT_I18N.operators, ...i18n?.operators },
1468
+ placeholders: { ...DEFAULT_I18N.placeholders, ...i18n?.placeholders },
1469
+ validation: { ...DEFAULT_I18N.validation, ...i18n?.validation },
1470
+ };
1471
+
1472
+ const fieldsMap = useMemo(() => getFieldsMap(fields), [fields]);
1473
+
1474
+ const updateFilter = useCallback(
1475
+ (filterId: string, updates: Partial<Filter<T>>) => {
1476
+ onChange(
1477
+ filters.map((filter) => {
1478
+ if (filter.id === filterId) {
1479
+ const updatedFilter = { ...filter, ...updates };
1480
+ if (
1481
+ updates.operator === "empty" ||
1482
+ updates.operator === "not_empty"
1483
+ ) {
1484
+ updatedFilter.values = [] as T[];
1485
+ }
1486
+ return updatedFilter;
1487
+ }
1488
+ return filter;
1489
+ }),
1490
+ );
1491
+ },
1492
+ [filters, onChange],
1493
+ );
1494
+
1495
+ const removeFilter = useCallback(
1496
+ (filterId: string) => {
1497
+ onChange(filters.filter((filter) => filter.id !== filterId));
1498
+ },
1499
+ [filters, onChange],
1500
+ );
1501
+
1502
+ const addFilter = useCallback(
1503
+ (fieldKey: string) => {
1504
+ const field = fieldsMap[fieldKey];
1505
+ if (field && field.key) {
1506
+ const defaultOperator =
1507
+ field.defaultOperator ||
1508
+ (field.type === "multiselect" ? "is_any_of" : "is");
1509
+ const defaultValues: unknown[] = field.type === "text" ? [""] : [];
1510
+ const newFilter = createFilter<T>(
1511
+ fieldKey,
1512
+ defaultOperator,
1513
+ defaultValues as T[],
1514
+ );
1515
+ setLastAddedFilterId(newFilter.id);
1516
+ onChange([...filters, newFilter]);
1517
+ setAddFilterOpen(false);
1518
+ setMenuSearchInput("");
1519
+ }
1520
+ },
1521
+ [fieldsMap, filters, onChange],
1522
+ );
1523
+
1524
+ const selectableFields = useMemo(() => {
1525
+ const flatFields = flattenFields(fields);
1526
+ return flatFields.filter((field) => {
1527
+ if (!field.key || field.type === "separator") return false;
1528
+ if (allowMultiple) return true;
1529
+ return !filters.some((filter) => filter.field === field.key);
1530
+ });
1531
+ }, [fields, filters, allowMultiple]);
1532
+
1533
+ const filteredFields = useMemo(() => {
1534
+ return selectableFields.filter(
1535
+ (f) =>
1536
+ !menuSearchInput ||
1537
+ f.label?.toLowerCase().includes(menuSearchInput.toLowerCase()),
1538
+ );
1539
+ }, [selectableFields, menuSearchInput]);
1540
+
1541
+ useEffect(() => {
1542
+ if (addFilterOpen && filteredFields.length > 0) {
1543
+ setHighlightedIndex(0);
1544
+ }
1545
+ }, [addFilterOpen, filteredFields.length]);
1546
+
1547
+ return (
1548
+ <FilterContext.Provider
1549
+ value={{
1550
+ variant,
1551
+ size,
1552
+ radius,
1553
+ i18n: mergedI18n,
1554
+ className,
1555
+ trigger,
1556
+ allowMultiple,
1557
+ }}
1558
+ >
1559
+ <div
1560
+ className={cn(filtersContainerVariants({ variant, size }), className)}
1561
+ >
1562
+ {selectableFields.length > 0 && (
1563
+ <DropdownMenu
1564
+ open={addFilterOpen}
1565
+ onOpenChange={(open) => {
1566
+ setAddFilterOpen(open);
1567
+ if (!open) {
1568
+ setMenuSearchInput("");
1569
+ setSessionFilterIds({});
1570
+ } else {
1571
+ setActiveMenu("root");
1572
+ }
1573
+ }}
1574
+ >
1575
+ <DropdownMenuTrigger asChild>
1576
+ {trigger || (
1577
+ <Button variant="outline">
1578
+ <HugeiconsIcon icon={Plus01Icon} strokeWidth={2} />
1579
+ {mergedI18n.addFilter}
1580
+ </Button>
1581
+ )}
1582
+ </DropdownMenuTrigger>
1583
+ <DropdownMenuContent
1584
+ className={cn("w-[220px]", menuPopupClassName)}
1585
+ align="start"
1586
+ >
1587
+ {showSearchInput && (
1588
+ <>
1589
+ <div className="relative">
1590
+ <Input
1591
+ ref={rootInputRef}
1592
+ role="combobox"
1593
+ aria-controls={`${rootId}-listbox`}
1594
+ aria-activedescendant={
1595
+ highlightedIndex >= 0
1596
+ ? `${rootId}-item-${highlightedIndex}`
1597
+ : undefined
1598
+ }
1599
+ placeholder={mergedI18n.searchFields}
1600
+ className={cn(
1601
+ "h-8 rounded-none border-0 bg-transparent! px-2 text-sm shadow-none",
1602
+ "focus-visible:border-border focus-visible:ring-0 focus-visible:ring-offset-0",
1603
+ )}
1604
+ value={menuSearchInput}
1605
+ onChange={(e) => setMenuSearchInput(e.target.value)}
1606
+ onClick={(e) => e.stopPropagation()}
1607
+ onKeyDown={(e) => {
1608
+ if (e.key === "ArrowDown") {
1609
+ e.preventDefault();
1610
+ if (filteredFields.length > 0) {
1611
+ setHighlightedIndex((prev) =>
1612
+ prev < filteredFields.length - 1 ? prev + 1 : 0,
1613
+ );
1614
+ }
1615
+ } else if (e.key === "ArrowUp") {
1616
+ e.preventDefault();
1617
+ if (filteredFields.length > 0) {
1618
+ setHighlightedIndex((prev) =>
1619
+ prev > 0 ? prev - 1 : filteredFields.length - 1,
1620
+ );
1621
+ }
1622
+ } else if (
1623
+ (e.key === "ArrowRight" || e.key === "ArrowLeft") &&
1624
+ highlightedIndex >= 0
1625
+ ) {
1626
+ const field = filteredFields[highlightedIndex];
1627
+ const hasSubMenu =
1628
+ field &&
1629
+ (field.type === "select" ||
1630
+ field.type === "multiselect") &&
1631
+ field.options?.length;
1632
+
1633
+ if (e.key === "ArrowRight" && hasSubMenu) {
1634
+ e.preventDefault();
1635
+ setOpenSubMenu(field.key || null);
1636
+ setActiveMenu(field.key || "root");
1637
+ } else if (e.key === "ArrowLeft") {
1638
+ e.preventDefault();
1639
+ if (openSubMenu) {
1640
+ setOpenSubMenu(null);
1641
+ setActiveMenu("root");
1642
+ }
1643
+ }
1644
+ } else if (e.key === "Enter" && highlightedIndex >= 0) {
1645
+ e.preventDefault();
1646
+ const field = filteredFields[highlightedIndex];
1647
+ if (field.key) {
1648
+ const hasSubMenu =
1649
+ (field.type === "select" ||
1650
+ field.type === "multiselect") &&
1651
+ field.options?.length;
1652
+ if (!hasSubMenu) {
1653
+ addFilter(field.key);
1654
+ } else {
1655
+ if (openSubMenu === field.key) {
1656
+ setOpenSubMenu(null);
1657
+ setActiveMenu("root");
1658
+ } else {
1659
+ setOpenSubMenu(field.key);
1660
+ setActiveMenu(field.key);
1661
+ }
1662
+ }
1663
+ }
1664
+ } else if (e.key === "Escape") {
1665
+ setAddFilterOpen(false);
1666
+ }
1667
+ e.stopPropagation();
1668
+ }}
1669
+ />
1670
+ {enableShortcut && shortcutLabel && (
1671
+ <Kbd className="bg-background absolute top-1/2 right-2 -translate-y-1/2 border">
1672
+ {shortcutLabel}
1673
+ </Kbd>
1674
+ )}
1675
+ </div>
1676
+ <DropdownMenuSeparator />
1677
+ </>
1678
+ )}
1679
+
1680
+ <div className="relative flex max-h-full">
1681
+ <div
1682
+ className="flex max-h-[min(var(--radix-dropdown-menu-content-available-height),24rem)] w-full scroll-pt-2 scroll-pb-2 flex-col overscroll-contain"
1683
+ role="listbox"
1684
+ id={`${rootId}-listbox`}
1685
+ >
1686
+ <ScrollArea className="**:data-[slot=scroll-area-scrollbar]:m-0">
1687
+ {(() => {
1688
+ if (filteredFields.length === 0) {
1689
+ return (
1690
+ <div className="text-muted-foreground py-2 text-center text-sm">
1691
+ {mergedI18n.noFieldsFound}
1692
+ </div>
1693
+ );
1694
+ }
1695
+
1696
+ return filteredFields.map((field, index) => {
1697
+ const isHighlighted = highlightedIndex === index;
1698
+ const itemId = `${rootId}-item-${index}`;
1699
+ const hasSubMenu =
1700
+ (field.type === "select" ||
1701
+ field.type === "multiselect") &&
1702
+ field.options?.length;
1703
+
1704
+ if (hasSubMenu) {
1705
+ const isMultiSelect = field.type === "multiselect";
1706
+ const fieldKey = field.key as string;
1707
+ const sessionFilterId = sessionFilterIds[fieldKey];
1708
+ const sessionFilter = sessionFilterId
1709
+ ? filters.find((f) => f.id === sessionFilterId)
1710
+ : null;
1711
+ const currentValues = sessionFilter?.values || [];
1712
+
1713
+ return (
1714
+ <DropdownMenuSub
1715
+ key={fieldKey}
1716
+ open={openSubMenu === fieldKey}
1717
+ onOpenChange={(open) => {
1718
+ if (open) {
1719
+ setOpenSubMenu((prev) =>
1720
+ prev === fieldKey ? prev : fieldKey,
1721
+ );
1722
+ } else {
1723
+ if (openSubMenu === fieldKey) {
1724
+ setOpenSubMenu(null);
1725
+ setActiveMenu("root");
1726
+ }
1727
+ }
1728
+ }}
1729
+ >
1730
+ <DropdownMenuSubTrigger
1731
+ id={itemId}
1732
+ role="option"
1733
+ aria-selected={isHighlighted}
1734
+ data-highlighted={isHighlighted || undefined}
1735
+ onMouseEnter={() => setHighlightedIndex(index)}
1736
+ className="data-[state=open]:bg-accent data-[state=open]:text-accent-foreground data-highlighted:bg-accent data-highlighted:text-accent-foreground"
1737
+ >
1738
+ {field.icon}
1739
+ <span>{field.label}</span>
1740
+ </DropdownMenuSubTrigger>
1741
+ <DropdownMenuSubContent className="w-[200px]">
1742
+ <FilterSubmenuContent
1743
+ field={field}
1744
+ currentValues={currentValues}
1745
+ isMultiSelect={isMultiSelect}
1746
+ i18n={mergedI18n}
1747
+ isActive={activeMenu === fieldKey}
1748
+ onActive={() => {
1749
+ if (field.searchable !== false) {
1750
+ setActiveMenu(fieldKey);
1751
+ }
1752
+ }}
1753
+ onBack={() => {
1754
+ setOpenSubMenu(null);
1755
+ setActiveMenu("root");
1756
+ }}
1757
+ onClose={() => setAddFilterOpen(false)}
1758
+ onToggle={(value, isSelected) => {
1759
+ if (isMultiSelect) {
1760
+ const nextValues = isSelected
1761
+ ? (currentValues.filter(
1762
+ (v) => v !== value,
1763
+ ) as T[])
1764
+ : ([...currentValues, value] as T[]);
1765
+
1766
+ if (sessionFilter) {
1767
+ if (nextValues.length === 0) {
1768
+ onChange(
1769
+ filters.filter(
1770
+ (f) => f.id !== sessionFilter.id,
1771
+ ),
1772
+ );
1773
+ setSessionFilterIds((prev) => ({
1774
+ ...prev,
1775
+ [fieldKey]: "",
1776
+ }));
1777
+ } else {
1778
+ onChange(
1779
+ filters.map((f) =>
1780
+ f.id === sessionFilter.id
1781
+ ? { ...f, values: nextValues }
1782
+ : f,
1783
+ ),
1784
+ );
1785
+ }
1786
+ } else {
1787
+ const newFilter = createFilter<T>(
1788
+ fieldKey,
1789
+ field.defaultOperator || "is_any_of",
1790
+ nextValues,
1791
+ );
1792
+ onChange([...filters, newFilter]);
1793
+ setSessionFilterIds((prev) => ({
1794
+ ...prev,
1795
+ [fieldKey]: newFilter.id,
1796
+ }));
1797
+ }
1798
+ } else {
1799
+ const newFilter = createFilter<T>(
1800
+ fieldKey,
1801
+ field.defaultOperator || "is",
1802
+ [value] as T[],
1803
+ );
1804
+ setLastAddedFilterId(newFilter.id);
1805
+ onChange([...filters, newFilter]);
1806
+ setAddFilterOpen(false);
1807
+ }
1808
+ }}
1809
+ />
1810
+ </DropdownMenuSubContent>
1811
+ </DropdownMenuSub>
1812
+ );
1813
+ }
1814
+
1815
+ return (
1816
+ <DropdownMenuItem
1817
+ key={field.key}
1818
+ id={itemId}
1819
+ role="option"
1820
+ aria-selected={isHighlighted}
1821
+ data-highlighted={isHighlighted || undefined}
1822
+ onMouseEnter={() => setHighlightedIndex(index)}
1823
+ onClick={() => field.key && addFilter(field.key)}
1824
+ className="data-highlighted:bg-accent data-highlighted:text-accent-foreground"
1825
+ >
1826
+ {field.icon}
1827
+ <span>{field.label}</span>
1828
+ </DropdownMenuItem>
1829
+ );
1830
+ });
1831
+ })()}
1832
+ </ScrollArea>
1833
+ </div>
1834
+ </div>
1835
+ </DropdownMenuContent>
1836
+ </DropdownMenu>
1837
+ )}
1838
+
1839
+ {filters.map((filter) => {
1840
+ const field = fieldsMap[filter.field];
1841
+ if (!field) return null;
1842
+ return (
1843
+ <ButtonGroup key={filter.id}>
1844
+ <ButtonGroupText className="">
1845
+ {field.icon && field.icon}
1846
+ {field.label}
1847
+ </ButtonGroupText>
1848
+ <FilterOperatorDropdown<T>
1849
+ field={field}
1850
+ operator={filter.operator}
1851
+ values={filter.values}
1852
+ onChange={(operator) => updateFilter(filter.id, { operator })}
1853
+ />
1854
+ <FilterValueSelector<T>
1855
+ field={field}
1856
+ values={filter.values}
1857
+ operator={filter.operator}
1858
+ onChange={(values) => updateFilter(filter.id, { values })}
1859
+ autoFocus={filter.id === lastAddedFilterId}
1860
+ />
1861
+ <FilterRemoveButton onClick={() => removeFilter(filter.id)} />
1862
+ </ButtonGroup>
1863
+ );
1864
+ })}
1865
+ </div>
1866
+ </FilterContext.Provider>
1867
+ );
1868
+ }
1869
+
1870
+ export const createFilter = <T = unknown,>(
1871
+ field: string,
1872
+ operator?: string,
1873
+ values: T[] = [],
1874
+ ): Filter<T> => ({
1875
+ id: `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`,
1876
+ field,
1877
+ operator: operator || "is",
1878
+ values,
1879
+ });
1880
+
1881
+ export const createFilterGroup = <T = unknown,>(
1882
+ id: string,
1883
+ label: string,
1884
+ fields: FilterFieldConfig<T>[],
1885
+ initialFilters: Filter<T>[] = [],
1886
+ ): FilterGroup<T> => ({
1887
+ id,
1888
+ label,
1889
+ filters: initialFilters,
1890
+ fields,
1891
+ });