File size: 10,064 Bytes
4088a7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// ===== Custom Multi-Select Dropdown Component =====
// Replaces native <select multiple> with a modern chip-based UI

class MultiSelect {
    constructor(element, options = {}) {
        this.original = element;
        this.id = element.id;
        this.options = {
            placeholder: options.placeholder || 'Select...',
            searchable: options.searchable !== false,
            selectAll: options.selectAll !== false,
            maxDisplay: options.maxDisplay || 3,
        };

        // Extract options from the original <select>
        this.items = Array.from(element.options).map(o => ({
            value: o.value,
            label: o.textContent,
            selected: o.selected,
        }));

        this.selected = new Set(this.items.filter(i => i.selected).map(i => i.value));
        this.searchTerm = '';
        this.isOpen = false;

        this._build();
        this._bindEvents();
    }

    _build() {
        // Hide original select
        this.original.style.display = 'none';

        // Create wrapper
        this.wrapper = document.createElement('div');
        this.wrapper.className = 'ms-wrapper';
        this.wrapper.setAttribute('data-for', this.id);

        // Trigger button
        this.trigger = document.createElement('div');
        this.trigger.className = 'ms-trigger';
        this.trigger.tabIndex = 0;

        this.triggerContent = document.createElement('div');
        this.triggerContent.className = 'ms-trigger-content';

        this.triggerArrow = document.createElement('div');
        this.triggerArrow.className = 'ms-arrow';
        this.triggerArrow.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="6 9 12 15 18 9"/></svg>';

        this.trigger.appendChild(this.triggerContent);
        this.trigger.appendChild(this.triggerArrow);

        // Dropdown
        this.dropdown = document.createElement('div');
        this.dropdown.className = 'ms-dropdown';

        // Search input
        if (this.options.searchable && this.items.length > 5) {
            this.searchWrap = document.createElement('div');
            this.searchWrap.className = 'ms-search-wrap';
            this.searchInput = document.createElement('input');
            this.searchInput.type = 'text';
            this.searchInput.className = 'ms-search';
            this.searchInput.placeholder = 'Search...';
            this.searchWrap.appendChild(this.searchInput);
            this.dropdown.appendChild(this.searchWrap);
        }

        // Select All / Clear
        if (this.options.selectAll && this.items.length > 2) {
            this.actionsBar = document.createElement('div');
            this.actionsBar.className = 'ms-actions';
            this.actionsBar.innerHTML = `
                <button type="button" class="ms-action-btn ms-select-all">Select All</button>
                <button type="button" class="ms-action-btn ms-clear-all">Clear</button>
            `;
            this.dropdown.appendChild(this.actionsBar);
        }

        // Options list
        this.optionsList = document.createElement('div');
        this.optionsList.className = 'ms-options';
        this.dropdown.appendChild(this.optionsList);

        this.wrapper.appendChild(this.trigger);
        this.wrapper.appendChild(this.dropdown);

        // Insert after original
        this.original.parentNode.insertBefore(this.wrapper, this.original.nextSibling);

        this._renderOptions();
        this._renderTrigger();
    }

    _renderOptions() {
        const filtered = this.items.filter(item =>
            !this.searchTerm || item.label.toLowerCase().includes(this.searchTerm.toLowerCase())
        );

        this.optionsList.innerHTML = filtered.map(item => `
            <label class="ms-option ${this.selected.has(item.value) ? 'selected' : ''}" data-value="${item.value}">
                <span class="ms-checkbox ${this.selected.has(item.value) ? 'checked' : ''}">
                    <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20 6 9 17 4 12"/></svg>
                </span>
                <span class="ms-option-label">${item.label}</span>
            </label>
        `).join('');

        if (filtered.length === 0) {
            this.optionsList.innerHTML = '<div class="ms-empty">No matches</div>';
        }
    }

