@hiroleague/taskmanager 0.0.2 → 0.0.4

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 (179) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/architecture-YZFGNWBL-DoE0KxgG.js +1 -0
  3. package/dist/assets/architectureDiagram-Q4EWVU46-DeuBhy7X.js +36 -0
  4. package/dist/assets/{blockDiagram-DXYQGD6D-DQzEOPT2.js → blockDiagram-DXYQGD6D-BDBy9ns9.js} +1 -1
  5. package/dist/assets/{c4Diagram-AHTNJAMY-B2Yfcwbo.js → c4Diagram-AHTNJAMY-CpqJj_8a.js} +1 -1
  6. package/dist/assets/channel-PHRyjspt.js +1 -0
  7. package/dist/assets/{chunk-2KRD3SAO-C2e-_49I.js → chunk-2KRD3SAO-DEpUsxdZ.js} +1 -1
  8. package/dist/assets/chunk-336JU56O-BGQvSwLk.js +2 -0
  9. package/dist/assets/chunk-426QAEUC-Cl9nQN9c.js +1 -0
  10. package/dist/assets/{chunk-4TB4RGXK-AZq3s1Dh.js → chunk-4TB4RGXK-Dq7aiIrZ.js} +2 -2
  11. package/dist/assets/{chunk-5FUZZQ4R-XEga0hMC.js → chunk-5FUZZQ4R-B_HuuUjf.js} +1 -1
  12. package/dist/assets/{chunk-5PVQY5BW-BrmXs2Gs.js → chunk-5PVQY5BW-cGfZCZGU.js} +2 -2
  13. package/dist/assets/{chunk-67CJDMHE-B1-M78qu.js → chunk-67CJDMHE-BMYAVZfw.js} +1 -1
  14. package/dist/assets/{chunk-7N4EOEYR-D7mYFpz-.js → chunk-7N4EOEYR-Ct-EY7Nc.js} +1 -1
  15. package/dist/assets/{chunk-AA7GKIK3-VWI9k39i.js → chunk-AA7GKIK3-Bd4HFpeo.js} +1 -1
  16. package/dist/assets/{chunk-CIAEETIT-hnu4zamm.js → chunk-CIAEETIT-CrFUkPMT.js} +1 -1
  17. package/dist/assets/{chunk-EDXVE4YY-DxUqDyxy.js → chunk-EDXVE4YY-DMDyt0NF.js} +1 -1
  18. package/dist/assets/{chunk-ENJZ2VHE-BgZKYo1l.js → chunk-ENJZ2VHE-DrWzOrpd.js} +1 -1
  19. package/dist/assets/{chunk-FOC6F5B3-BJsh9nO9.js → chunk-FOC6F5B3-Bemzq96j.js} +1 -1
  20. package/dist/assets/{chunk-ICPOFSXX-BNR1V8rT.js → chunk-ICPOFSXX-DkUVjrLw.js} +5 -5
  21. package/dist/assets/{chunk-K5T4RW27-BLIPdXaZ.js → chunk-K5T4RW27-ALKIf000.js} +5 -5
  22. package/dist/assets/{chunk-KGLVRYIC-DvaW2TkT.js → chunk-KGLVRYIC-Bg6HNTZ-.js} +1 -1
  23. package/dist/assets/{chunk-LIHQZDEY-CUsM0M11.js → chunk-LIHQZDEY-DeyGongE.js} +1 -1
  24. package/dist/assets/{chunk-ORNJ4GCN-CfluNV0_.js → chunk-ORNJ4GCN-Bx83s1bJ.js} +1 -1
  25. package/dist/assets/{chunk-OYMX7WX6-CkWzw4JX.js → chunk-OYMX7WX6-BqRUtRpL.js} +1 -1
  26. package/dist/assets/{chunk-U2HBQHQK-DTJPeU7W.js → chunk-U2HBQHQK-DogcerR6.js} +1 -1
  27. package/dist/assets/{chunk-X2U36JSP-CrTnmMqG.js → chunk-X2U36JSP-CwVWdmZV.js} +1 -1
  28. package/dist/assets/chunk-XPW4576I-DQpNCogT.js +32 -0
  29. package/dist/assets/{chunk-YZCP3GAM-9wq0QKUn.js → chunk-YZCP3GAM-crQSbji9.js} +1 -1
  30. package/dist/assets/{chunk-ZZ45TVLE-D3I1kLlo.js → chunk-ZZ45TVLE-Bk1S1YtS.js} +1 -1
  31. package/dist/assets/classDiagram-6PBFFD2Q-B_TabGaU.js +1 -0
  32. package/dist/assets/classDiagram-v2-HSJHXN6E-CGnZkUWw.js +1 -0
  33. package/dist/assets/clone-D4ka472w.js +1 -0
  34. package/dist/assets/{cose-bilkent-S5V4N54A-BygGvZGW.js → cose-bilkent-S5V4N54A-RBTHUit8.js} +1 -1
  35. package/dist/assets/cytoscape.esm-BGJwlmkf.js +321 -0
  36. package/dist/assets/dagre-B32eYLtm.js +1 -0
  37. package/dist/assets/{dagre-KV5264BT-lveZDhBf.js → dagre-KV5264BT-nX7tuXXn.js} +1 -1
  38. package/dist/assets/diagram-5BDNPKRD-DRxMXlQr.js +10 -0
  39. package/dist/assets/diagram-G4DWMVQ6-CoojevGm.js +24 -0
  40. package/dist/assets/diagram-MMDJMWI5-CWtJyfVW.js +43 -0
  41. package/dist/assets/diagram-TYMM5635-CsDJC4Hq.js +24 -0
  42. package/dist/assets/{erDiagram-SMLLAGMA-dx09stuy.js → erDiagram-SMLLAGMA-Cf7Xtd9A.js} +2 -2
  43. package/dist/assets/{flatten-B2BZ0pzY.js → flatten-CYX_pHZ7.js} +1 -1
  44. package/dist/assets/{flowDiagram-DWJPFMVM-CJi2WISS.js → flowDiagram-DWJPFMVM-DQaeR16a.js} +3 -3
  45. package/dist/assets/{ganttDiagram-T4ZO3ILL-OCTvbRxF.js → ganttDiagram-T4ZO3ILL-8EIcztcH.js} +1 -1
  46. package/dist/assets/gitGraph-7Q5UKJZL-BH9A1SAZ.js +1 -0
  47. package/dist/assets/{gitGraphDiagram-UUTBAWPF-Bjj94M12.js → gitGraphDiagram-UUTBAWPF-DO9ODqYw.js} +1 -1
  48. package/dist/assets/graphlib-bPBqlJKT.js +1 -0
  49. package/dist/assets/identity-Me9aart9.js +1 -0
  50. package/dist/assets/index-BpzHnKdP.css +1 -0
  51. package/dist/assets/index-DmNErTAP.js +273 -0
  52. package/dist/assets/info-OMHHGYJF-BvKR-zWh.js +1 -0
  53. package/dist/assets/infoDiagram-42DDH7IO-pRTXCm5C.js +2 -0
  54. package/dist/assets/isEmpty-Cu0k-j1j.js +1 -0
  55. package/dist/assets/{ishikawaDiagram-UXIWVN3A-Cnc1bwBo.js → ishikawaDiagram-UXIWVN3A-BP2YE5QI.js} +2 -2
  56. package/dist/assets/{journeyDiagram-VCZTEJTY-BkMxoaPq.js → journeyDiagram-VCZTEJTY-B3l2juoL.js} +1 -1
  57. package/dist/assets/{kanban-definition-6JOO6SKY-CwHbIze0.js → kanban-definition-6JOO6SKY-BpIpEOZZ.js} +4 -4
  58. package/dist/assets/{line-DNzQATGr.js → line-otOkzGl8.js} +1 -1
  59. package/dist/assets/mermaid-parser.core-xWsW24Gq.js +4 -0
  60. package/dist/assets/{mindmap-definition-QFDTVHPH-DswAJiEd.js → mindmap-definition-QFDTVHPH-B9khyC7X.js} +3 -3
  61. package/dist/assets/packet-4T2RLAQJ-D8Dw3nmf.js +1 -0
  62. package/dist/assets/pie-ZZUOXDRM-ZghowlAE.js +1 -0
  63. package/dist/assets/{pieDiagram-DEJITSTG-DgQTCddl.js → pieDiagram-DEJITSTG-v32hL3i7.js} +1 -1
  64. package/dist/assets/{quadrantDiagram-34T5L4WZ-c0iZxo2I.js → quadrantDiagram-34T5L4WZ-DIL3GDFt.js} +1 -1
  65. package/dist/assets/radar-PYXPWWZC-D-PK3JOd.js +1 -0
  66. package/dist/assets/reduce-CImcgAcU.js +1 -0
  67. package/dist/assets/{requirementDiagram-MS252O5E-D1moa23Z.js → requirementDiagram-MS252O5E-D8os2-4y.js} +2 -2
  68. package/dist/assets/{sankeyDiagram-XADWPNL6-woJZoQ58.js → sankeyDiagram-XADWPNL6-BV70D4l5.js} +1 -1
  69. package/dist/assets/{sequenceDiagram-FGHM5R23-Dvhj7HGn.js → sequenceDiagram-FGHM5R23-Cwu8hQW1.js} +1 -1
  70. package/dist/assets/stateDiagram-FHFEXIEX-oYUWv7Fb.js +1 -0
  71. package/dist/assets/stateDiagram-v2-QKLJ7IA2-CFUTpFu-.js +1 -0
  72. package/dist/assets/{timeline-definition-GMOUNBTQ-z-IncVmK.js → timeline-definition-GMOUNBTQ-CxSdKxpL.js} +1 -1
  73. package/dist/assets/treeView-SZITEDCU-uVgaJQzG.js +1 -0
  74. package/dist/assets/treemap-W4RFUUIX-Dcad_9AN.js +1 -0
  75. package/dist/assets/vennDiagram-DHZGUBPP-D4wgD7QI.js +34 -0
  76. package/dist/assets/wardley-RL74JXVD-CFXrK8mx.js +1 -0
  77. package/dist/assets/{wardleyDiagram-NUSXRM2D-D-kouujI.js → wardleyDiagram-NUSXRM2D-5Q201ea3.js} +1 -1
  78. package/dist/assets/{xychartDiagram-5P7HB3ND-D1lnM0pL.js → xychartDiagram-5P7HB3ND-BPZv_axd.js} +3 -3
  79. package/dist/index.html +17 -13
  80. package/package.json +2 -4
  81. package/skills/hiro-task-manager-cli/SKILL.md +6 -4
  82. package/skills/hiro-task-manager-cli/reference/cli-access-policy.md +1 -0
  83. package/skills/hiro-task-manager-cli/reference/releases.md +14 -0
  84. package/src/cli/bootstrap/launcher.ts +19 -5
  85. package/src/cli/bootstrap/program.test.ts +46 -0
  86. package/src/cli/bootstrap/program.ts +50 -1
  87. package/src/cli/commands/query.ts +56 -56
  88. package/src/cli/commands/releases.ts +22 -0
  89. package/src/cli/handlers/boards.test.ts +669 -669
  90. package/src/cli/handlers/cli-wiring.test.ts +38 -1
  91. package/src/cli/handlers/releases.ts +15 -0
  92. package/src/cli/handlers/search.test.ts +374 -374
  93. package/src/cli/handlers/search.ts +17 -17
  94. package/src/cli/lib/cli-http-errors.test.ts +85 -85
  95. package/src/cli/lib/launcherUi.test.ts +74 -0
  96. package/src/cli/lib/launcherUi.ts +47 -0
  97. package/src/cli/lib/write/releases.ts +64 -1
  98. package/src/cli/lib/write-result.test.ts +3 -0
  99. package/src/cli/lib/write-result.ts +3 -0
  100. package/src/cli/lib/writeCommands.breadth.test.ts +143 -0
  101. package/src/cli/lib/writeCommands.ts +1 -0
  102. package/src/cli/subprocess.real-stack.test.ts +625 -611
  103. package/src/cli/subprocess.smoke.test.ts +954 -954
  104. package/src/client/api/useBoardChangeStream.ts +421 -168
  105. package/src/client/api/useBoardIndexStream.ts +35 -0
  106. package/src/client/components/board/BoardStatsChips.tsx +233 -233
  107. package/src/client/components/board/BoardStatsContext.tsx +41 -41
  108. package/src/client/components/board/boardHeaderButtonStyles.ts +38 -38
  109. package/src/client/components/board/shortcuts/useBoardShortcutKeydown.ts +49 -49
  110. package/src/client/components/board/useBoardCanvasPanScroll.ts +108 -108
  111. package/src/client/components/board/useBoardTaskContainerDroppableReact.ts +33 -33
  112. package/src/client/components/board/useBoardTaskSortableReact.ts +26 -26
  113. package/src/client/components/layout/AppShell.tsx +5 -2
  114. package/src/client/components/layout/NotificationToasts.tsx +38 -1
  115. package/src/client/components/multi-select.tsx +1206 -1206
  116. package/src/client/components/routing/BoardPage.tsx +20 -20
  117. package/src/client/components/routing/NavigationRegistrar.tsx +13 -13
  118. package/src/client/components/task/TaskCard.tsx +643 -643
  119. package/src/client/components/ui/badge.tsx +49 -49
  120. package/src/client/components/ui/button.tsx +65 -65
  121. package/src/client/components/ui/command.tsx +193 -193
  122. package/src/client/components/ui/dialog.tsx +163 -163
  123. package/src/client/components/ui/input-group.tsx +155 -155
  124. package/src/client/components/ui/input.tsx +19 -19
  125. package/src/client/components/ui/popover.tsx +87 -87
  126. package/src/client/components/ui/separator.tsx +28 -28
  127. package/src/client/components/ui/textarea.tsx +18 -18
  128. package/src/client/index.css +248 -248
  129. package/src/client/lib/appNavigate.ts +16 -16
  130. package/src/client/lib/taskCardDate.ts +111 -111
  131. package/src/client/lib/utils.ts +6 -6
  132. package/src/client/store/notificationUi.ts +14 -0
  133. package/src/server/auth.ts +351 -351
  134. package/src/server/events.ts +31 -4
  135. package/src/server/migrations/registry.ts +43 -43
  136. package/src/server/notificationEvents.ts +8 -1
  137. package/src/server/routes/boards.ts +15 -1
  138. package/src/server/routes/trash.ts +6 -1
  139. package/src/shared/boardEvents.ts +6 -0
  140. package/src/shared/runtimeConfig.ts +256 -256
  141. package/src/shared/skillsInstall.ts +2 -3
  142. package/dist/assets/architecture-YZFGNWBL-C1MoQeSs.js +0 -1
  143. package/dist/assets/architectureDiagram-Q4EWVU46-DUEfvDBu.js +0 -36
  144. package/dist/assets/channel-yBmN_ln0.js +0 -1
  145. package/dist/assets/classDiagram-6PBFFD2Q-Dx_f-9b7.js +0 -1
  146. package/dist/assets/classDiagram-v2-HSJHXN6E-CSfvZ-nt.js +0 -1
  147. package/dist/assets/clone-CXokakwV.js +0 -1
  148. package/dist/assets/cytoscape.esm-BIYWHPG0.js +0 -321
  149. package/dist/assets/dagre-Do0eD9eI.js +0 -1
  150. package/dist/assets/diagram-5BDNPKRD-Dq5yM_uY.js +0 -10
  151. package/dist/assets/diagram-G4DWMVQ6-D-SYOmKm.js +0 -24
  152. package/dist/assets/diagram-MMDJMWI5-lU5t9BZA.js +0 -43
  153. package/dist/assets/diagram-TYMM5635-6tfUbY3R.js +0 -24
  154. package/dist/assets/gitGraph-7Q5UKJZL-BXTuQaDM.js +0 -1
  155. package/dist/assets/graphlib-BIlXYGdM.js +0 -1
  156. package/dist/assets/identity-D4WOnl_h.js +0 -1
  157. package/dist/assets/index-CZZuue3D.js +0 -304
  158. package/dist/assets/index-hMFTu7sr.css +0 -1
  159. package/dist/assets/info-OMHHGYJF-BeeKt8-X.js +0 -1
  160. package/dist/assets/infoDiagram-42DDH7IO-wq_opQKO.js +0 -2
  161. package/dist/assets/mermaid-parser.core-DrLhKJ48.js +0 -4
  162. package/dist/assets/packet-4T2RLAQJ-DQ-H9_jd.js +0 -1
  163. package/dist/assets/pie-ZZUOXDRM-BSj0Jsyj.js +0 -1
  164. package/dist/assets/radar-PYXPWWZC-B7-oRPFL.js +0 -1
  165. package/dist/assets/reduce-Uumu9GdR.js +0 -1
  166. package/dist/assets/stateDiagram-FHFEXIEX-Dx5CjenB.js +0 -1
  167. package/dist/assets/stateDiagram-v2-QKLJ7IA2-C_PkrTdc.js +0 -1
  168. package/dist/assets/treeView-SZITEDCU-CFXle9Az.js +0 -1
  169. package/dist/assets/treemap-W4RFUUIX-CAW3vWh8.js +0 -1
  170. package/dist/assets/vennDiagram-DHZGUBPP-CT1ehozU.js +0 -34
  171. package/dist/assets/wardley-RL74JXVD-7q3ju4kc.js +0 -1
  172. package/scripts/postinstall-message.mjs +0 -160
  173. /package/dist/assets/{chunk-4BX2VUAB-ean5NKtU.js → chunk-4BX2VUAB-C70mcfQR.js} +0 -0
  174. /package/dist/assets/{chunk-55IACEB6-CvSRyJqy.js → chunk-55IACEB6-CWfnqcLM.js} +0 -0
  175. /package/dist/assets/{chunk-BSJP7CBP-D8kBlJsf.js → chunk-BSJP7CBP-B0LrXV9y.js} +0 -0
  176. /package/dist/assets/{chunk-FMBD7UC4-DrNhFt1N.js → chunk-FMBD7UC4-_mV71Mwu.js} +0 -0
  177. /package/dist/assets/{chunk-QZHKN3VN-Csp3OYJY.js → chunk-QZHKN3VN-t2nrsegL.js} +0 -0
  178. /package/dist/assets/{katex-8mXVa4k3.js → katex-B2dtGfSp.js} +0 -0
  179. /package/dist/assets/{rough.esm-DtEqI08j.js → rough.esm-DEh6Frf9.js} +0 -0
