File size: 6,697 Bytes
3425d88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
201
202
203
204
205
206
/**
 * Initialize custom select components
 * @param {HTMLElement} select - The select container element
 */
function initSelect(select) {
  const type = select.dataset.type;
  const btn = select.querySelector('.select-btn');
  const label = select.querySelector('.select-label');
  const list = select.querySelector('.select-list');
  const input = select.querySelector('input[type="hidden"]');
  const arrow = btn.querySelector('svg');
  const selectedValues = new Map();

  let originalParent = list.parentNode;
  let movedToBody = false;
  let rafId = null;
  let portal = null;
  
  // Open/close functionality
  btn.addEventListener('click', (e) => {
    e.stopPropagation();
    const isOpen = !list.classList.contains('pointer-events-none');
    closeAllSelects();
    if (!isOpen) openList();
  });

  function openList() {
    if (!movedToBody) {
      originalParent = list.parentNode;
      portal = document.createElement('div');
      portal.className = 'select-portal';
      Object.assign(portal.style, {
        position: 'fixed',
        left: '0px',
        top: '0px',
        zIndex: '9999',
        pointerEvents: 'none'
      });
      portal.appendChild(list);
      document.body.appendChild(portal);
      movedToBody = true;
    }

    const btnRect = btn.getBoundingClientRect();
    const listRect = list.getBoundingClientRect();
    const margin = 8;
    const maxAllowed = Math.min((listRect.height + 12), 400);
    const spaceBelow = window.innerHeight - btnRect.bottom;
    const spaceAbove = btnRect.top;
    const preferBelow = spaceBelow >= Math.min(maxAllowed, spaceAbove);
    const availableSpace = preferBelow ? spaceBelow : spaceAbove;
    const maxHeight = Math.max(0, Math.min(maxAllowed, Math.floor(availableSpace - margin)));

    if (portal) {
      Object.assign(portal.style, {
        left: `${Math.round(btnRect.left)}px`,
        top: preferBelow
          ? `${Math.round(btnRect.bottom)}px`
          : `${Math.round(btnRect.top - maxHeight)}px`,
        minWidth: `${Math.round(btnRect.width)}px`,
        pointerEvents: 'auto'
      });
    }

    if (maxHeight > 0) {
      list.classList.remove('overflow-hidden');
      list.style.maxHeight = `${maxHeight}px`;
      list.style.overflowY = 'auto';
    }

    list.classList.remove('pointer-events-none', 'opacity-0', 'scale-95');
    list.classList.add('opacity-100', 'scale-100');
    if (arrow) arrow.classList.add('rotate-180');

    window.addEventListener('resize', updatePosition);
    window.addEventListener('scroll', updatePosition, true);
  }

  function updatePosition() {
    if (rafId) return;
    rafId = requestAnimationFrame(() => {
      const btnRect = btn.getBoundingClientRect();
      const listRect = list.getBoundingClientRect();
      const margin = 8;
      const maxAllowed = Math.min((listRect.height + 12), 400);
      const spaceBelow = window.innerHeight - btnRect.bottom;
      const spaceAbove = btnRect.top;
      const preferBelow = spaceBelow >= Math.min(maxAllowed, spaceAbove);
      const availableSpace = preferBelow ? spaceBelow : spaceAbove;
      const maxHeight = Math.max(0, Math.min(maxAllowed, Math.floor(availableSpace - margin)));

      if (portal) {
        portal.style.left = `${Math.round(btnRect.left)}px`;
        portal.style.top = preferBelow
          ? `${Math.round(btnRect.bottom)}px`
          : `${Math.round(btnRect.top - maxHeight)}px`;
      }

      if (maxHeight > 0) {
        list.style.maxHeight = `${maxHeight}px`;
      }

      rafId = null;
    });
  }

  function closeList() {
    list.classList.add('pointer-events-none', 'opacity-0', 'scale-95');
    list.classList.remove('opacity-100', 'scale-100');
    if (arrow) arrow.classList.remove('rotate-180');

    window.removeEventListener('resize', updatePosition);
    window.removeEventListener('scroll', updatePosition, true);
    if (rafId) { cancelAnimationFrame(rafId); rafId = null; }

    if (movedToBody) {
      originalParent.appendChild(list);
      if (portal && portal.parentNode) {
        portal.parentNode.removeChild(portal);
      }
      portal = null;
      movedToBody = false;
      list.style.position = '';
      list.style.left = '';
      list.style.top = '';
      list.style.minWidth = '';
      list.style.zIndex = '';
      list.style.maxHeight = '';
      list.style.overflowY = '';
    }
  }

  // Selection functionality
  list.querySelectorAll('li').forEach(li => {
    li.addEventListener('click', (e) => {
      e.stopPropagation();
      const value = li.dataset.value;
      const text = li.dataset.label;

      if (type === 'single') {
        input.value = value;
        label.textContent = text;
        input.dispatchEvent(new Event('change'));
        closeList();
      }

      if (type === 'multi') {
        const checkbox = li.querySelector('input[type="checkbox"]');
        checkbox.checked = !checkbox.checked;

        checkbox.checked
          ? selectedValues.set(value, text)
          : selectedValues.delete(value);

        const selected = Array.from(selectedValues.entries());
        input.value = selected.map(([v]) => v).join(',');
        input.dispatchEvent(new Event('change'));

        label.textContent = selected.length
          ? selected.map(([_, t]) => t).join(', ')
          : 'Select options';
      }
    });
  });

  // Expose methods
  select._list = list;
  select.close = closeList;
  select.reset = function() {
    input.value = '';
    label.textContent = type === 'single' ? 'Select an option' : 'Select options';
    selectedValues.clear();
    list.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = false);
  };
}

// Global close handler
window.addEventListener('click', (e) => {
  document.querySelectorAll('.custom-select').forEach(select => {
    const list = select._list || select.querySelector('.select-list');
    if (!select.contains(e.target) && (!list || !list.contains(e.target))) {
      if (typeof select.close === 'function') select.close();
    }
  });
});

function closeAllSelects() {
  document.querySelectorAll('.custom-select').forEach(select => {
    if (typeof select.close === 'function') {
      select.close();
    } else {
      const list = select.querySelector('.select-list');
      if (list) {
        list.classList.add('pointer-events-none', 'opacity-0', 'scale-95');
        list.classList.remove('opacity-100', 'scale-100');
      }
      const arrow = select.querySelector('svg');
      if (arrow) arrow.classList.remove('rotate-180');
    }
  });
}

// Initialize all selects on page load
document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('.custom-select').forEach(initSelect);
});