    _renderTrigger() {
        if (this.selected.size === 0) {
            this.triggerContent.innerHTML = `<span class="ms-placeholder">${this.options.placeholder}</span>`;
        } else if (this.selected.size <= this.options.maxDisplay) {
            const chips = Array.from(this.selected).map(val => {
                const item = this.items.find(i => i.value === val);
                return `<span class="ms-chip">${item ? item.label : val}<button type="button" class="ms-chip-remove" data-value="${val}">&times;</button></span>`;
            }).join('');
            this.triggerContent.innerHTML = chips;
        } else {
            const count = this.selected.size;
            const firstTwo = Array.from(this.selected).slice(0, 2).map(val => {
                const item = this.items.find(i => i.value === val);
                return item ? item.label : val;
            }).join(', ');
            this.triggerContent.innerHTML = `<span class="ms-chip">${firstTwo}</span><span class="ms-chip ms-chip-count">+${count - 2} more</span>`;
        }

        // Sync original select
        Array.from(this.original.options).forEach(o => {
            o.selected = this.selected.has(o.value);
        });
    }

    _bindEvents() {
        // Toggle dropdown
        this.trigger.addEventListener('click', (e) => {
            if (e.target.closest('.ms-chip-remove')) {
                const val = e.target.closest('.ms-chip-remove').dataset.value;
                this.selected.delete(val);
                this._renderTrigger();
                this._renderOptions();
                e.stopPropagation();
                return;
            }
            this.toggle();
        });

        // Keyboard
        this.trigger.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                this.toggle();
            } else if (e.key === 'Escape') {
                this.close();
            }
        });

        // Option click
        this.optionsList.addEventListener('click', (e) => {
            const option = e.target.closest('.ms-option');
            if (!option) return;
            const value = option.dataset.value;
            if (this.selected.has(value)) {
                this.selected.delete(value);
            } else {
                this.selected.add(value);
            }
            this._renderOptions();
            this._renderTrigger();
        });

        // Search
        if (this.searchInput) {
            this.searchInput.addEventListener('input', (e) => {
                this.searchTerm = e.target.value;
                this._renderOptions();
            });
            this.searchInput.addEventListener('click', (e) => e.stopPropagation());
        }

        // Select All / Clear
        if (this.actionsBar) {
            this.actionsBar.querySelector('.ms-select-all').addEventListener('click', (e) => {
                e.stopPropagation();
                this.items.forEach(i => this.selected.add(i.value));
                this._renderOptions();
                this._renderTrigger();
            });
            this.actionsBar.querySelector('.ms-clear-all').addEventListener('click', (e) => {
                e.stopPropagation();
                this.selected.clear();
                this._renderOptions();
                this._renderTrigger();
            });
        }

        // Close on outside click
        document.addEventListener('click', (e) => {
            if (!this.wrapper.contains(e.target)) {
                this.close();
            }
        });
    }

    toggle() {
        this.isOpen ? this.close() : this.open();
    }

    open() {
        this.isOpen = true;
        this.wrapper.classList.add('open');
        if (this.searchInput) {
            this.searchInput.value = '';
            this.searchTerm = '';
            this._renderOptions();
            setTimeout(() => this.searchInput.focus(), 50);
        }
    }

    close() {
        this.isOpen = false;
        this.wrapper.classList.remove('open');
    }

    getValues() {
        return Array.from(this.selected);
    }

    setValues(values) {
        this.selected = new Set(values);
        this._renderTrigger();
        this._renderOptions();
    }

    clear() {
        this.selected.clear();
        this._renderTrigger();
        this._renderOptions();
    }

    selectAll() {
        this.items.forEach(i => this.selected.add(i.value));
        this._renderTrigger();
        this._renderOptions();
    }
}

// Registry of all multi-select instances
window._multiSelects = {};

// Auto-initialize all <select multiple> elements
function initMultiSelects() {
    document.querySelectorAll('select[multiple]').forEach(el => {
        if (el.dataset.msInit) return; // already initialized
        el.dataset.msInit = 'true';
        const ms = new MultiSelect(el, {
            placeholder: el.dataset.placeholder || 'All',
            searchable: el.options.length > 5,
        });
        window._multiSelects[el.id] = ms;
    });
}

// Helper to get values from a multi-select by ID
function getMultiSelectValues(id) {
    const ms = window._multiSelects[id];
    if (ms) return ms.getValues();
    // Fallback to native
    const el = document.getElementById(id);
    if (!el) return [];
    return Array.from(el.selectedOptions).map(o => o.value);
}

// Helper to clear a multi-select by ID
function clearMultiSelect(id) {
    const ms = window._multiSelects[id];
    if (ms) ms.clear();
}

document.addEventListener('DOMContentLoaded', () => {
    initMultiSelects();
});