@@ -1,1206 +1,1206 @@
1
- import * as React from "react";
2
- import { cva, type VariantProps } from "class-variance-authority";
3
- import {
4
- CheckIcon,
5
- XCircle,
6
- ChevronDown,
7
- XIcon,
8
- WandSparkles,
9
- } from "lucide-react";
10
-
11
- import { cn } from "@/lib/utils";
12
- import { Separator } from "@/components/ui/separator";
13
- import { Button } from "@/components/ui/button";
14
- import { Badge } from "@/components/ui/badge";
15
- import {
16
- Popover,
17
- PopoverContent,
18
- PopoverTrigger,
19
- } from "@/components/ui/popover";
20
- import {
21
- Command,
22
- CommandEmpty,
23
- CommandGroup,
24
- CommandInput,
25
- CommandItem,
26
- CommandList,
27
- CommandSeparator,
28
- } from "@/components/ui/command";
29
-
30
- /**
31
- * Animation types and configurations
32
- */
33
- export interface AnimationConfig {
34
- /** Badge animation type */
35
- badgeAnimation?: "bounce" | "pulse" | "wiggle" | "fade" | "slide" | "none";
36
- /** Popover animation type */
37
- popoverAnimation?: "scale" | "slide" | "fade" | "flip" | "none";
38
- /** Option hover animation type */
39
- optionHoverAnimation?: "highlight" | "scale" | "glow" | "none";
40
- /** Animation duration in seconds */
41
- duration?: number;
42
- /** Animation delay in seconds */
43
- delay?: number;
44
- }
45
-
46
- /**
47
- * Variants for the multi-select component to handle different styles.
48
- * Uses class-variance-authority (cva) to define different styles based on "variant" prop.
49
- */
50
- const multiSelectVariants = cva("m-1 transition-all duration-300 ease-in-out", {
51
- variants: {
52
- variant: {
53
- default: "border-foreground/10 text-foreground bg-card hover:bg-card/80",
54
- secondary:
55
- "border-foreground/10 bg-secondary text-secondary-foreground hover:bg-secondary/80",
56
- destructive:
57
- "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
58
- inverted: "inverted",
59
- },
60
- badgeAnimation: {
61
- bounce: "hover:-translate-y-1 hover:scale-110",
62
- pulse: "hover:animate-pulse",
63
- wiggle: "hover:animate-wiggle",
64
- fade: "hover:opacity-80",
65
- slide: "hover:translate-x-1",
66
- none: "",
67
- },
68
- },
69
- defaultVariants: {
70
- variant: "default",
71
- badgeAnimation: "bounce",
72
- },
73
- });
74
-
75
- /**
76
- * Option interface for MultiSelect component
77
- */
78
- interface MultiSelectOption {
79
- /** The text to display for the option. */
80
- label: string;
81
- /** The unique value associated with the option. */
82
- value: string;
83
- /** Optional icon component to display alongside the option. */
84
- icon?: React.ComponentType<{ className?: string }>;
85
- /** Whether this option is disabled */
86
- disabled?: boolean;
87
- /** Custom styling for the option */
88
- style?: {
89
- /** Custom badge color */
90
- badgeColor?: string;
91
- /** Custom icon color */
92
- iconColor?: string;
93
- /** Gradient background for badge */
94
- gradient?: string;
95
- };
96
- }
97
-
98
- /**
99
- * Group interface for organizing options
100
- */
101
- interface MultiSelectGroup {
102
- /** Group heading */
103
- heading: string;
104
- /** Options in this group */
105
- options: MultiSelectOption[];
106
- }
107
-
108
- /**
109
- * Props for MultiSelect component
110
- */
111
- interface MultiSelectProps
112
- extends Omit<
113
- React.ButtonHTMLAttributes<HTMLButtonElement>,
114
- "animationConfig"
115
- >,
116
- VariantProps<typeof multiSelectVariants> {
117
- /**
118
- * An array of option objects or groups to be displayed in the multi-select component.
119
- */
120
- options: MultiSelectOption[] | MultiSelectGroup[];
121
- /**
122
- * Callback function triggered when the selected values change.
123
- * Receives an array of the new selected values.
124
- */
125
- onValueChange: (value: string[]) => void;
126
-
127
- /** The default selected values when the component mounts. */
128
- defaultValue?: string[];
129
-
130
- /**
131
- * Placeholder text to be displayed when no values are selected.
132
- * Optional, defaults to "Select options".
133
- */
134
- placeholder?: string;
135
-
136
- /**
137
- * Animation duration in seconds for the visual effects (e.g., bouncing badges).
138
- * Optional, defaults to 0 (no animation).
139
- */
140
- animation?: number;
141
-
142
- /**
143
- * Advanced animation configuration for different component parts.
144
- * Optional, allows fine-tuning of various animation effects.
145
- */
146
- animationConfig?: AnimationConfig;
147
-
148
- /**
149
- * Maximum number of items to display. Extra selected items will be summarized.
150
- * Optional, defaults to 3.
151
- */
152
- maxCount?: number;
153
-
154
- /**
155
- * The modality of the popover. When set to true, interaction with outside elements
156
- * will be disabled and only popover content will be visible to screen readers.
157
- * Optional, defaults to false.
158
- */
159
- modalPopover?: boolean;
160
-
161
- /**
162
- * If true, renders the multi-select component as a child of another component.
163
- * Optional, defaults to false.
164
- */
165
- asChild?: boolean;
166
-
167
- /**
168
- * Additional class names to apply custom styles to the multi-select component.
169
- * Optional, can be used to add custom styles.
170
- */
171
- className?: string;
172
-
173
- /**
174
- * If true, disables the select all functionality.
175
- * Optional, defaults to false.
176
- */
177
- hideSelectAll?: boolean;
178
-
179
- /**
180
- * If true, shows search functionality in the popover.
181
- * If false, hides the search input completely.
182
- * Optional, defaults to true.
183
- */
184
- searchable?: boolean;
185
-
186
- /**
187
- * Custom empty state message when no options match search.
188
- * Optional, defaults to "No results found."
189
- */
190
- emptyIndicator?: React.ReactNode;
191
-
192
- /**
193
- * If true, allows the component to grow and shrink with its content.
194
- * If false, uses fixed width behavior.
195
- * Optional, defaults to false.
196
- */
197
- autoSize?: boolean;
198
-
199
- /**
200
- * If true, shows badges in a single line with horizontal scroll.
201
- * If false, badges wrap to multiple lines.
202
- * Optional, defaults to false.
203
- */
204
- singleLine?: boolean;
205
-
206
- /**
207
- * Custom CSS class for the popover content.
208
- * Optional, can be used to customize popover appearance.
209
- */
210
- popoverClassName?: string;
211
-
212
- /**
213
- * If true, disables the component completely.
214
- * Optional, defaults to false.
215
- */
216
- disabled?: boolean;
217
-
218
- /**
219
- * Responsive configuration for different screen sizes.
220
- * Allows customizing maxCount and other properties based on viewport.
221
- * Can be boolean true for default responsive behavior or an object for custom configuration.
222
- */
223
- responsive?:
224
- | boolean
225
- | {
226
- /** Configuration for mobile devices (< 640px) */
227
- mobile?: {
228
- maxCount?: number;
229
- hideIcons?: boolean;
230
- compactMode?: boolean;
231
- };
232
- /** Configuration for tablet devices (640px - 1024px) */
233
- tablet?: {
234
- maxCount?: number;
235
- hideIcons?: boolean;
236
- compactMode?: boolean;
237
- };
238
- /** Configuration for desktop devices (> 1024px) */
239
- desktop?: {
240
- maxCount?: number;
241
- hideIcons?: boolean;
242
- compactMode?: boolean;
243
- };
244
- };
245
-
246
- /**
247
- * Minimum width for the component.
248
- * Optional, defaults to auto-sizing based on content.
249
- * When set, component will not shrink below this width.
250
- */
251
- minWidth?: string;
252
-
253
- /**
254
- * Maximum width for the component.
255
- * Optional, defaults to 100% of container.
256
- * Component will not exceed container boundaries.
257
- */
258
- maxWidth?: string;
259
-
260
- /**
261
- * If true, automatically removes duplicate options based on their value.
262
- * Optional, defaults to false (shows warning in dev mode instead).
263
- */
264
- deduplicateOptions?: boolean;
265
-
266
- /**
267
- * If true, the component will reset its internal state when defaultValue changes.
268
- * Useful for React Hook Form integration and form reset functionality.
269
- * Optional, defaults to true.
270
- */
271
- resetOnDefaultValueChange?: boolean;
272
-
273
- /**
274
- * If true, automatically closes the popover after selecting an option.
275
- * Useful for single-selection-like behavior or mobile UX.
276
- * Optional, defaults to false.
277
- */
278
- closeOnSelect?: boolean;
279
- }
280
-
281
- /**
282
- * Imperative methods exposed through ref
283
- */
284
- export interface MultiSelectRef {
285
- /**
286
- * Programmatically reset the component to its default value
287
- */
288
- reset: () => void;
289
- /**
290
- * Get current selected values
291
- */
292
- getSelectedValues: () => string[];
293
- /**
294
- * Set selected values programmatically
295
- */
296
- setSelectedValues: (values: string[]) => void;
297
- /**
298
- * Clear all selected values
299
- */
300
- clear: () => void;
301
- /**
302
- * Focus the component
303
- */
304
- focus: () => void;
305
- }
306
-
307
- export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
308
- (
309
- {
310
- options,
311
- onValueChange,
312
- variant,
313
- defaultValue = [],
314
- placeholder = "Select options",
315
- animation = 0,
316
- animationConfig,
317
- maxCount = 3,
318
- modalPopover = false,
319
- asChild = false,
320
- className,
321
- hideSelectAll = false,
322
- searchable = true,
323
- emptyIndicator,
324
- autoSize = false,
325
- singleLine = false,
326
- popoverClassName,
327
- disabled = false,
328
- responsive,
329
- minWidth,
330
- maxWidth,
331
- deduplicateOptions = false,
332
- resetOnDefaultValueChange = true,
333
- closeOnSelect = false,
334
- ...props
335
- },
336
- ref
337
- ) => {
338
- const [selectedValues, setSelectedValues] =
339
- React.useState<string[]>(defaultValue);
340
- const [isPopoverOpen, setIsPopoverOpen] = React.useState(false);
341
- const [isAnimating, setIsAnimating] = React.useState(false);
342
- const [searchValue, setSearchValue] = React.useState("");
343
-
344
- const [politeMessage, setPoliteMessage] = React.useState("");
345
- const [assertiveMessage, setAssertiveMessage] = React.useState("");
346
- const prevSelectedCount = React.useRef(selectedValues.length);
347
- const prevIsOpen = React.useRef(isPopoverOpen);
348
- const prevSearchValue = React.useRef(searchValue);
349
-
350
- const announce = React.useCallback(
351
- (message: string, priority: "polite" | "assertive" = "polite") => {
352
- if (priority === "assertive") {
353
- setAssertiveMessage(message);
354
- setTimeout(() => setAssertiveMessage(""), 100);
355
- } else {
356
- setPoliteMessage(message);
357
- setTimeout(() => setPoliteMessage(""), 100);
358
- }
359
- },
360
- []
361
- );
362
-
363
- const multiSelectId = React.useId();
364
- const listboxId = `${multiSelectId}-listbox`;
365
- const triggerDescriptionId = `${multiSelectId}-description`;
366
- const selectedCountId = `${multiSelectId}-count`;
367
-
368
- const prevDefaultValueRef = React.useRef<string[]>(defaultValue);
369
-
370
- const isGroupedOptions = React.useCallback(
371
- (
372
- opts: MultiSelectOption[] | MultiSelectGroup[]
373
- ): opts is MultiSelectGroup[] => {
374
- return opts.length > 0 && "heading" in opts[0];
375
- },
376
- []
377
- );
378
-
379
- const arraysEqual = React.useCallback(
380
- (a: string[], b: string[]): boolean => {
381
- if (a.length !== b.length) return false;
382
- const sortedA = [...a].sort();
383
- const sortedB = [...b].sort();
384
- return sortedA.every((val, index) => val === sortedB[index]);
385
- },
386
- []
387
- );
388
-
389
- const resetToDefault = React.useCallback(() => {
390
- setSelectedValues(defaultValue);
391
- setIsPopoverOpen(false);
392
- setSearchValue("");
393
- onValueChange(defaultValue);
394
- }, [defaultValue, onValueChange]);
395
-
396
- const buttonRef = React.useRef<HTMLButtonElement>(null);
397
-
398
- React.useImperativeHandle(
399
- ref,
400
- () => ({
401
- reset: resetToDefault,
402
- getSelectedValues: () => selectedValues,
403
- setSelectedValues: (values: string[]) => {
404
- setSelectedValues(values);
405
- onValueChange(values);
406
- },
407
- clear: () => {
408
- setSelectedValues([]);
409
- onValueChange([]);
410
- },
411
- focus: () => {
412
- if (buttonRef.current) {
413
- buttonRef.current.focus();
414
- const originalOutline = buttonRef.current.style.outline;
415
- const originalOutlineOffset = buttonRef.current.style.outlineOffset;
416
- buttonRef.current.style.outline = "2px solid hsl(var(--ring))";
417
- buttonRef.current.style.outlineOffset = "2px";
418
- setTimeout(() => {
419
- if (buttonRef.current) {
420
- buttonRef.current.style.outline = originalOutline;
421
- buttonRef.current.style.outlineOffset = originalOutlineOffset;
422
- }
423
- }, 1000);
424
- }
425
- },
426
- }),
427
- [resetToDefault, selectedValues, onValueChange]
428
- );
429
-
430
- const [screenSize, setScreenSize] = React.useState<
431
- "mobile" | "tablet" | "desktop"
432
- >("desktop");
433
-
434
- React.useEffect(() => {
435
- if (typeof window === "undefined") return;
436
- const handleResize = () => {
437
- const width = window.innerWidth;
438
- if (width < 640) {
439
- setScreenSize("mobile");
440
- } else if (width < 1024) {
441
- setScreenSize("tablet");
442
- } else {
443
- setScreenSize("desktop");
444
- }
445
- };
446
- handleResize();
447
- window.addEventListener("resize", handleResize);
448
- return () => {
449
- if (typeof window !== "undefined") {
450
- window.removeEventListener("resize", handleResize);
451
- }
452
- };
453
- }, []);
454
-
455
- const getResponsiveSettings = () => {
456
- if (!responsive) {
457
- return {
458
- maxCount: maxCount,
459
- hideIcons: false,
460
- compactMode: false,
461
- };
462
- }
463
- if (responsive === true) {
464
- const defaultResponsive = {
465
- mobile: { maxCount: 2, hideIcons: false, compactMode: true },
466
- tablet: { maxCount: 4, hideIcons: false, compactMode: false },
467
- desktop: { maxCount: 6, hideIcons: false, compactMode: false },
468
- };
469
- const currentSettings = defaultResponsive[screenSize];
470
- return {
471
- maxCount: currentSettings?.maxCount ?? maxCount,
472
- hideIcons: currentSettings?.hideIcons ?? false,
473
- compactMode: currentSettings?.compactMode ?? false,
474
- };
475
- }
476
- const currentSettings = responsive[screenSize];
477
- return {
478
- maxCount: currentSettings?.maxCount ?? maxCount,
479
- hideIcons: currentSettings?.hideIcons ?? false,
480
- compactMode: currentSettings?.compactMode ?? false,
481
- };
482
- };
483
-
484
- const responsiveSettings = getResponsiveSettings();
485
-
486
- const getBadgeAnimationClass = () => {
487
- if (animationConfig?.badgeAnimation) {
488
- switch (animationConfig.badgeAnimation) {
489
- case "bounce":
490
- return isAnimating
491
- ? "animate-bounce"
492
- : "hover:-translate-y-1 hover:scale-110";
493
- case "pulse":
494
- return "hover:animate-pulse";
495
- case "wiggle":
496
- return "hover:animate-wiggle";
497
- case "fade":
498
- return "hover:opacity-80";
499
- case "slide":
500
- return "hover:translate-x-1";
501
- case "none":
502
- return "";
503
- default:
504
- return "";
505
- }
506
- }
507
- return isAnimating ? "animate-bounce" : "";
508
- };
509
-
510
- const getPopoverAnimationClass = () => {
511
- if (animationConfig?.popoverAnimation) {
512
- switch (animationConfig.popoverAnimation) {
513
- case "scale":
514
- return "animate-scaleIn";
515
- case "slide":
516
- return "animate-slideInDown";
517
- case "fade":
518
- return "animate-fadeIn";
519
- case "flip":
520
- return "animate-flipIn";
521
- case "none":
522
- return "";
523
- default:
524
- return "";
525
- }
526
- }
527
- return "";
528
- };
529
-
530
- const getAllOptions = React.useCallback((): MultiSelectOption[] => {
531
- if (options.length === 0) return [];
532
- let allOptions: MultiSelectOption[];
533
- if (isGroupedOptions(options)) {
534
- allOptions = options.flatMap((group) => group.options);
535
- } else {
536
- allOptions = options;
537
- }
538
- const valueSet = new Set<string>();
539
- const duplicates: string[] = [];
540
- const uniqueOptions: MultiSelectOption[] = [];
541
- allOptions.forEach((option) => {
542
- if (valueSet.has(option.value)) {
543
- duplicates.push(option.value);
544
- if (!deduplicateOptions) {
545
- uniqueOptions.push(option);
546
- }
547
- } else {
548
- valueSet.add(option.value);
549
- uniqueOptions.push(option);
550
- }
551
- });
552
- if (process.env.NODE_ENV === "development" && duplicates.length > 0) {
553
- const action = deduplicateOptions
554
- ? "automatically removed"
555
- : "detected";
556
- console.warn(
557
- `MultiSelect: Duplicate option values ${action}: ${duplicates.join(
558
- ", "
559
- )}. ` +
560
- `${
561
- deduplicateOptions
562
- ? "Duplicates have been removed automatically."
563
- : "This may cause unexpected behavior. Consider setting 'deduplicateOptions={true}' or ensure all option values are unique."
564
- }`
565
- );
566
- }
567
- return deduplicateOptions ? uniqueOptions : allOptions;
568
- }, [options, deduplicateOptions, isGroupedOptions]);
569
-
570
- const getOptionByValue = React.useCallback(
571
- (value: string): MultiSelectOption | undefined => {
572
- const option = getAllOptions().find((option) => option.value === value);
573
- if (!option && process.env.NODE_ENV === "development") {
574
- console.warn(
575
- `MultiSelect: Option with value "${value}" not found in options list`
576
- );
577
- }
578
- return option;
579
- },
580
- [getAllOptions]
581
- );
582
-
583
- const filteredOptions = React.useMemo(() => {
584
- if (!searchable || !searchValue) return options;
585
- if (options.length === 0) return [];
586
- if (isGroupedOptions(options)) {
587
- return options
588
- .map((group) => ({
589
- ...group,
590
- options: group.options.filter(
591
- (option) =>
592
- option.label
593
- .toLowerCase()
594
- .includes(searchValue.toLowerCase()) ||
595
- option.value.toLowerCase().includes(searchValue.toLowerCase())
596
- ),
597
- }))
598
- .filter((group) => group.options.length > 0);
599
- }
600
- return options.filter(
601
- (option) =>
602
- option.label.toLowerCase().includes(searchValue.toLowerCase()) ||
603
- option.value.toLowerCase().includes(searchValue.toLowerCase())
604
- );
605
- }, [options, searchValue, searchable, isGroupedOptions]);
606
-
607
- const handleInputKeyDown = (
608
- event: React.KeyboardEvent<HTMLInputElement>
609
- ) => {
610
- if (event.key === "Enter") {
611
- setIsPopoverOpen(true);
612
- } else if (event.key === "Backspace" && !event.currentTarget.value) {
613
- const newSelectedValues = [...selectedValues];
614
- newSelectedValues.pop();
615
- setSelectedValues(newSelectedValues);
616
- onValueChange(newSelectedValues);
617
- }
618
- };
619
-
620
- const toggleOption = (optionValue: string) => {
621
- if (disabled) return;
622
- const option = getOptionByValue(optionValue);
623
- if (option?.disabled) return;
624
- const newSelectedValues = selectedValues.includes(optionValue)
625
- ? selectedValues.filter((value) => value !== optionValue)
626
- : [...selectedValues, optionValue];
627
- setSelectedValues(newSelectedValues);
628
- onValueChange(newSelectedValues);
629
- if (closeOnSelect) {
630
- setIsPopoverOpen(false);
631
- }
632
- };
633
-
634
- const handleClear = () => {
635
- if (disabled) return;
636
- setSelectedValues([]);
637
- onValueChange([]);
638
- };
639
-
640
- const handleTogglePopover = () => {
641
- if (disabled) return;
642
- setIsPopoverOpen((prev) => !prev);
643
- };
644
-
645
- const clearExtraOptions = () => {
646
- if (disabled) return;
647
- const newSelectedValues = selectedValues.slice(
648
- 0,
649
- responsiveSettings.maxCount
650
- );
651
- setSelectedValues(newSelectedValues);
652
- onValueChange(newSelectedValues);
653
- };
654
-
655
- const toggleAll = () => {
656
- if (disabled) return;
657
- const allOptions = getAllOptions().filter((option) => !option.disabled);
658
- if (selectedValues.length === allOptions.length) {
659
- handleClear();
660
- } else {
661
- const allValues = allOptions.map((option) => option.value);
662
- setSelectedValues(allValues);
663
- onValueChange(allValues);
664
- }
665
-
666
- if (closeOnSelect) {
667
- setIsPopoverOpen(false);
668
- }
669
- };
670
-
671
- React.useEffect(() => {
672
- if (!resetOnDefaultValueChange) return;
673
- const prevDefaultValue = prevDefaultValueRef.current;
674
- if (!arraysEqual(prevDefaultValue, defaultValue)) {
675
- if (!arraysEqual(selectedValues, defaultValue)) {
676
- setSelectedValues(defaultValue);
677
- }
678
- prevDefaultValueRef.current = [...defaultValue];
679
- }
680
- }, [defaultValue, selectedValues, arraysEqual, resetOnDefaultValueChange]);
681
-
682
- const getWidthConstraints = () => {
683
- const defaultMinWidth = screenSize === "mobile" ? "0px" : "200px";
684
- const effectiveMinWidth = minWidth || defaultMinWidth;
685
- const effectiveMaxWidth = maxWidth || "100%";
686
- return {
687
- minWidth: effectiveMinWidth,
688
- maxWidth: effectiveMaxWidth,
689
- width: autoSize ? "auto" : "100%",
690
- };
691
- };
692
-
693
- const widthConstraints = getWidthConstraints();
694
-
695
- React.useEffect(() => {
696
- if (!isPopoverOpen) {
697
- setSearchValue("");
698
- }
699
- }, [isPopoverOpen]);
700
-
701
- React.useEffect(() => {
702
- const selectedCount = selectedValues.length;
703
- const allOptions = getAllOptions();
704
- const totalOptions = allOptions.filter((opt) => !opt.disabled).length;
705
- if (selectedCount !== prevSelectedCount.current) {
706
- const diff = selectedCount - prevSelectedCount.current;
707
- if (diff > 0) {
708
- const addedItems = selectedValues.slice(-diff);
709
- const addedLabels = addedItems
710
- .map(
711
- (value) => allOptions.find((opt) => opt.value === value)?.label
712
- )
713
- .filter(Boolean);
714
-
715
- if (addedLabels.length === 1) {
716
- announce(
717
- `${addedLabels[0]} selected. ${selectedCount} of ${totalOptions} options selected.`
718
- );
719
- } else {
720
- announce(
721
- `${addedLabels.length} options selected. ${selectedCount} of ${totalOptions} total selected.`
722
- );
723
- }
724
- } else if (diff < 0) {
725
- announce(
726
- `Option removed. ${selectedCount} of ${totalOptions} options selected.`
727
- );
728
- }
729
- prevSelectedCount.current = selectedCount;
730
- }
731
-
732
- if (isPopoverOpen !== prevIsOpen.current) {
733
- if (isPopoverOpen) {
734
- announce(
735
- `Dropdown opened. ${totalOptions} options available. Use arrow keys to navigate.`
736
- );
737
- } else {
738
- announce("Dropdown closed.");
739
- }
740
- prevIsOpen.current = isPopoverOpen;
741
- }
742
-
743
- if (
744
- searchValue !== prevSearchValue.current &&
745
- searchValue !== undefined
746
- ) {
747
- if (searchValue && isPopoverOpen) {
748
- const filteredCount = allOptions.filter(
749
- (opt) =>
750
- opt.label.toLowerCase().includes(searchValue.toLowerCase()) ||
751
- opt.value.toLowerCase().includes(searchValue.toLowerCase())
752
- ).length;
753
-
754
- announce(
755
- `${filteredCount} option${
756
- filteredCount === 1 ? "" : "s"
757
- } found for "${searchValue}"`
758
- );
759
- }
760
- prevSearchValue.current = searchValue;
761
- }
762
- }, [selectedValues, isPopoverOpen, searchValue, announce, getAllOptions]);
763
-
764
- return (
765
- <>
766
- <div className="sr-only">
767
- <div aria-live="polite" aria-atomic="true" role="status">
768
- {politeMessage}
769
- </div>
770
- <div aria-live="assertive" aria-atomic="true" role="alert">
771
- {assertiveMessage}
772
- </div>
773
- </div>
774
-
775
- <Popover
776
- open={isPopoverOpen}
777
- onOpenChange={setIsPopoverOpen}
778
- modal={modalPopover}>
779
- <div id={triggerDescriptionId} className="sr-only">
780
- Multi-select dropdown. Use arrow keys to navigate, Enter to select,
781
- and Escape to close.
782
- </div>
783
- <div id={selectedCountId} className="sr-only" aria-live="polite">
784
- {selectedValues.length === 0
785
- ? "No options selected"
786
- : `${selectedValues.length} option${
787
- selectedValues.length === 1 ? "" : "s"
788
- } selected: ${selectedValues
789
- .map((value) => getOptionByValue(value)?.label)
790
- .filter(Boolean)
791
- .join(", ")}`}
792
- </div>
793
-
794
- <PopoverTrigger asChild>
795
- <Button
796
- ref={buttonRef}
797
- {...props}
798
- onClick={handleTogglePopover}
799
- disabled={disabled}
800
- role="combobox"
801
- aria-expanded={isPopoverOpen}
802
- aria-haspopup="listbox"
803
- aria-controls={isPopoverOpen ? listboxId : undefined}
804
- aria-describedby={`${triggerDescriptionId} ${selectedCountId}`}
805
- aria-label={`Multi-select: ${selectedValues.length} of ${
806
- getAllOptions().length
807
- } options selected. ${placeholder}`}
808
- className={cn(
809
- "flex p-1 rounded-md border min-h-8 h-auto items-center justify-between bg-inherit hover:bg-inherit [&_svg]:pointer-events-auto",
810
- autoSize ? "w-auto" : "w-full",
811
- responsiveSettings.compactMode && "min-h-7 text-sm",
812
- screenSize === "mobile" && "min-h-9 text-sm",
813
- disabled && "opacity-50 cursor-not-allowed",
814
- className
815
- )}
816
- style={{
817
- ...widthConstraints,
818
- maxWidth: `min(${widthConstraints.maxWidth}, 100%)`,
819
- }}>
820
- {selectedValues.length > 0 ? (
821
- <div className="flex min-w-0 items-center justify-between gap-2 w-full">
822
- <div
823
- className={cn(
824
- "flex min-w-0 flex-1 items-center gap-1",
825
- singleLine
826
- ? "overflow-hidden whitespace-nowrap"
827
- : "flex-wrap",
828
- responsiveSettings.compactMode && "gap-0.5"
829
- )}>
830
- {selectedValues
831
- .slice(0, responsiveSettings.maxCount)
832
- .map((value) => {
833
- const option = getOptionByValue(value);
834
- const IconComponent = option?.icon;
835
- const customStyle = option?.style;
836
- if (!option) {
837
- return null;
838
- }
839
- const badgeStyle: React.CSSProperties = {
840
- animationDuration: `${animation}s`,
841
- ...(customStyle?.badgeColor && {
842
- backgroundColor: customStyle.badgeColor,
843
- }),
844
- ...(customStyle?.gradient && {
845
- background: customStyle.gradient,
846
- color: "white",
847
- }),
848
- };
849
- return (
850
- <Badge
851
- key={value}
852
- className={cn(
853
- getBadgeAnimationClass(),
854
- multiSelectVariants({ variant }),
855
- customStyle?.gradient &&
856
- "text-white border-transparent",
857
- singleLine && "min-w-0 max-w-[8.5rem]",
858
- responsiveSettings.compactMode &&
859
- "text-xs px-1.5 py-0.5",
860
- screenSize === "mobile" &&
861
- "max-w-[120px] truncate",
862
- singleLine && "flex-shrink-0 whitespace-nowrap",
863
- "[&>svg]:pointer-events-auto"
864
- )}
865
- style={{
866
- ...badgeStyle,
867
- animationDuration: `${
868
- animationConfig?.duration || animation
869
- }s`,
870
- animationDelay: `${animationConfig?.delay || 0}s`,
871
- }}>
872
- {IconComponent && !responsiveSettings.hideIcons && (
873
- <IconComponent
874
- className={cn(
875
- "h-4 w-4 mr-2",
876
- responsiveSettings.compactMode &&
877
- "h-3 w-3 mr-1",
878
- customStyle?.iconColor && "text-current"
879
- )}
880
- {...(customStyle?.iconColor && {
881
- style: { color: customStyle.iconColor },
882
- })}
883
- />
884
- )}
885
- <span
886
- className={cn(
887
- singleLine && "truncate",
888
- screenSize === "mobile" && "truncate"
889
- )}>
890
- {option.label}
891
- </span>
892
- <div
893
- role="button"
894
- tabIndex={0}
895
- onClick={(event) => {
896
- event.stopPropagation();
897
- toggleOption(value);
898
- }}
899
- onKeyDown={(event) => {
900
- if (
901
- event.key === "Enter" ||
902
- event.key === " "
903
- ) {
904
- event.preventDefault();
905
- event.stopPropagation();
906
- toggleOption(value);
907
- }
908
- }}
909
- aria-label={`Remove ${option.label} from selection`}
910
- className="ml-2 h-4 w-4 cursor-pointer hover:bg-white/20 rounded-sm p-0.5 -m-0.5 focus:outline-none focus:ring-1 focus:ring-white/50">
911
- <XCircle
912
- className={cn(
913
- "h-3 w-3",
914
- responsiveSettings.compactMode &&
915
- "h-2.5 w-2.5"
916
- )}
917
- />
918
- </div>
919
- </Badge>
920
- );
921
- })
922
- .filter(Boolean)}
923
- {selectedValues.length > responsiveSettings.maxCount && (
924
- <Badge
925
- className={cn(
926
- "bg-transparent text-foreground border-foreground/1 hover:bg-transparent",
927
- getBadgeAnimationClass(),
928
- multiSelectVariants({ variant }),
929
- singleLine && "min-w-0 max-w-[7rem]",
930
- responsiveSettings.compactMode &&
931
- "text-xs px-1.5 py-0.5",
932
- singleLine && "flex-shrink-0 whitespace-nowrap",
933
- "[&>svg]:pointer-events-auto"
934
- )}
935
- style={{
936
- animationDuration: `${
937
- animationConfig?.duration || animation
938
- }s`,
939
- animationDelay: `${animationConfig?.delay || 0}s`,
940
- }}>
941
- {`+ ${
942
- selectedValues.length - responsiveSettings.maxCount
943
- } more`}
944
- <XCircle
945
- className={cn(
946
- "ml-2 h-4 w-4 cursor-pointer",
947
- responsiveSettings.compactMode && "ml-1 h-3 w-3"
948
- )}
949
- onClick={(event) => {
950
- event.stopPropagation();
951
- clearExtraOptions();
952
- }}
953
- />
954
- </Badge>
955
- )}
956
- </div>
957
- <div className="flex items-center justify-between">
958
- <div
959
- role="button"
960
- tabIndex={0}
961
- onClick={(event) => {
962
- event.stopPropagation();
963
- handleClear();
964
- }}
965
- onKeyDown={(event) => {
966
- if (event.key === "Enter" || event.key === " ") {
967
- event.preventDefault();
968
- event.stopPropagation();
969
- handleClear();
970
- }
971
- }}
972
- aria-label={`Clear all ${selectedValues.length} selected options`}
973
- className="flex items-center justify-center h-4 w-4 mx-2 cursor-pointer text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1 rounded-sm">
974
- <XIcon className="h-4 w-4" />
975
- </div>
976
- <Separator
977
- orientation="vertical"
978
- className="flex min-h-6 h-full"
979
- />
980
- <ChevronDown
981
- className="h-4 mx-2 cursor-pointer text-muted-foreground"
982
- aria-hidden="true"
983
- />
984
- </div>
985
- </div>
986
- ) : (
987
- <div className="flex items-center justify-between w-full mx-auto">
988
- <span className="text-sm text-muted-foreground mx-3">
989
- {placeholder}
990
- </span>
991
- <ChevronDown className="h-4 cursor-pointer text-muted-foreground mx-2" />
992
- </div>
993
- )}
994
- </Button>
995
- </PopoverTrigger>
996
- <PopoverContent
997
- id={listboxId}
998
- role="listbox"
999
- aria-multiselectable="true"
1000
- aria-label="Available options"
1001
- className={cn(
1002
- "w-auto p-0",
1003
- getPopoverAnimationClass(),
1004
- screenSize === "mobile" && "w-[85vw] max-w-[280px]",
1005
- screenSize === "tablet" && "w-[70vw] max-w-md",
1006
- screenSize === "desktop" && "min-w-[300px]",
1007
- popoverClassName
1008
- )}
1009
- style={{
1010
- animationDuration: `${animationConfig?.duration || animation}s`,
1011
- animationDelay: `${animationConfig?.delay || 0}s`,
1012
- maxWidth: `min(${widthConstraints.maxWidth}, 85vw)`,
1013
- maxHeight: screenSize === "mobile" ? "70vh" : "60vh",
1014
- touchAction: "manipulation",
1015
- }}
1016
- align="start"
1017
- onEscapeKeyDown={() => setIsPopoverOpen(false)}>
1018
- <Command>
1019
- {searchable && (
1020
- <CommandInput
1021
- placeholder="Search options..."
1022
- onKeyDown={handleInputKeyDown}
1023
- value={searchValue}
1024
- onValueChange={setSearchValue}
1025
- aria-label="Search through available options"
1026
- aria-describedby={`${multiSelectId}-search-help`}
1027
- />
1028
- )}
1029
- {searchable && (
1030
- <div id={`${multiSelectId}-search-help`} className="sr-only">
1031
- Type to filter options. Use arrow keys to navigate results.
1032
- </div>
1033
- )}
1034
- <CommandList
1035
- className={cn(
1036
- "max-h-[40vh] overflow-y-auto multiselect-scrollbar",
1037
- screenSize === "mobile" && "max-h-[50vh]",
1038
- "overscroll-behavior-y-contain"
1039
- )}>
1040
- <CommandEmpty>
1041
- {emptyIndicator || "No results found."}
1042
- </CommandEmpty>{" "}
1043
- {!hideSelectAll && !searchValue && (
1044
- <CommandGroup>
1045
- <CommandItem
1046
- key="all"
1047
- onSelect={toggleAll}
1048
- role="option"
1049
- aria-selected={
1050
- selectedValues.length ===
1051
- getAllOptions().filter((opt) => !opt.disabled).length
1052
- }
1053
- aria-label={`Select all ${
1054
- getAllOptions().length
1055
- } options`}
1056
- className="cursor-pointer">
1057
- <div
1058
- className={cn(
1059
- "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
1060
- selectedValues.length ===
1061
- getAllOptions().filter((opt) => !opt.disabled)
1062
- .length
1063
- ? "bg-primary text-primary-foreground"
1064
- : "opacity-50 [&_svg]:invisible"
1065
- )}
1066
- aria-hidden="true">
1067
- <CheckIcon className="h-4 w-4" />
1068
- </div>
1069
- <span>
1070
- (Select All
1071
- {getAllOptions().length > 20
1072
- ? ` - ${getAllOptions().length} options`
1073
- : ""}
1074
- )
1075
- </span>
1076
- </CommandItem>
1077
- </CommandGroup>
1078
- )}
1079
- {isGroupedOptions(filteredOptions) ? (
1080
- filteredOptions.map((group) => (
1081
- <CommandGroup key={group.heading} heading={group.heading}>
1082
- {group.options.map((option) => {
1083
- const isSelected = selectedValues.includes(
1084
- option.value
1085
- );
1086
- return (
1087
- <CommandItem
1088
- key={option.value}
1089
- onSelect={() => toggleOption(option.value)}
1090
- role="option"
1091
- aria-selected={isSelected}
1092
- aria-disabled={option.disabled}
1093
- aria-label={`${option.label}${
1094
- isSelected ? ", selected" : ", not selected"
1095
- }${option.disabled ? ", disabled" : ""}`}
1096
- className={cn(
1097
- "cursor-pointer",
1098
- option.disabled && "opacity-50 cursor-not-allowed"
1099
- )}
1100
- disabled={option.disabled}>
1101
- <div
1102
- className={cn(
1103
- "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
1104
- isSelected
1105
- ? "bg-primary text-primary-foreground"
1106
- : "opacity-50 [&_svg]:invisible"
1107
- )}
1108
- aria-hidden="true">
1109
- <CheckIcon className="h-4 w-4" />
1110
- </div>
1111
- {option.icon && (
1112
- <option.icon
1113
- className="mr-2 h-4 w-4 text-muted-foreground"
1114
- aria-hidden="true"
1115
- />
1116
- )}
1117
- <span>{option.label}</span>
1118
- </CommandItem>
1119
- );
1120
- })}
1121
- </CommandGroup>
1122
- ))
1123
- ) : (
1124
- <CommandGroup>
1125
- {filteredOptions.map((option) => {
1126
- const isSelected = selectedValues.includes(option.value);
1127
- return (
1128
- <CommandItem
1129
- key={option.value}
1130
- onSelect={() => toggleOption(option.value)}
1131
- role="option"
1132
- aria-selected={isSelected}
1133
- aria-disabled={option.disabled}
1134
- aria-label={`${option.label}${
1135
- isSelected ? ", selected" : ", not selected"
1136
- }${option.disabled ? ", disabled" : ""}`}
1137
- className={cn(
1138
- "cursor-pointer",
1139
- option.disabled && "opacity-50 cursor-not-allowed"
1140
- )}
1141
- disabled={option.disabled}>
1142
- <div
1143
- className={cn(
1144
- "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
1145
- isSelected
1146
- ? "bg-primary text-primary-foreground"
1147
- : "opacity-50 [&_svg]:invisible"
1148
- )}
1149
- aria-hidden="true">
1150
- <CheckIcon className="h-4 w-4" />
1151
- </div>
1152
- {option.icon && (
1153
- <option.icon
1154
- className="mr-2 h-4 w-4 text-muted-foreground"
1155
- aria-hidden="true"
1156
- />
1157
- )}
1158
- <span>{option.label}</span>
1159
- </CommandItem>
1160
- );
1161
- })}
1162
- </CommandGroup>
1163
- )}
1164
- <CommandSeparator />
1165
- <CommandGroup>
1166
- <div className="flex items-center justify-between">
1167
- {selectedValues.length > 0 && (
1168
- <>
1169
- <CommandItem
1170
- onSelect={handleClear}
1171
- className="flex-1 justify-center cursor-pointer">
1172
- Clear
1173
- </CommandItem>
1174
- <Separator
1175
- orientation="vertical"
1176
- className="flex min-h-6 h-full"
1177
- />
1178
- </>
1179
- )}
1180
- <CommandItem
1181
- onSelect={() => setIsPopoverOpen(false)}
1182
- className="flex-1 justify-center cursor-pointer max-w-full">
1183
- Close
1184
- </CommandItem>
1185
- </div>
1186
- </CommandGroup>
1187
- </CommandList>
1188
- </Command>
1189
- </PopoverContent>
1190
- {animation > 0 && selectedValues.length > 0 && (
1191
- <WandSparkles
1192
- className={cn(
1193
- "cursor-pointer my-2 text-foreground bg-background w-3 h-3",
1194
- isAnimating ? "" : "text-muted-foreground"
1195
- )}
1196
- onClick={() => setIsAnimating(!isAnimating)}
1197
- />
1198
- )}
1199
- </Popover>
1200
- </>
1201
- );
1202
- }
1203
- );
1204
-
1205
- MultiSelect.displayName = "MultiSelect";
1206
- export type { MultiSelectOption, MultiSelectGroup, MultiSelectProps };
1
+ import * as React from "react";
2
+ import { cva, type VariantProps } from "class-variance-authority";
3
+ import {
4
+ CheckIcon,
5
+ XCircle,
6
+ ChevronDown,
7
+ XIcon,
8
+ WandSparkles,
9
+ } from "lucide-react";
10
+
11
+ import { cn } from "@/lib/utils";
12
+ import { Separator } from "@/components/ui/separator";
13
+ import { Button } from "@/components/ui/button";
14
+ import { Badge } from "@/components/ui/badge";
15
+ import {
16
+ Popover,
17
+ PopoverContent,
18
+ PopoverTrigger,
19
+ } from "@/components/ui/popover";
20
+ import {
21
+ Command,
22
+ CommandEmpty,
23
+ CommandGroup,
24
+ CommandInput,
25
+ CommandItem,
26
+ CommandList,
27
+ CommandSeparator,
28
+ } from "@/components/ui/command";
29
+
30
+ /**
31
+ * Animation types and configurations
32
+ */
33
+ export interface AnimationConfig {
34
+ /** Badge animation type */
35
+ badgeAnimation?: "bounce" | "pulse" | "wiggle" | "fade" | "slide" | "none";
36
+ /** Popover animation type */
37
+ popoverAnimation?: "scale" | "slide" | "fade" | "flip" | "none";
38
+ /** Option hover animation type */
39
+ optionHoverAnimation?: "highlight" | "scale" | "glow" | "none";
40
+ /** Animation duration in seconds */
41
+ duration?: number;
42
+ /** Animation delay in seconds */
43
+ delay?: number;
44
+ }
45
+
46
+ /**
47
+ * Variants for the multi-select component to handle different styles.
48
+ * Uses class-variance-authority (cva) to define different styles based on "variant" prop.
49
+ */
50
+ const multiSelectVariants = cva("m-1 transition-all duration-300 ease-in-out", {
51
+ variants: {
52
+ variant: {
53
+ default: "border-foreground/10 text-foreground bg-card hover:bg-card/80",
54
+ secondary:
55
+ "border-foreground/10 bg-secondary text-secondary-foreground hover:bg-secondary/80",
56
+ destructive:
57
+ "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
58
+ inverted: "inverted",
59
+ },
60
+ badgeAnimation: {
61
+ bounce: "hover:-translate-y-1 hover:scale-110",
62
+ pulse: "hover:animate-pulse",
63
+ wiggle: "hover:animate-wiggle",
64
+ fade: "hover:opacity-80",
65
+ slide: "hover:translate-x-1",
66
+ none: "",
67
+ },
68
+ },
69
+ defaultVariants: {
70
+ variant: "default",
71
+ badgeAnimation: "bounce",
72
+ },
73
+ });
74
+
75
+ /**
76
+ * Option interface for MultiSelect component
77
+ */
78
+ interface MultiSelectOption {
79
+ /** The text to display for the option. */
80
+ label: string;
81
+ /** The unique value associated with the option. */
82
+ value: string;
83
+ /** Optional icon component to display alongside the option. */
84
+ icon?: React.ComponentType<{ className?: string }>;
85
+ /** Whether this option is disabled */
86
+ disabled?: boolean;
87
+ /** Custom styling for the option */
88
+ style?: {
89
+ /** Custom badge color */
90
+ badgeColor?: string;
91
+ /** Custom icon color */
92
+ iconColor?: string;
93
+ /** Gradient background for badge */
94
+ gradient?: string;
95
+ };
96
+ }
97
+
98
+ /**
99
+ * Group interface for organizing options
100
+ */
101
+ interface MultiSelectGroup {
102
+ /** Group heading */
103
+ heading: string;
104
+ /** Options in this group */
105
+ options: MultiSelectOption[];
106
+ }
107
+
108
+ /**
109
+ * Props for MultiSelect component
110
+ */
111
+ interface MultiSelectProps
112
+ extends Omit<
113
+ React.ButtonHTMLAttributes<HTMLButtonElement>,
114
+ "animationConfig"
115
+ >,
116
+ VariantProps<typeof multiSelectVariants> {
117
+ /**
118
+ * An array of option objects or groups to be displayed in the multi-select component.
119
+ */
120
+ options: MultiSelectOption[] | MultiSelectGroup[];
121
+ /**
122
+ * Callback function triggered when the selected values change.
123
+ * Receives an array of the new selected values.
124
+ */
125
+ onValueChange: (value: string[]) => void;
126
+
127
+ /** The default selected values when the component mounts. */
128
+ defaultValue?: string[];
129
+
130
+ /**
131
+ * Placeholder text to be displayed when no values are selected.
132
+ * Optional, defaults to "Select options".
133
+ */
134
+ placeholder?: string;
135
+
136
+ /**
137
+ * Animation duration in seconds for the visual effects (e.g., bouncing badges).
138
+ * Optional, defaults to 0 (no animation).
139
+ */
140
+ animation?: number;
141
+
142
+ /**
143
+ * Advanced animation configuration for different component parts.
144
+ * Optional, allows fine-tuning of various animation effects.
145
+ */
146
+ animationConfig?: AnimationConfig;
147
+
148
+ /**
149
+ * Maximum number of items to display. Extra selected items will be summarized.
150
+ * Optional, defaults to 3.
151
+ */
152
+ maxCount?: number;
153
+
154
+ /**
155
+ * The modality of the popover. When set to true, interaction with outside elements
156
+ * will be disabled and only popover content will be visible to screen readers.
157
+ * Optional, defaults to false.
158
+ */
159
+ modalPopover?: boolean;
160
+
161
+ /**
162
+ * If true, renders the multi-select component as a child of another component.
163
+ * Optional, defaults to false.
164
+ */
165
+ asChild?: boolean;
166
+
167
+ /**
168
+ * Additional class names to apply custom styles to the multi-select component.
169
+ * Optional, can be used to add custom styles.
170
+ */
171
+ className?: string;
172
+
173
+ /**
174
+ * If true, disables the select all functionality.
175
+ * Optional, defaults to false.
176
+ */
177
+ hideSelectAll?: boolean;
178
+
179
+ /**
180
+ * If true, shows search functionality in the popover.
181
+ * If false, hides the search input completely.
182
+ * Optional, defaults to true.
183
+ */
184
+ searchable?: boolean;
185
+
186
+ /**
187
+ * Custom empty state message when no options match search.
188
+ * Optional, defaults to "No results found."
189
+ */
190
+ emptyIndicator?: React.ReactNode;
191
+
192
+ /**
193
+ * If true, allows the component to grow and shrink with its content.
194
+ * If false, uses fixed width behavior.
195
+ * Optional, defaults to false.
196
+ */
197
+ autoSize?: boolean;
198
+
199
+ /**
200
+ * If true, shows badges in a single line with horizontal scroll.
201
+ * If false, badges wrap to multiple lines.
202
+ * Optional, defaults to false.
203
+ */
204
+ singleLine?: boolean;
205
+
206
+ /**
207
+ * Custom CSS class for the popover content.
208
+ * Optional, can be used to customize popover appearance.
209
+ */
210
+ popoverClassName?: string;
211
+
212
+ /**
213
+ * If true, disables the component completely.
214
+ * Optional, defaults to false.
215
+ */
216
+ disabled?: boolean;
217
+
218
+ /**
219
+ * Responsive configuration for different screen sizes.
220
+ * Allows customizing maxCount and other properties based on viewport.
221
+ * Can be boolean true for default responsive behavior or an object for custom configuration.
222
+ */
223
+ responsive?:
224
+ | boolean
225
+ | {
226
+ /** Configuration for mobile devices (< 640px) */
227
+ mobile?: {
228
+ maxCount?: number;
229
+ hideIcons?: boolean;
230
+ compactMode?: boolean;
231
+ };
232
+ /** Configuration for tablet devices (640px - 1024px) */
233
+ tablet?: {
234
+ maxCount?: number;
235
+ hideIcons?: boolean;
236
+ compactMode?: boolean;
237
+ };
238
+ /** Configuration for desktop devices (> 1024px) */
239
+ desktop?: {
240
+ maxCount?: number;
241
+ hideIcons?: boolean;
242
+ compactMode?: boolean;
243
+ };
244
+ };
245
+
246
+ /**
247
+ * Minimum width for the component.
248
+ * Optional, defaults to auto-sizing based on content.
249
+ * When set, component will not shrink below this width.
250
+ */
251
+ minWidth?: string;
252
+
253
+ /**
254
+ * Maximum width for the component.
255
+ * Optional, defaults to 100% of container.
256
+ * Component will not exceed container boundaries.
257
+ */
258
+ maxWidth?: string;
259
+
260
+ /**
261
+ * If true, automatically removes duplicate options based on their value.
262
+ * Optional, defaults to false (shows warning in dev mode instead).
263
+ */
264
+ deduplicateOptions?: boolean;
265
+
266
+ /**
267
+ * If true, the component will reset its internal state when defaultValue changes.
268
+ * Useful for React Hook Form integration and form reset functionality.
269
+ * Optional, defaults to true.
270
+ */
271
+ resetOnDefaultValueChange?: boolean;
272
+
273
+ /**
274
+ * If true, automatically closes the popover after selecting an option.
275
+ * Useful for single-selection-like behavior or mobile UX.
276
+ * Optional, defaults to false.
277
+ */
278
+ closeOnSelect?: boolean;
279
+ }
280
+
281
+ /**
282
+ * Imperative methods exposed through ref
283
+ */
284
+ export interface MultiSelectRef {
285
+ /**
286
+ * Programmatically reset the component to its default value
287
+ */
288
+ reset: () => void;
289
+ /**
290
+ * Get current selected values
291
+ */
292
+ getSelectedValues: () => string[];
293
+ /**
294
+ * Set selected values programmatically
295
+ */
296
+ setSelectedValues: (values: string[]) => void;
297
+ /**
298
+ * Clear all selected values
299
+ */
300
+ clear: () => void;
301
+ /**
302
+ * Focus the component
303
+ */
304
+ focus: () => void;
305
+ }
306
+
307
+ export const MultiSelect = React.forwardRef<MultiSelectRef, MultiSelectProps>(
308
+ (
309
+ {
310
+ options,
311
+ onValueChange,
312
+ variant,
313
+ defaultValue = [],
314
+ placeholder = "Select options",
315
+ animation = 0,
316
+ animationConfig,
317
+ maxCount = 3,
318
+ modalPopover = false,
319
+ asChild = false,
320
+ className,
321
+ hideSelectAll = false,
322
+ searchable = true,
323
+ emptyIndicator,
324
+ autoSize = false,
325
+ singleLine = false,
326
+ popoverClassName,
327
+ disabled = false,
328
+ responsive,
329
+ minWidth,
330
+ maxWidth,
331
+ deduplicateOptions = false,
332
+ resetOnDefaultValueChange = true,
333
+ closeOnSelect = false,
334
+ ...props
335
+ },
336
+ ref
337
+ ) => {
338
+ const [selectedValues, setSelectedValues] =
339
+ React.useState<string[]>(defaultValue);
340
+ const [isPopoverOpen, setIsPopoverOpen] = React.useState(false);
341
+ const [isAnimating, setIsAnimating] = React.useState(false);
342
+ const [searchValue, setSearchValue] = React.useState("");
343
+
344
+ const [politeMessage, setPoliteMessage] = React.useState("");
345
+ const [assertiveMessage, setAssertiveMessage] = React.useState("");
346
+ const prevSelectedCount = React.useRef(selectedValues.length);
347
+ const prevIsOpen = React.useRef(isPopoverOpen);
348
+ const prevSearchValue = React.useRef(searchValue);
349
+
350
+ const announce = React.useCallback(
351
+ (message: string, priority: "polite" | "assertive" = "polite") => {
352
+ if (priority === "assertive") {
353
+ setAssertiveMessage(message);
354
+ setTimeout(() => setAssertiveMessage(""), 100);
355
+ } else {
356
+ setPoliteMessage(message);
357
+ setTimeout(() => setPoliteMessage(""), 100);
358
+ }
359
+ },
360
+ []
361
+ );
362
+
363
+ const multiSelectId = React.useId();
364
+ const listboxId = `${multiSelectId}-listbox`;
365
+ const triggerDescriptionId = `${multiSelectId}-description`;
366
+ const selectedCountId = `${multiSelectId}-count`;
367
+
368
+ const prevDefaultValueRef = React.useRef<string[]>(defaultValue);
369
+
370
+ const isGroupedOptions = React.useCallback(
371
+ (
372
+ opts: MultiSelectOption[] | MultiSelectGroup[]
373
+ ): opts is MultiSelectGroup[] => {
374
+ return opts.length > 0 && "heading" in opts[0];
375
+ },
376
+ []
377
+ );
378
+
379
+ const arraysEqual = React.useCallback(
380
+ (a: string[], b: string[]): boolean => {
381
+ if (a.length !== b.length) return false;
382
+ const sortedA = [...a].sort();
383
+ const sortedB = [...b].sort();
384
+ return sortedA.every((val, index) => val === sortedB[index]);
385
+ },
386
+ []
387
+ );
388
+
389
+ const resetToDefault = React.useCallback(() => {
390
+ setSelectedValues(defaultValue);
391
+ setIsPopoverOpen(false);
392
+ setSearchValue("");
393
+ onValueChange(defaultValue);
394
+ }, [defaultValue, onValueChange]);
395
+
396
+ const buttonRef = React.useRef<HTMLButtonElement>(null);
397
+
398
+ React.useImperativeHandle(
399
+ ref,
400
+ () => ({
401
+ reset: resetToDefault,
402
+ getSelectedValues: () => selectedValues,
403
+ setSelectedValues: (values: string[]) => {
404
+ setSelectedValues(values);
405
+ onValueChange(values);
406
+ },
407
+ clear: () => {
408
+ setSelectedValues([]);
409
+ onValueChange([]);
410
+ },
411
+ focus: () => {
412
+ if (buttonRef.current) {
413
+ buttonRef.current.focus();
414
+ const originalOutline = buttonRef.current.style.outline;
415
+ const originalOutlineOffset = buttonRef.current.style.outlineOffset;
416
+ buttonRef.current.style.outline = "2px solid hsl(var(--ring))";
417
+ buttonRef.current.style.outlineOffset = "2px";
418
+ setTimeout(() => {
419
+ if (buttonRef.current) {
420
+ buttonRef.current.style.outline = originalOutline;
421
+ buttonRef.current.style.outlineOffset = originalOutlineOffset;
422
+ }
423
+ }, 1000);
424
+ }
425
+ },
426
+ }),
427
+ [resetToDefault, selectedValues, onValueChange]
428
+ );
429
+
430
+ const [screenSize, setScreenSize] = React.useState<
431
+ "mobile" | "tablet" | "desktop"
432
+ >("desktop");
433
+
434
+ React.useEffect(() => {
435
+ if (typeof window === "undefined") return;
436
+ const handleResize = () => {
437
+ const width = window.innerWidth;
438
+ if (width < 640) {
439
+ setScreenSize("mobile");
440
+ } else if (width < 1024) {
441
+ setScreenSize("tablet");
442
+ } else {
443
+ setScreenSize("desktop");
444
+ }
445
+ };
446
+ handleResize();
447
+ window.addEventListener("resize", handleResize);
448
+ return () => {
449
+ if (typeof window !== "undefined") {
450
+ window.removeEventListener("resize", handleResize);
451
+ }
452
+ };
453
+ }, []);
454
+
455
+ const getResponsiveSettings = () => {
456
+ if (!responsive) {
457
+ return {
458
+ maxCount: maxCount,
459
+ hideIcons: false,
460
+ compactMode: false,
461
+ };
462
+ }
463
+ if (responsive === true) {
464
+ const defaultResponsive = {
465
+ mobile: { maxCount: 2, hideIcons: false, compactMode: true },
466
+ tablet: { maxCount: 4, hideIcons: false, compactMode: false },
467
+ desktop: { maxCount: 6, hideIcons: false, compactMode: false },
468
+ };
469
+ const currentSettings = defaultResponsive[screenSize];
470
+ return {
471
+ maxCount: currentSettings?.maxCount ?? maxCount,
472
+ hideIcons: currentSettings?.hideIcons ?? false,
473
+ compactMode: currentSettings?.compactMode ?? false,
474
+ };
475
+ }
476
+ const currentSettings = responsive[screenSize];
477
+ return {
478
+ maxCount: currentSettings?.maxCount ?? maxCount,
479
+ hideIcons: currentSettings?.hideIcons ?? false,
480
+ compactMode: currentSettings?.compactMode ?? false,
481
+ };
482
+ };
483
+
484
+ const responsiveSettings = getResponsiveSettings();
485
+
486
+ const getBadgeAnimationClass = () => {
487
+ if (animationConfig?.badgeAnimation) {
488
+ switch (animationConfig.badgeAnimation) {
489
+ case "bounce":
490
+ return isAnimating
491
+ ? "animate-bounce"
492
+ : "hover:-translate-y-1 hover:scale-110";
493
+ case "pulse":
494
+ return "hover:animate-pulse";
495
+ case "wiggle":
496
+ return "hover:animate-wiggle";
497
+ case "fade":
498
+ return "hover:opacity-80";
499
+ case "slide":
500
+ return "hover:translate-x-1";
501
+ case "none":
502
+ return "";
503
+ default:
504
+ return "";
505
+ }
506
+ }
507
+ return isAnimating ? "animate-bounce" : "";
508
+ };
509
+
510
+ const getPopoverAnimationClass = () => {
511
+ if (animationConfig?.popoverAnimation) {
512
+ switch (animationConfig.popoverAnimation) {
513
+ case "scale":
514
+ return "animate-scaleIn";
515
+ case "slide":
516
+ return "animate-slideInDown";
517
+ case "fade":
518
+ return "animate-fadeIn";
519
+ case "flip":
520
+ return "animate-flipIn";
521
+ case "none":
522
+ return "";
523
+ default:
524
+ return "";
525
+ }
526
+ }
527
+ return "";
528
+ };
529
+
530
+ const getAllOptions = React.useCallback((): MultiSelectOption[] => {
531
+ if (options.length === 0) return [];
532
+ let allOptions: MultiSelectOption[];
533
+ if (isGroupedOptions(options)) {
534
+ allOptions = options.flatMap((group) => group.options);
535
+ } else {
536
+ allOptions = options;
537
+ }
538
+ const valueSet = new Set<string>();
539
+ const duplicates: string[] = [];
540
+ const uniqueOptions: MultiSelectOption[] = [];
541
+ allOptions.forEach((option) => {
542
+ if (valueSet.has(option.value)) {
543
+ duplicates.push(option.value);
544
+ if (!deduplicateOptions) {
545
+ uniqueOptions.push(option);
546
+ }
547
+ } else {
548
+ valueSet.add(option.value);
549
+ uniqueOptions.push(option);
550
+ }
551
+ });
552
+ if (process.env.NODE_ENV === "development" && duplicates.length > 0) {
553
+ const action = deduplicateOptions
554
+ ? "automatically removed"
555
+ : "detected";
556
+ console.warn(
557
+ `MultiSelect: Duplicate option values ${action}: ${duplicates.join(
558
+ ", "
559
+ )}. ` +
560
+ `${
561
+ deduplicateOptions
562
+ ? "Duplicates have been removed automatically."
563
+ : "This may cause unexpected behavior. Consider setting 'deduplicateOptions={true}' or ensure all option values are unique."
564
+ }`
565
+ );
566
+ }
567
+ return deduplicateOptions ? uniqueOptions : allOptions;
568
+ }, [options, deduplicateOptions, isGroupedOptions]);
569
+
570
+ const getOptionByValue = React.useCallback(
571
+ (value: string): MultiSelectOption | undefined => {
572
+ const option = getAllOptions().find((option) => option.value === value);
573
+ if (!option && process.env.NODE_ENV === "development") {
574
+ console.warn(
575
+ `MultiSelect: Option with value "${value}" not found in options list`
576
+ );
577
+ }
578
+ return option;
579
+ },
580
+ [getAllOptions]
581
+ );
582
+
583
+ const filteredOptions = React.useMemo(() => {
584
+ if (!searchable || !searchValue) return options;
585
+ if (options.length === 0) return [];
586
+ if (isGroupedOptions(options)) {
587
+ return options
588
+ .map((group) => ({
589
+ ...group,
590
+ options: group.options.filter(
591
+ (option) =>
592
+ option.label
593
+ .toLowerCase()
594
+ .includes(searchValue.toLowerCase()) ||
595
+ option.value.toLowerCase().includes(searchValue.toLowerCase())
596
+ ),
597
+ }))
598
+ .filter((group) => group.options.length > 0);
599
+ }
600
+ return options.filter(
601
+ (option) =>
602
+ option.label.toLowerCase().includes(searchValue.toLowerCase()) ||
603
+ option.value.toLowerCase().includes(searchValue.toLowerCase())
604
+ );
605
+ }, [options, searchValue, searchable, isGroupedOptions]);
606
+
607
+ const handleInputKeyDown = (
608
+ event: React.KeyboardEvent<HTMLInputElement>
609
+ ) => {
610
+ if (event.key === "Enter") {
611
+ setIsPopoverOpen(true);
612
+ } else if (event.key === "Backspace" && !event.currentTarget.value) {
613
+ const newSelectedValues = [...selectedValues];
614
+ newSelectedValues.pop();
615
+ setSelectedValues(newSelectedValues);
616
+ onValueChange(newSelectedValues);
617
+ }
618
+ };
619
+
620
+ const toggleOption = (optionValue: string) => {
621
+ if (disabled) return;
622
+ const option = getOptionByValue(optionValue);
623
+ if (option?.disabled) return;
624
+ const newSelectedValues = selectedValues.includes(optionValue)
625
+ ? selectedValues.filter((value) => value !== optionValue)
626
+ : [...selectedValues, optionValue];
627
+ setSelectedValues(newSelectedValues);
628
+ onValueChange(newSelectedValues);
629
+ if (closeOnSelect) {
630
+ setIsPopoverOpen(false);
631
+ }
632
+ };
633
+
634
+ const handleClear = () => {
635
+ if (disabled) return;
636
+ setSelectedValues([]);
637
+ onValueChange([]);
638
+ };
639
+
640
+ const handleTogglePopover = () => {
641
+ if (disabled) return;
642
+ setIsPopoverOpen((prev) => !prev);
643
+ };
644
+
645
+ const clearExtraOptions = () => {
646
+ if (disabled) return;
647
+ const newSelectedValues = selectedValues.slice(
648
+ 0,
649
+ responsiveSettings.maxCount
650
+ );
651
+ setSelectedValues(newSelectedValues);
652
+ onValueChange(newSelectedValues);
653
+ };
654
+
655
+ const toggleAll = () => {
656
+ if (disabled) return;
657
+ const allOptions = getAllOptions().filter((option) => !option.disabled);
658
+ if (selectedValues.length === allOptions.length) {
659
+ handleClear();
660
+ } else {
661
+ const allValues = allOptions.map((option) => option.value);
662
+ setSelectedValues(allValues);
663
+ onValueChange(allValues);
664
+ }
665
+
666
+ if (closeOnSelect) {
667
+ setIsPopoverOpen(false);
668
+ }
669
+ };
670
+
671
+ React.useEffect(() => {
672
+ if (!resetOnDefaultValueChange) return;
673
+ const prevDefaultValue = prevDefaultValueRef.current;
674
+ if (!arraysEqual(prevDefaultValue, defaultValue)) {
675
+ if (!arraysEqual(selectedValues, defaultValue)) {
676
+ setSelectedValues(defaultValue);
677
+ }
678
+ prevDefaultValueRef.current = [...defaultValue];
679
+ }
680
+ }, [defaultValue, selectedValues, arraysEqual, resetOnDefaultValueChange]);
681
+
682
+ const getWidthConstraints = () => {
683
+ const defaultMinWidth = screenSize === "mobile" ? "0px" : "200px";
684
+ const effectiveMinWidth = minWidth || defaultMinWidth;
685
+ const effectiveMaxWidth = maxWidth || "100%";
686
+ return {
687
+ minWidth: effectiveMinWidth,
688
+ maxWidth: effectiveMaxWidth,
689
+ width: autoSize ? "auto" : "100%",
690
+ };
691
+ };
692
+
693
+ const widthConstraints = getWidthConstraints();
694
+
695
+ React.useEffect(() => {
696
+ if (!isPopoverOpen) {
697
+ setSearchValue("");
698
+ }
699
+ }, [isPopoverOpen]);
700
+
701
+ React.useEffect(() => {
702
+ const selectedCount = selectedValues.length;
703
+ const allOptions = getAllOptions();
704
+ const totalOptions = allOptions.filter((opt) => !opt.disabled).length;
705
+ if (selectedCount !== prevSelectedCount.current) {
706
+ const diff = selectedCount - prevSelectedCount.current;
707
+ if (diff > 0) {
708
+ const addedItems = selectedValues.slice(-diff);
709
+ const addedLabels = addedItems
710
+ .map(
711
+ (value) => allOptions.find((opt) => opt.value === value)?.label
712
+ )
713
+ .filter(Boolean);
714
+
715
+ if (addedLabels.length === 1) {
716
+ announce(
717
+ `${addedLabels[0]} selected. ${selectedCount} of ${totalOptions} options selected.`
718
+ );
719
+ } else {
720
+ announce(
721
+ `${addedLabels.length} options selected. ${selectedCount} of ${totalOptions} total selected.`
722
+ );
723
+ }
724
+ } else if (diff < 0) {
725
+ announce(
726
+ `Option removed. ${selectedCount} of ${totalOptions} options selected.`
727
+ );
728
+ }
729
+ prevSelectedCount.current = selectedCount;
730
+ }
731
+
732
+ if (isPopoverOpen !== prevIsOpen.current) {
733
+ if (isPopoverOpen) {
734
+ announce(
735
+ `Dropdown opened. ${totalOptions} options available. Use arrow keys to navigate.`
736
+ );
737
+ } else {
738
+ announce("Dropdown closed.");
739
+ }
740
+ prevIsOpen.current = isPopoverOpen;
741
+ }
742
+
743
+ if (
744
+ searchValue !== prevSearchValue.current &&
745
+ searchValue !== undefined
746
+ ) {
747
+ if (searchValue && isPopoverOpen) {
748
+ const filteredCount = allOptions.filter(
749
+ (opt) =>
750
+ opt.label.toLowerCase().includes(searchValue.toLowerCase()) ||
751
+ opt.value.toLowerCase().includes(searchValue.toLowerCase())
752
+ ).length;
753
+
754
+ announce(
755
+ `${filteredCount} option${
756
+ filteredCount === 1 ? "" : "s"
757
+ } found for "${searchValue}"`
758
+ );
759
+ }
760
+ prevSearchValue.current = searchValue;
761
+ }
762
+ }, [selectedValues, isPopoverOpen, searchValue, announce, getAllOptions]);
763
+
764
+ return (
765
+ <>
766
+ <div className="sr-only">
767
+ <div aria-live="polite" aria-atomic="true" role="status">
768
+ {politeMessage}
769
+ </div>
770
+ <div aria-live="assertive" aria-atomic="true" role="alert">
771
+ {assertiveMessage}
772
+ </div>
773
+ </div>
774
+
775
+ <Popover
776
+ open={isPopoverOpen}
777
+ onOpenChange={setIsPopoverOpen}
778
+ modal={modalPopover}>
779
+ <div id={triggerDescriptionId} className="sr-only">
780
+ Multi-select dropdown. Use arrow keys to navigate, Enter to select,
781
+ and Escape to close.
782
+ </div>
783
+ <div id={selectedCountId} className="sr-only" aria-live="polite">
784
+ {selectedValues.length === 0
785
+ ? "No options selected"
786
+ : `${selectedValues.length} option${
787
+ selectedValues.length === 1 ? "" : "s"
788
+ } selected: ${selectedValues
789
+ .map((value) => getOptionByValue(value)?.label)
790
+ .filter(Boolean)
791
+ .join(", ")}`}
792
+ </div>
793
+
794
+ <PopoverTrigger asChild>
795
+ <Button
796
+ ref={buttonRef}
797
+ {...props}
798
+ onClick={handleTogglePopover}
799
+ disabled={disabled}
800
+ role="combobox"
801
+ aria-expanded={isPopoverOpen}
802
+ aria-haspopup="listbox"
803
+ aria-controls={isPopoverOpen ? listboxId : undefined}
804
+ aria-describedby={`${triggerDescriptionId} ${selectedCountId}`}
805
+ aria-label={`Multi-select: ${selectedValues.length} of ${
806
+ getAllOptions().length
807
+ } options selected. ${placeholder}`}
808
+ className={cn(
809
+ "flex p-1 rounded-md border min-h-8 h-auto items-center justify-between bg-inherit hover:bg-inherit [&_svg]:pointer-events-auto",
810
+ autoSize ? "w-auto" : "w-full",
811
+ responsiveSettings.compactMode && "min-h-7 text-sm",
812
+ screenSize === "mobile" && "min-h-9 text-sm",
813
+ disabled && "opacity-50 cursor-not-allowed",
814
+ className
815
+ )}
816
+ style={{
817
+ ...widthConstraints,
818
+ maxWidth: `min(${widthConstraints.maxWidth}, 100%)`,
819
+ }}>
820
+ {selectedValues.length > 0 ? (
821
+ <div className="flex min-w-0 items-center justify-between gap-2 w-full">
822
+ <div
823
+ className={cn(
824
+ "flex min-w-0 flex-1 items-center gap-1",
825
+ singleLine
826
+ ? "overflow-hidden whitespace-nowrap"
827
+ : "flex-wrap",
828
+ responsiveSettings.compactMode && "gap-0.5"
829
+ )}>
830
+ {selectedValues
831
+ .slice(0, responsiveSettings.maxCount)
832
+ .map((value) => {
833
+ const option = getOptionByValue(value);
834
+ const IconComponent = option?.icon;
835
+ const customStyle = option?.style;
836
+ if (!option) {
837
+ return null;
838
+ }
839
+ const badgeStyle: React.CSSProperties = {
840
+ animationDuration: `${animation}s`,
841
+ ...(customStyle?.badgeColor && {
842
+ backgroundColor: customStyle.badgeColor,
843
+ }),
844
+ ...(customStyle?.gradient && {
845
+ background: customStyle.gradient,
846
+ color: "white",
847
+ }),
848
+ };
849
+ return (
850
+ <Badge
851
+ key={value}
852
+ className={cn(
853
+ getBadgeAnimationClass(),
854
+ multiSelectVariants({ variant }),
855
+ customStyle?.gradient &&
856
+ "text-white border-transparent",
857
+ singleLine && "min-w-0 max-w-[8.5rem]",
858
+ responsiveSettings.compactMode &&
859
+ "text-xs px-1.5 py-0.5",
860
+ screenSize === "mobile" &&
861
+ "max-w-[120px] truncate",
862
+ singleLine && "flex-shrink-0 whitespace-nowrap",
863
+ "[&>svg]:pointer-events-auto"
864
+ )}
865
+ style={{
866
+ ...badgeStyle,
867
+ animationDuration: `${
868
+ animationConfig?.duration || animation
869
+ }s`,
870
+ animationDelay: `${animationConfig?.delay || 0}s`,
871
+ }}>
872
+ {IconComponent && !responsiveSettings.hideIcons && (
873
+ <IconComponent
874
+ className={cn(
875
+ "h-4 w-4 mr-2",
876
+ responsiveSettings.compactMode &&
877
+ "h-3 w-3 mr-1",
878
+ customStyle?.iconColor && "text-current"
879
+ )}
880
+ {...(customStyle?.iconColor && {
881
+ style: { color: customStyle.iconColor },
882
+ })}
883
+ />
884
+ )}
885
+ <span
886
+ className={cn(
887
+ singleLine && "truncate",
888
+ screenSize === "mobile" && "truncate"
889
+ )}>
890
+ {option.label}
891
+ </span>
892
+ <div
893
+ role="button"
894
+ tabIndex={0}
895
+ onClick={(event) => {
896
+ event.stopPropagation();
897
+ toggleOption(value);
898
+ }}
899
+ onKeyDown={(event) => {
900
+ if (
901
+ event.key === "Enter" ||
902
+ event.key === " "
903
+ ) {
904
+ event.preventDefault();
905
+ event.stopPropagation();
906
+ toggleOption(value);
907
+ }
908
+ }}
909
+ aria-label={`Remove ${option.label} from selection`}
910
+ className="ml-2 h-4 w-4 cursor-pointer hover:bg-white/20 rounded-sm p-0.5 -m-0.5 focus:outline-none focus:ring-1 focus:ring-white/50">
911
+ <XCircle
912
+ className={cn(
913
+ "h-3 w-3",
914
+ responsiveSettings.compactMode &&
915
+ "h-2.5 w-2.5"
916
+ )}
917
+ />
918
+ </div>
919
+ </Badge>
920
+ );
921
+ })
922
+ .filter(Boolean)}
923
+ {selectedValues.length > responsiveSettings.maxCount && (
924
+ <Badge
925
+ className={cn(
926
+ "bg-transparent text-foreground border-foreground/1 hover:bg-transparent",
927
+ getBadgeAnimationClass(),
928
+ multiSelectVariants({ variant }),
929
+ singleLine && "min-w-0 max-w-[7rem]",
930
+ responsiveSettings.compactMode &&
931
+ "text-xs px-1.5 py-0.5",
932
+ singleLine && "flex-shrink-0 whitespace-nowrap",
933
+ "[&>svg]:pointer-events-auto"
934
+ )}
935
+ style={{
936
+ animationDuration: `${
937
+ animationConfig?.duration || animation
938
+ }s`,
939
+ animationDelay: `${animationConfig?.delay || 0}s`,
940
+ }}>
941
+ {`+ ${
942
+ selectedValues.length - responsiveSettings.maxCount
943
+ } more`}
944
+ <XCircle
945
+ className={cn(
946
+ "ml-2 h-4 w-4 cursor-pointer",
947
+ responsiveSettings.compactMode && "ml-1 h-3 w-3"
948
+ )}
949
+ onClick={(event) => {
950
+ event.stopPropagation();
951
+ clearExtraOptions();
952
+ }}
953
+ />
954
+ </Badge>
955
+ )}
956
+ </div>
957
+ <div className="flex items-center justify-between">
958
+ <div
959
+ role="button"
960
+ tabIndex={0}
961
+ onClick={(event) => {
962
+ event.stopPropagation();
963
+ handleClear();
964
+ }}
965
+ onKeyDown={(event) => {
966
+ if (event.key === "Enter" || event.key === " ") {
967
+ event.preventDefault();
968
+ event.stopPropagation();
969
+ handleClear();
970
+ }
971
+ }}
972
+ aria-label={`Clear all ${selectedValues.length} selected options`}
973
+ className="flex items-center justify-center h-4 w-4 mx-2 cursor-pointer text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1 rounded-sm">
974
+ <XIcon className="h-4 w-4" />
975
+ </div>
976
+ <Separator
977
+ orientation="vertical"
978
+ className="flex min-h-6 h-full"
979
+ />
980
+ <ChevronDown
981
+ className="h-4 mx-2 cursor-pointer text-muted-foreground"
982
+ aria-hidden="true"
983
+ />
984
+ </div>
985
+ </div>
986
+ ) : (
987
+ <div className="flex items-center justify-between w-full mx-auto">
988
+ <span className="text-sm text-muted-foreground mx-3">
989
+ {placeholder}
990
+ </span>
991
+ <ChevronDown className="h-4 cursor-pointer text-muted-foreground mx-2" />
992
+ </div>
993
+ )}
994
+ </Button>
995
+ </PopoverTrigger>
996
+ <PopoverContent
997
+ id={listboxId}
998
+ role="listbox"
999
+ aria-multiselectable="true"
1000
+ aria-label="Available options"
1001
+ className={cn(
1002
+ "w-auto p-0",
1003
+ getPopoverAnimationClass(),
1004
+ screenSize === "mobile" && "w-[85vw] max-w-[280px]",
1005
+ screenSize === "tablet" && "w-[70vw] max-w-md",
1006
+ screenSize === "desktop" && "min-w-[300px]",
1007
+ popoverClassName
1008
+ )}
1009
+ style={{
1010
+ animationDuration: `${animationConfig?.duration || animation}s`,
1011
+ animationDelay: `${animationConfig?.delay || 0}s`,
1012
+ maxWidth: `min(${widthConstraints.maxWidth}, 85vw)`,
1013
+ maxHeight: screenSize === "mobile" ? "70vh" : "60vh",
1014
+ touchAction: "manipulation",
1015
+ }}
1016
+ align="start"
1017
+ onEscapeKeyDown={() => setIsPopoverOpen(false)}>
1018
+ <Command>
1019
+ {searchable && (
1020
+ <CommandInput
1021
+ placeholder="Search options..."
1022
+ onKeyDown={handleInputKeyDown}
1023
+ value={searchValue}
1024
+ onValueChange={setSearchValue}
1025
+ aria-label="Search through available options"
1026
+ aria-describedby={`${multiSelectId}-search-help`}
1027
+ />
1028
+ )}
1029
+ {searchable && (
1030
+ <div id={`${multiSelectId}-search-help`} className="sr-only">
1031
+ Type to filter options. Use arrow keys to navigate results.
1032
+ </div>
1033
+ )}
1034
+ <CommandList
1035
+ className={cn(
1036
+ "max-h-[40vh] overflow-y-auto multiselect-scrollbar",
1037
+ screenSize === "mobile" && "max-h-[50vh]",
1038
+ "overscroll-behavior-y-contain"
1039
+ )}>
1040
+ <CommandEmpty>
1041
+ {emptyIndicator || "No results found."}
1042
+ </CommandEmpty>{" "}
1043
+ {!hideSelectAll && !searchValue && (
1044
+ <CommandGroup>
1045
+ <CommandItem
1046
+ key="all"
1047
+ onSelect={toggleAll}
1048
+ role="option"
1049
+ aria-selected={
1050
+ selectedValues.length ===
1051
+ getAllOptions().filter((opt) => !opt.disabled).length
1052
+ }
1053
+ aria-label={`Select all ${
1054
+ getAllOptions().length
1055
+ } options`}
1056
+ className="cursor-pointer">
1057
+ <div
1058
+ className={cn(
1059
+ "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
1060
+ selectedValues.length ===
1061
+ getAllOptions().filter((opt) => !opt.disabled)
1062
+ .length
1063
+ ? "bg-primary text-primary-foreground"
1064
+ : "opacity-50 [&_svg]:invisible"
1065
+ )}
1066
+ aria-hidden="true">
1067
+ <CheckIcon className="h-4 w-4" />
1068
+ </div>
1069
+ <span>
1070
+ (Select All
1071
+ {getAllOptions().length > 20
1072
+ ? ` - ${getAllOptions().length} options`
1073
+ : ""}
1074
+ )
1075
+ </span>
1076
+ </CommandItem>
1077
+ </CommandGroup>
1078
+ )}
1079
+ {isGroupedOptions(filteredOptions) ? (
1080
+ filteredOptions.map((group) => (
1081
+ <CommandGroup key={group.heading} heading={group.heading}>
1082
+ {group.options.map((option) => {
1083
+ const isSelected = selectedValues.includes(
1084
+ option.value
1085
+ );
1086
+ return (
1087
+ <CommandItem
1088
+ key={option.value}
1089
+ onSelect={() => toggleOption(option.value)}
1090
+ role="option"
1091
+ aria-selected={isSelected}
1092
+ aria-disabled={option.disabled}
1093
+ aria-label={`${option.label}${
1094
+ isSelected ? ", selected" : ", not selected"
1095
+ }${option.disabled ? ", disabled" : ""}`}
1096
+ className={cn(
1097
+ "cursor-pointer",
1098
+ option.disabled && "opacity-50 cursor-not-allowed"
1099
+ )}
1100
+ disabled={option.disabled}>
1101
+ <div
1102
+ className={cn(
1103
+ "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
1104
+ isSelected
1105
+ ? "bg-primary text-primary-foreground"
1106
+ : "opacity-50 [&_svg]:invisible"
1107
+ )}
1108
+ aria-hidden="true">
1109
+ <CheckIcon className="h-4 w-4" />
1110
+ </div>
1111
+ {option.icon && (
1112
+ <option.icon
1113
+ className="mr-2 h-4 w-4 text-muted-foreground"
1114
+ aria-hidden="true"
1115
+ />
1116
+ )}
1117
+ <span>{option.label}</span>
1118
+ </CommandItem>
1119
+ );
1120
+ })}
1121
+ </CommandGroup>
1122
+ ))
1123
+ ) : (
1124
+ <CommandGroup>
1125
+ {filteredOptions.map((option) => {
1126
+ const isSelected = selectedValues.includes(option.value);
1127
+ return (
1128
+ <CommandItem
1129
+ key={option.value}
1130
+ onSelect={() => toggleOption(option.value)}
1131
+ role="option"
1132
+ aria-selected={isSelected}
1133
+ aria-disabled={option.disabled}
1134
+ aria-label={`${option.label}${
1135
+ isSelected ? ", selected" : ", not selected"
1136
+ }${option.disabled ? ", disabled" : ""}`}
1137
+ className={cn(
1138
+ "cursor-pointer",
1139
+ option.disabled && "opacity-50 cursor-not-allowed"
1140
+ )}
1141
+ disabled={option.disabled}>
1142
+ <div
1143
+ className={cn(
1144
+ "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
1145
+ isSelected
1146
+ ? "bg-primary text-primary-foreground"
1147
+ : "opacity-50 [&_svg]:invisible"
1148
+ )}
1149
+ aria-hidden="true">
1150
+ <CheckIcon className="h-4 w-4" />
1151
+ </div>
1152
+ {option.icon && (
1153
+ <option.icon
1154
+ className="mr-2 h-4 w-4 text-muted-foreground"
1155
+ aria-hidden="true"
1156
+ />
1157
+ )}
1158
+ <span>{option.label}</span>
1159
+ </CommandItem>
1160
+ );
1161
+ })}
1162
+ </CommandGroup>
1163
+ )}
1164
+ <CommandSeparator />
1165
+ <CommandGroup>
1166
+ <div className="flex items-center justify-between">
1167
+ {selectedValues.length > 0 && (
1168
+ <>
1169
+ <CommandItem
1170
+ onSelect={handleClear}
1171
+ className="flex-1 justify-center cursor-pointer">
1172
+ Clear
1173
+ </CommandItem>
1174
+ <Separator
1175
+ orientation="vertical"
1176
+ className="flex min-h-6 h-full"
1177
+ />
1178
+ </>
1179
+ )}
1180
+ <CommandItem
1181
+ onSelect={() => setIsPopoverOpen(false)}
1182
+ className="flex-1 justify-center cursor-pointer max-w-full">
1183
+ Close
1184
+ </CommandItem>
1185
+ </div>
1186
+ </CommandGroup>
1187
+ </CommandList>
1188
+ </Command>
1189
+ </PopoverContent>
1190
+ {animation > 0 && selectedValues.length > 0 && (
1191
+ <WandSparkles
1192
+ className={cn(
1193
+ "cursor-pointer my-2 text-foreground bg-background w-3 h-3",
1194
+ isAnimating ? "" : "text-muted-foreground"
1195
+ )}
1196
+ onClick={() => setIsAnimating(!isAnimating)}
1197
+ />
1198
+ )}
1199
+ </Popover>
1200
+ </>
1201
+ );
1202
+ }
1203
+ );
1204
+
1205
+ MultiSelect.displayName = "MultiSelect";
1206
+ export type { MultiSelectOption, MultiSelectGroup, MultiSelectProps };