zidan-select 2.1.1 → 2.2.0

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.
@@ -0,0 +1,2515 @@
1
+ /*!
2
+ * ZidanForm Select-only v2.2.0
3
+ * Zero-dependency select / combobox / tags enhancement. Every other control family is omitted.
4
+ * Pairs with plugin-select-core.css and plugin-select-theme.css.
5
+ *
6
+ * Generated by scripts/build.mjs — edit zidan-form.js instead.
7
+ * https://github.com/akhtar1985/zidan-select
8
+ * MIT License © akhtar1985
9
+ *
10
+ * Classic <script> adds window.ZidanForm plus window.ZidanSelect / zidanSelect / initZidanSelects.
11
+ */
12
+ (function (root, factory) {
13
+ 'use strict';
14
+ var api = factory(root);
15
+ if (typeof window !== 'undefined') {
16
+ window.ZidanForm = api.ZidanForm;
17
+ if (api.ZidanSelect) {
18
+ window.ZidanSelect = api.ZidanSelect;
19
+ window.zidanSelect = api.zidanSelect;
20
+ window.initZidanSelects = api.initZidanSelects;
21
+ }
22
+ if (api.zidanField) window.zidanField = api.zidanField;
23
+ if (api.initZidanForms) window.initZidanForms = api.initZidanForms;
24
+ if (api.registerIcon) window.registerZidanIcon = api.registerIcon;
25
+ }
26
+ if (typeof module !== 'undefined' && module.exports) {
27
+ module.exports = api;
28
+ }
29
+ })(typeof window !== 'undefined' ? window : this, function (global) {
30
+ 'use strict';
31
+
32
+ var VERSION = '2.2.0';
33
+
34
+ // Loading the file twice (classic script + module wrapper, or two bundles)
35
+ // must not replace the classes and orphan the live instances.
36
+ if (global && global.ZidanForm && global.ZidanForm.__zidanFormGuard === VERSION) {
37
+ return global.ZidanForm.api;
38
+ }
39
+
40
+ var doc = typeof document !== 'undefined' ? document : null;
41
+
42
+ /* ------------------------------------------------------------------ *
43
+ * Constants & tiny helpers
44
+ * ------------------------------------------------------------------ */
45
+
46
+ var LAYOUTS = ['classic-clean', 'floating-label', 'soft-pill', 'bordered-brutalist', 'glass-elevated'];
47
+ var FRAMEWORKS = ['auto', 'none', 'vanilla', 'bootstrap', 'tailwind', 'bulma', 'foundation'];
48
+ var THEMES = ['default', 'modern', 'minimal', 'dark', 'glass'];
49
+ var FIELD_LAYOUTS = ['stacked', 'inline', 'card', 'compact', 'floating', 'outlined'];
50
+ var FIELD_KINDS = ['checkbox', 'radio', 'radio-group', 'file', 'input', 'textarea'];
51
+ var FIELDS_SELECTOR = '[data-zidan], [data-zidan-checkbox], [data-zidan-switch], [data-zidan-radio], ' +
52
+ '[data-zidan-radio-group], [data-zidan-file], [data-zidan-input], [data-zidan-textarea], .zidan-field';
53
+ var SELECT_SELECTOR = '[data-zidan-select], .zidan-select';
54
+ var FORM_SCOPE_SELECTOR = '[data-zidan-form], .zidan-form';
55
+ var SCROLLBARS = ['default', 'thin', 'fancy', 'hover', 'hidden'];
56
+ var EVENT_PREFIX = 'zidan:';
57
+ var uidSeq = 0;
58
+
59
+ function uid(prefix) {
60
+ uidSeq += 1;
61
+ return (prefix || 'zs') + '-' + uidSeq.toString(36) + Math.random().toString(36).slice(2, 6);
62
+ }
63
+
64
+ function hasClass(node, cls) {
65
+ return !!(node && node.classList && node.classList.contains(cls));
66
+ }
67
+
68
+ function addClass(node, cls) {
69
+ if (!node || !cls) return node;
70
+ cls.split(/\s+/).forEach(function (c) {
71
+ if (c) node.classList.add(c);
72
+ });
73
+ return node;
74
+ }
75
+
76
+ function el(tag, className, attrs, text) {
77
+ var node = doc.createElement(tag);
78
+ if (className) node.className = className;
79
+ if (attrs) {
80
+ Object.keys(attrs).forEach(function (key) {
81
+ var value = attrs[key];
82
+ if (value === null || value === undefined || value === false) return;
83
+ if (key === 'text') node.textContent = String(value);
84
+ else node.setAttribute(key, value === true ? '' : String(value));
85
+ });
86
+ }
87
+ if (text !== undefined && text !== null) node.textContent = String(text);
88
+ return node;
89
+ }
90
+
91
+ function toArray(value) {
92
+ if (value === null || value === undefined || value === '') return [];
93
+ return Array.isArray(value) ? value.slice() : [value];
94
+ }
95
+
96
+ function isElement(value) {
97
+ return !!(value && typeof value === 'object' && value.nodeType === 1);
98
+ }
99
+
100
+ function readBoolAttr(value, fallback) {
101
+ if (value === undefined || value === null || value === '') return fallback;
102
+ var v = String(value).toLowerCase();
103
+ return !(v === 'false' || v === '0' || v === 'no' || v === 'off');
104
+ }
105
+
106
+ /* copy own keys from each source; later sources win */
107
+ function mergeOptions() {
108
+ var out = {};
109
+ for (var i = 0; i < arguments.length; i++) {
110
+ (function (source) {
111
+ if (!source || typeof source !== 'object') return;
112
+ Object.keys(source).forEach(function (key) {
113
+ if (source[key] !== undefined) out[key] = source[key];
114
+ });
115
+ })(arguments[i]);
116
+ }
117
+ return out;
118
+ }
119
+
120
+ /* data-zidan-options='{"mode":"tags",...}' — options for CMS/JSON-only setups */
121
+ function parseOptionsAttr(node) {
122
+ if (!node || !node.getAttribute) return null;
123
+ var raw = node.getAttribute('data-zidan-options');
124
+ if (!raw) return null;
125
+ try {
126
+ var parsed = JSON.parse(raw);
127
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
128
+ } catch (error) {
129
+ if (typeof console !== 'undefined' && console.warn) {
130
+ console.warn('[ZidanForm] ignoring invalid data-zidan-options JSON on', node, error);
131
+ }
132
+ return null;
133
+ }
134
+ }
135
+
136
+ function clamp(value, min, max) {
137
+ return Math.min(max, Math.max(min, value));
138
+ }
139
+
140
+ function fillTemplate(template, vars) {
141
+ return String(template).replace(/\{(\w+)\}/g, function (match, key) {
142
+ return vars && vars[key] !== undefined && vars[key] !== null ? String(vars[key]) : match;
143
+ });
144
+ }
145
+
146
+ /* ---------------- opt-in icon presets ---------------- */
147
+
148
+ var ICON_PATHS = {
149
+ text: '<path d="M4 7h16M4 12h10M4 17h13"/>',
150
+ mail: '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/>',
151
+ phone: '<path d="M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1 1 .4 1.9.7 2.8a2 2 0 0 1-.5 2.1L8.1 9.9a16 16 0 0 0 6 6l1.3-1.2a2 2 0 0 1 2.1-.5c.9.3 1.8.6 2.8.7a2 2 0 0 1 1.7 2Z"/>',
152
+ user: '<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>',
153
+ lock: '<rect x="4" y="10" width="16" height="11" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/>',
154
+ search: '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',
155
+ calendar: '<rect x="3" y="5" width="18" height="16" rx="2"/><path d="M16 3v4M8 3v4M3 11h18"/>',
156
+ clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
157
+ link: '<path d="M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1.5 1.5"/><path d="M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1.5-1.5"/>',
158
+ hash: '<path d="M4 9h16M4 15h16M10 3 8 21M16 3l-2 18"/>',
159
+ palette: '<path d="M12 3a9 9 0 0 0 0 18h1.5a2.5 2.5 0 0 0 0-5H12a2 2 0 0 1 0-4h4a5 5 0 0 0 0-10Z"/><circle cx="8.5" cy="8.5" r="1"/><circle cx="8" cy="14" r="1"/>',
160
+ sliders: '<path d="M4 7h16M4 17h16"/><circle cx="9" cy="7" r="2.5"/><circle cx="15" cy="17" r="2.5"/>',
161
+ file: '<path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/>',
162
+ upload: '<path d="M12 16V4"/><path d="m7 9 5-5 5 5"/><path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"/>',
163
+ eye: '<path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6-10-6-10-6Z"/><circle cx="12" cy="12" r="3"/>',
164
+ 'eye-off': '<path d="m3 3 18 18"/><path d="M10.6 6.2A9.9 9.9 0 0 1 12 6c6.5 0 10 6 10 6a17 17 0 0 1-3.1 3.6"/><path d="M6.4 6.7C3.5 8.4 2 12 2 12s3.5 6 10 6c1.7 0 3.2-.4 4.5-1"/><path d="M9.9 9.9a3 3 0 0 0 4.2 4.2"/>',
165
+ check: '<path d="m4 12.5 5 5L20 6.5"/>',
166
+ x: '<path d="M6 6l12 12M18 6 6 18"/>',
167
+ plus: '<path d="M12 5v14M5 12h14"/>',
168
+ minus: '<path d="M5 12h14"/>',
169
+ 'chevron-down': '<path d="m6 9 6 6 6-6"/>',
170
+ 'chevron-up': '<path d="m6 15 6-6 6 6"/>',
171
+ 'chevron-left': '<path d="m15 6-6 6 6 6"/>',
172
+ 'chevron-right': '<path d="m9 6 6 6-6 6"/>',
173
+ alert: '<path d="M12 9v4"/><path d="M12 17h.01"/><path d="M10.3 3.9 2.6 17.4A2 2 0 0 0 4.3 20h15.4a2 2 0 0 0 1.7-2.6L13.7 3.9a2 2 0 0 0-3.4 0Z"/>',
174
+ info: '<circle cx="12" cy="12" r="9"/><path d="M12 11v5"/><path d="M12 8h.01"/>',
175
+ globe: '<circle cx="12" cy="12" r="9"/><path d="M3 12h18"/><path d="M12 3a15 15 0 0 1 0 18 15 15 0 0 1 0-18Z"/>',
176
+ 'map-pin': '<path d="M20 10c0 6-8 12-8 12S4 16 4 10a8 8 0 1 1 16 0Z"/><circle cx="12" cy="10" r="3"/>',
177
+ image: '<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/>',
178
+ refresh: '<path d="M20 11a8 8 0 0 0-14.9-3.9L3 10"/><path d="M3 5v5h5"/><path d="M4 13a8 8 0 0 0 14.9 3.9L21 14"/><path d="M21 19v-5h-5"/>',
179
+ trash: '<path d="M4 7h16"/><path d="M9 7V4h6v3"/><path d="M6 7l1 13h10l1-13"/><path d="M10 11v5M14 11v5"/>'
180
+ };
181
+
182
+ var ICON_REGISTRY = {};
183
+ Object.keys(ICON_PATHS).forEach(function (key) { ICON_REGISTRY[key] = ICON_PATHS[key]; });
184
+ var ICON_NAMESPACE = 'http://www.w3.org/2000/svg';
185
+
186
+ var ICON_ALLOWED = {
187
+ svg: 1, g: 1, path: 1, circle: 1, rect: 1, line: 1, polyline: 1,
188
+ polygon: 1, ellipse: 1, title: 1, defs: 1, clipPath: 1, clippath: 1, mask: 1
189
+ };
190
+
191
+ function sanitizeIcon(markup) {
192
+ if (typeof markup !== 'string' || !markup.trim()) return '';
193
+ var parsed;
194
+ try {
195
+ if (typeof global.DOMParser === 'undefined') return '';
196
+ parsed = new global.DOMParser().parseFromString(markup, 'image/svg+xml');
197
+ } catch (err) {
198
+ return '';
199
+ }
200
+ if (!parsed || !parsed.documentElement) return '';
201
+ var svg = parsed.documentElement;
202
+ if (String(svg.nodeName).toLowerCase() !== 'svg') return '';
203
+ if (parsed.getElementsByTagName('parsererror').length) return '';
204
+ var walk = function (node) {
205
+ Array.prototype.slice.call(node.children || []).forEach(function (child) {
206
+ var tag = String(child.nodeName);
207
+ if (tag !== tag.toLowerCase()) tag = tag.toLowerCase();
208
+ if (!ICON_ALLOWED[tag]) {
209
+ child.parentNode.removeChild(child);
210
+ return;
211
+ }
212
+ Array.prototype.slice.call(child.attributes || []).forEach(function (attr) {
213
+ var name = String(attr.name).toLowerCase();
214
+ if (name.indexOf('on') === 0) child.removeAttribute(attr.name);
215
+ if ((name === 'href' || name === 'xlink:href') && !/^#/.test(attr.value)) child.removeAttribute(attr.name);
216
+ if (/url\s*\(\s*['"]?\s*(?:https?:|\/\/)/i.test(attr.value)) child.removeAttribute(attr.name);
217
+ });
218
+ walk(child);
219
+ });
220
+ };
221
+ walk(svg);
222
+ return svg.outerHTML;
223
+ }
224
+
225
+ function iconSvgFromMarkup(markup) {
226
+ var paths = markup;
227
+ if (/^\s*</.test(paths) && !/^\s*<svg/i.test(paths)) {
228
+ paths = '<svg xmlns="' + ICON_NAMESPACE + '" viewBox="0 0 24 24" fill="none" stroke="currentColor" ' +
229
+ 'stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' + paths + '</svg>';
230
+ } else if (!/^\s*<svg/i.test(paths)) {
231
+ paths = '';
232
+ }
233
+ return sanitizeIcon(paths);
234
+ }
235
+
236
+ function iconNode(spec, className) {
237
+ var markup = '';
238
+ var name = '';
239
+ if (typeof spec === 'string' && spec) {
240
+ name = spec;
241
+ if (/^\s*</.test(spec)) {
242
+ markup = iconSvgFromMarkup(spec) || iconSvgFromMarkup('<path d="M4 12h16"/>');
243
+ } else if (ICON_REGISTRY[spec]) {
244
+ markup = iconSvgFromMarkup(ICON_REGISTRY[spec]) || '';
245
+ }
246
+ } else if (spec && typeof spec === 'object' && spec.name) {
247
+ name = spec.name;
248
+ markup = iconSvgFromMarkup(ICON_REGISTRY[spec.name] || '');
249
+ }
250
+ if (!markup) return null;
251
+ var node = doc.createElement('span');
252
+ if (className) node.className = className;
253
+ node.setAttribute('data-zs-icon', name || 'custom');
254
+ try {
255
+ node.innerHTML = markup;
256
+ } catch (err) {
257
+ return null;
258
+ }
259
+ var svg = node.firstChild;
260
+ if (svg) {
261
+ svg.setAttribute('focusable', 'false');
262
+ svg.setAttribute('aria-hidden', 'true');
263
+ svg.setAttribute('width', '18');
264
+ svg.setAttribute('height', '18');
265
+ }
266
+ return node;
267
+ }
268
+
269
+ var TYPE_ICONS = {
270
+ text: 'text',
271
+ email: 'mail',
272
+ password: 'lock',
273
+ number: 'hash',
274
+ tel: 'phone',
275
+ url: 'link',
276
+ search: 'search',
277
+ date: 'calendar',
278
+ time: 'clock',
279
+ 'datetime-local': 'calendar',
280
+ month: 'calendar',
281
+ week: 'calendar',
282
+ range: 'sliders',
283
+ color: 'palette'
284
+ };
285
+
286
+ function iconForType(type) {
287
+ return TYPE_ICONS[type] || '';
288
+ }
289
+
290
+ function registerIcon(name, markup) {
291
+ if (!name || typeof markup !== 'string') return ZidanSelect;
292
+ ICON_REGISTRY[String(name)] = markup;
293
+ return ZidanSelect;
294
+ }
295
+
296
+ /* ---------------- field options (JS options + data-* attributes) ---------------- */
297
+
298
+ function fieldOption(node, options, key, attr, fallback) {
299
+ if (options && options[key] !== undefined && options[key] !== null) return options[key];
300
+ if (node && attr && node.getAttribute) {
301
+ var value = node.getAttribute('data-zidan-' + attr);
302
+ if (value !== null && value !== '') return value;
303
+ }
304
+ return fallback;
305
+ }
306
+
307
+ function fieldBool(node, options, key, attr, fallback) {
308
+ if (options && options[key] !== undefined && options[key] !== null) return !!options[key];
309
+ if (node && attr && node.getAttribute) {
310
+ var value = node.getAttribute('data-zidan-' + attr);
311
+ if (value !== null) return readBoolAttr(value, fallback);
312
+ }
313
+ return fallback;
314
+ }
315
+
316
+ function fieldNumber(node, options, key, attr, fallback) {
317
+ var value = fieldOption(node, options, key, attr, fallback);
318
+ if (value === null || value === undefined || value === '') return fallback;
319
+ var number = parseFloat(value);
320
+ return isFinite(number) ? number : fallback;
321
+ }
322
+
323
+ function fieldList(node, options, key, attr, fallback) {
324
+ var value = fieldOption(node, options, key, attr, null);
325
+ if (value === null || value === undefined || value === '') return fallback;
326
+ if (Array.isArray(value)) return value.slice();
327
+ return String(value).split(',').map(function (item) { return item.trim(); }).filter(Boolean);
328
+ }
329
+
330
+ /* ---------------- validation messages ---------------- */
331
+
332
+ var FIELD_MESSAGES = {
333
+ required: 'This field is required.',
334
+ email: 'Enter a valid email address.',
335
+ url: 'Enter a valid URL.',
336
+ pattern: 'The value does not match the expected format.',
337
+ min: 'Value must be at least {min}.',
338
+ max: 'Value must be at most {max}.',
339
+ step: 'Value must be a multiple of {step}.',
340
+ minlength: 'Use at least {minlength} characters.',
341
+ maxlength: 'Use at most {maxlength} characters.',
342
+ badInput: 'Enter a valid value.',
343
+ phone: 'Enter a valid phone number for {country}.',
344
+ integer: 'Enter a whole number.',
345
+ date: 'Enter a valid date.',
346
+ weekend: 'Weekends are not available — pick a weekday.',
347
+ dateDisabled: 'This date is not available.',
348
+ fileType: 'This file type is not allowed.',
349
+ fileSize: 'This file is too large.',
350
+ fileCount: 'Too many files.',
351
+ generic: 'Please check this field.'
352
+ };
353
+
354
+ function validityMessage(input, messages) {
355
+ if (!input || !input.validity || input.validity.valid) return '';
356
+ var v = input.validity;
357
+ var map = messages || FIELD_MESSAGES;
358
+ var type = String(input.type || '').toLowerCase();
359
+ var key = '';
360
+ var vars = { min: input.getAttribute('min'), max: input.getAttribute('max'), step: input.getAttribute('step') };
361
+ if (v.valueMissing) key = 'required';
362
+ else if (v.typeMismatch) key = type === 'email' ? 'email' : (type === 'url' ? 'url' : 'generic');
363
+ else if (v.patternMismatch) key = 'pattern';
364
+ else if (v.rangeUnderflow) key = 'min';
365
+ else if (v.rangeOverflow) key = 'max';
366
+ else if (v.stepMismatch) key = 'step';
367
+ else if (v.tooShort) {
368
+ key = 'minlength';
369
+ vars.minlength = input.getAttribute('minlength');
370
+ } else if (v.tooLong) {
371
+ key = 'maxlength';
372
+ vars.maxlength = input.getAttribute('maxlength');
373
+ } else if (v.badInput || v.customError) key = 'badInput';
374
+ if (!key) return input.validationMessage || map.generic;
375
+ return fillTemplate(map[key] || FIELD_MESSAGES[key] || map.generic, vars);
376
+ }
377
+
378
+ /* first non-empty value of any of `names`, walking up the tree */
379
+ function inheritedAttr(node, names) {
380
+ var current = node;
381
+ while (current && current.nodeType === 1) {
382
+ for (var i = 0; i < names.length; i += 1) {
383
+ var value = current.getAttribute(names[i]);
384
+ if (value) return value;
385
+ }
386
+ current = current.parentElement;
387
+ }
388
+ return '';
389
+ }
390
+
391
+ function pickList(value, list, fallback) {
392
+ var candidate = String(value || '').toLowerCase();
393
+ return list.indexOf(candidate) === -1 ? fallback : candidate;
394
+ }
395
+
396
+ /* theme/framework/layout resolution shared by every field and the select */
397
+ function resolveScope(node, options) {
398
+ var opts = options || {};
399
+ var theme = opts.theme || inheritedAttr(node, ['data-zidan-theme', 'data-zs-theme']);
400
+ if (!theme && doc) theme = doc.documentElement.getAttribute('data-zs-theme') || '';
401
+ var framework = opts.framework || inheritedAttr(node, ['data-zidan-framework', 'data-zs-framework']);
402
+ if (!framework && doc) framework = doc.documentElement.getAttribute('data-zs-framework') || '';
403
+ var layout = opts.layout || inheritedAttr(node, ['data-zidan-layout', 'data-zs-layout']);
404
+ return {
405
+ theme: pickList(theme, THEMES, 'default'),
406
+ framework: pickList(framework, FRAMEWORKS, 'none'),
407
+ layout: layout ? String(layout).toLowerCase() : ''
408
+ };
409
+ }
410
+
411
+ function debounce(fn, wait) {
412
+ var timer = null;
413
+ function debounced() {
414
+ var args = arguments;
415
+ clearTimeout(timer);
416
+ timer = setTimeout(function () {
417
+ timer = null;
418
+ fn.apply(null, args);
419
+ }, wait);
420
+ }
421
+ debounced.cancel = function () {
422
+ clearTimeout(timer);
423
+ timer = null;
424
+ };
425
+ return debounced;
426
+ }
427
+
428
+ /* ------------------------------------------------------------------ *
429
+ * Defaults
430
+ * ------------------------------------------------------------------ */
431
+
432
+ var DEFAULTS = {
433
+ /* core */
434
+ mode: null, // 'select' | 'combobox' | 'tags'
435
+ layout: 'classic-clean',
436
+ themeFramework: 'auto', // 'auto' | 'vanilla' | 'bootstrap' | 'tailwind'
437
+ id: null,
438
+ name: null,
439
+ disabled: false,
440
+ required: false,
441
+ /* data */
442
+ options: null,
443
+ value: null,
444
+ label: null, // floating label text (falls back to placeholder)
445
+ placeholder: null,
446
+ /* behaviour */
447
+ multiple: false,
448
+ searchable: null,
449
+ clearable: false,
450
+ closeOnSelect: null,
451
+ maxDropdownHeight: 280,
452
+ noResultsText: 'No results found',
453
+ emptyText: 'No options',
454
+ loadingText: 'Searching…',
455
+ clearText: 'Clear selection',
456
+ /* combobox / async */
457
+ fetchOptions: null,
458
+ debounce: 250,
459
+ minChars: 0,
460
+ allowFreeText: false,
461
+ searchValues: true,
462
+ /* tags */
463
+ maxTags: Infinity,
464
+ minTagLength: 1,
465
+ maxTagLength: Infinity,
466
+ caseSensitive: false,
467
+ delimiters: [','],
468
+ commitOnTab: false,
469
+ commitOnBlur: false,
470
+ suggestions: null,
471
+ valueDelimiter: ',',
472
+ /* styling */
473
+ customClasses: {},
474
+ validation: null, // null | 'valid' | 'invalid'
475
+ scrollbar: 'default', // 'default' | 'thin' | 'fancy' | 'hover' | 'hidden'
476
+ /* callbacks */
477
+ filterOption: null,
478
+ renderOption: null,
479
+ renderSelected: null,
480
+ renderTag: null,
481
+ validateTag: null,
482
+ formatTag: null,
483
+ onInit: null,
484
+ onChange: null,
485
+ onSelect: null,
486
+ onOpen: null,
487
+ onClose: null,
488
+ onTagAdd: null,
489
+ onTagRemove: null,
490
+ onError: null
491
+ };
492
+
493
+ /* ------------------------------------------------------------------ *
494
+ * ZidanSelect
495
+ * ------------------------------------------------------------------ */
496
+
497
+ function ZidanSelect(target, options) {
498
+ if (!(this instanceof ZidanSelect)) return new ZidanSelect(target, options);
499
+ if (!doc) throw new Error('ZidanSelect requires a DOM environment.');
500
+
501
+ var element = typeof target === 'string' ? doc.querySelector(target) : target;
502
+ if (!isElement(element)) throw new Error('ZidanSelect: target element not found.');
503
+ if (element.__zidanSelect instanceof ZidanSelect) {
504
+ element.__zidanSelect.destroy();
505
+ }
506
+
507
+ this.el = element;
508
+ this.opts = this._normalizeOptions(options || {});
509
+ this.mode = this.opts.mode;
510
+ this.layout = this.opts.layout;
511
+ this.id = this.opts.id || uid('zs');
512
+ this.isMount = /^(DIV|SPAN|SECTION|ARTICLE|FORM-FIELD)$/i.test(element.tagName) ||
513
+ (element.hasAttribute('data-zidan-select') || hasClass(element, 'zidan-select')) &&
514
+ !/^(SELECT|INPUT|TEXTAREA)$/i.test(element.tagName);
515
+ this.native = this.isMount ? null : element;
516
+ this.syncEl = null;
517
+
518
+ this.items = [];
519
+ this.value_ = [];
520
+ this.tags = [];
521
+ this.activeIndex = -1;
522
+ this.opened = false;
523
+ this.loading = false;
524
+ this.error = null;
525
+ this.query = '';
526
+ this.rendered = [];
527
+ this.listeners = new Map();
528
+ this.asyncController = null;
529
+ this.timer = null;
530
+ this.savedInputText = '';
531
+ this.disabled_ = !!this.opts.disabled;
532
+ this.destroyed = false;
533
+ this.resizeObserver = null;
534
+
535
+ this._prepareData();
536
+ this._build();
537
+ this._prepareSync();
538
+ this._bind();
539
+ this._setInitialValue();
540
+ this._render();
541
+ this._observeResize();
542
+
543
+ element.__zidanSelect = this;
544
+ this.emit('init', { instance: this, mode: this.mode, layout: this.layout, framework: this.framework });
545
+ this.call('onInit', { instance: this, mode: this.mode, value: this.getValue() });
546
+ }
547
+
548
+ /* ---------------- option normalisation ---------------- */
549
+
550
+ ZidanSelect.prototype._normalizeOptions = function (options) {
551
+ options = mergeOptions(parseOptionsAttr(this.el), options);
552
+ var d = this.el.dataset || {};
553
+ var isNativeSelect = this.el.tagName === 'SELECT';
554
+ var isTagsMount = /tags/i.test(d.zidanSelect || '') || /tags/i.test(d.zidanMode || '');
555
+
556
+ var mode = options.mode || d.zidanMode || d.zidanSelect || (isTagsMount ? 'tags' : 'select');
557
+ mode = String(mode).toLowerCase();
558
+ if (mode === 'multi' || mode === 'multiselect') mode = 'select';
559
+ if (['select', 'combobox', 'tags'].indexOf(mode) === -1) mode = 'select';
560
+
561
+ var nativeMultiple = isNativeSelect ? this.el.multiple : false;
562
+
563
+ var framework = options.themeFramework || d.zidanFramework || 'auto';
564
+ framework = String(framework).toLowerCase();
565
+ if (FRAMEWORKS.indexOf(framework) === -1) framework = 'auto';
566
+
567
+ var layout = options.layout || d.zidanLayout || 'classic-clean';
568
+ layout = String(layout).toLowerCase();
569
+ if (LAYOUTS.indexOf(layout) === -1) layout = 'classic-clean';
570
+
571
+ var scrollbar = options.scrollbar || d.zidanScrollbar || DEFAULTS.scrollbar;
572
+ scrollbar = String(scrollbar).toLowerCase();
573
+ if (SCROLLBARS.indexOf(scrollbar) === -1) scrollbar = DEFAULTS.scrollbar;
574
+
575
+ var pick = function (key, fallback) {
576
+ return options[key] !== undefined && options[key] !== null ? options[key] : fallback;
577
+ };
578
+
579
+ var placeholderDefault = mode === 'tags' ? 'Add a tag…' : (mode === 'combobox' ? 'Type to search…' : 'Select an option…');
580
+
581
+ var merged = {};
582
+ Object.keys(DEFAULTS).forEach(function (key) {
583
+ merged[key] = DEFAULTS[key];
584
+ });
585
+
586
+ merged.mode = mode;
587
+ merged.layout = layout;
588
+ merged.themeFramework = framework;
589
+ merged.multiple = mode === 'tags' ? true : pick('multiple', nativeMultiple || readBoolAttr(d.zidanMultiple, false));
590
+ merged.searchable = pick('searchable', readBoolAttr(d.zidanSearchable, mode !== 'select'));
591
+ merged.clearable = pick('clearable', readBoolAttr(d.zidanClearable, false));
592
+ merged.disabled = pick('disabled', readBoolAttr(d.zidanDisabled, isNativeSelect ? this.el.disabled : false));
593
+ merged.placeholder = pick('placeholder',
594
+ d.zidanPlaceholder || (this.el.getAttribute && this.el.getAttribute('placeholder')) || placeholderDefault);
595
+ merged.label = pick('label', d.zidanLabel || null);
596
+ merged.name = pick('name', d.zidanName || (this.el.getAttribute && this.el.getAttribute('name')) || null);
597
+ merged.allowFreeText = pick('allowFreeText', readBoolAttr(d.zidanAllowFreeText, mode === 'tags'));
598
+ merged.maxTags = pick('maxTags', d.zidanMaxTags ? parseInt(d.zidanMaxTags, 10) || Infinity : DEFAULTS.maxTags);
599
+ merged.minTagLength = pick('minTagLength', d.zidanMinTagLength ? parseInt(d.zidanMinTagLength, 10) || 1 : DEFAULTS.minTagLength);
600
+ merged.maxTagLength = pick('maxTagLength', d.zidanMaxTagLength ? parseInt(d.zidanMaxTagLength, 10) || Infinity : DEFAULTS.maxTagLength);
601
+ merged.caseSensitive = pick('caseSensitive', readBoolAttr(d.zidanCaseSensitive, false));
602
+ merged.validation = pick('validation', d.zidanValidation || null);
603
+ merged.options = pick('options', null);
604
+ merged.suggestions = pick('suggestions', null);
605
+
606
+ // carry over every explicitly-passed option (callbacks, custom classes, ...)
607
+ Object.keys(options).forEach(function (key) {
608
+ if (options[key] !== undefined) merged[key] = options[key];
609
+ });
610
+
611
+ // these three are authoritative after the merge
612
+ merged.mode = mode;
613
+ merged.layout = layout;
614
+ merged.themeFramework = framework;
615
+ merged.scrollbar = scrollbar;
616
+ if (!merged.theme) merged.theme = d.zidanTheme || d.zsTheme || '';
617
+ if (mode === 'combobox') merged.searchable = true;
618
+ if (mode === 'tags' && merged.searchable === false) merged.searchable = true;
619
+ if (mode === 'tags') merged.multiple = true;
620
+ return merged;
621
+ };
622
+
623
+ ZidanSelect.prototype._prepareData = function () {
624
+ var source = this.opts.options;
625
+ if (!source && this.el.tagName === 'SELECT') source = this._optionsFromSelect(this.el);
626
+ if (!source) source = this.opts.suggestions || [];
627
+ this.items = this._normalizeItems(source);
628
+ if (this.mode === 'tags') {
629
+ var suggestionSource = this.opts.suggestions || this.opts.options;
630
+ if (!suggestionSource && this.el.tagName === 'SELECT') suggestionSource = this._optionsFromSelect(this.el);
631
+ this.suggestions = this._normalizeItems(suggestionSource || []);
632
+ }
633
+ };
634
+
635
+ ZidanSelect.prototype._optionsFromSelect = function (select) {
636
+ var out = [];
637
+ Array.prototype.slice.call(select.children || []).forEach(function (node) {
638
+ if (node.tagName === 'OPTGROUP') {
639
+ var groupLabel = node.label || '';
640
+ Array.prototype.slice.call(node.children).forEach(function (opt) {
641
+ if (opt.tagName !== 'OPTION') return;
642
+ out.push({
643
+ value: opt.value,
644
+ label: opt.textContent.trim(),
645
+ group: groupLabel,
646
+ disabled: opt.disabled
647
+ });
648
+ });
649
+ } else if (node.tagName === 'OPTION') {
650
+ out.push({
651
+ value: node.value,
652
+ label: node.textContent.trim(),
653
+ disabled: node.disabled
654
+ });
655
+ }
656
+ });
657
+ return out;
658
+ };
659
+
660
+ ZidanSelect.prototype._normalizeItems = function (input) {
661
+ var list = toArray(input);
662
+ var out = [];
663
+ var self = this;
664
+
665
+ list.forEach(function (item, index) {
666
+ if (item === null || item === undefined) return;
667
+ if (typeof item === 'string' || typeof item === 'number') {
668
+ out.push({ value: String(item), label: String(item), group: null, disabled: false });
669
+ return;
670
+ }
671
+ if (typeof item === 'object' && Array.isArray(item.options)) {
672
+ var groupName = item.label !== undefined ? String(item.label) : (item.group || '');
673
+ self._normalizeItems(item.options).forEach(function (child) {
674
+ child.group = groupName;
675
+ out.push(child);
676
+ });
677
+ return;
678
+ }
679
+ if (typeof item === 'object') {
680
+ var value = item.value !== undefined ? item.value : item.label !== undefined ? item.label : index;
681
+ out.push({
682
+ value: String(value),
683
+ label: item.label !== undefined ? String(item.label) : String(value),
684
+ group: item.group !== undefined ? String(item.group) : null,
685
+ disabled: !!item.disabled,
686
+ data: item.data
687
+ });
688
+ }
689
+ });
690
+ return out;
691
+ };
692
+
693
+ /* ---------------- DOM building ---------------- */
694
+
695
+ ZidanSelect.prototype._resolveFramework = function () {
696
+ if (this.opts.themeFramework && this.opts.themeFramework !== 'auto') return this.opts.themeFramework;
697
+ if (!doc) return 'vanilla';
698
+ try {
699
+ var rootStyle = global.getComputedStyle(doc.documentElement);
700
+ var bsBg = rootStyle.getPropertyValue('--bs-body-bg');
701
+ if (bsBg && bsBg.trim()) return 'bootstrap';
702
+ var sheets = doc.styleSheets || [];
703
+ for (var i = 0; i < sheets.length; i += 1) {
704
+ var href = sheets[i].href || '';
705
+ if (/bootstrap(\.min)?\.css/i.test(href)) return 'bootstrap';
706
+ if (/tailwind/i.test(href)) return 'tailwind';
707
+ }
708
+ if (doc.body && global.getComputedStyle(doc.body).getPropertyValue('--tw-ring-offset-shadow') !== '') return 'tailwind';
709
+ if (doc.querySelector('.btn-primary, .form-select, .form-control, .navbar')) return 'bootstrap';
710
+ } catch (err) { /* ignore: cross-origin or no CSSOM */ }
711
+ return 'vanilla';
712
+ };
713
+
714
+ ZidanSelect.prototype._applyCustomClass = function (node, key) {
715
+ var map = this.opts.customClasses || {};
716
+ var value = map[key];
717
+ if (value) addClass(node, value);
718
+ return node;
719
+ };
720
+
721
+ ZidanSelect.prototype._toggleCustomClass = function (node, key, on) {
722
+ var map = this.opts.customClasses || {};
723
+ var value = map[key];
724
+ if (!value) return node;
725
+ String(value).split(/\s+/).forEach(function (cls) {
726
+ if (!cls) return;
727
+ if (on) node.classList.add(cls);
728
+ else node.classList.remove(cls);
729
+ });
730
+ return node;
731
+ };
732
+
733
+ ZidanSelect.prototype._build = function () {
734
+ var self = this;
735
+ var opts = this.opts;
736
+ this.framework = this._resolveFramework();
737
+
738
+ var existingWrapper = this.el.parentNode && this.el.parentNode.classList &&
739
+ this.el.parentNode.classList.contains('zs-root--mount');
740
+
741
+ var scope = resolveScope(this.el, { theme: opts.theme, framework: opts.themeFramework, layout: opts.layout });
742
+ this.theme = scope.theme;
743
+
744
+ var rootEl = el('div', 'zs-root');
745
+ rootEl.id = this.id + '-root';
746
+ rootEl.setAttribute('data-zs-theme', this.theme);
747
+ rootEl.setAttribute('data-zs-layout', this.layout);
748
+ rootEl.setAttribute('data-zs-framework', this.framework);
749
+ rootEl.setAttribute('data-zs-mode', this.mode);
750
+ rootEl.setAttribute('data-zs-scrollbar', opts.scrollbar || 'default');
751
+ rootEl.classList.add('zs-root--' + this.mode);
752
+ if (this.mode === 'tags') rootEl.classList.add('zs-root--multiple');
753
+ if (opts.multiple && this.mode === 'select') rootEl.classList.add('zs-root--multiple');
754
+ if (this.layout === 'floating-label') rootEl.classList.add('zs-root--labeled');
755
+ this._applyCustomClass(rootEl, 'root');
756
+
757
+ /* control ------------------------------------------------------- */
758
+ var control = el('div', 'zs-control');
759
+ if (this.framework === 'bootstrap') {
760
+ control.classList.add('form-control', 'zs-bootstrap-control');
761
+ if (this.el.tagName === 'SELECT') control.classList.add('form-select');
762
+ }
763
+ this._applyCustomClass(control, 'control');
764
+
765
+ var chips = el('div', 'zs-chips');
766
+ chips.hidden = true;
767
+
768
+ var input = doc.createElement('input');
769
+ input.type = 'text';
770
+ input.className = 'zs-input';
771
+ input.id = this.id + '-input';
772
+ input.autocomplete = 'off';
773
+ input.spellcheck = false;
774
+ input.setAttribute('role', 'combobox');
775
+ input.setAttribute('aria-expanded', 'false');
776
+ input.setAttribute('aria-controls', this.id + '-listbox');
777
+ input.setAttribute('aria-autocomplete', (opts.searchable || this.mode !== 'select') ? 'list' : 'none');
778
+ input.setAttribute('aria-haspopup', 'listbox');
779
+ if (opts.ariaLabel || opts.label) input.setAttribute('aria-label', opts.ariaLabel || opts.label);
780
+ if (opts.disabled) input.disabled = true;
781
+ this._applyCustomClass(input, 'input');
782
+
783
+ var labelEl = null;
784
+ if (opts.label) {
785
+ labelEl = el('label', 'zs-label', { for: input.id });
786
+ labelEl.textContent = opts.label;
787
+ if (this.layout !== 'floating-label') rootEl.classList.add('zs-root--has-static-label');
788
+ }
789
+
790
+ var clearBtn = el('button', 'zs-clear', {
791
+ type: 'button',
792
+ tabindex: '-1',
793
+ 'aria-label': opts.clearText,
794
+ title: opts.clearText
795
+ });
796
+ clearBtn.innerHTML = '<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true" focusable="false"><path d="M3 3l10 10M13 3L3 13" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>';
797
+ clearBtn.hidden = true;
798
+
799
+ var arrow = el('span', 'zs-arrow', { 'aria-hidden': 'true' });
800
+ arrow.innerHTML = '<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false"><path d="M3.5 6l4.5 4.5L12.5 6" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>';
801
+
802
+ control.appendChild(chips);
803
+ control.appendChild(input);
804
+ control.appendChild(clearBtn);
805
+ control.appendChild(arrow);
806
+
807
+ if (labelEl) {
808
+ if (this.layout === 'floating-label') control.insertBefore(labelEl, chips);
809
+ else rootEl.appendChild(labelEl);
810
+ }
811
+
812
+ /* dropdown ------------------------------------------------------ */
813
+ var dropdown = el('div', 'zs-dropdown');
814
+ dropdown.id = this.id + '-listbox';
815
+ dropdown.setAttribute('role', 'listbox');
816
+ if (this.mode !== 'tags') {
817
+ dropdown.setAttribute('aria-multiselectable', String(!!(opts.multiple || this.mode === 'tags')));
818
+ }
819
+ this._applyCustomClass(dropdown, 'dropdown');
820
+
821
+ var live = el('div', 'zs-live', { 'aria-live': 'polite', 'aria-atomic': 'true' });
822
+
823
+ rootEl.appendChild(control);
824
+ rootEl.appendChild(dropdown);
825
+ rootEl.appendChild(live);
826
+
827
+ if (this.framework === 'bootstrap') {
828
+ if (opts.validation === 'invalid') control.classList.add('is-invalid');
829
+ if (opts.validation === 'valid') control.classList.add('is-valid');
830
+ if (this.mode === 'tags' || opts.multiple) rootEl.classList.add('zs-root--bootstrap');
831
+ }
832
+
833
+ /* mount into DOM ------------------------------------------------ */
834
+ if (this.isMount) {
835
+ if (!existingWrapper) this.el.classList.add('zs-root--mount');
836
+ this.el.appendChild(rootEl);
837
+ } else {
838
+ this.el.parentNode.insertBefore(rootEl, this.el);
839
+ }
840
+
841
+ this.root = rootEl;
842
+ this.controlEl = control;
843
+ this.chipsEl = chips;
844
+ this.input = input;
845
+ this.dropdown = dropdown;
846
+ this.clearBtn = clearBtn;
847
+ this.arrowEl = arrow;
848
+ this.labelEl = labelEl;
849
+ this.liveEl = live;
850
+ };
851
+
852
+ ZidanSelect.prototype._prepareSync = function () {
853
+ var self = this;
854
+ var opts = this.opts;
855
+
856
+ if (this.native) {
857
+ if (this.native.tagName === 'SELECT') {
858
+ this.syncEl = this.native;
859
+ if (this.native.multiple) {
860
+ this.opts.multiple = true;
861
+ this.root.classList.add('zs-root--multiple');
862
+ }
863
+ this.native.hidden = true;
864
+ this.native.classList.add('zs-native');
865
+ this.native.setAttribute('tabindex', '-1');
866
+ this.native.setAttribute('aria-hidden', 'true');
867
+ } else {
868
+ this.syncEl = this.native;
869
+ this.native.hidden = true;
870
+ this.native.setAttribute('tabindex', '-1');
871
+ this.native.setAttribute('aria-hidden', 'true');
872
+ }
873
+ // NOTE: `required` is intentionally NOT copied to the hidden native
874
+ // control — a display:none required field blocks submit with an
875
+ // unfocusable invalid control. We expose aria-required on our input
876
+ // and validation via setValidation('invalid').
877
+ if (opts.required) this.input.setAttribute('aria-required', 'true');
878
+ this.form = this.native.closest ? this.native.closest('form') : null;
879
+ } else {
880
+ if (opts.name) {
881
+ var hidden = el('input', 'zs-hidden', { type: 'hidden', name: opts.name });
882
+ this.root.appendChild(hidden);
883
+ this.syncEl = hidden;
884
+ this.form = this.el.closest ? this.el.closest('form') : null;
885
+ } else {
886
+ this.form = this.el.closest ? this.el.closest('form') : null;
887
+ }
888
+ }
889
+
890
+ if (this.form) {
891
+ this.onFormReset = function () {
892
+ setTimeout(function () { self._handleFormReset(); }, 0);
893
+ };
894
+ this.form.addEventListener('reset', this.onFormReset);
895
+ }
896
+ return this.syncEl;
897
+ };
898
+
899
+ /* ---------------- initial value ---------------- */
900
+
901
+ ZidanSelect.prototype._setInitialValue = function () {
902
+ var opts = this.opts;
903
+ var initial = opts.value;
904
+
905
+ if (initial === null || initial === undefined) {
906
+ if (this.native && this.native.tagName === 'SELECT') {
907
+ initial = this.native.multiple
908
+ ? Array.prototype.filter.call(this.native.options, function (o) { return o.selected; }).map(function (o) { return o.value; })
909
+ : this.native.value;
910
+ } else if (this.native) {
911
+ initial = this.native.value;
912
+ }
913
+ }
914
+
915
+ if (this.mode === 'tags') {
916
+ var raw = initial;
917
+ if (typeof raw === 'string' && raw && !Array.isArray(raw) && this.syncEl && this.syncEl.tagName !== 'SELECT') {
918
+ raw = raw.split(opts.valueDelimiter);
919
+ }
920
+ toArray(raw).forEach(function (tag) { this._addTagObject(String(tag), { silent: true }); }, this);
921
+ return;
922
+ }
923
+
924
+ if (initial === null || initial === undefined || initial === '') return;
925
+ this._setValueInternal(initial, { silent: true });
926
+ };
927
+
928
+ ZidanSelect.prototype._handleFormReset = function () {
929
+ var initial;
930
+ if (this.native && this.native.tagName === 'SELECT') {
931
+ initial = this.native.multiple
932
+ ? Array.prototype.filter.call(this.native.options, function (o) { return o.selected; }).map(function (o) { return o.value; })
933
+ : this.native.value;
934
+ } else if (this.native) {
935
+ initial = this.native.value;
936
+ } else if (this.opts.value !== null && this.opts.value !== undefined) {
937
+ initial = this.opts.value;
938
+ }
939
+
940
+ if (this.mode === 'tags') {
941
+ this.value_ = [];
942
+ toArray(initial).forEach(function (tag) { this._addTagObject(tag, { silent: true }); }, this);
943
+ this._render();
944
+ this._syncNative();
945
+ return;
946
+ }
947
+ this._setValueInternal(initial, { silent: true });
948
+ this._render();
949
+ };
950
+
951
+ /* ---------------- value helpers ---------------- */
952
+
953
+ ZidanSelect.prototype._hasValue = function (value) {
954
+ var needle = this.opts.caseSensitive ? String(value) : String(value).toLowerCase();
955
+ for (var i = 0; i < this.value_.length; i += 1) {
956
+ var current = this.opts.caseSensitive ? this.value_[i].value : this.value_[i].value.toLowerCase();
957
+ if (current === needle) return true;
958
+ }
959
+ return false;
960
+ };
961
+
962
+ ZidanSelect.prototype._itemFor = function (value) {
963
+ var needle = String(value);
964
+ for (var i = 0; i < this.items.length; i += 1) {
965
+ if (this.items[i].value === needle) return this.items[i];
966
+ }
967
+ for (var j = 0; j < this.value_.length; j += 1) {
968
+ if (this.value_[j].value === needle) return this.value_[j];
969
+ }
970
+ return { value: needle, label: needle };
971
+ };
972
+
973
+ ZidanSelect.prototype._setValueInternal = function (input, config) {
974
+ var cfg = config || {};
975
+ var previous = this.getValue();
976
+ var self = this;
977
+ var values = toArray(input);
978
+ var next = [];
979
+
980
+ values.forEach(function (value) {
981
+ if (value === null || value === undefined || value === '') return;
982
+ if (typeof value === 'object') {
983
+ next.push({ value: String(value.value !== undefined ? value.value : value.label), label: String(value.label !== undefined ? value.label : value.value), data: value.data });
984
+ return;
985
+ }
986
+ var str = String(value);
987
+ var match = null;
988
+ for (var i = 0; i < self.items.length; i += 1) {
989
+ if (self.items[i].value === str) { match = self.items[i]; break; }
990
+ }
991
+ next.push(match ? { value: match.value, label: match.label, data: match.data } : { value: str, label: str });
992
+ });
993
+
994
+ if (!this.opts.multiple && this.mode !== 'tags') next = next.slice(0, 1);
995
+ this.value_ = next;
996
+ if (next.length && this.opts.validation === 'invalid') this.opts.validation = null;
997
+ this._render();
998
+ this._syncNative();
999
+ if (!cfg.silent) {
1000
+ var current = this.getValue();
1001
+ if (current !== previous && JSON.stringify(current) !== JSON.stringify(previous)) {
1002
+ this.emit('change', { value: current, previousValue: previous, instance: this });
1003
+ this.call('onChange', { value: current, previousValue: previous, instance: this });
1004
+ }
1005
+ }
1006
+ return this;
1007
+ };
1008
+
1009
+ ZidanSelect.prototype._syncNative = function () {
1010
+ var sel = this.syncEl;
1011
+ if (!sel) return;
1012
+ var values = this.value_.map(function (v) { return v.value; });
1013
+
1014
+ if (sel.tagName === 'SELECT') {
1015
+ var i;
1016
+ if (sel.multiple) {
1017
+ for (i = 0; i < sel.options.length; i += 1) {
1018
+ sel.options[i].selected = values.indexOf(sel.options[i].value) !== -1;
1019
+ }
1020
+ var existing = Array.prototype.map.call(sel.options, function (o) { return o.value; });
1021
+ values.forEach(function (value) {
1022
+ if (existing.indexOf(value) === -1) {
1023
+ var option = doc.createElement('option');
1024
+ option.value = value;
1025
+ option.textContent = value;
1026
+ option.selected = true;
1027
+ sel.appendChild(option);
1028
+ }
1029
+ });
1030
+ } else {
1031
+ var target = values[0];
1032
+ if (target === undefined) {
1033
+ sel.value = '';
1034
+ } else {
1035
+ var found = false;
1036
+ for (i = 0; i < sel.options.length; i += 1) {
1037
+ if (sel.options[i].value === target) { found = true; break; }
1038
+ }
1039
+ if (!found) {
1040
+ var newOption = doc.createElement('option');
1041
+ newOption.value = target;
1042
+ newOption.textContent = this._itemFor(target).label;
1043
+ sel.appendChild(newOption);
1044
+ }
1045
+ sel.value = target;
1046
+ }
1047
+ }
1048
+ } else {
1049
+ sel.value = (this.opts.multiple || this.mode === 'tags')
1050
+ ? values.join(this.opts.valueDelimiter)
1051
+ : (values[0] || '');
1052
+ }
1053
+ };
1054
+
1055
+ /* ---------------- rendering ---------------- */
1056
+
1057
+ ZidanSelect.prototype._render = function () {
1058
+ var opts = this.opts;
1059
+ var hasValue = this.value_.length > 0;
1060
+
1061
+ this.root.classList.toggle('zs-root--has-value', hasValue);
1062
+ this.root.classList.toggle('zs-root--open', this.opened);
1063
+ this.root.classList.toggle('zs-root--disabled', !!this.disabled_);
1064
+ this.root.classList.toggle('zs-root--invalid', opts.validation === 'invalid');
1065
+ this.root.classList.toggle('zs-root--valid', opts.validation === 'valid');
1066
+ if (opts.validation === 'invalid') this.root.setAttribute('data-zs-validation', 'invalid');
1067
+ else if (opts.validation === 'valid') this.root.setAttribute('data-zs-validation', 'valid');
1068
+ else this.root.removeAttribute('data-zs-validation');
1069
+ if (opts.validation === 'invalid') this.input.setAttribute('aria-invalid', 'true');
1070
+ else if (opts.validation === 'valid') this.input.setAttribute('aria-invalid', 'false');
1071
+ else this.input.removeAttribute('aria-invalid');
1072
+ if (this.el.required || opts.required) this.input.setAttribute('aria-required', 'true');
1073
+
1074
+ if (opts.validation === 'invalid') this.controlEl.classList.add('is-invalid');
1075
+ else this.controlEl.classList.remove('is-invalid');
1076
+ if (opts.validation === 'valid') this.controlEl.classList.add('is-valid');
1077
+ else this.controlEl.classList.remove('is-valid');
1078
+ this._toggleCustomClass(this.controlEl, 'invalid', opts.validation === 'invalid');
1079
+
1080
+ this._renderChips();
1081
+ this._renderInputValue();
1082
+
1083
+ var showClear = opts.clearable && hasValue && !this.disabled_;
1084
+ this.clearBtn.hidden = !showClear;
1085
+ this.clearBtn.tabIndex = showClear ? 0 : -1;
1086
+
1087
+ this.input.disabled = !!this.disabled_;
1088
+ this.input.setAttribute('aria-expanded', String(this.opened));
1089
+ this.root.classList.toggle('zs-root--placeholder', !this.input.value && !hasValue);
1090
+
1091
+ return this;
1092
+ };
1093
+
1094
+ ZidanSelect.prototype._renderChips = function () {
1095
+ var self = this;
1096
+ var multi = this.mode === 'tags' || !!this.opts.multiple;
1097
+ var chips = this.chipsEl;
1098
+
1099
+ chips.textContent = '';
1100
+ chips.hidden = !multi;
1101
+ if (!multi) return;
1102
+
1103
+ this.value_.forEach(function (item, index) {
1104
+ var chip = el('span', 'zs-chip', { 'data-zs-index': index });
1105
+ if (self.framework === 'bootstrap') addClass(chip, 'badge rounded-pill');
1106
+ self._applyCustomClass(chip, 'chip');
1107
+
1108
+ var labelNode;
1109
+ var custom = typeof self.opts.renderTag === 'function' && self.mode === 'tags'
1110
+ ? self.opts.renderTag({ value: item.value, label: item.label }, { index: index, instance: self, disabled: self.disabled_ })
1111
+ : null;
1112
+
1113
+ if (self.mode === 'select' && typeof self.opts.renderSelected === 'function') {
1114
+ custom = self.opts.renderSelected({ value: item.value, label: item.label }, { index: index, instance: self });
1115
+ }
1116
+
1117
+ if (custom) {
1118
+ if (isElement(custom)) {
1119
+ labelNode = custom;
1120
+ chip.appendChild(labelNode);
1121
+ } else {
1122
+ var holder = el('span', 'zs-chip-label');
1123
+ holder.innerHTML = String(custom);
1124
+ chip.appendChild(holder);
1125
+ }
1126
+ } else {
1127
+ labelNode = el('span', 'zs-chip-label', null, item.label);
1128
+ chip.appendChild(labelNode);
1129
+ }
1130
+
1131
+ var removeBtn = el('button', 'zs-chip-remove', {
1132
+ type: 'button',
1133
+ 'aria-label': 'Remove ' + item.label,
1134
+ title: 'Remove ' + item.label,
1135
+ 'data-zs-remove': index
1136
+ });
1137
+ removeBtn.innerHTML = '<svg viewBox="0 0 16 16" width="10" height="10" aria-hidden="true" focusable="false"><path d="M4 4l8 8M12 4l-8 8" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>';
1138
+ self._applyCustomClass(removeBtn, 'chipRemove');
1139
+ chip.appendChild(removeBtn);
1140
+ chips.appendChild(chip);
1141
+ });
1142
+
1143
+ this.root.classList.toggle('zs-root--has-value', this.value_.length > 0);
1144
+ };
1145
+
1146
+ ZidanSelect.prototype._renderInputValue = function () {
1147
+ var single = this.mode !== 'tags' && !this.opts.multiple;
1148
+ if (!single) {
1149
+ this.input.placeholder = this.value_.length ? '' : (this.opts.placeholder || '');
1150
+ if (this.opened) {
1151
+ this.input.value = this.query;
1152
+ } else {
1153
+ this.input.value = '';
1154
+ }
1155
+ return;
1156
+ }
1157
+
1158
+ if (this.opened && this.opts.searchable) {
1159
+ this.input.value = this.query;
1160
+ this.input.placeholder = this.opts.placeholder || '';
1161
+ return;
1162
+ }
1163
+ if (this.opened && !this.opts.searchable) {
1164
+ this.input.value = this.value_.length ? this.value_[0].label : '';
1165
+ this.input.placeholder = this.opts.placeholder || '';
1166
+ return;
1167
+ }
1168
+ this.input.value = this.value_.length ? this.value_[0].label : '';
1169
+ this.input.placeholder = this.opts.placeholder || '';
1170
+ if (!this.value_.length) this.input.value = '';
1171
+ };
1172
+
1173
+ /* ---------------- dropdown ---------------- */
1174
+
1175
+ ZidanSelect.prototype._sourceItems = function () {
1176
+ if (this.mode === 'tags') return this.suggestions || [];
1177
+ if (typeof this.opts.fetchOptions === 'function' && this.asyncItems) return this.asyncItems;
1178
+ return this.items;
1179
+ };
1180
+
1181
+ ZidanSelect.prototype._visibleItems = function () {
1182
+ var self = this;
1183
+ var query = this.query.trim();
1184
+ var source = this._sourceItems();
1185
+ var isCaseSensitive = !!this.opts.caseSensitive;
1186
+
1187
+ if (!query) return source.slice();
1188
+
1189
+ return source.filter(function (item) {
1190
+ if (typeof self.opts.filterOption === 'function') {
1191
+ return !!self.opts.filterOption(item, query, {
1192
+ instance: self,
1193
+ mode: self.mode,
1194
+ caseSensitive: isCaseSensitive,
1195
+ selected: self._hasValue(item.value)
1196
+ });
1197
+ }
1198
+ var label = isCaseSensitive ? item.label : item.label.toLowerCase();
1199
+ var needle = isCaseSensitive ? query : query.toLowerCase();
1200
+ if (label.indexOf(needle) !== -1) return true;
1201
+ if (self.opts.searchValues) {
1202
+ var value = isCaseSensitive ? item.value : item.value.toLowerCase();
1203
+ if (value.indexOf(needle) !== -1) return true;
1204
+ }
1205
+ return false;
1206
+ });
1207
+ };
1208
+
1209
+ ZidanSelect.prototype._renderDropdown = function () {
1210
+ var self = this;
1211
+ if (!this.opened) return;
1212
+
1213
+ var scrollTop = this.dropdown.scrollTop;
1214
+ this.dropdown.textContent = '';
1215
+ this.rendered = [];
1216
+
1217
+ if (this.loading) {
1218
+ var loading = el('div', 'zs-state zs-state--loading', { role: 'status' });
1219
+ loading.appendChild(el('span', 'zs-spinner', { 'aria-hidden': 'true' }));
1220
+ loading.appendChild(el('span', 'zs-state-text', null, this.opts.loadingText));
1221
+ this.dropdown.appendChild(loading);
1222
+ } else if (this.error) {
1223
+ var errorEl = el('div', 'zs-state zs-state--error', { role: 'status' }, this.error.message || 'Something went wrong.');
1224
+ this.dropdown.appendChild(errorEl);
1225
+ } else {
1226
+ var items = this._visibleItems();
1227
+
1228
+ if (!items.length) {
1229
+ var emptyText = this.query ? this.opts.noResultsText : this.opts.emptyText;
1230
+ this.dropdown.appendChild(el('div', 'zs-state zs-state--empty', { role: 'status' }, emptyText));
1231
+ this.emit('no-results', { query: this.query, instance: this });
1232
+ } else {
1233
+ var lastGroup = null;
1234
+ items.forEach(function (item, index) {
1235
+ if (item.group && item.group !== lastGroup) {
1236
+ var header = el('div', 'zs-group', { role: 'presentation' }, item.group);
1237
+ self.dropdown.appendChild(header);
1238
+ lastGroup = item.group;
1239
+ }
1240
+
1241
+ var selected = self._hasValue(item.value);
1242
+ var option = el('div', 'zs-option', {
1243
+ role: 'option',
1244
+ id: self.id + '-opt-' + index,
1245
+ 'data-zs-option': index
1246
+ });
1247
+ option.setAttribute('aria-selected', String(selected));
1248
+ if (item.disabled) {
1249
+ option.setAttribute('aria-disabled', 'true');
1250
+ option.classList.add('zs-option--disabled');
1251
+ }
1252
+ if (selected) option.classList.add('zs-option--selected');
1253
+ self._applyCustomClass(option, 'option');
1254
+ if (selected) self._applyCustomClass(option, 'selected');
1255
+ if (item.disabled) self._applyCustomClass(option, 'disabled');
1256
+
1257
+ var content = null;
1258
+ if (typeof self.opts.renderOption === 'function') {
1259
+ content = self.opts.renderOption(item, {
1260
+ index: index,
1261
+ selected: selected,
1262
+ active: index === self.activeIndex,
1263
+ query: self.query,
1264
+ instance: self
1265
+ });
1266
+ }
1267
+
1268
+ if (content && isElement(content)) {
1269
+ option.appendChild(content);
1270
+ } else if (content !== null && content !== undefined && content !== '') {
1271
+ option.innerHTML = String(content);
1272
+ } else {
1273
+ option.appendChild(el('span', 'zs-option-label', null, item.label));
1274
+ }
1275
+
1276
+ if (index === self.activeIndex) {
1277
+ option.classList.add('zs-option--active');
1278
+ self._applyCustomClass(option, 'active');
1279
+ }
1280
+
1281
+ self.rendered.push({ element: option, item: item, index: index });
1282
+ self.dropdown.appendChild(option);
1283
+ });
1284
+ }
1285
+ }
1286
+
1287
+ this.dropdown.scrollTop = scrollTop;
1288
+ this._updateActiveDescendant(false);
1289
+ if (this.opened) this._position();
1290
+ };
1291
+
1292
+ ZidanSelect.prototype._updateActiveDescendant = function (scroll) {
1293
+ var active = this.rendered[this.activeIndex];
1294
+ if (active) {
1295
+ this.input.setAttribute('aria-activedescendant', active.element.id);
1296
+ if (scroll !== false) {
1297
+ var elTop = active.element.offsetTop;
1298
+ var elBottom = elTop + active.element.offsetHeight;
1299
+ if (elTop < this.dropdown.scrollTop) this.dropdown.scrollTop = elTop - 4;
1300
+ else if (elBottom > this.dropdown.scrollTop + this.dropdown.clientHeight) {
1301
+ this.dropdown.scrollTop = elBottom - this.dropdown.clientHeight + 4;
1302
+ }
1303
+ }
1304
+ } else {
1305
+ this.input.removeAttribute('aria-activedescendant');
1306
+ }
1307
+ };
1308
+
1309
+ ZidanSelect.prototype._position = function () {
1310
+ if (!this.opened) return;
1311
+ var rect = this.controlEl.getBoundingClientRect();
1312
+ var viewport = global.innerHeight || doc.documentElement.clientHeight;
1313
+ var spaceBelow = viewport - rect.bottom - 12;
1314
+ var spaceAbove = rect.top - 12;
1315
+ var dropUp = spaceBelow < 160 && spaceAbove > spaceBelow;
1316
+
1317
+ this.root.classList.toggle('zs-root--dropup', dropUp);
1318
+ var available = dropUp ? spaceAbove : spaceBelow;
1319
+ var maxHeight = clamp(available, 120, this.opts.maxDropdownHeight || 280);
1320
+ this.dropdown.style.maxHeight = Math.max(120, maxHeight) + 'px';
1321
+
1322
+ var width = rect.width;
1323
+ this.dropdown.style.minWidth = width + 'px';
1324
+ if (this.root.classList.contains('zs-root--mount')) {
1325
+ this.dropdown.style.left = '0px';
1326
+ this.dropdown.style.right = '0px';
1327
+ }
1328
+ };
1329
+
1330
+ /* ---------------- open / close ---------------- */
1331
+
1332
+ ZidanSelect.prototype.open = function () {
1333
+ if (this.destroyed || this.disabled_ || this.opened) return this;
1334
+
1335
+ this.opened = true;
1336
+ this.query = '';
1337
+ this.activeIndex = -1;
1338
+ if (this.mode === 'combobox' || (this.mode === 'select' && this.opts.searchable)) {
1339
+ this.savedInputText = this.input.value;
1340
+ }
1341
+ this.root.classList.add('zs-root--open');
1342
+ this.dropdown.setAttribute('data-zs-visible', 'true');
1343
+ this._render();
1344
+ this._renderDropdown();
1345
+ this._position();
1346
+ this.emit('open', { instance: this });
1347
+ this.call('onOpen', { instance: this });
1348
+
1349
+ if (typeof this.opts.fetchOptions === 'function' && !this.asyncItems) {
1350
+ this._fetch('');
1351
+ } else if (this.mode !== 'tags') {
1352
+ var first = this._firstEnabledIndex();
1353
+ if (first !== -1) {
1354
+ this.activeIndex = first;
1355
+ this._renderDropdown();
1356
+ }
1357
+ }
1358
+ if (this.opts.searchable && !this.disabled_) {
1359
+ try {
1360
+ this.input.select();
1361
+ } catch (err) {
1362
+ this.input.focus();
1363
+ }
1364
+ }
1365
+ var announceItems = this._visibleItems();
1366
+ this.announce(announceItems.length + ' option' + (announceItems.length === 1 ? '' : 's') + ' available');
1367
+ return this;
1368
+ };
1369
+
1370
+ ZidanSelect.prototype.close = function () {
1371
+ if (this.destroyed || !this.opened) return this;
1372
+ this.opened = false;
1373
+ this.root.classList.remove('zs-root--open');
1374
+ this.dropdown.removeAttribute('data-zs-visible');
1375
+ this.activeIndex = -1;
1376
+ this.query = '';
1377
+ this._render();
1378
+ this.emit('close', { instance: this });
1379
+ this.call('onClose', { instance: this });
1380
+ return this;
1381
+ };
1382
+
1383
+ ZidanSelect.prototype.toggle = function () {
1384
+ return this.opened ? this.close() : this.open();
1385
+ };
1386
+
1387
+ ZidanSelect.prototype._firstEnabledIndex = function () {
1388
+ var items = this._visibleItems();
1389
+ for (var i = 0; i < items.length; i += 1) {
1390
+ if (!items[i].disabled) return i;
1391
+ }
1392
+ return -1;
1393
+ };
1394
+
1395
+ /* ---------------- selection ---------------- */
1396
+
1397
+ ZidanSelect.prototype._selectRendered = function (index) {
1398
+ var entry = this.rendered[index];
1399
+ if (!entry || entry.item.disabled) return false;
1400
+ this._selectItem(entry.item);
1401
+ return true;
1402
+ };
1403
+
1404
+ ZidanSelect.prototype._selectItem = function (item) {
1405
+ if (!item || item.disabled) return this;
1406
+ var previous = this.getValue();
1407
+
1408
+ if (this.mode === 'tags') {
1409
+ this.addTag(item.label);
1410
+ this.query = '';
1411
+ this._renderDropdown();
1412
+ return this;
1413
+ }
1414
+
1415
+ if (this.mode === 'combobox' && this.opts.allowFreeText) {
1416
+ this._setValueInternal([item.value]);
1417
+ } else if (this.opts.multiple) {
1418
+ if (this._hasValue(item.value)) {
1419
+ this.value_ = this.value_.filter(function (v) { return v.value !== item.value; });
1420
+ this._render();
1421
+ this._syncNative();
1422
+ var current = this.getValue();
1423
+ if (JSON.stringify(current) !== JSON.stringify(previous)) {
1424
+ this.emit('change', { value: current, previousValue: previous, instance: this });
1425
+ this.call('onChange', { value: current, previousValue: previous, instance: this });
1426
+ }
1427
+ this._renderDropdown();
1428
+ return this;
1429
+ }
1430
+ this._setValueInternal(this.value_.concat([item]));
1431
+ } else {
1432
+ this._setValueInternal([item]);
1433
+ }
1434
+
1435
+ this.emit('select', { value: this.getValue(), item: item, instance: this });
1436
+ this.call('onSelect', { value: this.getValue(), item: item, instance: this });
1437
+
1438
+ var closeOnSelect = this.opts.closeOnSelect === null ? !this.opts.multiple : this.opts.closeOnSelect;
1439
+ if (closeOnSelect) this.close();
1440
+ else if (this.opened) this._renderDropdown();
1441
+ return this;
1442
+ };
1443
+
1444
+ /* ---------------- async loading ---------------- */
1445
+
1446
+ ZidanSelect.prototype._fetch = function (query) {
1447
+ var self = this;
1448
+ if (typeof this.opts.fetchOptions !== 'function') return;
1449
+ query = query === undefined || query === null ? '' : String(query);
1450
+
1451
+ if (this.asyncController) this.asyncController.abort();
1452
+ var controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
1453
+ this.asyncController = controller;
1454
+ this.loading = true;
1455
+ this.error = null;
1456
+ this._renderDropdown();
1457
+ this.announce(this.opts.loadingText);
1458
+
1459
+ var done = function (result) {
1460
+ self.loading = false;
1461
+ self.asyncItems = self._normalizeItems(result || []);
1462
+ self.activeIndex = -1;
1463
+ self._renderDropdown();
1464
+ var count = self._visibleItems().length;
1465
+ self.announce(count + ' result' + (count === 1 ? '' : 's'));
1466
+ };
1467
+ var fail = function (err) {
1468
+ self.loading = false;
1469
+ self.error = { message: (err && err.message) || 'Unable to load options.' };
1470
+ self.emit('error', { error: err, message: self.error.message, instance: self });
1471
+ self.call('onError', { error: err, message: self.error.message, instance: self });
1472
+ self._renderDropdown();
1473
+ };
1474
+
1475
+ try {
1476
+ var result = this.opts.fetchOptions(query, controller ? controller.signal : undefined);
1477
+ if (result && typeof result.then === 'function') {
1478
+ result.then(function (data) {
1479
+ if (controller && controller.signal.aborted) return;
1480
+ done(data);
1481
+ }).catch(function (err) {
1482
+ if (err && err.name === 'AbortError') return;
1483
+ if (controller && controller.signal.aborted) return;
1484
+ fail(err);
1485
+ });
1486
+ } else {
1487
+ done(result);
1488
+ }
1489
+ } catch (err) {
1490
+ if (err && err.name === 'AbortError') return;
1491
+ fail(err);
1492
+ }
1493
+ void self;
1494
+ };
1495
+
1496
+ /* ---------------- tags ---------------- */
1497
+
1498
+ ZidanSelect.prototype._tagError = function (message) {
1499
+ this.announce(message);
1500
+ this.emit('error', { message: message, instance: this });
1501
+ this.call('onError', { message: message, instance: this });
1502
+ this.root.classList.add('zs-root--shake');
1503
+ var rootEl = this.root;
1504
+ setTimeout(function () { rootEl.classList.remove('zs-root--shake'); }, 320);
1505
+ };
1506
+
1507
+ ZidanSelect.prototype._addTagObject = function (rawValue, config) {
1508
+ var cfg = config || {};
1509
+ var opts = this.opts;
1510
+ var raw = String(rawValue === null || rawValue === undefined ? '' : rawValue).trim();
1511
+ if (!raw) return false;
1512
+
1513
+ if (this.value_.length >= opts.maxTags) {
1514
+ if (!cfg.silent) this._tagError('You can add up to ' + opts.maxTags + ' tags.');
1515
+ return false;
1516
+ }
1517
+ if (raw.length < opts.minTagLength) {
1518
+ if (!cfg.silent) this._tagError('Tags need at least ' + opts.minTagLength + ' character' + (opts.minTagLength === 1 ? '' : 's') + '.');
1519
+ return false;
1520
+ }
1521
+ if (raw.length > opts.maxTagLength) {
1522
+ if (!cfg.silent) this._tagError('Tags can be at most ' + opts.maxTagLength + ' characters.');
1523
+ return false;
1524
+ }
1525
+ if (this._hasValue(raw)) {
1526
+ if (!cfg.silent) this._tagError('"' + raw + '" is already added.');
1527
+ return false;
1528
+ }
1529
+
1530
+ var formatted = raw;
1531
+ if (typeof opts.formatTag === 'function') {
1532
+ var formattedResult = opts.formatTag(raw, { instance: this, tags: this.getTags() });
1533
+ if (typeof formattedResult === 'string' && formattedResult) formatted = formattedResult;
1534
+ }
1535
+
1536
+ if (typeof opts.validateTag === 'function') {
1537
+ var validation = opts.validateTag(formatted, this.getTags(), { instance: this });
1538
+ if (validation === false) {
1539
+ if (!cfg.silent) this._tagError('"' + formatted + '" is not allowed.');
1540
+ return false;
1541
+ }
1542
+ if (typeof validation === 'string') {
1543
+ if (!cfg.silent) this._tagError(validation);
1544
+ return false;
1545
+ }
1546
+ }
1547
+
1548
+ var tag = { value: formatted, label: formatted };
1549
+ this.value_.push(tag);
1550
+ this.query = '';
1551
+ if (this.opts.validation === 'invalid') this.opts.validation = null;
1552
+
1553
+ if (!cfg.silent) {
1554
+ this._render();
1555
+ this._syncNative();
1556
+ if (this.opened) this._renderDropdown();
1557
+ this.announce(formatted + ' added. ' + this.value_.length + ' tag' + (this.value_.length === 1 ? '' : 's') + ' total.');
1558
+ this.emit('tag-add', { tag: formatted, value: this.getTags(), instance: this });
1559
+ this.call('onTagAdd', { tag: formatted, value: this.getTags(), instance: this });
1560
+ this.emit('change', { value: this.getTags(), instance: this });
1561
+ this.call('onChange', { value: this.getTags(), instance: this });
1562
+ }
1563
+ return true;
1564
+ };
1565
+
1566
+ ZidanSelect.prototype.addTag = function (tag) {
1567
+ var added = this._addTagObject(tag, {});
1568
+ this._render();
1569
+ if (this.opened) this._renderDropdown();
1570
+ return added;
1571
+ };
1572
+
1573
+ ZidanSelect.prototype.removeTag = function (tagOrIndex) {
1574
+ var index = typeof tagOrIndex === 'number'
1575
+ ? tagOrIndex
1576
+ : this.value_.findIndex(function (tag) {
1577
+ return String(tag.value) === String(tagOrIndex) || String(tag.label) === String(tagOrIndex);
1578
+ });
1579
+
1580
+ if (index < 0 || index >= this.value_.length) return false;
1581
+ var removed = this.value_.splice(index, 1)[0];
1582
+
1583
+ this._render();
1584
+ this._syncNative();
1585
+ if (this.opened) this._renderDropdown();
1586
+ this.announce(removed.label + ' removed. ' + this.value_.length + ' tag' + (this.value_.length === 1 ? '' : 's') + ' remaining.');
1587
+ this.emit('tag-remove', { tag: removed.value, value: this.getTags(), instance: this });
1588
+ this.call('onTagRemove', { tag: removed.value, value: this.getTags(), instance: this });
1589
+ this.emit('change', { value: this.getTags(), instance: this });
1590
+ this.call('onChange', { value: this.getTags(), instance: this });
1591
+ this.input.focus();
1592
+ return true;
1593
+ };
1594
+
1595
+ ZidanSelect.prototype.getTags = function () {
1596
+ return this.value_.map(function (tag) { return tag.value; });
1597
+ };
1598
+
1599
+ /* ---------------- keyboard ---------------- */
1600
+
1601
+ ZidanSelect.prototype._onKeyDown = function (event) {
1602
+ if (this.destroyed) return;
1603
+ var key = event.key;
1604
+ var items = this._visibleItems();
1605
+
1606
+ if (key === 'ArrowDown' || key === 'ArrowUp') {
1607
+ event.preventDefault();
1608
+ if (!this.opened) {
1609
+ this.open();
1610
+ return;
1611
+ }
1612
+ if (!items.length) return;
1613
+ var step = key === 'ArrowDown' ? 1 : -1;
1614
+ var next = this.activeIndex;
1615
+ for (var guard = 0; guard < items.length; guard += 1) {
1616
+ next += step;
1617
+ if (next < 0) next = items.length - 1;
1618
+ if (next >= items.length) next = 0;
1619
+ if (!items[next].disabled) break;
1620
+ }
1621
+ this.activeIndex = next;
1622
+ this._renderDropdown();
1623
+ return;
1624
+ }
1625
+
1626
+ if (key === 'Home' || key === 'End') {
1627
+ if (!this.opened) return;
1628
+ event.preventDefault();
1629
+ var found = -1;
1630
+ var i;
1631
+ if (key === 'Home') {
1632
+ for (i = 0; i < items.length; i += 1) { if (!items[i].disabled) { found = i; break; } }
1633
+ } else {
1634
+ for (i = items.length - 1; i >= 0; i -= 1) { if (!items[i].disabled) { found = i; break; } }
1635
+ }
1636
+ this.activeIndex = found;
1637
+ this._renderDropdown();
1638
+ return;
1639
+ }
1640
+
1641
+ if (key === 'Enter') {
1642
+ if (this.opened) {
1643
+ event.preventDefault();
1644
+ if (this.activeIndex >= 0) {
1645
+ this._selectRendered(this.activeIndex);
1646
+ if (this.mode === 'tags') this.query = '';
1647
+ return;
1648
+ }
1649
+ if (this.mode === 'tags') {
1650
+ this._commitTypedTag();
1651
+ return;
1652
+ }
1653
+ if ((this.mode === 'combobox' || this.mode === 'select') && this.opts.allowFreeText) {
1654
+ var text = this.query.trim();
1655
+ if (text) {
1656
+ this._setValueInternal([text]);
1657
+ this.emit('select', { value: this.getValue(), item: { value: text, label: text }, instance: this });
1658
+ this.call('onSelect', { value: this.getValue(), item: { value: text, label: text }, instance: this });
1659
+ this.close();
1660
+ }
1661
+ return;
1662
+ }
1663
+ if (items.length === 1) this._selectRendered(0);
1664
+ return;
1665
+ }
1666
+ if (this.mode === 'tags' && this.query.trim()) {
1667
+ event.preventDefault();
1668
+ this._commitTypedTag();
1669
+ return;
1670
+ }
1671
+ event.preventDefault();
1672
+ this.open();
1673
+ return;
1674
+ }
1675
+
1676
+ if (key === 'Escape') {
1677
+ if (this.opened) {
1678
+ event.preventDefault();
1679
+ this.close();
1680
+ }
1681
+ return;
1682
+ }
1683
+
1684
+ if (key === 'Tab') {
1685
+ if (this.mode === 'tags' && this.opts.commitOnTab && this.query.trim()) {
1686
+ this._commitTypedTag();
1687
+ }
1688
+ if (this.opened) this.close();
1689
+ return;
1690
+ }
1691
+
1692
+ if (key === 'Backspace') {
1693
+ if (this.mode === 'tags' && !this.input.value && !this.query && this.value_.length) {
1694
+ event.preventDefault();
1695
+ this.removeTag(this.value_.length - 1);
1696
+ return;
1697
+ }
1698
+ if (!this.input.value && this.opened) this.close();
1699
+ return;
1700
+ }
1701
+
1702
+ if (key === 'Delete' && this.opts.clearable && this.value_.length) {
1703
+ event.preventDefault();
1704
+ this.clear();
1705
+ }
1706
+ };
1707
+
1708
+ ZidanSelect.prototype._commitTypedTag = function () {
1709
+ var raw = this.input.value;
1710
+ var parts = this._splitTags(raw);
1711
+ var added = false;
1712
+ parts.forEach(function (part) { if (this._addTagObject(part, {})) added = true; }, this);
1713
+ this.input.value = '';
1714
+ this.query = '';
1715
+ this._render();
1716
+ this._syncNative();
1717
+ if (this.opened) this._renderDropdown();
1718
+ return added;
1719
+ };
1720
+
1721
+ ZidanSelect.prototype._splitTags = function (text) {
1722
+ var value = String(text || '');
1723
+ var delimiters = this.opts.delimiters || [];
1724
+ var parts = [value];
1725
+ delimiters.forEach(function (delimiter) {
1726
+ if (!delimiter) return;
1727
+ parts = parts.reduce(function (acc, chunk) {
1728
+ return acc.concat(chunk.split(delimiter));
1729
+ }, []);
1730
+ });
1731
+ return parts.map(function (part) { return part.trim(); }).filter(Boolean);
1732
+ };
1733
+
1734
+ /* ---------------- events wiring ---------------- */
1735
+
1736
+ ZidanSelect.prototype._bind = function () {
1737
+ var self = this;
1738
+
1739
+ this.onInput = function () {
1740
+ var value = self.input.value;
1741
+ self.query = value;
1742
+ if (self.opened) {
1743
+ if (typeof self.opts.fetchOptions === 'function' && self.query.length >= (self.opts.minChars || 0)) {
1744
+ if (self.opts.debounce > 0) self.debouncedFetch(self.query);
1745
+ else self._fetch(self.query);
1746
+ }
1747
+ self.activeIndex = self.mode === 'tags' ? -1 : self._firstEnabledIndex();
1748
+ self._renderDropdown();
1749
+ } else {
1750
+ // typed while closed (rare race): open first, then keep the text
1751
+ self.open();
1752
+ self.query = value;
1753
+ self.input.value = value;
1754
+ self._renderDropdown();
1755
+ }
1756
+ if (self.mode === 'tags') {
1757
+ var delimiters = self.opts.delimiters || [];
1758
+ var hasDelimiter = delimiters.some(function (delimiter) { return delimiter && value.indexOf(delimiter) !== -1; });
1759
+ if (hasDelimiter) {
1760
+ self._commitTypedTag();
1761
+ }
1762
+ }
1763
+ };
1764
+
1765
+ this.onKeyDown = function (event) { self._onKeyDown(event); };
1766
+
1767
+ this.onFocus = function () {
1768
+ if (self.disabled_) return;
1769
+ self.root.classList.add('zs-root--focus');
1770
+ if (self.mode === 'combobox' || self.mode === 'tags' || (self.mode === 'select' && self.opts.searchable)) {
1771
+ if (!self.opened) self.open();
1772
+ }
1773
+ };
1774
+
1775
+ this.onBlur = function () {
1776
+ self.root.classList.remove('zs-root--focus');
1777
+ setTimeout(function () {
1778
+ if (self.destroyed) return;
1779
+ if (self.root.contains(doc.activeElement)) return;
1780
+ if (self.mode === 'tags' && self.query.trim() && self.opts.commitOnBlur) {
1781
+ self._commitTypedTag();
1782
+ }
1783
+ if (self.mode === 'combobox' && self.opts.allowFreeText && self.query.trim()) {
1784
+ self._setValueInternal([self.query.trim()]);
1785
+ }
1786
+ self.query = '';
1787
+ self.close();
1788
+ self._render();
1789
+ }, 0);
1790
+ };
1791
+
1792
+ this.onControlClick = function (event) {
1793
+ if (self.disabled_) return;
1794
+ var target = event.target;
1795
+ if (target.closest && target.closest('.zs-clear')) return;
1796
+ if (target.closest && target.closest('.zs-chip-remove')) return;
1797
+ if (self.opened) {
1798
+ if (!self.opts.searchable && !self.input.readOnly) return;
1799
+ if (!self.opts.searchable) self.close();
1800
+ return;
1801
+ }
1802
+ self.open();
1803
+ };
1804
+
1805
+ this.onControlMouseDown = function (event) {
1806
+ if (event.target === self.input) return;
1807
+ if (event.target.closest && (event.target.closest('.zs-chip-remove') || event.target.closest('.zs-clear'))) {
1808
+ event.preventDefault();
1809
+ return;
1810
+ }
1811
+ if (event.target === self.controlEl || (event.target.closest && event.target.closest('.zs-chips'))) {
1812
+ event.preventDefault();
1813
+ self.input.focus();
1814
+ }
1815
+ };
1816
+
1817
+ this.onClearClick = function (event) {
1818
+ event.preventDefault();
1819
+ event.stopPropagation();
1820
+ self.clear();
1821
+ };
1822
+
1823
+ this.onChipsClick = function (event) {
1824
+ var button = event.target.closest ? event.target.closest('[data-zs-remove]') : null;
1825
+ if (!button) return;
1826
+ event.preventDefault();
1827
+ event.stopPropagation();
1828
+ var index = parseInt(button.getAttribute('data-zs-remove'), 10);
1829
+ if (isNaN(index)) return;
1830
+ if (self.mode === 'tags') self.removeTag(index);
1831
+ else {
1832
+ var item = self.value_[index];
1833
+ if (!item) return;
1834
+ var previous = self.getValue();
1835
+ self.value_.splice(index, 1);
1836
+ self._render();
1837
+ self._syncNative();
1838
+ self.emit('change', { value: self.getValue(), previousValue: previous, item: item, instance: self });
1839
+ self.call('onChange', { value: self.getValue(), previousValue: previous, item: item, instance: self });
1840
+ self.announce(item.label + ' removed.');
1841
+ if (self.opened) self._renderDropdown();
1842
+ }
1843
+ };
1844
+
1845
+ this.onDropdownMouseDown = function (event) {
1846
+ event.preventDefault();
1847
+ };
1848
+
1849
+ this.onDropdownClick = function (event) {
1850
+ var option = event.target.closest ? event.target.closest('[data-zs-option]') : null;
1851
+ if (!option) return;
1852
+ event.preventDefault();
1853
+ var index = parseInt(option.getAttribute('data-zs-option'), 10);
1854
+ if (isNaN(index)) return;
1855
+ self.activeIndex = index;
1856
+ self._selectRendered(index);
1857
+ if (self.mode === 'tags') self.input.focus();
1858
+ };
1859
+
1860
+ this.onDocumentPointerDown = function (event) {
1861
+ if (!self.opened) return;
1862
+ var path = event.composedPath ? event.composedPath() : [];
1863
+ if (path.indexOf(self.root) !== -1) return;
1864
+ if (self.root.contains(event.target)) return;
1865
+ self.close();
1866
+ self._render();
1867
+ };
1868
+
1869
+ this.onWindowResize = function () {
1870
+ if (self.opened) self._position();
1871
+ };
1872
+
1873
+ this.debouncedFetch = debounce(function (query) { self._fetch(query); }, this.opts.debounce);
1874
+
1875
+ if (this.el && this.el.addEventListener) {
1876
+ this.onNativeInvalid = function () {
1877
+ self.setValidation('invalid');
1878
+ if (self.input && self.input.focus) self.input.focus();
1879
+ };
1880
+ this.el.addEventListener('invalid', this.onNativeInvalid);
1881
+ }
1882
+
1883
+ this.input.addEventListener('input', this.onInput);
1884
+ this.input.addEventListener('keydown', this.onKeyDown);
1885
+ this.input.addEventListener('focus', this.onFocus);
1886
+ this.input.addEventListener('blur', this.onBlur);
1887
+ this.controlEl.addEventListener('click', this.onControlClick);
1888
+ this.controlEl.addEventListener('mousedown', this.onControlMouseDown);
1889
+ this.chipsEl.addEventListener('click', this.onChipsClick);
1890
+ this.clearBtn.addEventListener('click', this.onClearClick);
1891
+ this.dropdown.addEventListener('mousedown', this.onDropdownMouseDown);
1892
+ this.dropdown.addEventListener('click', this.onDropdownClick);
1893
+ doc.addEventListener('pointerdown', this.onDocumentPointerDown, true);
1894
+ global.addEventListener('resize', this.onWindowResize);
1895
+ };
1896
+
1897
+ ZidanSelect.prototype._observeResize = function () {
1898
+ if (typeof ResizeObserver === 'undefined') return;
1899
+ var self = this;
1900
+ this.resizeObserver = new ResizeObserver(function () {
1901
+ if (self.opened) self._position();
1902
+ });
1903
+ this.resizeObserver.observe(this.controlEl);
1904
+ };
1905
+
1906
+ /* ---------------- public API ---------------- */
1907
+
1908
+ ZidanSelect.prototype.getValue = function () {
1909
+ if (this.mode === 'tags') return this.getTags();
1910
+ var values = this.value_.map(function (item) { return item.value; });
1911
+ if (this.opts.multiple) return values;
1912
+ return values.length ? values[0] : null;
1913
+ };
1914
+
1915
+ ZidanSelect.prototype.setValue = function (value, config) {
1916
+ var cfg = config || {};
1917
+ if (this.mode === 'tags') {
1918
+ var raw = typeof value === 'string' ? this._splitTags(value) : toArray(value);
1919
+ var previous = this.getTags();
1920
+ this.value_ = [];
1921
+ raw.forEach(function (tag) { this._addTagObject(tag, { silent: true }); }, this);
1922
+ if (this.value_.length && this.opts.validation === 'invalid') this.opts.validation = null;
1923
+ this._render();
1924
+ this._syncNative();
1925
+ if (!cfg.silent) {
1926
+ var next = this.getTags();
1927
+ if (JSON.stringify(next) !== JSON.stringify(previous)) {
1928
+ this.emit('change', { value: next, previousValue: previous, instance: this });
1929
+ this.call('onChange', { value: next, previousValue: previous, instance: this });
1930
+ }
1931
+ }
1932
+ if (this.opened) this._renderDropdown();
1933
+ return this;
1934
+ }
1935
+ return this._setValueInternal(value, cfg);
1936
+ };
1937
+
1938
+ ZidanSelect.prototype.clear = function () {
1939
+ if (this.mode === 'tags') {
1940
+ if (!this.value_.length) return this;
1941
+ this.value_ = [];
1942
+ this._render();
1943
+ this._syncNative();
1944
+ this.announce('All tags removed.');
1945
+ this.emit('change', { value: [], instance: this });
1946
+ this.call('onChange', { value: [], instance: this });
1947
+ if (this.opened) this._renderDropdown();
1948
+ return this;
1949
+ }
1950
+ this._setValueInternal([], {});
1951
+ this._render();
1952
+ return this;
1953
+ };
1954
+
1955
+ ZidanSelect.prototype.setOptions = function (newOptions) {
1956
+ var items = this._normalizeItems(newOptions);
1957
+ if (this.mode === 'tags') {
1958
+ this.suggestions = items;
1959
+ } else {
1960
+ this.items = items;
1961
+ var self = this;
1962
+ this.value_ = this.value_.filter(function (item) {
1963
+ for (var i = 0; i < self.items.length; i += 1) {
1964
+ if (self.items[i].value === item.value) return true;
1965
+ }
1966
+ return self.opts.allowFreeText;
1967
+ });
1968
+ if (this.native && this.native.tagName === 'SELECT') {
1969
+ while (this.native.firstChild) this.native.removeChild(this.native.firstChild);
1970
+ this.items.forEach(function (item) {
1971
+ var option = doc.createElement('option');
1972
+ option.value = item.value;
1973
+ option.textContent = item.label;
1974
+ if (item.disabled) option.disabled = true;
1975
+ self.native.appendChild(option);
1976
+ });
1977
+ }
1978
+ }
1979
+ this.asyncItems = null;
1980
+ this.activeIndex = -1;
1981
+ this._render();
1982
+ this._syncNative();
1983
+ if (this.opened) this._renderDropdown();
1984
+ return this;
1985
+ };
1986
+
1987
+ ZidanSelect.prototype.enable = function () {
1988
+ this.disabled_ = false;
1989
+ this._render();
1990
+ return this;
1991
+ };
1992
+
1993
+ ZidanSelect.prototype.disable = function () {
1994
+ this.disabled_ = true;
1995
+ this.close();
1996
+ this._render();
1997
+ return this;
1998
+ };
1999
+
2000
+ ZidanSelect.prototype.setLayout = function (layoutName) {
2001
+ var next = String(layoutName || '').toLowerCase();
2002
+ if (LAYOUTS.indexOf(next) === -1) {
2003
+ throw new Error('ZidanSelect: unknown layout "' + layoutName + '". Use: ' + LAYOUTS.join(', '));
2004
+ }
2005
+ this.layout = next;
2006
+ this.opts.layout = next;
2007
+ this.root.setAttribute('data-zs-layout', next);
2008
+ this.root.classList.toggle('zs-root--labeled', next === 'floating-label');
2009
+ this._position();
2010
+ return this;
2011
+ };
2012
+
2013
+ ZidanSelect.prototype.setFramework = function (frameworkName) {
2014
+ var next = String(frameworkName || '').toLowerCase();
2015
+ if (FRAMEWORKS.indexOf(next) === -1) {
2016
+ throw new Error('ZidanSelect: unknown framework "' + frameworkName + '". Use: ' + FRAMEWORKS.join(', '));
2017
+ }
2018
+ this.opts.themeFramework = next;
2019
+ this.framework = next === 'auto' ? this._resolveFramework() : next;
2020
+ this.root.setAttribute('data-zs-framework', this.framework);
2021
+ this.controlEl.classList.toggle('form-control', this.framework === 'bootstrap');
2022
+ this.controlEl.classList.toggle('zs-bootstrap-control', this.framework === 'bootstrap');
2023
+ this.controlEl.classList.toggle('form-select', this.framework === 'bootstrap' && this.el.tagName === 'SELECT');
2024
+ this._applyCustomClass(this.root, 'root');
2025
+ this._render();
2026
+ return this;
2027
+ };
2028
+
2029
+ ZidanSelect.prototype.setScrollbar = function (scrollbarName) {
2030
+ var next = String(scrollbarName || '').toLowerCase();
2031
+ if (SCROLLBARS.indexOf(next) === -1) {
2032
+ throw new Error('ZidanSelect: unknown scrollbar "' + scrollbarName + '". Use: ' + SCROLLBARS.join(', '));
2033
+ }
2034
+ this.opts.scrollbar = next;
2035
+ if (this.root) this.root.setAttribute('data-zs-scrollbar', next);
2036
+ return this;
2037
+ };
2038
+
2039
+ ZidanSelect.prototype.setValidation = function (state) {
2040
+ this.opts.validation = state;
2041
+ this._render();
2042
+ return this;
2043
+ };
2044
+
2045
+ ZidanSelect.prototype.on = function (eventName, handler) {
2046
+ var name = this._eventName(eventName);
2047
+ this.root.addEventListener(name, handler);
2048
+ if (!this.listeners.has(name)) this.listeners.set(name, []);
2049
+ this.listeners.get(name).push(handler);
2050
+ return this;
2051
+ };
2052
+
2053
+ ZidanSelect.prototype.off = function (eventName, handler) {
2054
+ var name = this._eventName(eventName);
2055
+ var handlers = this.listeners.get(name) || [];
2056
+ if (handler) {
2057
+ this.root.removeEventListener(name, handler);
2058
+ this.listeners.set(name, handlers.filter(function (h) { return h !== handler; }));
2059
+ } else {
2060
+ var rootEl = this.root;
2061
+ handlers.forEach(function (h) { rootEl.removeEventListener(name, h); });
2062
+ this.listeners.set(name, []);
2063
+ }
2064
+ return this;
2065
+ };
2066
+
2067
+ ZidanSelect.prototype._eventName = function (eventName) {
2068
+ var name = String(eventName || '');
2069
+ return name.indexOf(EVENT_PREFIX) === 0 ? name : EVENT_PREFIX + name;
2070
+ };
2071
+
2072
+ ZidanSelect.prototype.emit = function (name, detail) {
2073
+ if (!this.root || !doc) return this;
2074
+ var event;
2075
+ try {
2076
+ event = new CustomEvent(EVENT_PREFIX + name, {
2077
+ bubbles: true,
2078
+ cancelable: false,
2079
+ detail: detail || {}
2080
+ });
2081
+ } catch (err) {
2082
+ event = doc.createEvent('CustomEvent');
2083
+ event.initCustomEvent(EVENT_PREFIX + name, true, false, detail || {});
2084
+ }
2085
+ this.root.dispatchEvent(event);
2086
+ return this;
2087
+ };
2088
+
2089
+ ZidanSelect.prototype.call = function (callbackName, payload) {
2090
+ var fn = this.opts[callbackName];
2091
+ if (typeof fn !== 'function') return undefined;
2092
+ try {
2093
+ return fn(payload);
2094
+ } catch (err) {
2095
+ this.emit('error', { error: err, message: (err && err.message) || String(err), callback: callbackName, instance: this });
2096
+ return undefined;
2097
+ }
2098
+ };
2099
+
2100
+ ZidanSelect.prototype.announce = function (message) {
2101
+ if (!this.liveEl || !message) return;
2102
+ this.liveEl.textContent = '';
2103
+ this.liveEl.textContent = message;
2104
+ };
2105
+
2106
+ ZidanSelect.prototype.destroy = function () {
2107
+ if (this.destroyed) return this;
2108
+ this.destroyed = true;
2109
+
2110
+ if (this.debouncedFetch) this.debouncedFetch.cancel();
2111
+ if (this.asyncController) this.asyncController.abort();
2112
+ if (this.resizeObserver) this.resizeObserver.disconnect();
2113
+ if (this.form && this.onFormReset) this.form.removeEventListener('reset', this.onFormReset);
2114
+
2115
+ doc.removeEventListener('pointerdown', this.onDocumentPointerDown, true);
2116
+ global.removeEventListener('resize', this.onWindowResize);
2117
+ if (this.el && this.onNativeInvalid) this.el.removeEventListener('invalid', this.onNativeInvalid);
2118
+
2119
+ this.emit('destroy', { instance: this });
2120
+
2121
+ if (this.root && this.root.parentNode) this.root.parentNode.removeChild(this.root);
2122
+
2123
+ if (this.native) {
2124
+ this.native.hidden = false;
2125
+ this.native.classList.remove('zs-native');
2126
+ this.native.removeAttribute('tabindex');
2127
+ this.native.removeAttribute('aria-hidden');
2128
+ } else if (this.el.classList && this.el.classList.contains('zs-root--mount')) {
2129
+ this.el.classList.remove('zs-root--mount');
2130
+ }
2131
+
2132
+ if (this.el.__zidanSelect === this) delete this.el.__zidanSelect;
2133
+ this.listeners.clear();
2134
+ var index = ZidanSelect.instances.indexOf(this);
2135
+ if (index !== -1) ZidanSelect.instances.splice(index, 1);
2136
+ return this;
2137
+ };
2138
+
2139
+ ZidanSelect.prototype.isOpen = function () {
2140
+ return this.opened;
2141
+ };
2142
+
2143
+ ZidanSelect.prototype.refresh = function () {
2144
+ this._render();
2145
+ if (this.opened) this._renderDropdown();
2146
+ return this;
2147
+ };
2148
+
2149
+ /* ---------------- factory, registry, auto-init ---------------- */
2150
+
2151
+ function fieldKindFor(node) {
2152
+ if (!isElement(node)) return null;
2153
+ var flag = String(node.getAttribute('data-zidan') || '').toLowerCase();
2154
+ if (FIELD_KINDS.indexOf(flag) !== -1) return flag;
2155
+ if (node.hasAttribute('data-zidan-radio-group')) return 'radio-group';
2156
+ if (node.hasAttribute('data-zidan-radio')) return 'radio';
2157
+ if (node.hasAttribute('data-zidan-checkbox') || node.hasAttribute('data-zidan-switch')) return 'checkbox';
2158
+ if (node.hasAttribute('data-zidan-file')) return 'file';
2159
+ if (node.hasAttribute('data-zidan-textarea')) return 'textarea';
2160
+ if (node.hasAttribute('data-zidan-input')) return 'input';
2161
+ var type = String(node.type || '').toLowerCase();
2162
+ if (type === 'checkbox') return 'checkbox';
2163
+ if (type === 'radio') return 'radio';
2164
+ if (type === 'file') return 'file';
2165
+ if (hasClass(node, 'zidan-field')) {
2166
+ if (node.tagName === 'FIELDSET') return node.querySelector('input[type="radio"]') ? 'radio-group' : null;
2167
+ if (node.tagName === 'TEXTAREA') return 'textarea';
2168
+ if (node.tagName !== 'INPUT') return null;
2169
+ // a lone radio needs its group container, so only the fieldset form is inferred
2170
+ if (type === 'radio') return null;
2171
+ if (typeof TEXT_TYPES !== 'undefined' && TEXT_TYPES.indexOf(type) !== -1) return 'input';
2172
+ }
2173
+ return null;
2174
+ }
2175
+
2176
+ function createField(node, kind, options) {
2177
+ var opts = mergeOptions(parseOptionsAttr(node), options);
2178
+ if (node.__zidanField && !opts.force) return node.__zidanField;
2179
+ switch (kind) {
2180
+ case 'checkbox':
2181
+ return typeof ZidanCheckbox !== 'undefined' ? new ZidanCheckbox(node, opts) : null;
2182
+ case 'radio':
2183
+ case 'radio-group':
2184
+ return typeof ZidanRadioGroup !== 'undefined' ? new ZidanRadioGroup(node, opts) : null;
2185
+ case 'file':
2186
+ return typeof ZidanFileUpload !== 'undefined' ? new ZidanFileUpload(node, opts) : null;
2187
+ case 'input':
2188
+ case 'textarea':
2189
+ return typeof ZidanTextField !== 'undefined' ? new ZidanTextField(node, opts) : null;
2190
+ default: return null;
2191
+ }
2192
+ }
2193
+
2194
+ function zidanField(target, options) {
2195
+ var nodes = [];
2196
+ if (typeof target === 'string') {
2197
+ nodes = Array.prototype.slice.call(doc.querySelectorAll(target));
2198
+ } else if (isElement(target)) {
2199
+ nodes = [target];
2200
+ } else if (target && typeof target.length === 'number') {
2201
+ nodes = Array.prototype.slice.call(target);
2202
+ }
2203
+ var created = [];
2204
+ nodes.forEach(function (node) {
2205
+ if (node.__zidanField) return;
2206
+ // zidanField() accepts a plain input/textarea too, so JS-only options
2207
+ // (output, counter, clearable, …) work without a data attribute
2208
+ var kind = fieldKindFor(node) || inferredTextKind(node);
2209
+ if (!kind) return;
2210
+ if (kind === 'radio' && !node.hasAttribute('data-zidan-radio')) {
2211
+ kind = 'radio-group';
2212
+ }
2213
+ var instance = createField(node, kind, options || {});
2214
+ if (instance) created.push(instance);
2215
+ });
2216
+ return created.length === 1 ? created[0] : created;
2217
+ }
2218
+
2219
+ function initFieldList(nodes, options) {
2220
+ var instances = [];
2221
+ nodes.forEach(function (node) {
2222
+ if (!isElement(node) || node.__zidanField) return;
2223
+ var kind = fieldKindFor(node);
2224
+ if (!kind) return;
2225
+ if (kind === 'radio') kind = 'radio-group';
2226
+ var instance = createField(node, kind, options || {});
2227
+ if (instance) instances.push(instance);
2228
+ });
2229
+ return instances;
2230
+ }
2231
+
2232
+ function initZidanForms(container, options) {
2233
+ var scope = container || doc;
2234
+ if (!scope || !scope.querySelectorAll) return [];
2235
+ var nodes = Array.prototype.slice.call(scope.querySelectorAll(FIELDS_SELECTOR));
2236
+ if (isElement(scope) && scope.matches && scope.matches(FIELDS_SELECTOR)) nodes.unshift(scope);
2237
+ return initFieldList(nodes, options);
2238
+ }
2239
+
2240
+ var ZidanForm = {
2241
+ version: VERSION,
2242
+ __zidanFormGuard: VERSION,
2243
+ // live registries: pushing a name here makes it a valid theme/layout
2244
+ themes: THEMES,
2245
+ frameworks: FRAMEWORKS.slice(),
2246
+ fieldLayouts: FIELD_LAYOUTS,
2247
+ fields: [],
2248
+ _register: function (field) {
2249
+ if (ZidanForm.fields.indexOf(field) === -1) ZidanForm.fields.push(field);
2250
+ },
2251
+ _unregister: function (field) {
2252
+ var index = ZidanForm.fields.indexOf(field);
2253
+ if (index !== -1) ZidanForm.fields.splice(index, 1);
2254
+ },
2255
+ get: function (target) {
2256
+ var node = typeof target === 'string' ? doc.querySelector(target) : target;
2257
+ return isElement(node) ? node.__zidanField || null : null;
2258
+ },
2259
+ init: function (scope, options) {
2260
+ return initZidanForms(scope || doc, options || {});
2261
+ },
2262
+ field: zidanField,
2263
+ refresh: function (scope) {
2264
+ initZidanForms(scope || doc, {});
2265
+ ZidanForm.fields.slice().forEach(function (field) { field.update(); });
2266
+ return ZidanForm.fields.slice();
2267
+ },
2268
+ destroyAll: function () {
2269
+ ZidanForm.fields.slice().forEach(function (field) { field.destroy(); });
2270
+ ZidanForm.fields = [];
2271
+ if (typeof ZidanSelect !== 'undefined' && ZidanSelect.destroyAll) ZidanSelect.destroyAll();
2272
+ return ZidanForm;
2273
+ },
2274
+ /* keep a subtree in sync when it is re-rendered by a framework */
2275
+ observe: function (scope, options) {
2276
+ var root = scope || doc.body;
2277
+ if (!root || !global.MutationObserver) return null;
2278
+ var observer = new global.MutationObserver(function (records) {
2279
+ records.forEach(function (record) {
2280
+ Array.prototype.slice.call(record.addedNodes).forEach(function (node) {
2281
+ if (!isElement(node)) return;
2282
+ if (fieldKindFor(node)) createField(node, fieldKindFor(node) === 'radio' ? 'radio-group' : fieldKindFor(node), options || {});
2283
+ if (node.querySelectorAll) initZidanForms(node, options || {});
2284
+ });
2285
+ });
2286
+ // drop instances whose control left the document
2287
+ ZidanForm.fields.slice().forEach(function (field) {
2288
+ if (!field.el.isConnected) field.destroy();
2289
+ });
2290
+ if (typeof ZidanSelect !== 'undefined') {
2291
+ ZidanSelect.instances.slice().forEach(function (instance) {
2292
+ if (!instance.el.isConnected) instance.destroy();
2293
+ });
2294
+ }
2295
+ });
2296
+ observer.observe(root, { childList: true, subtree: true });
2297
+ return observer;
2298
+ }
2299
+ };
2300
+
2301
+ ZidanForm.api = null;
2302
+
2303
+ /* registries, presets and helpers shared by every field type */
2304
+ ZidanForm.registerIcon = registerIcon;
2305
+ ZidanForm.icons = ICON_REGISTRY;
2306
+ if (typeof PHONE_COUNTRIES !== 'undefined') {
2307
+ ZidanForm.phoneCountries = PHONE_COUNTRIES;
2308
+ ZidanForm.phoneFormats = PHONE_FORMATS.slice();
2309
+ ZidanForm.formatPhone = formatPhone;
2310
+ ZidanForm.detectPhoneCountry = detectPhoneCountry;
2311
+ }
2312
+ ZidanForm.messages = FIELD_MESSAGES;
2313
+ ZidanForm.variants = {};
2314
+ if (typeof CHECKBOX_VARIANTS !== 'undefined') ZidanForm.variants.checkbox = CHECKBOX_VARIANTS.slice();
2315
+ if (typeof SWITCH_STYLES !== 'undefined') ZidanForm.variants.switch = SWITCH_STYLES.slice();
2316
+ if (typeof RADIO_VARIANTS !== 'undefined') ZidanForm.variants.radio = RADIO_VARIANTS.slice();
2317
+ if (typeof FILE_VARIANTS !== 'undefined') ZidanForm.variants.file = FILE_VARIANTS.slice();
2318
+ if (typeof RANGE_VARIANTS !== 'undefined') ZidanForm.variants.range = RANGE_VARIANTS.slice();
2319
+ if (typeof STEPPER_MODES !== 'undefined') ZidanForm.stepperModes = STEPPER_MODES.slice();
2320
+ ZidanForm.fieldLayouts = FIELD_LAYOUTS.slice();
2321
+
2322
+ /* static helpers */
2323
+ if (typeof ZidanSelect !== 'undefined') {
2324
+ ZidanSelect.version = VERSION;
2325
+ ZidanSelect.__zidanSelectGuard = VERSION;
2326
+ ZidanSelect.layouts = LAYOUTS.slice();
2327
+ ZidanSelect.frameworks = FRAMEWORKS.slice();
2328
+ ZidanSelect.scrollbars = SCROLLBARS.slice();
2329
+ ZidanSelect.defaults = DEFAULTS;
2330
+ ZidanSelect.get = function (target) {
2331
+ var element = typeof target === 'string' ? doc.querySelector(target) : target;
2332
+ if (!isElement(element)) return null;
2333
+ return element.__zidanSelect || null;
2334
+ };
2335
+ ZidanSelect.instances = [];
2336
+ ZidanSelect.destroyAll = function () {
2337
+ ZidanSelect.instances.slice().forEach(function (instance) { instance.destroy(); });
2338
+ ZidanSelect.instances = [];
2339
+ };
2340
+ }
2341
+
2342
+ /* ------------------------------------------------------------------ *
2343
+ * Factory + auto-init
2344
+ * ------------------------------------------------------------------ */
2345
+
2346
+ function zidanSelect(target, options) {
2347
+ var nodes = [];
2348
+ if (typeof target === 'string') {
2349
+ nodes = Array.prototype.slice.call(doc.querySelectorAll(target));
2350
+ } else if (target && typeof target.length === 'number' && !isElement(target) && target !== global) {
2351
+ nodes = Array.prototype.slice.call(target);
2352
+ } else if (isElement(target)) {
2353
+ nodes = [target];
2354
+ }
2355
+
2356
+ var instances = nodes.map(function (node) {
2357
+ var instance = new ZidanSelect(node, options || {});
2358
+ ZidanSelect.instances.push(instance);
2359
+ return instance;
2360
+ });
2361
+
2362
+ return instances.length === 1 ? instances[0] : instances;
2363
+ }
2364
+
2365
+ function initSelectList(nodes, options) {
2366
+ return nodes.filter(function (node) {
2367
+ return isElement(node) && !node.__zidanSelect;
2368
+ }).map(function (node) {
2369
+ ZidanSelect.instances.push(new ZidanSelect(node, options || {}));
2370
+ return node.__zidanSelect;
2371
+ });
2372
+ }
2373
+
2374
+ function initZidanSelects(container, options) {
2375
+ var scope = container || doc;
2376
+ if (!scope || !scope.querySelectorAll) return [];
2377
+ var nodes = Array.prototype.slice.call(scope.querySelectorAll(SELECT_SELECTOR));
2378
+ if (isElement(scope) && scope.matches && scope.matches(SELECT_SELECTOR)) nodes.unshift(scope);
2379
+ return initSelectList(nodes, options);
2380
+ }
2381
+
2382
+ /* a config target is a CSS selector string or { selector, options } */
2383
+ function eachTarget(list, run) {
2384
+ toArray(list).forEach(function (entry) {
2385
+ if (!entry) return;
2386
+ if (typeof entry === 'string') run(entry, null);
2387
+ else if (entry.selector) run(String(entry.selector), entry.options || null);
2388
+ });
2389
+ }
2390
+
2391
+ function initSelectTargets(list, shared) {
2392
+ eachTarget(list, function (selector, options) {
2393
+ initSelectList(Array.prototype.slice.call(doc.querySelectorAll(selector)),
2394
+ mergeOptions(shared, options));
2395
+ });
2396
+ }
2397
+
2398
+ function initFieldTargets(list, shared) {
2399
+ eachTarget(list, function (selector, options) {
2400
+ var opts = mergeOptions(shared, options);
2401
+ Array.prototype.slice.call(doc.querySelectorAll(selector)).forEach(function (node) {
2402
+ if (!isElement(node) || node.__zidanField) return;
2403
+ var kind = fieldKindFor(node) || inferredTextKind(node);
2404
+ if (!kind) return;
2405
+ if (kind === 'radio') kind = 'radio-group';
2406
+ createField(node, kind, opts);
2407
+ });
2408
+ });
2409
+ }
2410
+
2411
+ /* explicit targets may point at a plain text input or textarea */
2412
+ function inferredTextKind(node) {
2413
+ if (typeof TEXT_TYPES === 'undefined' || !isElement(node)) return null;
2414
+ if (node.tagName === 'TEXTAREA') return 'textarea';
2415
+ if (node.tagName !== 'INPUT') return null;
2416
+ return TEXT_TYPES.indexOf(String(node.type).toLowerCase()) !== -1 ? 'input' : null;
2417
+ }
2418
+
2419
+ /* a form scope enhances every native select inside, marked or not */
2420
+ function initScopeSelects(scope, options) {
2421
+ if (typeof ZidanSelect === 'undefined') return [];
2422
+ var selector = SELECT_SELECTOR + ', select';
2423
+ var nodes = Array.prototype.slice.call(scope.querySelectorAll(selector));
2424
+ if (isElement(scope) && scope.matches && scope.matches(selector)) nodes.unshift(scope);
2425
+ return initSelectList(nodes, options);
2426
+ }
2427
+
2428
+ function initScope(scope, selectOptions, fieldOptions) {
2429
+ if (!isElement(scope)) return;
2430
+ initScopeSelects(scope, selectOptions);
2431
+ if (typeof ZidanFileUpload !== 'undefined') {
2432
+ // a form scope also picks up plain file inputs, not just marked ones
2433
+ initFieldList(Array.prototype.slice.call(scope.querySelectorAll('input[type="file"]')), fieldOptions);
2434
+ }
2435
+ if (typeof ZidanCheckbox !== 'undefined' || typeof ZidanRadioGroup !== 'undefined' ||
2436
+ typeof ZidanFileUpload !== 'undefined' || typeof ZidanTextField !== 'undefined') {
2437
+ initZidanForms(scope, fieldOptions);
2438
+ }
2439
+ }
2440
+
2441
+ function initFormScopes(list, selectOptions, fieldOptions) {
2442
+ Array.prototype.slice.call(doc.querySelectorAll(FORM_SCOPE_SELECTOR))
2443
+ .forEach(function (scope) { initScope(scope, selectOptions, fieldOptions); });
2444
+ eachTarget(list, function (selector, options) {
2445
+ Array.prototype.slice.call(doc.querySelectorAll(selector)).forEach(function (scope) {
2446
+ initScope(scope, mergeOptions(selectOptions, options), mergeOptions(fieldOptions, options));
2447
+ });
2448
+ });
2449
+ }
2450
+
2451
+ function autoInit() {
2452
+ if (!doc) return;
2453
+ var config = global.ZIDAN_FORM_CONFIG || global.ZIDAN_SELECT_CONFIG || {};
2454
+ if (config.autoInit === false) return;
2455
+ if (global.ZidanSelect && global.ZidanSelect.autoInit === false) return;
2456
+ if (doc.documentElement.getAttribute('data-zidan-auto-init') === 'false') return;
2457
+
2458
+ var hasSelect = typeof ZidanSelect !== 'undefined';
2459
+ var hasFields = typeof ZidanCheckbox !== 'undefined' || typeof ZidanRadioGroup !== 'undefined' ||
2460
+ typeof ZidanFileUpload !== 'undefined' || typeof ZidanTextField !== 'undefined';
2461
+ var selectOptions = config.options || {};
2462
+ var fieldOptions = config.fieldOptions || config.fields || {};
2463
+
2464
+ // explicit targets run first so their per-target options win over the
2465
+ // generic attribute scan (the scan then skips what is already initialised)
2466
+ if (hasSelect) {
2467
+ if (config.selector) {
2468
+ // legacy: an explicit selector replaces the data-attribute scan
2469
+ initSelectTargets(config.selector, selectOptions);
2470
+ } else {
2471
+ initSelectTargets(config.targets || config.selectors, selectOptions);
2472
+ }
2473
+ }
2474
+ if (hasFields) initFieldTargets(config.fieldTargets, fieldOptions);
2475
+ initFormScopes(config.formTargets, selectOptions, fieldOptions);
2476
+
2477
+ if (hasSelect && !config.selector) initZidanSelects(doc, selectOptions);
2478
+ if (hasFields) initZidanForms(doc, fieldOptions);
2479
+ }
2480
+
2481
+ if (doc) {
2482
+ if (doc.readyState === 'loading') {
2483
+ doc.addEventListener('DOMContentLoaded', autoInit);
2484
+ } else {
2485
+ setTimeout(autoInit, 0);
2486
+ }
2487
+ }
2488
+
2489
+ var api = {
2490
+ ZidanForm: ZidanForm,
2491
+ registerIcon: registerIcon
2492
+ };
2493
+ if (typeof ZidanSelect !== 'undefined') {
2494
+ api.ZidanSelect = ZidanSelect;
2495
+ api.zidanSelect = zidanSelect;
2496
+ api.initZidanSelects = initZidanSelects;
2497
+ }
2498
+ if (typeof ZidanCheckbox !== 'undefined' || typeof ZidanRadioGroup !== 'undefined' ||
2499
+ typeof ZidanFileUpload !== 'undefined' || typeof ZidanTextField !== 'undefined') {
2500
+ api.zidanField = zidanField;
2501
+ api.initZidanForms = initZidanForms;
2502
+ }
2503
+ if (typeof ZidanCheckbox !== 'undefined') api.ZidanCheckbox = ZidanCheckbox;
2504
+ if (typeof ZidanRadioGroup !== 'undefined') api.ZidanRadioGroup = ZidanRadioGroup;
2505
+ if (typeof ZidanFileUpload !== 'undefined') api.ZidanFileUpload = ZidanFileUpload;
2506
+ if (typeof ZidanTextField !== 'undefined') api.ZidanTextField = ZidanTextField;
2507
+ if (typeof formatPhone === 'function') {
2508
+ api.formatPhone = formatPhone;
2509
+ api.detectPhoneCountry = detectPhoneCountry;
2510
+ }
2511
+
2512
+ ZidanForm.api = api;
2513
+
2514
+ return api;
2515
+ });