File size: 6,295 Bytes
d97b8f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import React, { useState, useRef, useEffect } from 'react';
import { cn } from '@/lib/utils';
import { ChevronDown, Check } from 'lucide-react';

export interface CustomSelectOption {
  value: string;
  label: string;
}

interface CustomSelectProps {
  options: CustomSelectOption[];
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  className?: string;
  triggerClassName?: string;
  dropdownClassName?: string;
  disabled?: boolean;
}

export const CustomSelect: React.FC<CustomSelectProps> = ({

  options,

  value,

  onChange,

  placeholder = "Select an option",

  className = "",

  triggerClassName = "",

  dropdownClassName = "",

  disabled = false,

}) => {
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Get the selected option label
  const selectedOption = options.find(option => option.value === value);
  const displayValue = selectedOption ? selectedOption.label : placeholder;

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    const handleTouchStart = (event: TouchEvent) => {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
      document.addEventListener('touchstart', handleTouchStart, { passive: true });
    }
    
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('touchstart', handleTouchStart);
    };
  }, [isOpen]);

  // Handle keyboard navigation
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (!isOpen) return;
      
      if (e.key === 'Escape') {
        setIsOpen(false);
      } else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
        e.preventDefault();
        const currentIndex = options.findIndex(option => option.value === value);
        let newIndex = currentIndex;
        
        if (e.key === 'ArrowDown') {
          newIndex = currentIndex < options.length - 1 ? currentIndex + 1 : 0;
        } else {
          newIndex = currentIndex > 0 ? currentIndex - 1 : options.length - 1;
        }
        
        onChange(options[newIndex].value);
      }
    };
    
    if (isOpen) {
      window.addEventListener('keydown', handleKeyDown);
    }
    
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [isOpen, options, value, onChange]);

  // Handle scroll locking when dropdown is open
  useEffect(() => {
    if (isOpen && dropdownRef.current) {
      // Scroll selected item into view
      const selectedItem = dropdownRef.current.querySelector('[aria-selected="true"]');
      if (selectedItem) {
        selectedItem.scrollIntoView({ block: 'nearest' });
      }
    }
  }, [isOpen, value]);

  // Toggle dropdown
  const handleToggle = (e: React.MouseEvent<HTMLDivElement>) => {
    e.stopPropagation();
    if (!disabled) {
      setIsOpen(!isOpen);
    }
  };

  // Select an option
  const handleSelect = (optionValue: string, e: React.MouseEvent) => {
    e.stopPropagation();
    e.preventDefault();
    onChange(optionValue);
    setIsOpen(false);
  };

  return (
    <div 

      ref={containerRef}

      className={cn(

        "relative inline-block w-full",

        className

      )}

    >

      {/* Trigger button */}

      <div

        className={cn(

          "flex items-center justify-between w-full px-3 py-2 text-sm border rounded-md cursor-pointer select-none",

          "bg-background border-input",

          disabled ? "opacity-50 cursor-not-allowed" : "hover:bg-accent/10",

          triggerClassName

        )}

        onClick={handleToggle}

        onTouchEnd={(e) => {

          e.stopPropagation();

          if (!disabled) {

            setIsOpen(!isOpen);

          }

        }}

        aria-haspopup="listbox"

        aria-expanded={isOpen}

        role="combobox"

        tabIndex={0}

      >

        <span className="truncate">{displayValue}</span>

        <ChevronDown className={cn("h-4 w-4 transition-transform duration-200", isOpen && "transform rotate-180")} />

      </div>



      {/* Dropdown menu */}

      {isOpen && (

        <div

          ref={dropdownRef}

          className={cn(

            "absolute z-[9999] w-full mt-1 bg-popover border border-border rounded-md shadow-md max-h-60 overflow-auto",

            "animate-in fade-in-0 zoom-in-95",

            dropdownClassName

          )}

          role="listbox"

          aria-orientation="vertical"

          style={{ 

            transformOrigin: 'top',

            boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',

          }}

        >

          <div className="py-1">

            {options.map((option) => (

              <div

                key={option.value}

                className={cn(

                  "flex items-center px-3 py-1.5 text-sm cursor-pointer select-none",

                  option.value === value

                    ? "bg-primary/10 text-primary font-medium"

                    : "text-foreground hover:bg-primary/5 hover:text-primary"

                )}

                role="option"

                aria-selected={option.value === value}

                tabIndex={-1}

                onClick={(e) => handleSelect(option.value, e)}

                onTouchEnd={(e) => {

                  e.stopPropagation();

                  handleSelect(option.value, e as any);

                }}

              >

                <span className="flex-grow truncate">{option.label}</span>

                {option.value === value && (

                  <Check className="h-4 w-4 ml-2 shrink-0 text-primary" />

                )}

              </div>

            ))}

          </div>

        </div>

      )}

    </div>
  );
};