zidan-select 0.0.0-stage → 2.0.2

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,3047 @@
1
+ /*!
2
+ * ZidanForm v2.0.0
3
+ * Zero-dependency form enhancement library: select / combobox / tags,
4
+ * checkboxes, switches, radio groups, file upload with drag & drop, and
5
+ * text inputs / textarea. Structure and theming are split into
6
+ * plugin-core.css and plugin-theme.css.
7
+ *
8
+ * https://github.com/akhtar1985/zidan-select
9
+ * MIT License © akhtar1985
10
+ *
11
+ * Works as a classic <script> (adds window.ZidanForm plus the legacy
12
+ * window.ZidanSelect / zidanSelect / initZidanSelects names) and as an ES
13
+ * module (see zidan-form.mjs, which re-exports this file).
14
+ */
15
+ (function (root, factory) {
16
+ 'use strict';
17
+ var api = factory(root);
18
+ if (typeof window !== 'undefined') {
19
+ window.ZidanForm = api.ZidanForm;
20
+ window.ZidanSelect = api.ZidanSelect;
21
+ window.zidanSelect = api.zidanSelect;
22
+ window.initZidanSelects = api.initZidanSelects;
23
+ window.zidanField = api.zidanField;
24
+ window.initZidanForms = api.initZidanForms;
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.0.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]';
53
+ var SCROLLBARS = ['default', 'thin', 'fancy', 'hover', 'hidden'];
54
+ var EVENT_PREFIX = 'zidan:';
55
+ var uidSeq = 0;
56
+
57
+ function uid(prefix) {
58
+ uidSeq += 1;
59
+ return (prefix || 'zs') + '-' + uidSeq.toString(36) + Math.random().toString(36).slice(2, 6);
60
+ }
61
+
62
+ function hasClass(node, cls) {
63
+ return !!(node && node.classList && node.classList.contains(cls));
64
+ }
65
+
66
+ function addClass(node, cls) {
67
+ if (!node || !cls) return node;
68
+ cls.split(/\s+/).forEach(function (c) {
69
+ if (c) node.classList.add(c);
70
+ });
71
+ return node;
72
+ }
73
+
74
+ function el(tag, className, attrs, text) {
75
+ var node = doc.createElement(tag);
76
+ if (className) node.className = className;
77
+ if (attrs) {
78
+ Object.keys(attrs).forEach(function (key) {
79
+ var value = attrs[key];
80
+ if (value === null || value === undefined || value === false) return;
81
+ if (key === 'text') node.textContent = String(value);
82
+ else node.setAttribute(key, value === true ? '' : String(value));
83
+ });
84
+ }
85
+ if (text !== undefined && text !== null) node.textContent = String(text);
86
+ return node;
87
+ }
88
+
89
+ function toArray(value) {
90
+ if (value === null || value === undefined || value === '') return [];
91
+ return Array.isArray(value) ? value.slice() : [value];
92
+ }
93
+
94
+ function isElement(value) {
95
+ return !!(value && typeof value === 'object' && value.nodeType === 1);
96
+ }
97
+
98
+ function readBoolAttr(value, fallback) {
99
+ if (value === undefined || value === null || value === '') return fallback;
100
+ var v = String(value).toLowerCase();
101
+ return !(v === 'false' || v === '0' || v === 'no' || v === 'off');
102
+ }
103
+
104
+ function clamp(value, min, max) {
105
+ return Math.min(max, Math.max(min, value));
106
+ }
107
+
108
+ /* first non-empty value of any of `names`, walking up the tree */
109
+ function inheritedAttr(node, names) {
110
+ var current = node;
111
+ while (current && current.nodeType === 1) {
112
+ for (var i = 0; i < names.length; i += 1) {
113
+ var value = current.getAttribute(names[i]);
114
+ if (value) return value;
115
+ }
116
+ current = current.parentElement;
117
+ }
118
+ return '';
119
+ }
120
+
121
+ function pickList(value, list, fallback) {
122
+ var candidate = String(value || '').toLowerCase();
123
+ return list.indexOf(candidate) === -1 ? fallback : candidate;
124
+ }
125
+
126
+ /* theme/framework/layout resolution shared by every field and the select */
127
+ function resolveScope(node, options) {
128
+ var opts = options || {};
129
+ var theme = opts.theme || inheritedAttr(node, ['data-zidan-theme', 'data-zs-theme']);
130
+ if (!theme && doc) theme = doc.documentElement.getAttribute('data-zs-theme') || '';
131
+ var framework = opts.framework || inheritedAttr(node, ['data-zidan-framework', 'data-zs-framework']);
132
+ if (!framework && doc) framework = doc.documentElement.getAttribute('data-zs-framework') || '';
133
+ var layout = opts.layout || inheritedAttr(node, ['data-zidan-layout', 'data-zs-layout']);
134
+ return {
135
+ theme: pickList(theme, THEMES, 'default'),
136
+ framework: pickList(framework, FRAMEWORKS, 'none'),
137
+ layout: layout ? String(layout).toLowerCase() : ''
138
+ };
139
+ }
140
+
141
+ function debounce(fn, wait) {
142
+ var timer = null;
143
+ function debounced() {
144
+ var args = arguments;
145
+ clearTimeout(timer);
146
+ timer = setTimeout(function () {
147
+ timer = null;
148
+ fn.apply(null, args);
149
+ }, wait);
150
+ }
151
+ debounced.cancel = function () {
152
+ clearTimeout(timer);
153
+ timer = null;
154
+ };
155
+ return debounced;
156
+ }
157
+
158
+ /* ------------------------------------------------------------------ *
159
+ * Defaults
160
+ * ------------------------------------------------------------------ */
161
+
162
+ var DEFAULTS = {
163
+ /* core */
164
+ mode: null, // 'select' | 'combobox' | 'tags'
165
+ layout: 'classic-clean',
166
+ themeFramework: 'auto', // 'auto' | 'vanilla' | 'bootstrap' | 'tailwind'
167
+ id: null,
168
+ name: null,
169
+ disabled: false,
170
+ required: false,
171
+ /* data */
172
+ options: null,
173
+ value: null,
174
+ label: null, // floating label text (falls back to placeholder)
175
+ placeholder: null,
176
+ /* behaviour */
177
+ multiple: false,
178
+ searchable: null,
179
+ clearable: false,
180
+ closeOnSelect: null,
181
+ maxDropdownHeight: 280,
182
+ noResultsText: 'No results found',
183
+ emptyText: 'No options',
184
+ loadingText: 'Searching…',
185
+ clearText: 'Clear selection',
186
+ /* combobox / async */
187
+ fetchOptions: null,
188
+ debounce: 250,
189
+ minChars: 0,
190
+ allowFreeText: false,
191
+ searchValues: true,
192
+ /* tags */
193
+ maxTags: Infinity,
194
+ minTagLength: 1,
195
+ maxTagLength: Infinity,
196
+ caseSensitive: false,
197
+ delimiters: [','],
198
+ commitOnTab: false,
199
+ commitOnBlur: false,
200
+ suggestions: null,
201
+ valueDelimiter: ',',
202
+ /* styling */
203
+ customClasses: {},
204
+ validation: null, // null | 'valid' | 'invalid'
205
+ scrollbar: 'default', // 'default' | 'thin' | 'fancy' | 'hover' | 'hidden'
206
+ /* callbacks */
207
+ filterOption: null,
208
+ renderOption: null,
209
+ renderSelected: null,
210
+ renderTag: null,
211
+ validateTag: null,
212
+ formatTag: null,
213
+ onInit: null,
214
+ onChange: null,
215
+ onSelect: null,
216
+ onOpen: null,
217
+ onClose: null,
218
+ onTagAdd: null,
219
+ onTagRemove: null,
220
+ onError: null
221
+ };
222
+
223
+ /* ------------------------------------------------------------------ *
224
+ * ZidanSelect
225
+ * ------------------------------------------------------------------ */
226
+
227
+ function ZidanSelect(target, options) {
228
+ if (!(this instanceof ZidanSelect)) return new ZidanSelect(target, options);
229
+ if (!doc) throw new Error('ZidanSelect requires a DOM environment.');
230
+
231
+ var element = typeof target === 'string' ? doc.querySelector(target) : target;
232
+ if (!isElement(element)) throw new Error('ZidanSelect: target element not found.');
233
+ if (element.__zidanSelect instanceof ZidanSelect) {
234
+ element.__zidanSelect.destroy();
235
+ }
236
+
237
+ this.el = element;
238
+ this.opts = this._normalizeOptions(options || {});
239
+ this.mode = this.opts.mode;
240
+ this.layout = this.opts.layout;
241
+ this.id = this.opts.id || uid('zs');
242
+ this.isMount = /^(DIV|SPAN|SECTION|ARTICLE|FORM-FIELD)$/i.test(element.tagName) ||
243
+ element.hasAttribute('data-zidan-select') && !/^(SELECT|INPUT|TEXTAREA)$/i.test(element.tagName);
244
+ this.native = this.isMount ? null : element;
245
+ this.syncEl = null;
246
+
247
+ this.items = [];
248
+ this.value_ = [];
249
+ this.tags = [];
250
+ this.activeIndex = -1;
251
+ this.opened = false;
252
+ this.loading = false;
253
+ this.error = null;
254
+ this.query = '';
255
+ this.rendered = [];
256
+ this.listeners = new Map();
257
+ this.asyncController = null;
258
+ this.timer = null;
259
+ this.savedInputText = '';
260
+ this.disabled_ = !!this.opts.disabled;
261
+ this.destroyed = false;
262
+ this.resizeObserver = null;
263
+
264
+ this._prepareData();
265
+ this._build();
266
+ this._prepareSync();
267
+ this._bind();
268
+ this._setInitialValue();
269
+ this._render();
270
+ this._observeResize();
271
+
272
+ element.__zidanSelect = this;
273
+ this.emit('init', { instance: this, mode: this.mode, layout: this.layout, framework: this.framework });
274
+ this.call('onInit', { instance: this, mode: this.mode, value: this.getValue() });
275
+ }
276
+
277
+ /* ---------------- option normalisation ---------------- */
278
+
279
+ ZidanSelect.prototype._normalizeOptions = function (options) {
280
+ var d = this.el.dataset || {};
281
+ var isNativeSelect = this.el.tagName === 'SELECT';
282
+ var isTagsMount = /tags/i.test(d.zidanSelect || '') || /tags/i.test(d.zidanMode || '');
283
+
284
+ var mode = options.mode || d.zidanMode || d.zidanSelect || (isTagsMount ? 'tags' : 'select');
285
+ mode = String(mode).toLowerCase();
286
+ if (mode === 'multi' || mode === 'multiselect') mode = 'select';
287
+ if (['select', 'combobox', 'tags'].indexOf(mode) === -1) mode = 'select';
288
+
289
+ var nativeMultiple = isNativeSelect ? this.el.multiple : false;
290
+
291
+ var framework = options.themeFramework || d.zidanFramework || 'auto';
292
+ framework = String(framework).toLowerCase();
293
+ if (FRAMEWORKS.indexOf(framework) === -1) framework = 'auto';
294
+
295
+ var layout = options.layout || d.zidanLayout || 'classic-clean';
296
+ layout = String(layout).toLowerCase();
297
+ if (LAYOUTS.indexOf(layout) === -1) layout = 'classic-clean';
298
+
299
+ var scrollbar = options.scrollbar || d.zidanScrollbar || DEFAULTS.scrollbar;
300
+ scrollbar = String(scrollbar).toLowerCase();
301
+ if (SCROLLBARS.indexOf(scrollbar) === -1) scrollbar = DEFAULTS.scrollbar;
302
+
303
+ var pick = function (key, fallback) {
304
+ return options[key] !== undefined && options[key] !== null ? options[key] : fallback;
305
+ };
306
+
307
+ var placeholderDefault = mode === 'tags' ? 'Add a tag…' : (mode === 'combobox' ? 'Type to search…' : 'Select an option…');
308
+
309
+ var merged = {};
310
+ Object.keys(DEFAULTS).forEach(function (key) {
311
+ merged[key] = DEFAULTS[key];
312
+ });
313
+
314
+ merged.mode = mode;
315
+ merged.layout = layout;
316
+ merged.themeFramework = framework;
317
+ merged.multiple = mode === 'tags' ? true : pick('multiple', nativeMultiple || readBoolAttr(d.zidanMultiple, false));
318
+ merged.searchable = pick('searchable', readBoolAttr(d.zidanSearchable, mode !== 'select'));
319
+ merged.clearable = pick('clearable', readBoolAttr(d.zidanClearable, false));
320
+ merged.disabled = pick('disabled', readBoolAttr(d.zidanDisabled, isNativeSelect ? this.el.disabled : false));
321
+ merged.placeholder = pick('placeholder',
322
+ d.zidanPlaceholder || (this.el.getAttribute && this.el.getAttribute('placeholder')) || placeholderDefault);
323
+ merged.label = pick('label', d.zidanLabel || null);
324
+ merged.name = pick('name', d.zidanName || (this.el.getAttribute && this.el.getAttribute('name')) || null);
325
+ merged.allowFreeText = pick('allowFreeText', readBoolAttr(d.zidanAllowFreeText, mode === 'tags'));
326
+ merged.maxTags = pick('maxTags', d.zidanMaxTags ? parseInt(d.zidanMaxTags, 10) || Infinity : DEFAULTS.maxTags);
327
+ merged.minTagLength = pick('minTagLength', d.zidanMinTagLength ? parseInt(d.zidanMinTagLength, 10) || 1 : DEFAULTS.minTagLength);
328
+ merged.maxTagLength = pick('maxTagLength', d.zidanMaxTagLength ? parseInt(d.zidanMaxTagLength, 10) || Infinity : DEFAULTS.maxTagLength);
329
+ merged.caseSensitive = pick('caseSensitive', readBoolAttr(d.zidanCaseSensitive, false));
330
+ merged.validation = pick('validation', d.zidanValidation || null);
331
+ merged.options = pick('options', null);
332
+ merged.suggestions = pick('suggestions', null);
333
+
334
+ // carry over every explicitly-passed option (callbacks, custom classes, ...)
335
+ Object.keys(options).forEach(function (key) {
336
+ if (options[key] !== undefined) merged[key] = options[key];
337
+ });
338
+
339
+ // these three are authoritative after the merge
340
+ merged.mode = mode;
341
+ merged.layout = layout;
342
+ merged.themeFramework = framework;
343
+ merged.scrollbar = scrollbar;
344
+ if (!merged.theme) merged.theme = d.zidanTheme || d.zsTheme || '';
345
+ if (mode === 'combobox') merged.searchable = true;
346
+ if (mode === 'tags' && merged.searchable === false) merged.searchable = true;
347
+ if (mode === 'tags') merged.multiple = true;
348
+ return merged;
349
+ };
350
+
351
+ ZidanSelect.prototype._prepareData = function () {
352
+ var source = this.opts.options;
353
+ if (!source && this.el.tagName === 'SELECT') source = this._optionsFromSelect(this.el);
354
+ if (!source) source = this.opts.suggestions || [];
355
+ this.items = this._normalizeItems(source);
356
+ if (this.mode === 'tags') {
357
+ var suggestionSource = this.opts.suggestions || this.opts.options;
358
+ if (!suggestionSource && this.el.tagName === 'SELECT') suggestionSource = this._optionsFromSelect(this.el);
359
+ this.suggestions = this._normalizeItems(suggestionSource || []);
360
+ }
361
+ };
362
+
363
+ ZidanSelect.prototype._optionsFromSelect = function (select) {
364
+ var out = [];
365
+ Array.prototype.slice.call(select.children || []).forEach(function (node) {
366
+ if (node.tagName === 'OPTGROUP') {
367
+ var groupLabel = node.label || '';
368
+ Array.prototype.slice.call(node.children).forEach(function (opt) {
369
+ if (opt.tagName !== 'OPTION') return;
370
+ out.push({
371
+ value: opt.value,
372
+ label: opt.textContent.trim(),
373
+ group: groupLabel,
374
+ disabled: opt.disabled
375
+ });
376
+ });
377
+ } else if (node.tagName === 'OPTION') {
378
+ out.push({
379
+ value: node.value,
380
+ label: node.textContent.trim(),
381
+ disabled: node.disabled
382
+ });
383
+ }
384
+ });
385
+ return out;
386
+ };
387
+
388
+ ZidanSelect.prototype._normalizeItems = function (input) {
389
+ var list = toArray(input);
390
+ var out = [];
391
+ var self = this;
392
+
393
+ list.forEach(function (item, index) {
394
+ if (item === null || item === undefined) return;
395
+ if (typeof item === 'string' || typeof item === 'number') {
396
+ out.push({ value: String(item), label: String(item), group: null, disabled: false });
397
+ return;
398
+ }
399
+ if (typeof item === 'object' && Array.isArray(item.options)) {
400
+ var groupName = item.label !== undefined ? String(item.label) : (item.group || '');
401
+ self._normalizeItems(item.options).forEach(function (child) {
402
+ child.group = groupName;
403
+ out.push(child);
404
+ });
405
+ return;
406
+ }
407
+ if (typeof item === 'object') {
408
+ var value = item.value !== undefined ? item.value : item.label !== undefined ? item.label : index;
409
+ out.push({
410
+ value: String(value),
411
+ label: item.label !== undefined ? String(item.label) : String(value),
412
+ group: item.group !== undefined ? String(item.group) : null,
413
+ disabled: !!item.disabled,
414
+ data: item.data
415
+ });
416
+ }
417
+ });
418
+ return out;
419
+ };
420
+
421
+ /* ---------------- DOM building ---------------- */
422
+
423
+ ZidanSelect.prototype._resolveFramework = function () {
424
+ if (this.opts.themeFramework && this.opts.themeFramework !== 'auto') return this.opts.themeFramework;
425
+ if (!doc) return 'vanilla';
426
+ try {
427
+ var rootStyle = global.getComputedStyle(doc.documentElement);
428
+ var bsBg = rootStyle.getPropertyValue('--bs-body-bg');
429
+ if (bsBg && bsBg.trim()) return 'bootstrap';
430
+ var sheets = doc.styleSheets || [];
431
+ for (var i = 0; i < sheets.length; i += 1) {
432
+ var href = sheets[i].href || '';
433
+ if (/bootstrap(\.min)?\.css/i.test(href)) return 'bootstrap';
434
+ if (/tailwind/i.test(href)) return 'tailwind';
435
+ }
436
+ if (doc.body && global.getComputedStyle(doc.body).getPropertyValue('--tw-ring-offset-shadow') !== '') return 'tailwind';
437
+ if (doc.querySelector('.btn-primary, .form-select, .form-control, .navbar')) return 'bootstrap';
438
+ } catch (err) { /* ignore: cross-origin or no CSSOM */ }
439
+ return 'vanilla';
440
+ };
441
+
442
+ ZidanSelect.prototype._applyCustomClass = function (node, key) {
443
+ var map = this.opts.customClasses || {};
444
+ var value = map[key];
445
+ if (value) addClass(node, value);
446
+ return node;
447
+ };
448
+
449
+ ZidanSelect.prototype._toggleCustomClass = function (node, key, on) {
450
+ var map = this.opts.customClasses || {};
451
+ var value = map[key];
452
+ if (!value) return node;
453
+ String(value).split(/\s+/).forEach(function (cls) {
454
+ if (!cls) return;
455
+ if (on) node.classList.add(cls);
456
+ else node.classList.remove(cls);
457
+ });
458
+ return node;
459
+ };
460
+
461
+ ZidanSelect.prototype._build = function () {
462
+ var self = this;
463
+ var opts = this.opts;
464
+ this.framework = this._resolveFramework();
465
+
466
+ var existingWrapper = this.el.parentNode && this.el.parentNode.classList &&
467
+ this.el.parentNode.classList.contains('zs-root--mount');
468
+
469
+ var scope = resolveScope(this.el, { theme: opts.theme, framework: opts.themeFramework, layout: opts.layout });
470
+ this.theme = scope.theme;
471
+
472
+ var rootEl = el('div', 'zs-root');
473
+ rootEl.id = this.id + '-root';
474
+ rootEl.setAttribute('data-zs-theme', this.theme);
475
+ rootEl.setAttribute('data-zs-layout', this.layout);
476
+ rootEl.setAttribute('data-zs-framework', this.framework);
477
+ rootEl.setAttribute('data-zs-mode', this.mode);
478
+ rootEl.setAttribute('data-zs-scrollbar', opts.scrollbar || 'default');
479
+ rootEl.classList.add('zs-root--' + this.mode);
480
+ if (this.mode === 'tags') rootEl.classList.add('zs-root--multiple');
481
+ if (opts.multiple && this.mode === 'select') rootEl.classList.add('zs-root--multiple');
482
+ if (this.layout === 'floating-label') rootEl.classList.add('zs-root--labeled');
483
+ this._applyCustomClass(rootEl, 'root');
484
+
485
+ /* control ------------------------------------------------------- */
486
+ var control = el('div', 'zs-control');
487
+ if (this.framework === 'bootstrap') {
488
+ control.classList.add('form-control', 'zs-bootstrap-control');
489
+ if (this.el.tagName === 'SELECT') control.classList.add('form-select');
490
+ }
491
+ this._applyCustomClass(control, 'control');
492
+
493
+ var chips = el('div', 'zs-chips');
494
+ chips.hidden = true;
495
+
496
+ var input = doc.createElement('input');
497
+ input.type = 'text';
498
+ input.className = 'zs-input';
499
+ input.id = this.id + '-input';
500
+ input.autocomplete = 'off';
501
+ input.spellcheck = false;
502
+ input.setAttribute('role', 'combobox');
503
+ input.setAttribute('aria-expanded', 'false');
504
+ input.setAttribute('aria-controls', this.id + '-listbox');
505
+ input.setAttribute('aria-autocomplete', (opts.searchable || this.mode !== 'select') ? 'list' : 'none');
506
+ input.setAttribute('aria-haspopup', 'listbox');
507
+ if (opts.ariaLabel || opts.label) input.setAttribute('aria-label', opts.ariaLabel || opts.label);
508
+ if (opts.disabled) input.disabled = true;
509
+ this._applyCustomClass(input, 'input');
510
+
511
+ var labelEl = null;
512
+ if (opts.label) {
513
+ labelEl = el('label', 'zs-label', { for: input.id });
514
+ labelEl.textContent = opts.label;
515
+ if (this.layout !== 'floating-label') rootEl.classList.add('zs-root--has-static-label');
516
+ }
517
+
518
+ var clearBtn = el('button', 'zs-clear', {
519
+ type: 'button',
520
+ tabindex: '-1',
521
+ 'aria-label': opts.clearText,
522
+ title: opts.clearText
523
+ });
524
+ 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>';
525
+ clearBtn.hidden = true;
526
+
527
+ var arrow = el('span', 'zs-arrow', { 'aria-hidden': 'true' });
528
+ 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>';
529
+
530
+ control.appendChild(chips);
531
+ control.appendChild(input);
532
+ control.appendChild(clearBtn);
533
+ control.appendChild(arrow);
534
+
535
+ if (labelEl) {
536
+ if (this.layout === 'floating-label') control.insertBefore(labelEl, chips);
537
+ else rootEl.appendChild(labelEl);
538
+ }
539
+
540
+ /* dropdown ------------------------------------------------------ */
541
+ var dropdown = el('div', 'zs-dropdown');
542
+ dropdown.id = this.id + '-listbox';
543
+ dropdown.setAttribute('role', 'listbox');
544
+ if (this.mode !== 'tags') {
545
+ dropdown.setAttribute('aria-multiselectable', String(!!(opts.multiple || this.mode === 'tags')));
546
+ }
547
+ this._applyCustomClass(dropdown, 'dropdown');
548
+
549
+ var live = el('div', 'zs-live', { 'aria-live': 'polite', 'aria-atomic': 'true' });
550
+
551
+ rootEl.appendChild(control);
552
+ rootEl.appendChild(dropdown);
553
+ rootEl.appendChild(live);
554
+
555
+ if (this.framework === 'bootstrap') {
556
+ if (opts.validation === 'invalid') control.classList.add('is-invalid');
557
+ if (opts.validation === 'valid') control.classList.add('is-valid');
558
+ if (this.mode === 'tags' || opts.multiple) rootEl.classList.add('zs-root--bootstrap');
559
+ }
560
+
561
+ /* mount into DOM ------------------------------------------------ */
562
+ if (this.isMount) {
563
+ if (!existingWrapper) this.el.classList.add('zs-root--mount');
564
+ this.el.appendChild(rootEl);
565
+ } else {
566
+ this.el.parentNode.insertBefore(rootEl, this.el);
567
+ }
568
+
569
+ this.root = rootEl;
570
+ this.controlEl = control;
571
+ this.chipsEl = chips;
572
+ this.input = input;
573
+ this.dropdown = dropdown;
574
+ this.clearBtn = clearBtn;
575
+ this.arrowEl = arrow;
576
+ this.labelEl = labelEl;
577
+ this.liveEl = live;
578
+ };
579
+
580
+ ZidanSelect.prototype._prepareSync = function () {
581
+ var self = this;
582
+ var opts = this.opts;
583
+
584
+ if (this.native) {
585
+ if (this.native.tagName === 'SELECT') {
586
+ this.syncEl = this.native;
587
+ if (this.native.multiple) {
588
+ this.opts.multiple = true;
589
+ this.root.classList.add('zs-root--multiple');
590
+ }
591
+ this.native.hidden = true;
592
+ this.native.classList.add('zs-native');
593
+ this.native.setAttribute('tabindex', '-1');
594
+ this.native.setAttribute('aria-hidden', 'true');
595
+ } else {
596
+ this.syncEl = this.native;
597
+ this.native.hidden = true;
598
+ this.native.setAttribute('tabindex', '-1');
599
+ this.native.setAttribute('aria-hidden', 'true');
600
+ }
601
+ // NOTE: `required` is intentionally NOT copied to the hidden native
602
+ // control — a display:none required field blocks submit with an
603
+ // unfocusable invalid control. We expose aria-required on our input
604
+ // and validation via setValidation('invalid').
605
+ if (opts.required) this.input.setAttribute('aria-required', 'true');
606
+ this.form = this.native.closest ? this.native.closest('form') : null;
607
+ } else {
608
+ if (opts.name) {
609
+ var hidden = el('input', 'zs-hidden', { type: 'hidden', name: opts.name });
610
+ this.root.appendChild(hidden);
611
+ this.syncEl = hidden;
612
+ this.form = this.el.closest ? this.el.closest('form') : null;
613
+ } else {
614
+ this.form = this.el.closest ? this.el.closest('form') : null;
615
+ }
616
+ }
617
+
618
+ if (this.form) {
619
+ this.onFormReset = function () {
620
+ setTimeout(function () { self._handleFormReset(); }, 0);
621
+ };
622
+ this.form.addEventListener('reset', this.onFormReset);
623
+ }
624
+ return this.syncEl;
625
+ };
626
+
627
+ /* ---------------- initial value ---------------- */
628
+
629
+ ZidanSelect.prototype._setInitialValue = function () {
630
+ var opts = this.opts;
631
+ var initial = opts.value;
632
+
633
+ if (initial === null || initial === undefined) {
634
+ if (this.native && this.native.tagName === 'SELECT') {
635
+ initial = this.native.multiple
636
+ ? Array.prototype.filter.call(this.native.options, function (o) { return o.selected; }).map(function (o) { return o.value; })
637
+ : this.native.value;
638
+ } else if (this.native) {
639
+ initial = this.native.value;
640
+ }
641
+ }
642
+
643
+ if (this.mode === 'tags') {
644
+ var raw = initial;
645
+ if (typeof raw === 'string' && raw && !Array.isArray(raw) && this.syncEl && this.syncEl.tagName !== 'SELECT') {
646
+ raw = raw.split(opts.valueDelimiter);
647
+ }
648
+ toArray(raw).forEach(function (tag) { this._addTagObject(String(tag), { silent: true }); }, this);
649
+ return;
650
+ }
651
+
652
+ if (initial === null || initial === undefined || initial === '') return;
653
+ this._setValueInternal(initial, { silent: true });
654
+ };
655
+
656
+ ZidanSelect.prototype._handleFormReset = function () {
657
+ var initial;
658
+ if (this.native && this.native.tagName === 'SELECT') {
659
+ initial = this.native.multiple
660
+ ? Array.prototype.filter.call(this.native.options, function (o) { return o.selected; }).map(function (o) { return o.value; })
661
+ : this.native.value;
662
+ } else if (this.native) {
663
+ initial = this.native.value;
664
+ } else if (this.opts.value !== null && this.opts.value !== undefined) {
665
+ initial = this.opts.value;
666
+ }
667
+
668
+ if (this.mode === 'tags') {
669
+ this.value_ = [];
670
+ toArray(initial).forEach(function (tag) { this._addTagObject(tag, { silent: true }); }, this);
671
+ this._render();
672
+ this._syncNative();
673
+ return;
674
+ }
675
+ this._setValueInternal(initial, { silent: true });
676
+ this._render();
677
+ };
678
+
679
+ /* ---------------- value helpers ---------------- */
680
+
681
+ ZidanSelect.prototype._hasValue = function (value) {
682
+ var needle = this.opts.caseSensitive ? String(value) : String(value).toLowerCase();
683
+ for (var i = 0; i < this.value_.length; i += 1) {
684
+ var current = this.opts.caseSensitive ? this.value_[i].value : this.value_[i].value.toLowerCase();
685
+ if (current === needle) return true;
686
+ }
687
+ return false;
688
+ };
689
+
690
+ ZidanSelect.prototype._itemFor = function (value) {
691
+ var needle = String(value);
692
+ for (var i = 0; i < this.items.length; i += 1) {
693
+ if (this.items[i].value === needle) return this.items[i];
694
+ }
695
+ for (var j = 0; j < this.value_.length; j += 1) {
696
+ if (this.value_[j].value === needle) return this.value_[j];
697
+ }
698
+ return { value: needle, label: needle };
699
+ };
700
+
701
+ ZidanSelect.prototype._setValueInternal = function (input, config) {
702
+ var cfg = config || {};
703
+ var previous = this.getValue();
704
+ var self = this;
705
+ var values = toArray(input);
706
+ var next = [];
707
+
708
+ values.forEach(function (value) {
709
+ if (value === null || value === undefined || value === '') return;
710
+ if (typeof value === 'object') {
711
+ next.push({ value: String(value.value !== undefined ? value.value : value.label), label: String(value.label !== undefined ? value.label : value.value), data: value.data });
712
+ return;
713
+ }
714
+ var str = String(value);
715
+ var match = null;
716
+ for (var i = 0; i < self.items.length; i += 1) {
717
+ if (self.items[i].value === str) { match = self.items[i]; break; }
718
+ }
719
+ next.push(match ? { value: match.value, label: match.label, data: match.data } : { value: str, label: str });
720
+ });
721
+
722
+ if (!this.opts.multiple && this.mode !== 'tags') next = next.slice(0, 1);
723
+ this.value_ = next;
724
+ this._render();
725
+ this._syncNative();
726
+ if (!cfg.silent) {
727
+ var current = this.getValue();
728
+ if (current !== previous && JSON.stringify(current) !== JSON.stringify(previous)) {
729
+ this.emit('change', { value: current, previousValue: previous, instance: this });
730
+ this.call('onChange', { value: current, previousValue: previous, instance: this });
731
+ }
732
+ }
733
+ return this;
734
+ };
735
+
736
+ ZidanSelect.prototype._syncNative = function () {
737
+ var sel = this.syncEl;
738
+ if (!sel) return;
739
+ var values = this.value_.map(function (v) { return v.value; });
740
+
741
+ if (sel.tagName === 'SELECT') {
742
+ var i;
743
+ if (sel.multiple) {
744
+ for (i = 0; i < sel.options.length; i += 1) {
745
+ sel.options[i].selected = values.indexOf(sel.options[i].value) !== -1;
746
+ }
747
+ var existing = Array.prototype.map.call(sel.options, function (o) { return o.value; });
748
+ values.forEach(function (value) {
749
+ if (existing.indexOf(value) === -1) {
750
+ var option = doc.createElement('option');
751
+ option.value = value;
752
+ option.textContent = value;
753
+ option.selected = true;
754
+ sel.appendChild(option);
755
+ }
756
+ });
757
+ } else {
758
+ var target = values[0];
759
+ if (target === undefined) {
760
+ sel.value = '';
761
+ } else {
762
+ var found = false;
763
+ for (i = 0; i < sel.options.length; i += 1) {
764
+ if (sel.options[i].value === target) { found = true; break; }
765
+ }
766
+ if (!found) {
767
+ var newOption = doc.createElement('option');
768
+ newOption.value = target;
769
+ newOption.textContent = this._itemFor(target).label;
770
+ sel.appendChild(newOption);
771
+ }
772
+ sel.value = target;
773
+ }
774
+ }
775
+ } else {
776
+ sel.value = (this.opts.multiple || this.mode === 'tags')
777
+ ? values.join(this.opts.valueDelimiter)
778
+ : (values[0] || '');
779
+ }
780
+ };
781
+
782
+ /* ---------------- rendering ---------------- */
783
+
784
+ ZidanSelect.prototype._render = function () {
785
+ var opts = this.opts;
786
+ var hasValue = this.value_.length > 0;
787
+
788
+ this.root.classList.toggle('zs-root--has-value', hasValue);
789
+ this.root.classList.toggle('zs-root--open', this.opened);
790
+ this.root.classList.toggle('zs-root--disabled', !!this.disabled_);
791
+ this.root.classList.toggle('zs-root--invalid', opts.validation === 'invalid');
792
+ this.root.classList.toggle('zs-root--valid', opts.validation === 'valid');
793
+
794
+ if (opts.validation === 'invalid') this.controlEl.classList.add('is-invalid');
795
+ else this.controlEl.classList.remove('is-invalid');
796
+ if (opts.validation === 'valid') this.controlEl.classList.add('is-valid');
797
+ else this.controlEl.classList.remove('is-valid');
798
+ this._toggleCustomClass(this.controlEl, 'invalid', opts.validation === 'invalid');
799
+
800
+ this._renderChips();
801
+ this._renderInputValue();
802
+
803
+ var showClear = opts.clearable && hasValue && !this.disabled_;
804
+ this.clearBtn.hidden = !showClear;
805
+ this.clearBtn.tabIndex = showClear ? 0 : -1;
806
+
807
+ this.input.disabled = !!this.disabled_;
808
+ this.input.setAttribute('aria-expanded', String(this.opened));
809
+ this.root.classList.toggle('zs-root--placeholder', !this.input.value && !hasValue);
810
+
811
+ return this;
812
+ };
813
+
814
+ ZidanSelect.prototype._renderChips = function () {
815
+ var self = this;
816
+ var multi = this.mode === 'tags' || !!this.opts.multiple;
817
+ var chips = this.chipsEl;
818
+
819
+ chips.textContent = '';
820
+ chips.hidden = !multi;
821
+ if (!multi) return;
822
+
823
+ this.value_.forEach(function (item, index) {
824
+ var chip = el('span', 'zs-chip', { 'data-zs-index': index });
825
+ if (self.framework === 'bootstrap') addClass(chip, 'badge rounded-pill');
826
+ self._applyCustomClass(chip, 'chip');
827
+
828
+ var labelNode;
829
+ var custom = typeof self.opts.renderTag === 'function' && self.mode === 'tags'
830
+ ? self.opts.renderTag({ value: item.value, label: item.label }, { index: index, instance: self, disabled: self.disabled_ })
831
+ : null;
832
+
833
+ if (self.mode === 'select' && typeof self.opts.renderSelected === 'function') {
834
+ custom = self.opts.renderSelected({ value: item.value, label: item.label }, { index: index, instance: self });
835
+ }
836
+
837
+ if (custom) {
838
+ if (isElement(custom)) {
839
+ labelNode = custom;
840
+ chip.appendChild(labelNode);
841
+ } else {
842
+ var holder = el('span', 'zs-chip-label');
843
+ holder.innerHTML = String(custom);
844
+ chip.appendChild(holder);
845
+ }
846
+ } else {
847
+ labelNode = el('span', 'zs-chip-label', null, item.label);
848
+ chip.appendChild(labelNode);
849
+ }
850
+
851
+ var removeBtn = el('button', 'zs-chip-remove', {
852
+ type: 'button',
853
+ 'aria-label': 'Remove ' + item.label,
854
+ title: 'Remove ' + item.label,
855
+ 'data-zs-remove': index
856
+ });
857
+ 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>';
858
+ self._applyCustomClass(removeBtn, 'chipRemove');
859
+ chip.appendChild(removeBtn);
860
+ chips.appendChild(chip);
861
+ });
862
+
863
+ this.root.classList.toggle('zs-root--has-value', this.value_.length > 0);
864
+ };
865
+
866
+ ZidanSelect.prototype._renderInputValue = function () {
867
+ var single = this.mode !== 'tags' && !this.opts.multiple;
868
+ if (!single) {
869
+ this.input.placeholder = this.value_.length ? '' : (this.opts.placeholder || '');
870
+ if (this.opened) {
871
+ this.input.value = this.query;
872
+ } else {
873
+ this.input.value = '';
874
+ }
875
+ return;
876
+ }
877
+
878
+ if (this.opened && this.opts.searchable) {
879
+ this.input.value = this.query;
880
+ this.input.placeholder = this.opts.placeholder || '';
881
+ return;
882
+ }
883
+ if (this.opened && !this.opts.searchable) {
884
+ this.input.value = this.value_.length ? this.value_[0].label : '';
885
+ this.input.placeholder = this.opts.placeholder || '';
886
+ return;
887
+ }
888
+ this.input.value = this.value_.length ? this.value_[0].label : '';
889
+ this.input.placeholder = this.opts.placeholder || '';
890
+ if (!this.value_.length) this.input.value = '';
891
+ };
892
+
893
+ /* ---------------- dropdown ---------------- */
894
+
895
+ ZidanSelect.prototype._sourceItems = function () {
896
+ if (this.mode === 'tags') return this.suggestions || [];
897
+ if (typeof this.opts.fetchOptions === 'function' && this.asyncItems) return this.asyncItems;
898
+ return this.items;
899
+ };
900
+
901
+ ZidanSelect.prototype._visibleItems = function () {
902
+ var self = this;
903
+ var query = this.query.trim();
904
+ var source = this._sourceItems();
905
+ var isCaseSensitive = !!this.opts.caseSensitive;
906
+
907
+ if (!query) return source.slice();
908
+
909
+ return source.filter(function (item) {
910
+ if (typeof self.opts.filterOption === 'function') {
911
+ return !!self.opts.filterOption(item, query, {
912
+ instance: self,
913
+ mode: self.mode,
914
+ caseSensitive: isCaseSensitive,
915
+ selected: self._hasValue(item.value)
916
+ });
917
+ }
918
+ var label = isCaseSensitive ? item.label : item.label.toLowerCase();
919
+ var needle = isCaseSensitive ? query : query.toLowerCase();
920
+ if (label.indexOf(needle) !== -1) return true;
921
+ if (self.opts.searchValues) {
922
+ var value = isCaseSensitive ? item.value : item.value.toLowerCase();
923
+ if (value.indexOf(needle) !== -1) return true;
924
+ }
925
+ return false;
926
+ });
927
+ };
928
+
929
+ ZidanSelect.prototype._renderDropdown = function () {
930
+ var self = this;
931
+ if (!this.opened) return;
932
+
933
+ var scrollTop = this.dropdown.scrollTop;
934
+ this.dropdown.textContent = '';
935
+ this.rendered = [];
936
+
937
+ if (this.loading) {
938
+ var loading = el('div', 'zs-state zs-state--loading', { role: 'status' });
939
+ loading.appendChild(el('span', 'zs-spinner', { 'aria-hidden': 'true' }));
940
+ loading.appendChild(el('span', 'zs-state-text', null, this.opts.loadingText));
941
+ this.dropdown.appendChild(loading);
942
+ } else if (this.error) {
943
+ var errorEl = el('div', 'zs-state zs-state--error', { role: 'status' }, this.error.message || 'Something went wrong.');
944
+ this.dropdown.appendChild(errorEl);
945
+ } else {
946
+ var items = this._visibleItems();
947
+
948
+ if (!items.length) {
949
+ var emptyText = this.query ? this.opts.noResultsText : this.opts.emptyText;
950
+ this.dropdown.appendChild(el('div', 'zs-state zs-state--empty', { role: 'status' }, emptyText));
951
+ this.emit('no-results', { query: this.query, instance: this });
952
+ } else {
953
+ var lastGroup = null;
954
+ items.forEach(function (item, index) {
955
+ if (item.group && item.group !== lastGroup) {
956
+ var header = el('div', 'zs-group', { role: 'presentation' }, item.group);
957
+ self.dropdown.appendChild(header);
958
+ lastGroup = item.group;
959
+ }
960
+
961
+ var selected = self._hasValue(item.value);
962
+ var option = el('div', 'zs-option', {
963
+ role: 'option',
964
+ id: self.id + '-opt-' + index,
965
+ 'data-zs-option': index
966
+ });
967
+ option.setAttribute('aria-selected', String(selected));
968
+ if (item.disabled) {
969
+ option.setAttribute('aria-disabled', 'true');
970
+ option.classList.add('zs-option--disabled');
971
+ }
972
+ if (selected) option.classList.add('zs-option--selected');
973
+ self._applyCustomClass(option, 'option');
974
+ if (selected) self._applyCustomClass(option, 'selected');
975
+ if (item.disabled) self._applyCustomClass(option, 'disabled');
976
+
977
+ var content = null;
978
+ if (typeof self.opts.renderOption === 'function') {
979
+ content = self.opts.renderOption(item, {
980
+ index: index,
981
+ selected: selected,
982
+ active: index === self.activeIndex,
983
+ query: self.query,
984
+ instance: self
985
+ });
986
+ }
987
+
988
+ if (content && isElement(content)) {
989
+ option.appendChild(content);
990
+ } else if (content !== null && content !== undefined && content !== '') {
991
+ option.innerHTML = String(content);
992
+ } else {
993
+ option.appendChild(el('span', 'zs-option-label', null, item.label));
994
+ }
995
+
996
+ if (index === self.activeIndex) {
997
+ option.classList.add('zs-option--active');
998
+ self._applyCustomClass(option, 'active');
999
+ }
1000
+
1001
+ self.rendered.push({ element: option, item: item, index: index });
1002
+ self.dropdown.appendChild(option);
1003
+ });
1004
+ }
1005
+ }
1006
+
1007
+ this.dropdown.scrollTop = scrollTop;
1008
+ this._updateActiveDescendant(false);
1009
+ if (this.opened) this._position();
1010
+ };
1011
+
1012
+ ZidanSelect.prototype._updateActiveDescendant = function (scroll) {
1013
+ var active = this.rendered[this.activeIndex];
1014
+ if (active) {
1015
+ this.input.setAttribute('aria-activedescendant', active.element.id);
1016
+ if (scroll !== false) {
1017
+ var elTop = active.element.offsetTop;
1018
+ var elBottom = elTop + active.element.offsetHeight;
1019
+ if (elTop < this.dropdown.scrollTop) this.dropdown.scrollTop = elTop - 4;
1020
+ else if (elBottom > this.dropdown.scrollTop + this.dropdown.clientHeight) {
1021
+ this.dropdown.scrollTop = elBottom - this.dropdown.clientHeight + 4;
1022
+ }
1023
+ }
1024
+ } else {
1025
+ this.input.removeAttribute('aria-activedescendant');
1026
+ }
1027
+ };
1028
+
1029
+ ZidanSelect.prototype._position = function () {
1030
+ if (!this.opened) return;
1031
+ var rect = this.controlEl.getBoundingClientRect();
1032
+ var viewport = global.innerHeight || doc.documentElement.clientHeight;
1033
+ var spaceBelow = viewport - rect.bottom - 12;
1034
+ var spaceAbove = rect.top - 12;
1035
+ var dropUp = spaceBelow < 160 && spaceAbove > spaceBelow;
1036
+
1037
+ this.root.classList.toggle('zs-root--dropup', dropUp);
1038
+ var available = dropUp ? spaceAbove : spaceBelow;
1039
+ var maxHeight = clamp(available, 120, this.opts.maxDropdownHeight || 280);
1040
+ this.dropdown.style.maxHeight = Math.max(120, maxHeight) + 'px';
1041
+
1042
+ var width = rect.width;
1043
+ this.dropdown.style.minWidth = width + 'px';
1044
+ if (this.root.classList.contains('zs-root--mount')) {
1045
+ this.dropdown.style.left = '0px';
1046
+ this.dropdown.style.right = '0px';
1047
+ }
1048
+ };
1049
+
1050
+ /* ---------------- open / close ---------------- */
1051
+
1052
+ ZidanSelect.prototype.open = function () {
1053
+ if (this.destroyed || this.disabled_ || this.opened) return this;
1054
+
1055
+ this.opened = true;
1056
+ this.query = '';
1057
+ this.activeIndex = -1;
1058
+ if (this.mode === 'combobox' || (this.mode === 'select' && this.opts.searchable)) {
1059
+ this.savedInputText = this.input.value;
1060
+ }
1061
+ this.root.classList.add('zs-root--open');
1062
+ this.dropdown.setAttribute('data-zs-visible', 'true');
1063
+ this._render();
1064
+ this._renderDropdown();
1065
+ this._position();
1066
+ this.emit('open', { instance: this });
1067
+ this.call('onOpen', { instance: this });
1068
+
1069
+ if (typeof this.opts.fetchOptions === 'function' && !this.asyncItems) {
1070
+ this._fetch('');
1071
+ } else if (this.mode !== 'tags') {
1072
+ var first = this._firstEnabledIndex();
1073
+ if (first !== -1) {
1074
+ this.activeIndex = first;
1075
+ this._renderDropdown();
1076
+ }
1077
+ }
1078
+ if (this.opts.searchable && !this.disabled_) {
1079
+ try {
1080
+ this.input.select();
1081
+ } catch (err) {
1082
+ this.input.focus();
1083
+ }
1084
+ }
1085
+ var announceItems = this._visibleItems();
1086
+ this.announce(announceItems.length + ' option' + (announceItems.length === 1 ? '' : 's') + ' available');
1087
+ return this;
1088
+ };
1089
+
1090
+ ZidanSelect.prototype.close = function () {
1091
+ if (this.destroyed || !this.opened) return this;
1092
+ this.opened = false;
1093
+ this.root.classList.remove('zs-root--open');
1094
+ this.dropdown.removeAttribute('data-zs-visible');
1095
+ this.activeIndex = -1;
1096
+ this.query = '';
1097
+ this._render();
1098
+ this.emit('close', { instance: this });
1099
+ this.call('onClose', { instance: this });
1100
+ return this;
1101
+ };
1102
+
1103
+ ZidanSelect.prototype.toggle = function () {
1104
+ return this.opened ? this.close() : this.open();
1105
+ };
1106
+
1107
+ ZidanSelect.prototype._firstEnabledIndex = function () {
1108
+ var items = this._visibleItems();
1109
+ for (var i = 0; i < items.length; i += 1) {
1110
+ if (!items[i].disabled) return i;
1111
+ }
1112
+ return -1;
1113
+ };
1114
+
1115
+ /* ---------------- selection ---------------- */
1116
+
1117
+ ZidanSelect.prototype._selectRendered = function (index) {
1118
+ var entry = this.rendered[index];
1119
+ if (!entry || entry.item.disabled) return false;
1120
+ this._selectItem(entry.item);
1121
+ return true;
1122
+ };
1123
+
1124
+ ZidanSelect.prototype._selectItem = function (item) {
1125
+ if (!item || item.disabled) return this;
1126
+ var previous = this.getValue();
1127
+
1128
+ if (this.mode === 'tags') {
1129
+ this.addTag(item.label);
1130
+ this.query = '';
1131
+ this._renderDropdown();
1132
+ return this;
1133
+ }
1134
+
1135
+ if (this.mode === 'combobox' && this.opts.allowFreeText) {
1136
+ this._setValueInternal([item.value]);
1137
+ } else if (this.opts.multiple) {
1138
+ if (this._hasValue(item.value)) {
1139
+ this.value_ = this.value_.filter(function (v) { return v.value !== item.value; });
1140
+ this._render();
1141
+ this._syncNative();
1142
+ var current = this.getValue();
1143
+ if (JSON.stringify(current) !== JSON.stringify(previous)) {
1144
+ this.emit('change', { value: current, previousValue: previous, instance: this });
1145
+ this.call('onChange', { value: current, previousValue: previous, instance: this });
1146
+ }
1147
+ this._renderDropdown();
1148
+ return this;
1149
+ }
1150
+ this._setValueInternal(this.value_.concat([item]));
1151
+ } else {
1152
+ this._setValueInternal([item]);
1153
+ }
1154
+
1155
+ this.emit('select', { value: this.getValue(), item: item, instance: this });
1156
+ this.call('onSelect', { value: this.getValue(), item: item, instance: this });
1157
+
1158
+ var closeOnSelect = this.opts.closeOnSelect === null ? !this.opts.multiple : this.opts.closeOnSelect;
1159
+ if (closeOnSelect) this.close();
1160
+ else if (this.opened) this._renderDropdown();
1161
+ return this;
1162
+ };
1163
+
1164
+ /* ---------------- async loading ---------------- */
1165
+
1166
+ ZidanSelect.prototype._fetch = function (query) {
1167
+ var self = this;
1168
+ if (typeof this.opts.fetchOptions !== 'function') return;
1169
+ query = query === undefined || query === null ? '' : String(query);
1170
+
1171
+ if (this.asyncController) this.asyncController.abort();
1172
+ var controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
1173
+ this.asyncController = controller;
1174
+ this.loading = true;
1175
+ this.error = null;
1176
+ this._renderDropdown();
1177
+ this.announce(this.opts.loadingText);
1178
+
1179
+ var done = function (result) {
1180
+ self.loading = false;
1181
+ self.asyncItems = self._normalizeItems(result || []);
1182
+ self.activeIndex = -1;
1183
+ self._renderDropdown();
1184
+ var count = self._visibleItems().length;
1185
+ self.announce(count + ' result' + (count === 1 ? '' : 's'));
1186
+ };
1187
+ var fail = function (err) {
1188
+ self.loading = false;
1189
+ self.error = { message: (err && err.message) || 'Unable to load options.' };
1190
+ self.emit('error', { error: err, message: self.error.message, instance: self });
1191
+ self.call('onError', { error: err, message: self.error.message, instance: self });
1192
+ self._renderDropdown();
1193
+ };
1194
+
1195
+ try {
1196
+ var result = this.opts.fetchOptions(query, controller ? controller.signal : undefined);
1197
+ if (result && typeof result.then === 'function') {
1198
+ result.then(function (data) {
1199
+ if (controller && controller.signal.aborted) return;
1200
+ done(data);
1201
+ }).catch(function (err) {
1202
+ if (err && err.name === 'AbortError') return;
1203
+ if (controller && controller.signal.aborted) return;
1204
+ fail(err);
1205
+ });
1206
+ } else {
1207
+ done(result);
1208
+ }
1209
+ } catch (err) {
1210
+ if (err && err.name === 'AbortError') return;
1211
+ fail(err);
1212
+ }
1213
+ void self;
1214
+ };
1215
+
1216
+ /* ---------------- tags ---------------- */
1217
+
1218
+ ZidanSelect.prototype._tagError = function (message) {
1219
+ this.announce(message);
1220
+ this.emit('error', { message: message, instance: this });
1221
+ this.call('onError', { message: message, instance: this });
1222
+ this.root.classList.add('zs-root--shake');
1223
+ var rootEl = this.root;
1224
+ setTimeout(function () { rootEl.classList.remove('zs-root--shake'); }, 320);
1225
+ };
1226
+
1227
+ ZidanSelect.prototype._addTagObject = function (rawValue, config) {
1228
+ var cfg = config || {};
1229
+ var opts = this.opts;
1230
+ var raw = String(rawValue === null || rawValue === undefined ? '' : rawValue).trim();
1231
+ if (!raw) return false;
1232
+
1233
+ if (this.value_.length >= opts.maxTags) {
1234
+ if (!cfg.silent) this._tagError('You can add up to ' + opts.maxTags + ' tags.');
1235
+ return false;
1236
+ }
1237
+ if (raw.length < opts.minTagLength) {
1238
+ if (!cfg.silent) this._tagError('Tags need at least ' + opts.minTagLength + ' character' + (opts.minTagLength === 1 ? '' : 's') + '.');
1239
+ return false;
1240
+ }
1241
+ if (raw.length > opts.maxTagLength) {
1242
+ if (!cfg.silent) this._tagError('Tags can be at most ' + opts.maxTagLength + ' characters.');
1243
+ return false;
1244
+ }
1245
+ if (this._hasValue(raw)) {
1246
+ if (!cfg.silent) this._tagError('"' + raw + '" is already added.');
1247
+ return false;
1248
+ }
1249
+
1250
+ var formatted = raw;
1251
+ if (typeof opts.formatTag === 'function') {
1252
+ var formattedResult = opts.formatTag(raw, { instance: this, tags: this.getTags() });
1253
+ if (typeof formattedResult === 'string' && formattedResult) formatted = formattedResult;
1254
+ }
1255
+
1256
+ if (typeof opts.validateTag === 'function') {
1257
+ var validation = opts.validateTag(formatted, this.getTags(), { instance: this });
1258
+ if (validation === false) {
1259
+ if (!cfg.silent) this._tagError('"' + formatted + '" is not allowed.');
1260
+ return false;
1261
+ }
1262
+ if (typeof validation === 'string') {
1263
+ if (!cfg.silent) this._tagError(validation);
1264
+ return false;
1265
+ }
1266
+ }
1267
+
1268
+ var tag = { value: formatted, label: formatted };
1269
+ this.value_.push(tag);
1270
+ this.query = '';
1271
+
1272
+ if (!cfg.silent) {
1273
+ this._render();
1274
+ this._syncNative();
1275
+ if (this.opened) this._renderDropdown();
1276
+ this.announce(formatted + ' added. ' + this.value_.length + ' tag' + (this.value_.length === 1 ? '' : 's') + ' total.');
1277
+ this.emit('tag-add', { tag: formatted, value: this.getTags(), instance: this });
1278
+ this.call('onTagAdd', { tag: formatted, value: this.getTags(), instance: this });
1279
+ this.emit('change', { value: this.getTags(), instance: this });
1280
+ this.call('onChange', { value: this.getTags(), instance: this });
1281
+ }
1282
+ return true;
1283
+ };
1284
+
1285
+ ZidanSelect.prototype.addTag = function (tag) {
1286
+ var added = this._addTagObject(tag, {});
1287
+ this._render();
1288
+ if (this.opened) this._renderDropdown();
1289
+ return added;
1290
+ };
1291
+
1292
+ ZidanSelect.prototype.removeTag = function (tagOrIndex) {
1293
+ var index = typeof tagOrIndex === 'number'
1294
+ ? tagOrIndex
1295
+ : this.value_.findIndex(function (tag) {
1296
+ return String(tag.value) === String(tagOrIndex) || String(tag.label) === String(tagOrIndex);
1297
+ });
1298
+
1299
+ if (index < 0 || index >= this.value_.length) return false;
1300
+ var removed = this.value_.splice(index, 1)[0];
1301
+
1302
+ this._render();
1303
+ this._syncNative();
1304
+ if (this.opened) this._renderDropdown();
1305
+ this.announce(removed.label + ' removed. ' + this.value_.length + ' tag' + (this.value_.length === 1 ? '' : 's') + ' remaining.');
1306
+ this.emit('tag-remove', { tag: removed.value, value: this.getTags(), instance: this });
1307
+ this.call('onTagRemove', { tag: removed.value, value: this.getTags(), instance: this });
1308
+ this.emit('change', { value: this.getTags(), instance: this });
1309
+ this.call('onChange', { value: this.getTags(), instance: this });
1310
+ this.input.focus();
1311
+ return true;
1312
+ };
1313
+
1314
+ ZidanSelect.prototype.getTags = function () {
1315
+ return this.value_.map(function (tag) { return tag.value; });
1316
+ };
1317
+
1318
+ /* ---------------- keyboard ---------------- */
1319
+
1320
+ ZidanSelect.prototype._onKeyDown = function (event) {
1321
+ if (this.destroyed) return;
1322
+ var key = event.key;
1323
+ var items = this._visibleItems();
1324
+
1325
+ if (key === 'ArrowDown' || key === 'ArrowUp') {
1326
+ event.preventDefault();
1327
+ if (!this.opened) {
1328
+ this.open();
1329
+ return;
1330
+ }
1331
+ if (!items.length) return;
1332
+ var step = key === 'ArrowDown' ? 1 : -1;
1333
+ var next = this.activeIndex;
1334
+ for (var guard = 0; guard < items.length; guard += 1) {
1335
+ next += step;
1336
+ if (next < 0) next = items.length - 1;
1337
+ if (next >= items.length) next = 0;
1338
+ if (!items[next].disabled) break;
1339
+ }
1340
+ this.activeIndex = next;
1341
+ this._renderDropdown();
1342
+ return;
1343
+ }
1344
+
1345
+ if (key === 'Home' || key === 'End') {
1346
+ if (!this.opened) return;
1347
+ event.preventDefault();
1348
+ var found = -1;
1349
+ var i;
1350
+ if (key === 'Home') {
1351
+ for (i = 0; i < items.length; i += 1) { if (!items[i].disabled) { found = i; break; } }
1352
+ } else {
1353
+ for (i = items.length - 1; i >= 0; i -= 1) { if (!items[i].disabled) { found = i; break; } }
1354
+ }
1355
+ this.activeIndex = found;
1356
+ this._renderDropdown();
1357
+ return;
1358
+ }
1359
+
1360
+ if (key === 'Enter') {
1361
+ if (this.opened) {
1362
+ event.preventDefault();
1363
+ if (this.activeIndex >= 0) {
1364
+ this._selectRendered(this.activeIndex);
1365
+ if (this.mode === 'tags') this.query = '';
1366
+ return;
1367
+ }
1368
+ if (this.mode === 'tags') {
1369
+ this._commitTypedTag();
1370
+ return;
1371
+ }
1372
+ if ((this.mode === 'combobox' || this.mode === 'select') && this.opts.allowFreeText) {
1373
+ var text = this.query.trim();
1374
+ if (text) {
1375
+ this._setValueInternal([text]);
1376
+ this.emit('select', { value: this.getValue(), item: { value: text, label: text }, instance: this });
1377
+ this.call('onSelect', { value: this.getValue(), item: { value: text, label: text }, instance: this });
1378
+ this.close();
1379
+ }
1380
+ return;
1381
+ }
1382
+ if (items.length === 1) this._selectRendered(0);
1383
+ return;
1384
+ }
1385
+ if (this.mode === 'tags' && this.query.trim()) {
1386
+ event.preventDefault();
1387
+ this._commitTypedTag();
1388
+ return;
1389
+ }
1390
+ event.preventDefault();
1391
+ this.open();
1392
+ return;
1393
+ }
1394
+
1395
+ if (key === 'Escape') {
1396
+ if (this.opened) {
1397
+ event.preventDefault();
1398
+ this.close();
1399
+ }
1400
+ return;
1401
+ }
1402
+
1403
+ if (key === 'Tab') {
1404
+ if (this.mode === 'tags' && this.opts.commitOnTab && this.query.trim()) {
1405
+ this._commitTypedTag();
1406
+ }
1407
+ if (this.opened) this.close();
1408
+ return;
1409
+ }
1410
+
1411
+ if (key === 'Backspace') {
1412
+ if (this.mode === 'tags' && !this.input.value && !this.query && this.value_.length) {
1413
+ event.preventDefault();
1414
+ this.removeTag(this.value_.length - 1);
1415
+ return;
1416
+ }
1417
+ if (!this.input.value && this.opened) this.close();
1418
+ return;
1419
+ }
1420
+
1421
+ if (key === 'Delete' && this.opts.clearable && this.value_.length) {
1422
+ event.preventDefault();
1423
+ this.clear();
1424
+ }
1425
+ };
1426
+
1427
+ ZidanSelect.prototype._commitTypedTag = function () {
1428
+ var raw = this.input.value;
1429
+ var parts = this._splitTags(raw);
1430
+ var added = false;
1431
+ parts.forEach(function (part) { if (this._addTagObject(part, {})) added = true; }, this);
1432
+ this.input.value = '';
1433
+ this.query = '';
1434
+ this._render();
1435
+ this._syncNative();
1436
+ if (this.opened) this._renderDropdown();
1437
+ return added;
1438
+ };
1439
+
1440
+ ZidanSelect.prototype._splitTags = function (text) {
1441
+ var value = String(text || '');
1442
+ var delimiters = this.opts.delimiters || [];
1443
+ var parts = [value];
1444
+ delimiters.forEach(function (delimiter) {
1445
+ if (!delimiter) return;
1446
+ parts = parts.reduce(function (acc, chunk) {
1447
+ return acc.concat(chunk.split(delimiter));
1448
+ }, []);
1449
+ });
1450
+ return parts.map(function (part) { return part.trim(); }).filter(Boolean);
1451
+ };
1452
+
1453
+ /* ---------------- events wiring ---------------- */
1454
+
1455
+ ZidanSelect.prototype._bind = function () {
1456
+ var self = this;
1457
+
1458
+ this.onInput = function () {
1459
+ var value = self.input.value;
1460
+ self.query = value;
1461
+ if (self.opened) {
1462
+ if (typeof self.opts.fetchOptions === 'function' && self.query.length >= (self.opts.minChars || 0)) {
1463
+ if (self.opts.debounce > 0) self.debouncedFetch(self.query);
1464
+ else self._fetch(self.query);
1465
+ }
1466
+ self.activeIndex = self.mode === 'tags' ? -1 : self._firstEnabledIndex();
1467
+ self._renderDropdown();
1468
+ } else {
1469
+ // typed while closed (rare race): open first, then keep the text
1470
+ self.open();
1471
+ self.query = value;
1472
+ self.input.value = value;
1473
+ self._renderDropdown();
1474
+ }
1475
+ if (self.mode === 'tags') {
1476
+ var delimiters = self.opts.delimiters || [];
1477
+ var hasDelimiter = delimiters.some(function (delimiter) { return delimiter && value.indexOf(delimiter) !== -1; });
1478
+ if (hasDelimiter) {
1479
+ self._commitTypedTag();
1480
+ }
1481
+ }
1482
+ };
1483
+
1484
+ this.onKeyDown = function (event) { self._onKeyDown(event); };
1485
+
1486
+ this.onFocus = function () {
1487
+ if (self.disabled_) return;
1488
+ self.root.classList.add('zs-root--focus');
1489
+ if (self.mode === 'combobox' || self.mode === 'tags' || (self.mode === 'select' && self.opts.searchable)) {
1490
+ if (!self.opened) self.open();
1491
+ }
1492
+ };
1493
+
1494
+ this.onBlur = function () {
1495
+ self.root.classList.remove('zs-root--focus');
1496
+ setTimeout(function () {
1497
+ if (self.destroyed) return;
1498
+ if (self.root.contains(doc.activeElement)) return;
1499
+ if (self.mode === 'tags' && self.query.trim() && self.opts.commitOnBlur) {
1500
+ self._commitTypedTag();
1501
+ }
1502
+ if (self.mode === 'combobox' && self.opts.allowFreeText && self.query.trim()) {
1503
+ self._setValueInternal([self.query.trim()]);
1504
+ }
1505
+ self.query = '';
1506
+ self.close();
1507
+ self._render();
1508
+ }, 0);
1509
+ };
1510
+
1511
+ this.onControlClick = function (event) {
1512
+ if (self.disabled_) return;
1513
+ var target = event.target;
1514
+ if (target.closest && target.closest('.zs-clear')) return;
1515
+ if (target.closest && target.closest('.zs-chip-remove')) return;
1516
+ if (self.opened) {
1517
+ if (!self.opts.searchable && !self.input.readOnly) return;
1518
+ if (!self.opts.searchable) self.close();
1519
+ return;
1520
+ }
1521
+ self.open();
1522
+ };
1523
+
1524
+ this.onControlMouseDown = function (event) {
1525
+ if (event.target === self.input) return;
1526
+ if (event.target.closest && (event.target.closest('.zs-chip-remove') || event.target.closest('.zs-clear'))) {
1527
+ event.preventDefault();
1528
+ return;
1529
+ }
1530
+ if (event.target === self.controlEl || (event.target.closest && event.target.closest('.zs-chips'))) {
1531
+ event.preventDefault();
1532
+ self.input.focus();
1533
+ }
1534
+ };
1535
+
1536
+ this.onClearClick = function (event) {
1537
+ event.preventDefault();
1538
+ event.stopPropagation();
1539
+ self.clear();
1540
+ };
1541
+
1542
+ this.onChipsClick = function (event) {
1543
+ var button = event.target.closest ? event.target.closest('[data-zs-remove]') : null;
1544
+ if (!button) return;
1545
+ event.preventDefault();
1546
+ event.stopPropagation();
1547
+ var index = parseInt(button.getAttribute('data-zs-remove'), 10);
1548
+ if (isNaN(index)) return;
1549
+ if (self.mode === 'tags') self.removeTag(index);
1550
+ else {
1551
+ var item = self.value_[index];
1552
+ if (!item) return;
1553
+ var previous = self.getValue();
1554
+ self.value_.splice(index, 1);
1555
+ self._render();
1556
+ self._syncNative();
1557
+ self.emit('change', { value: self.getValue(), previousValue: previous, item: item, instance: self });
1558
+ self.call('onChange', { value: self.getValue(), previousValue: previous, item: item, instance: self });
1559
+ self.announce(item.label + ' removed.');
1560
+ if (self.opened) self._renderDropdown();
1561
+ }
1562
+ };
1563
+
1564
+ this.onDropdownMouseDown = function (event) {
1565
+ event.preventDefault();
1566
+ };
1567
+
1568
+ this.onDropdownClick = function (event) {
1569
+ var option = event.target.closest ? event.target.closest('[data-zs-option]') : null;
1570
+ if (!option) return;
1571
+ event.preventDefault();
1572
+ var index = parseInt(option.getAttribute('data-zs-option'), 10);
1573
+ if (isNaN(index)) return;
1574
+ self.activeIndex = index;
1575
+ self._selectRendered(index);
1576
+ if (self.mode === 'tags') self.input.focus();
1577
+ };
1578
+
1579
+ this.onDocumentPointerDown = function (event) {
1580
+ if (!self.opened) return;
1581
+ var path = event.composedPath ? event.composedPath() : [];
1582
+ if (path.indexOf(self.root) !== -1) return;
1583
+ if (self.root.contains(event.target)) return;
1584
+ self.close();
1585
+ self._render();
1586
+ };
1587
+
1588
+ this.onWindowResize = function () {
1589
+ if (self.opened) self._position();
1590
+ };
1591
+
1592
+ this.debouncedFetch = debounce(function (query) { self._fetch(query); }, this.opts.debounce);
1593
+
1594
+ this.input.addEventListener('input', this.onInput);
1595
+ this.input.addEventListener('keydown', this.onKeyDown);
1596
+ this.input.addEventListener('focus', this.onFocus);
1597
+ this.input.addEventListener('blur', this.onBlur);
1598
+ this.controlEl.addEventListener('click', this.onControlClick);
1599
+ this.controlEl.addEventListener('mousedown', this.onControlMouseDown);
1600
+ this.chipsEl.addEventListener('click', this.onChipsClick);
1601
+ this.clearBtn.addEventListener('click', this.onClearClick);
1602
+ this.dropdown.addEventListener('mousedown', this.onDropdownMouseDown);
1603
+ this.dropdown.addEventListener('click', this.onDropdownClick);
1604
+ doc.addEventListener('pointerdown', this.onDocumentPointerDown, true);
1605
+ global.addEventListener('resize', this.onWindowResize);
1606
+ };
1607
+
1608
+ ZidanSelect.prototype._observeResize = function () {
1609
+ if (typeof ResizeObserver === 'undefined') return;
1610
+ var self = this;
1611
+ this.resizeObserver = new ResizeObserver(function () {
1612
+ if (self.opened) self._position();
1613
+ });
1614
+ this.resizeObserver.observe(this.controlEl);
1615
+ };
1616
+
1617
+ /* ---------------- public API ---------------- */
1618
+
1619
+ ZidanSelect.prototype.getValue = function () {
1620
+ if (this.mode === 'tags') return this.getTags();
1621
+ var values = this.value_.map(function (item) { return item.value; });
1622
+ if (this.opts.multiple) return values;
1623
+ return values.length ? values[0] : null;
1624
+ };
1625
+
1626
+ ZidanSelect.prototype.setValue = function (value, config) {
1627
+ var cfg = config || {};
1628
+ if (this.mode === 'tags') {
1629
+ var raw = typeof value === 'string' ? this._splitTags(value) : toArray(value);
1630
+ var previous = this.getTags();
1631
+ this.value_ = [];
1632
+ raw.forEach(function (tag) { this._addTagObject(tag, { silent: true }); }, this);
1633
+ this._render();
1634
+ this._syncNative();
1635
+ if (!cfg.silent) {
1636
+ var next = this.getTags();
1637
+ if (JSON.stringify(next) !== JSON.stringify(previous)) {
1638
+ this.emit('change', { value: next, previousValue: previous, instance: this });
1639
+ this.call('onChange', { value: next, previousValue: previous, instance: this });
1640
+ }
1641
+ }
1642
+ if (this.opened) this._renderDropdown();
1643
+ return this;
1644
+ }
1645
+ return this._setValueInternal(value, cfg);
1646
+ };
1647
+
1648
+ ZidanSelect.prototype.clear = function () {
1649
+ if (this.mode === 'tags') {
1650
+ if (!this.value_.length) return this;
1651
+ this.value_ = [];
1652
+ this._render();
1653
+ this._syncNative();
1654
+ this.announce('All tags removed.');
1655
+ this.emit('change', { value: [], instance: this });
1656
+ this.call('onChange', { value: [], instance: this });
1657
+ if (this.opened) this._renderDropdown();
1658
+ return this;
1659
+ }
1660
+ this._setValueInternal([], {});
1661
+ this._render();
1662
+ return this;
1663
+ };
1664
+
1665
+ ZidanSelect.prototype.setOptions = function (newOptions) {
1666
+ var items = this._normalizeItems(newOptions);
1667
+ if (this.mode === 'tags') {
1668
+ this.suggestions = items;
1669
+ } else {
1670
+ this.items = items;
1671
+ var self = this;
1672
+ this.value_ = this.value_.filter(function (item) {
1673
+ for (var i = 0; i < self.items.length; i += 1) {
1674
+ if (self.items[i].value === item.value) return true;
1675
+ }
1676
+ return self.opts.allowFreeText;
1677
+ });
1678
+ }
1679
+ this.asyncItems = null;
1680
+ this.activeIndex = -1;
1681
+ this._render();
1682
+ this._syncNative();
1683
+ if (this.opened) this._renderDropdown();
1684
+ return this;
1685
+ };
1686
+
1687
+ ZidanSelect.prototype.enable = function () {
1688
+ this.disabled_ = false;
1689
+ this._render();
1690
+ return this;
1691
+ };
1692
+
1693
+ ZidanSelect.prototype.disable = function () {
1694
+ this.disabled_ = true;
1695
+ this.close();
1696
+ this._render();
1697
+ return this;
1698
+ };
1699
+
1700
+ ZidanSelect.prototype.setLayout = function (layoutName) {
1701
+ var next = String(layoutName || '').toLowerCase();
1702
+ if (LAYOUTS.indexOf(next) === -1) {
1703
+ throw new Error('ZidanSelect: unknown layout "' + layoutName + '". Use: ' + LAYOUTS.join(', '));
1704
+ }
1705
+ this.layout = next;
1706
+ this.opts.layout = next;
1707
+ this.root.setAttribute('data-zs-layout', next);
1708
+ this.root.classList.toggle('zs-root--labeled', next === 'floating-label');
1709
+ this._position();
1710
+ return this;
1711
+ };
1712
+
1713
+ ZidanSelect.prototype.setFramework = function (frameworkName) {
1714
+ var next = String(frameworkName || '').toLowerCase();
1715
+ if (FRAMEWORKS.indexOf(next) === -1) {
1716
+ throw new Error('ZidanSelect: unknown framework "' + frameworkName + '". Use: ' + FRAMEWORKS.join(', '));
1717
+ }
1718
+ this.opts.themeFramework = next;
1719
+ this.framework = next === 'auto' ? this._resolveFramework() : next;
1720
+ this.root.setAttribute('data-zs-framework', this.framework);
1721
+ this.controlEl.classList.toggle('form-control', this.framework === 'bootstrap');
1722
+ this.controlEl.classList.toggle('zs-bootstrap-control', this.framework === 'bootstrap');
1723
+ this.controlEl.classList.toggle('form-select', this.framework === 'bootstrap' && this.el.tagName === 'SELECT');
1724
+ this._applyCustomClass(this.root, 'root');
1725
+ this._render();
1726
+ return this;
1727
+ };
1728
+
1729
+ ZidanSelect.prototype.setScrollbar = function (scrollbarName) {
1730
+ var next = String(scrollbarName || '').toLowerCase();
1731
+ if (SCROLLBARS.indexOf(next) === -1) {
1732
+ throw new Error('ZidanSelect: unknown scrollbar "' + scrollbarName + '". Use: ' + SCROLLBARS.join(', '));
1733
+ }
1734
+ this.opts.scrollbar = next;
1735
+ if (this.root) this.root.setAttribute('data-zs-scrollbar', next);
1736
+ return this;
1737
+ };
1738
+
1739
+ ZidanSelect.prototype.setValidation = function (state) {
1740
+ this.opts.validation = state;
1741
+ this._render();
1742
+ return this;
1743
+ };
1744
+
1745
+ ZidanSelect.prototype.on = function (eventName, handler) {
1746
+ var name = this._eventName(eventName);
1747
+ this.root.addEventListener(name, handler);
1748
+ if (!this.listeners.has(name)) this.listeners.set(name, []);
1749
+ this.listeners.get(name).push(handler);
1750
+ return this;
1751
+ };
1752
+
1753
+ ZidanSelect.prototype.off = function (eventName, handler) {
1754
+ var name = this._eventName(eventName);
1755
+ var handlers = this.listeners.get(name) || [];
1756
+ if (handler) {
1757
+ this.root.removeEventListener(name, handler);
1758
+ this.listeners.set(name, handlers.filter(function (h) { return h !== handler; }));
1759
+ } else {
1760
+ var rootEl = this.root;
1761
+ handlers.forEach(function (h) { rootEl.removeEventListener(name, h); });
1762
+ this.listeners.set(name, []);
1763
+ }
1764
+ return this;
1765
+ };
1766
+
1767
+ ZidanSelect.prototype._eventName = function (eventName) {
1768
+ var name = String(eventName || '');
1769
+ return name.indexOf(EVENT_PREFIX) === 0 ? name : EVENT_PREFIX + name;
1770
+ };
1771
+
1772
+ ZidanSelect.prototype.emit = function (name, detail) {
1773
+ if (!this.root || !doc) return this;
1774
+ var event;
1775
+ try {
1776
+ event = new CustomEvent(EVENT_PREFIX + name, {
1777
+ bubbles: true,
1778
+ cancelable: false,
1779
+ detail: detail || {}
1780
+ });
1781
+ } catch (err) {
1782
+ event = doc.createEvent('CustomEvent');
1783
+ event.initCustomEvent(EVENT_PREFIX + name, true, false, detail || {});
1784
+ }
1785
+ this.root.dispatchEvent(event);
1786
+ return this;
1787
+ };
1788
+
1789
+ ZidanSelect.prototype.call = function (callbackName, payload) {
1790
+ var fn = this.opts[callbackName];
1791
+ if (typeof fn !== 'function') return undefined;
1792
+ try {
1793
+ return fn(payload);
1794
+ } catch (err) {
1795
+ this.emit('error', { error: err, message: (err && err.message) || String(err), callback: callbackName, instance: this });
1796
+ return undefined;
1797
+ }
1798
+ };
1799
+
1800
+ ZidanSelect.prototype.announce = function (message) {
1801
+ if (!this.liveEl || !message) return;
1802
+ this.liveEl.textContent = '';
1803
+ this.liveEl.textContent = message;
1804
+ };
1805
+
1806
+ ZidanSelect.prototype.destroy = function () {
1807
+ if (this.destroyed) return this;
1808
+ this.destroyed = true;
1809
+
1810
+ if (this.debouncedFetch) this.debouncedFetch.cancel();
1811
+ if (this.asyncController) this.asyncController.abort();
1812
+ if (this.resizeObserver) this.resizeObserver.disconnect();
1813
+ if (this.form && this.onFormReset) this.form.removeEventListener('reset', this.onFormReset);
1814
+
1815
+ doc.removeEventListener('pointerdown', this.onDocumentPointerDown, true);
1816
+ global.removeEventListener('resize', this.onWindowResize);
1817
+
1818
+ this.emit('destroy', { instance: this });
1819
+
1820
+ if (this.root && this.root.parentNode) this.root.parentNode.removeChild(this.root);
1821
+
1822
+ if (this.native) {
1823
+ this.native.hidden = false;
1824
+ this.native.classList.remove('zs-native');
1825
+ this.native.removeAttribute('tabindex');
1826
+ this.native.removeAttribute('aria-hidden');
1827
+ } else if (this.el.classList && this.el.classList.contains('zs-root--mount')) {
1828
+ this.el.classList.remove('zs-root--mount');
1829
+ }
1830
+
1831
+ if (this.el.__zidanSelect === this) delete this.el.__zidanSelect;
1832
+ this.listeners.clear();
1833
+ var index = ZidanSelect.instances.indexOf(this);
1834
+ if (index !== -1) ZidanSelect.instances.splice(index, 1);
1835
+ return this;
1836
+ };
1837
+
1838
+ ZidanSelect.prototype.isOpen = function () {
1839
+ return this.opened;
1840
+ };
1841
+
1842
+ ZidanSelect.prototype.refresh = function () {
1843
+ this._render();
1844
+ if (this.opened) this._renderDropdown();
1845
+ return this;
1846
+ };
1847
+
1848
+ /* ================================================================== *
1849
+ * Part 2 — opt-in form fields
1850
+ *
1851
+ * The real control always stays in the DOM (1×1px, never display:none),
1852
+ * so FormData, form.reset(), constraint validation and jQuery Validation's
1853
+ * ":hidden" ignore all keep working. Wrappers only mirror its state.
1854
+ * ================================================================== */
1855
+
1856
+ var VALIDATION_STATES = ['valid', 'invalid'];
1857
+ var CHECKBOX_VARIANTS = ['default', 'switch', 'card'];
1858
+ var RADIO_VARIANTS = ['stacked', 'inline', 'card'];
1859
+
1860
+ function textWithout(rootNode, skip) {
1861
+ var out = '';
1862
+ Array.prototype.slice.call(rootNode.childNodes).forEach(function (node) {
1863
+ if (node === skip || node.nodeType !== 3) return;
1864
+ out += node.nodeValue;
1865
+ });
1866
+ return out.replace(/\s+/g, ' ').trim();
1867
+ }
1868
+
1869
+ function moveTextInto(label, target) {
1870
+ Array.prototype.slice.call(label.childNodes).forEach(function (node) {
1871
+ if (node.nodeType === 3 && node.nodeValue.trim()) target.appendChild(node);
1872
+ });
1873
+ return target;
1874
+ }
1875
+
1876
+ /* ---------------- shared base ---------------- */
1877
+
1878
+ function ZidanFieldBase(target, options, kind) {
1879
+ if (!doc) throw new Error('ZidanForm requires a DOM environment.');
1880
+ if (!isElement(target)) throw new Error('ZidanForm: target element not found.');
1881
+ this.el = target;
1882
+ this.kind = kind;
1883
+ this.opts = options || {};
1884
+ this.id = target.id || (target.id = uid('zf'));
1885
+ this.root = null;
1886
+ this.touched = false;
1887
+ this.validation = null;
1888
+ this.destroyed = false;
1889
+ this._listeners = [];
1890
+ this._cleanups = [];
1891
+ this.formEl = target.form || (target.closest ? target.closest('form') : null);
1892
+ var scope = resolveScope(target, this.opts);
1893
+ this.theme = scope.theme;
1894
+ this.framework = scope.framework;
1895
+ this.layout = this.opts.layout || scope.layout;
1896
+ }
1897
+
1898
+ ZidanFieldBase.prototype.on = function (node, type, handler, config) {
1899
+ if (!node || !node.addEventListener) return this;
1900
+ node.addEventListener(type, handler, config);
1901
+ this._listeners.push([node, type, handler, config]);
1902
+ return this;
1903
+ };
1904
+
1905
+ ZidanFieldBase.prototype.emit = function (name, detail) {
1906
+ if (!this.root) return this;
1907
+ var payload = detail || {};
1908
+ payload.instance = this;
1909
+ payload.kind = this.kind;
1910
+ try {
1911
+ this.root.dispatchEvent(new CustomEvent(EVENT_PREFIX + name, { detail: payload, bubbles: true }));
1912
+ } catch (err) { /* CustomEvent unsupported: events are optional */ }
1913
+ return this;
1914
+ };
1915
+
1916
+ ZidanFieldBase.prototype.call = function (name, payload) {
1917
+ var fn = this.opts[name];
1918
+ if (typeof fn !== 'function') return undefined;
1919
+ try { return fn(payload); } catch (err) { this.emit('error', { error: err, callback: name }); }
1920
+ return undefined;
1921
+ };
1922
+
1923
+ ZidanFieldBase.prototype._scope = function (kind) {
1924
+ var root = el('div', 'zs-field');
1925
+ root.id = this.id + '-field';
1926
+ root.setAttribute('data-zs-kind', kind);
1927
+ root.classList.add('zs-field--' + kind);
1928
+ this._applyScope(root);
1929
+ this.root = root;
1930
+ return root;
1931
+ };
1932
+
1933
+ ZidanFieldBase.prototype._applyScope = function (root) {
1934
+ root.setAttribute('data-zs-theme', this.theme);
1935
+ root.setAttribute('data-zs-framework', this.framework);
1936
+ if (this.layout) root.setAttribute('data-zs-layout', this.layout);
1937
+ return root;
1938
+ };
1939
+
1940
+ ZidanFieldBase.prototype.setTheme = function (name) {
1941
+ this.theme = pickList(name, THEMES, this.theme);
1942
+ if (this.root) this.root.setAttribute('data-zs-theme', this.theme);
1943
+ return this;
1944
+ };
1945
+
1946
+ ZidanFieldBase.prototype.setFramework = function (name) {
1947
+ this.framework = pickList(name, FRAMEWORKS, this.framework);
1948
+ if (this.root) this.root.setAttribute('data-zs-framework', this.framework);
1949
+ return this;
1950
+ };
1951
+
1952
+ ZidanFieldBase.prototype.setLayout = function (name) {
1953
+ this.layout = pickList(name, FIELD_LAYOUTS, this.layout || 'stacked');
1954
+ if (this.root) this.root.setAttribute('data-zs-layout', this.layout);
1955
+ return this;
1956
+ };
1957
+
1958
+ ZidanFieldBase.prototype.validationTargets = function () {
1959
+ return [this.el];
1960
+ };
1961
+
1962
+ /* mirror native constraint validity into classes and aria-invalid */
1963
+ ZidanFieldBase.prototype._bindValidity = function () {
1964
+ var self = this;
1965
+ this.validationTargets().forEach(function (input) {
1966
+ self.on(input, 'invalid', function () {
1967
+ self.touched = true;
1968
+ self.setValidation('invalid');
1969
+ });
1970
+ self.on(input, 'blur', function () {
1971
+ self.touched = true;
1972
+ self._mirrorValidity();
1973
+ });
1974
+ self.on(input, 'input', function () { self._mirrorValidity(); });
1975
+ self.on(input, 'change', function () { self._mirrorValidity(); });
1976
+ });
1977
+ this.on(this.formEl, 'reset', function () {
1978
+ global.setTimeout(function () {
1979
+ if (self.destroyed) return;
1980
+ self.touched = false;
1981
+ self.setValidation(null);
1982
+ self.update();
1983
+ }, 0);
1984
+ });
1985
+ var preset = this.opts.validation || this.el.getAttribute('data-zidan-validation') ||
1986
+ this.el.getAttribute('data-zs-validation');
1987
+ if (preset === 'valid' || preset === 'invalid') this.setValidation(preset);
1988
+ };
1989
+
1990
+ ZidanFieldBase.prototype._mirrorValidity = function () {
1991
+ var target = this.el;
1992
+ if (!target || !target.validity) return this;
1993
+ if (target.validity.valid) {
1994
+ if (this.validation === 'invalid') this.setValidation(null);
1995
+ return this;
1996
+ }
1997
+ if (this.touched || this.opts.alwaysValidate) this.setValidation('invalid');
1998
+ return this;
1999
+ };
2000
+
2001
+ ZidanFieldBase.prototype.setValidation = function (state) {
2002
+ this.validation = VALIDATION_STATES.indexOf(state) === -1 ? null : state;
2003
+ if (this.root) {
2004
+ this.root.classList.toggle('zs-field--invalid', this.validation === 'invalid');
2005
+ this.root.classList.toggle('zs-field--valid', this.validation === 'valid');
2006
+ if (this.validation) this.root.setAttribute('data-zs-validation', this.validation);
2007
+ else this.root.removeAttribute('data-zs-validation');
2008
+ }
2009
+ this.validationTargets().forEach(function (input) {
2010
+ if (state === 'invalid') input.setAttribute('aria-invalid', 'true');
2011
+ else if (state === 'valid') input.setAttribute('aria-invalid', 'false');
2012
+ else input.removeAttribute('aria-invalid');
2013
+ });
2014
+ this.emit('validation', { state: this.validation });
2015
+ this.call('onValidation', { state: this.validation, instance: this });
2016
+ return this;
2017
+ };
2018
+
2019
+ ZidanFieldBase.prototype.getValidation = function () {
2020
+ return this.validation;
2021
+ };
2022
+
2023
+ ZidanFieldBase.prototype.update = function () {
2024
+ if (this._sync) this._sync();
2025
+ this._mirrorValidity();
2026
+ return this;
2027
+ };
2028
+
2029
+ ZidanFieldBase.prototype.refresh = function () {
2030
+ return this.update();
2031
+ };
2032
+
2033
+ ZidanFieldBase.prototype.destroy = function () {
2034
+ if (this.destroyed) return this;
2035
+ this.destroyed = true;
2036
+ this._listeners.forEach(function (entry) {
2037
+ entry[0].removeEventListener(entry[1], entry[2], entry[3]);
2038
+ });
2039
+ this._listeners.length = 0;
2040
+ if (this._teardown) this._teardown();
2041
+ this._cleanups.forEach(function (fn) { fn(); });
2042
+ this._cleanups.length = 0;
2043
+ this.emit('destroy', {});
2044
+ if (this.root && this.root.parentNode) this.root.parentNode.removeChild(this.root);
2045
+ if (this.el.__zidanField === this) delete this.el.__zidanField;
2046
+ ZidanForm._unregister(this);
2047
+ return this;
2048
+ };
2049
+
2050
+ /* ---------------- checkbox ---------------- */
2051
+
2052
+ function ZidanCheckbox(target, options) {
2053
+ if (!(this instanceof ZidanCheckbox)) return new ZidanCheckbox(target, options);
2054
+ if (!/^checkbox$/i.test(target.type)) {
2055
+ throw new Error('ZidanCheckbox: expected an <input type="checkbox">.');
2056
+ }
2057
+ ZidanFieldBase.call(this, target, options, 'checkbox');
2058
+ var self = this;
2059
+ var input = target;
2060
+ var variant = pickList(
2061
+ this.opts.variant || input.getAttribute('data-zidan-variant') ||
2062
+ (input.hasAttribute('data-zidan-switch') ? 'switch' : 'default'),
2063
+ CHECKBOX_VARIANTS,
2064
+ 'default'
2065
+ );
2066
+ this.variant = variant;
2067
+
2068
+ var originalParent = input.parentNode;
2069
+ var originalNext = input.nextSibling;
2070
+ var wrappingLabel = input.closest ? input.closest('label') : null;
2071
+ var externalLabel = null;
2072
+ var labelText = this.opts.label || input.getAttribute('data-zidan-label') || '';
2073
+
2074
+ if (!labelText) {
2075
+ if (wrappingLabel) {
2076
+ labelText = textWithout(wrappingLabel, input);
2077
+ } else if (input.labels && input.labels[0]) {
2078
+ externalLabel = input.labels[0];
2079
+ labelText = textWithout(externalLabel, input);
2080
+ }
2081
+ }
2082
+
2083
+ var root = this._scope('checkbox');
2084
+ root.setAttribute('data-zs-variant', variant);
2085
+ // mount outside the original <label>: it is removed once its text is moved
2086
+ var mountParent = wrappingLabel && wrappingLabel.parentNode ? wrappingLabel.parentNode : originalParent;
2087
+ var mountBefore = wrappingLabel && wrappingLabel.parentNode ? wrappingLabel : input;
2088
+ mountParent.insertBefore(root, mountBefore);
2089
+
2090
+ // reuse the author's <label> when there is one, so destroy() can put the
2091
+ // original markup back untouched
2092
+ var check = wrappingLabel || doc.createElement('label');
2093
+ addClass(check, 'zs-check');
2094
+ if (!wrappingLabel) check.setAttribute('for', this.id);
2095
+
2096
+ var indicator = el('span', variant === 'switch' ? 'zs-switch-track' : 'zs-check-box', { 'aria-hidden': 'true' });
2097
+ var text = el('span', 'zs-check-label');
2098
+ text.textContent = labelText || '';
2099
+
2100
+ if (wrappingLabel) {
2101
+ Array.prototype.slice.call(check.childNodes).forEach(function (node) {
2102
+ if (node.nodeType === 3) node.parentNode.removeChild(node);
2103
+ });
2104
+ check.insertBefore(indicator, input);
2105
+ if (input.parentNode !== check) check.appendChild(input);
2106
+ check.appendChild(text);
2107
+ } else {
2108
+ check.appendChild(indicator);
2109
+ check.appendChild(input);
2110
+ check.appendChild(text);
2111
+ }
2112
+ root.appendChild(check);
2113
+
2114
+ if (externalLabel) {
2115
+ externalLabel.hidden = true;
2116
+ externalLabel.setAttribute('data-zs-hidden-label', 'true');
2117
+ this._cleanups.push(function () {
2118
+ externalLabel.hidden = false;
2119
+ externalLabel.removeAttribute('data-zs-hidden-label');
2120
+ });
2121
+ }
2122
+
2123
+ var hintText = this.opts.hint || input.getAttribute('data-zidan-hint');
2124
+ if (hintText) {
2125
+ var hint = el('p', 'zs-field__hint', { id: this.id + '-hint' }, hintText);
2126
+ root.appendChild(hint);
2127
+ input.setAttribute('aria-describedby', this.id + '-hint');
2128
+ this._cleanups.push(function () { input.removeAttribute('aria-describedby'); });
2129
+ }
2130
+
2131
+ this.check = check;
2132
+ this._restoreInput = function () {
2133
+ var parent = root.parentNode || originalParent;
2134
+ var anchor = root.parentNode ? root : null;
2135
+ if (wrappingLabel) {
2136
+ if (indicator.parentNode) indicator.parentNode.removeChild(indicator);
2137
+ if (text.parentNode) text.parentNode.removeChild(text);
2138
+ if (labelText) check.appendChild(doc.createTextNode(' ' + labelText));
2139
+ check.classList.remove('zs-check');
2140
+ parent.insertBefore(check, anchor);
2141
+ input.classList.remove('zs-native-input');
2142
+ return;
2143
+ }
2144
+ parent.insertBefore(input, anchor);
2145
+ input.classList.remove('zs-native-input');
2146
+ };
2147
+
2148
+ addClass(input, 'zs-native-input');
2149
+ if (this.opts.indeterminate || input.hasAttribute('data-zidan-indeterminate')) {
2150
+ input.indeterminate = true;
2151
+ }
2152
+
2153
+ this.on(input, 'change', function () {
2154
+ self.update();
2155
+ self.emit('change', { checked: input.checked, value: input.value });
2156
+ self.call('onChange', { checked: input.checked, value: input.value, instance: self });
2157
+ });
2158
+ this._bindValidity();
2159
+
2160
+ input.__zidanField = this;
2161
+ this.update();
2162
+ this.emit('init', { variant: variant });
2163
+ this.call('onInit', { instance: this, variant: variant });
2164
+ ZidanForm._register(this);
2165
+ }
2166
+
2167
+ ZidanCheckbox.prototype = Object.create(ZidanFieldBase.prototype);
2168
+ ZidanCheckbox.prototype.constructor = ZidanCheckbox;
2169
+
2170
+ ZidanCheckbox.prototype._sync = function () {
2171
+ var input = this.el;
2172
+ var checked = !!input.checked;
2173
+ var indeterminate = !!input.indeterminate;
2174
+ this.root.classList.toggle('zs-field--checked', checked);
2175
+ this.root.classList.toggle('zs-field--indeterminate', indeterminate);
2176
+ this.root.classList.toggle('zs-field--disabled', !!input.disabled);
2177
+ this.check.classList.toggle('zs-check--checked', checked);
2178
+ this.check.classList.toggle('zs-check--indeterminate', indeterminate);
2179
+ this.check.classList.toggle('zs-check--disabled', !!input.disabled);
2180
+ };
2181
+
2182
+ ZidanCheckbox.prototype.setIndeterminate = function (on) {
2183
+ this.el.indeterminate = !!on;
2184
+ return this.update();
2185
+ };
2186
+
2187
+ ZidanCheckbox.prototype.isChecked = function () {
2188
+ return !!this.el.checked;
2189
+ };
2190
+
2191
+ ZidanCheckbox.prototype._teardown = function () {
2192
+ if (this._restoreInput) this._restoreInput();
2193
+ };
2194
+
2195
+ /* ---------------- radio group ---------------- */
2196
+
2197
+ function ZidanRadioGroup(target, options) {
2198
+ if (!(this instanceof ZidanRadioGroup)) return new ZidanRadioGroup(target, options);
2199
+ ZidanFieldBase.call(this, target, options, 'radio-group');
2200
+ var variant = pickList(this.opts.variant || target.getAttribute('data-zidan-variant'), RADIO_VARIANTS, 'stacked');
2201
+ this.variant = variant;
2202
+ this.root = target;
2203
+ addClass(target, 'zs-radio-group');
2204
+ target.setAttribute('data-zs-kind', 'radio-group');
2205
+ target.setAttribute('data-zs-variant', variant);
2206
+ this._applyScope(target);
2207
+ if (!target.hasAttribute('role')) target.setAttribute('role', 'radiogroup');
2208
+ this._labels = [];
2209
+ this._enhance();
2210
+ this._bindValidity();
2211
+ var self = this;
2212
+ this.on(target, 'change', function () {
2213
+ self.update();
2214
+ var value = self.getValue();
2215
+ self.emit('change', { value: value });
2216
+ self.call('onChange', { value: value, instance: self });
2217
+ });
2218
+ this.update();
2219
+ target.__zidanField = this;
2220
+ this.emit('init', { variant: variant });
2221
+ ZidanForm._register(this);
2222
+ }
2223
+
2224
+ ZidanRadioGroup.prototype = Object.create(ZidanFieldBase.prototype);
2225
+ ZidanRadioGroup.prototype.constructor = ZidanRadioGroup;
2226
+
2227
+ ZidanRadioGroup.prototype._enhance = function () {
2228
+ var self = this;
2229
+ var nodes = Array.prototype.slice.call(this.el.querySelectorAll('input[type="radio"]'));
2230
+ this.radios = [];
2231
+ nodes.forEach(function (input) {
2232
+ if (input.__zidanRadio) {
2233
+ self.radios.push(input);
2234
+ return;
2235
+ }
2236
+ input.__zidanRadio = true;
2237
+ self.radios.push(input);
2238
+
2239
+ var holder = input.closest ? input.closest('label') : null;
2240
+ var created = false;
2241
+ if (!holder) {
2242
+ holder = doc.createElement('label');
2243
+ holder.className = 'zs-radio';
2244
+ holder.setAttribute('for', input.id || (input.id = uid('zr')));
2245
+ input.parentNode.insertBefore(holder, input);
2246
+ holder.appendChild(input);
2247
+ created = true;
2248
+ } else {
2249
+ holder.classList.add('zs-radio');
2250
+ }
2251
+
2252
+ var textWrapper = holder.querySelector('.zs-radio-label');
2253
+ if (!textWrapper) {
2254
+ textWrapper = el('span', 'zs-radio-label');
2255
+ var labelText = self.opts.labels && self.opts.labels[input.value] !== undefined
2256
+ ? self.opts.labels[input.value]
2257
+ : (input.getAttribute('data-zidan-label') || '');
2258
+ if (labelText) {
2259
+ textWrapper.textContent = labelText;
2260
+ } else if (created) {
2261
+ textWrapper.textContent = input.value;
2262
+ } else {
2263
+ moveTextInto(holder, textWrapper);
2264
+ }
2265
+ if (!textWrapper.textContent.trim()) textWrapper.textContent = input.value;
2266
+ holder.appendChild(textWrapper);
2267
+ }
2268
+
2269
+ var dot = holder.querySelector('.zs-radio-dot');
2270
+ if (!dot) {
2271
+ dot = el('span', 'zs-radio-dot', { 'aria-hidden': 'true' });
2272
+ holder.insertBefore(dot, holder.firstChild);
2273
+ }
2274
+
2275
+ addClass(input, 'zs-native-input');
2276
+
2277
+ self._labels.push({ holder: holder, dot: dot, text: textWrapper, created: created, input: input });
2278
+
2279
+ self._cleanups.push(function () {
2280
+ input.classList.remove('zs-native-input');
2281
+ if (created) {
2282
+ holder.parentNode.insertBefore(input, holder);
2283
+ holder.parentNode.removeChild(holder);
2284
+ } else {
2285
+ holder.classList.remove('zs-radio');
2286
+ if (dot.parentNode) dot.parentNode.removeChild(dot);
2287
+ if (textWrapper.parentNode) textWrapper.parentNode.removeChild(textWrapper);
2288
+ }
2289
+ delete input.__zidanRadio;
2290
+ });
2291
+ });
2292
+ };
2293
+
2294
+ ZidanRadioGroup.prototype.validationTargets = function () {
2295
+ return this.radios || [];
2296
+ };
2297
+
2298
+ ZidanRadioGroup.prototype._sync = function () {
2299
+ var self = this;
2300
+ (this.radios || []).forEach(function (input) {
2301
+ var holder = input.closest ? input.closest('.zs-radio') : null;
2302
+ var checked = !!input.checked;
2303
+ if (holder) {
2304
+ holder.classList.toggle('zs-radio--checked', checked);
2305
+ holder.classList.toggle('zs-radio--disabled', !!input.disabled);
2306
+ }
2307
+ input.classList.toggle('zs-native-input--checked', checked);
2308
+ });
2309
+ this.root.classList.toggle('zs-field--disabled', (this.radios || []).every(function (input) { return input.disabled; }));
2310
+ };
2311
+
2312
+ ZidanRadioGroup.prototype.getValue = function () {
2313
+ for (var i = 0; i < this.radios.length; i += 1) {
2314
+ if (this.radios[i].checked) return this.radios[i].value;
2315
+ }
2316
+ return '';
2317
+ };
2318
+
2319
+ ZidanRadioGroup.prototype.setValue = function (value) {
2320
+ var found = false;
2321
+ this.radios.forEach(function (input) {
2322
+ input.checked = !found && input.value === String(value);
2323
+ if (input.checked) found = true;
2324
+ });
2325
+ return this.update();
2326
+ };
2327
+
2328
+ /* ---------------- file upload ---------------- */
2329
+
2330
+ function formatBytes(bytes) {
2331
+ if (!bytes && bytes !== 0) return '';
2332
+ if (bytes < 1024) return bytes + ' B';
2333
+ if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(bytes < 10240 ? 1 : 0) + ' KB';
2334
+ return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
2335
+ }
2336
+
2337
+ function fileExtension(name) {
2338
+ var match = /\.([a-z0-9]+)$/i.exec(String(name || ''));
2339
+ return match ? '.' + match[1].toLowerCase() : '';
2340
+ }
2341
+
2342
+ function matchesAccept(file, accept) {
2343
+ if (!accept) return true;
2344
+ return String(accept).split(',').some(function (raw) {
2345
+ var token = raw.trim().toLowerCase();
2346
+ if (!token) return false;
2347
+ if (token.indexOf('.') === 0) return fileExtension(file.name) === token;
2348
+ if (token.indexOf('/*') !== -1) return String(file.type).toLowerCase().indexOf(token.split('/')[0] + '/') === 0;
2349
+ return String(file.type).toLowerCase() === token;
2350
+ });
2351
+ }
2352
+
2353
+ function ZidanFileUpload(target, options) {
2354
+ if (!(this instanceof ZidanFileUpload)) return new ZidanFileUpload(target, options);
2355
+ if (!/^file$/i.test(target.type)) {
2356
+ throw new Error('ZidanFileUpload: expected an <input type="file">.');
2357
+ }
2358
+ ZidanFieldBase.call(this, target, options, 'file');
2359
+ var self = this;
2360
+ var input = target;
2361
+ var opts = this.opts;
2362
+
2363
+ var originalParent = input.parentNode;
2364
+ var originalNext = input.nextSibling;
2365
+ var root = this._scope('file');
2366
+ originalParent.insertBefore(root, input);
2367
+
2368
+ var drop = doc.createElement('label');
2369
+ drop.className = 'zs-file-drop';
2370
+ drop.setAttribute('for', this.id);
2371
+
2372
+ var icon = el('span', 'zs-file-icon', { 'aria-hidden': 'true' });
2373
+ var title = el('span', 'zs-file-drop-title', null,
2374
+ opts.title || input.getAttribute('data-zidan-title') || 'Choose a file');
2375
+ var hint = el('span', 'zs-file-drop-hint', null,
2376
+ opts.dropHint || input.getAttribute('data-zidan-drop-hint') ||
2377
+ (input.multiple ? 'or drag files here — multiple allowed' : 'or drag it here'));
2378
+ drop.appendChild(icon);
2379
+ drop.appendChild(title);
2380
+ drop.appendChild(hint);
2381
+ drop.appendChild(input);
2382
+ root.appendChild(drop);
2383
+
2384
+ var list = el('ul', 'zs-file-list');
2385
+ root.appendChild(list);
2386
+
2387
+ var footer = el('div', 'zs-file-meta-row');
2388
+ var status = el('span', 'zs-file-status', { 'role': 'status', 'aria-live': 'polite' });
2389
+ var clearBtn = el('button', 'zs-file-clear', { type: 'button' });
2390
+ clearBtn.textContent = opts.clearLabel || 'Clear all';
2391
+ clearBtn.hidden = true;
2392
+ footer.appendChild(status);
2393
+ footer.appendChild(clearBtn);
2394
+ root.appendChild(footer);
2395
+
2396
+ var acceptHint = opts.accept || input.accept;
2397
+ if (acceptHint) {
2398
+ hint.textContent = hint.textContent + ' · ' + acceptHint;
2399
+ }
2400
+
2401
+ this.drop = drop;
2402
+ this.list = list;
2403
+ this.status = status;
2404
+ this.clearBtn = clearBtn;
2405
+ this._urls = [];
2406
+ this._restoreInput = function () {
2407
+ var parent = root.parentNode || originalParent;
2408
+ parent.insertBefore(input, root.parentNode ? root : null);
2409
+ input.classList.remove('zs-native-input', 'zs-file-input');
2410
+ };
2411
+
2412
+ addClass(input, 'zs-native-input');
2413
+ addClass(input, 'zs-file-input');
2414
+
2415
+ this.on(input, 'change', function () {
2416
+ self._validate();
2417
+ self._render();
2418
+ self.emit('change', { files: self.getFiles() });
2419
+ self.call('onChange', { files: self.getFiles(), instance: self });
2420
+ });
2421
+
2422
+ var dragDepth = 0;
2423
+ ['dragenter', 'dragover'].forEach(function (type) {
2424
+ self.on(drop, type, function (event) {
2425
+ event.preventDefault();
2426
+ if (type === 'dragenter') dragDepth += 1;
2427
+ drop.classList.add('zs-file-drop--over');
2428
+ });
2429
+ });
2430
+ self.on(drop, 'dragleave', function () {
2431
+ dragDepth = Math.max(0, dragDepth - 1);
2432
+ if (!dragDepth) drop.classList.remove('zs-file-drop--over');
2433
+ });
2434
+ self.on(drop, 'drop', function (event) {
2435
+ event.preventDefault();
2436
+ dragDepth = 0;
2437
+ drop.classList.remove('zs-file-drop--over');
2438
+ if (!event.dataTransfer || !event.dataTransfer.files || !event.dataTransfer.files.length) return;
2439
+ var incoming = Array.prototype.slice.call(event.dataTransfer.files);
2440
+ if (!input.multiple) incoming = incoming.slice(0, 1);
2441
+ self._applyFiles(incoming, true);
2442
+ });
2443
+
2444
+ self.on(clearBtn, 'click', function () {
2445
+ input.value = '';
2446
+ self._validate();
2447
+ self._render();
2448
+ self.emit('change', { files: [] });
2449
+ });
2450
+
2451
+ this._bindValidity();
2452
+ input.__zidanField = this;
2453
+ this._render();
2454
+ this.emit('init', {});
2455
+ ZidanForm._register(this);
2456
+ }
2457
+
2458
+ ZidanFileUpload.prototype = Object.create(ZidanFieldBase.prototype);
2459
+ ZidanFileUpload.prototype.constructor = ZidanFileUpload;
2460
+
2461
+ ZidanFileUpload.prototype.getFiles = function () {
2462
+ return this.el.files ? Array.prototype.slice.call(this.el.files) : [];
2463
+ };
2464
+
2465
+ ZidanFileUpload.prototype._applyFiles = function (files, fromDrop) {
2466
+ var dt = new DataTransfer();
2467
+ files.forEach(function (file) { dt.items.add(file); });
2468
+ this.el.files = dt.files;
2469
+ if (fromDrop) {
2470
+ this.el.dispatchEvent(new Event('change', { bubbles: true }));
2471
+ } else {
2472
+ this._validate();
2473
+ this._render();
2474
+ }
2475
+ };
2476
+
2477
+ ZidanFileUpload.prototype._validate = function () {
2478
+ var input = this.el;
2479
+ var opts = this.opts;
2480
+ var files = this.getFiles();
2481
+ var maxFiles = parseInt(opts.maxFiles || input.getAttribute('data-zidan-max-files'), 10);
2482
+ var maxSize = parseInt(opts.maxSize || input.getAttribute('data-zidan-max-size'), 10);
2483
+ if (!(maxSize > 0)) {
2484
+ var sizeMb = opts.maxSizeMB;
2485
+ if (sizeMb === undefined || sizeMb === null || sizeMb === '') {
2486
+ sizeMb = input.getAttribute('data-zidan-max-size-mb');
2487
+ }
2488
+ if (sizeMb !== null && sizeMb !== undefined && sizeMb !== '') {
2489
+ var sizeMbValue = parseFloat(sizeMb);
2490
+ if (sizeMbValue > 0) maxSize = Math.round(sizeMbValue * 1024 * 1024);
2491
+ }
2492
+ }
2493
+ var accept = opts.accept || input.accept;
2494
+ var error = '';
2495
+
2496
+ if (maxFiles && files.length > maxFiles) {
2497
+ error = 'Too many files — ' + maxFiles + ' maximum.';
2498
+ files = files.slice(0, maxFiles);
2499
+ this._applyFiles(files, false);
2500
+ }
2501
+ if (!error && maxSize) {
2502
+ for (var i = 0; i < files.length; i += 1) {
2503
+ if (files[i].size > maxSize) {
2504
+ error = '"' + files[i].name + '" is ' + formatBytes(files[i].size) + ' — limit ' + formatBytes(maxSize) + '.';
2505
+ break;
2506
+ }
2507
+ }
2508
+ }
2509
+ if (!error && accept) {
2510
+ for (var j = 0; j < files.length; j += 1) {
2511
+ if (!matchesAccept(files[j], accept)) {
2512
+ error = '"' + files[j].name + '" is not an allowed type (' + accept + ').';
2513
+ break;
2514
+ }
2515
+ }
2516
+ }
2517
+
2518
+ this.root.classList.toggle('zs-field--invalid', !!error);
2519
+ if (error) this.el.setAttribute('aria-invalid', 'true');
2520
+ else if (this.validation !== 'invalid') this.el.removeAttribute('aria-invalid');
2521
+ this.drop.classList.toggle('zs-file-drop--invalid', !!error);
2522
+ this.status.textContent = error || '';
2523
+ this.status.classList.toggle('zs-file-status--error', !!error);
2524
+ this.emit('validation', { state: error ? 'invalid' : this.validation, message: error });
2525
+ return !error;
2526
+ };
2527
+
2528
+ ZidanFileUpload.prototype._sync = function () {
2529
+ this._render();
2530
+ };
2531
+
2532
+ ZidanFileUpload.prototype._render = function () {
2533
+ var self = this;
2534
+ var files = this.getFiles();
2535
+ // detach first, then revoke a tick later: revoking a blob that a live
2536
+ // <img> still points at (or that is mid-decode) makes the browser raise a
2537
+ // failed-resource error
2538
+ this.list.textContent = '';
2539
+ this._revokeLater(this._urls);
2540
+ this._urls = [];
2541
+ this.list.hidden = files.length === 0;
2542
+ this.clearBtn.hidden = files.length === 0;
2543
+ this.root.classList.toggle('zs-field--filled', files.length > 0);
2544
+ if (!this.status.textContent) {
2545
+ this.status.textContent = files.length
2546
+ ? files.length + (files.length === 1 ? ' file selected' : ' files selected') + ' · ' + formatBytes(files.reduce(function (total, file) { return total + file.size; }, 0))
2547
+ : '';
2548
+ }
2549
+
2550
+ files.forEach(function (file, index) {
2551
+ var item = el('li', 'zs-file-item');
2552
+ var thumb = el('span', 'zs-file-thumb');
2553
+ if (/^image\//.test(file.type)) {
2554
+ var url = URL.createObjectURL(file);
2555
+ self._urls.push(url);
2556
+ var img = doc.createElement('img');
2557
+ img.src = url;
2558
+ img.alt = '';
2559
+ thumb.appendChild(img);
2560
+ } else {
2561
+ thumb.textContent = (fileExtension(file.name) || 'file').replace('.', '').slice(0, 4).toUpperCase();
2562
+ }
2563
+ var meta = el('span', 'zs-file-info');
2564
+ var name = el('span', 'zs-file-name', null, file.name);
2565
+ var size = el('span', 'zs-file-size', null, formatBytes(file.size) + (file.type ? ' · ' + file.type : ''));
2566
+ meta.appendChild(name);
2567
+ meta.appendChild(size);
2568
+
2569
+ var remove = el('button', 'zs-file-remove', {
2570
+ type: 'button',
2571
+ 'aria-label': 'Remove ' + file.name
2572
+ });
2573
+ remove.textContent = '\u00d7';
2574
+ self.on(remove, 'click', function () {
2575
+ var next = self.getFiles().filter(function (candidate, position) { return position !== index; });
2576
+ self._applyFiles(next, false);
2577
+ self.emit('remove', { file: file });
2578
+ self.call('onRemove', { file: file, instance: self });
2579
+ });
2580
+
2581
+ item.appendChild(thumb);
2582
+ item.appendChild(meta);
2583
+ item.appendChild(remove);
2584
+ self.list.appendChild(item);
2585
+ });
2586
+ };
2587
+
2588
+ ZidanFileUpload.prototype.clear = function () {
2589
+ this.el.value = '';
2590
+ this._validate();
2591
+ this._render();
2592
+ return this;
2593
+ };
2594
+
2595
+ ZidanFileUpload.prototype._revokeLater = function (urls) {
2596
+ if (!urls || !urls.length) return;
2597
+ global.setTimeout(function () {
2598
+ urls.forEach(function (url) {
2599
+ try { URL.revokeObjectURL(url); } catch (err) { /* already gone */ }
2600
+ });
2601
+ }, 800);
2602
+ };
2603
+
2604
+ ZidanFileUpload.prototype._teardown = function () {
2605
+ this._revokeLater(this._urls);
2606
+ this._urls = [];
2607
+ if (this._restoreInput) this._restoreInput();
2608
+ };
2609
+
2610
+ /* ---------------- text inputs & textarea ---------------- */
2611
+
2612
+ var TEXT_TYPES = ['text', 'email', 'password', 'number', 'tel', 'url', 'search', 'date', 'time', 'datetime-local', 'month', 'week', 'range', 'color'];
2613
+
2614
+ function ZidanTextField(target, options) {
2615
+ if (!(this instanceof ZidanTextField)) return new ZidanTextField(target, options);
2616
+ var isTextarea = target.tagName === 'TEXTAREA';
2617
+ if (!isTextarea && !/^(INPUT)$/i.test(target.tagName)) {
2618
+ throw new Error('ZidanTextField: expected an <input> or <textarea>.');
2619
+ }
2620
+ if (!isTextarea && TEXT_TYPES.indexOf(String(target.type).toLowerCase()) === -1) {
2621
+ throw new Error('ZidanTextField: unsupported input type "' + target.type + '".');
2622
+ }
2623
+ ZidanFieldBase.call(this, target, options, isTextarea ? 'textarea' : 'input');
2624
+ var self = this;
2625
+ var input = target;
2626
+ var opts = this.opts;
2627
+ var type = isTextarea ? 'textarea' : String(input.type).toLowerCase();
2628
+
2629
+ var originalParent = input.parentNode;
2630
+ var originalNext = input.nextSibling;
2631
+ var externalLabel = input.labels && input.labels[0] ? input.labels[0] : null;
2632
+ if (externalLabel && externalLabel.closest && externalLabel.closest('.zs-field')) externalLabel = null;
2633
+ var labelText = opts.label || input.getAttribute('data-zidan-label') ||
2634
+ (externalLabel ? textWithout(externalLabel, input) : '') || '';
2635
+ var layout = this.layout || 'stacked';
2636
+ var floating = /^(floating|outlined)$/.test(layout);
2637
+
2638
+ var root = this._scope(isTextarea ? 'textarea' : 'input');
2639
+ root.setAttribute('data-zs-type', type);
2640
+ originalParent.insertBefore(root, input);
2641
+
2642
+ var label = null;
2643
+ if (labelText) {
2644
+ label = el('label', 'zs-field__label', { for: this.id });
2645
+ label.textContent = labelText;
2646
+ if (!floating) root.appendChild(label);
2647
+ }
2648
+ if (externalLabel && labelText) {
2649
+ externalLabel.hidden = true;
2650
+ externalLabel.setAttribute('data-zs-hidden-label', 'true');
2651
+ this._cleanups.push(function () {
2652
+ externalLabel.hidden = false;
2653
+ externalLabel.removeAttribute('data-zs-hidden-label');
2654
+ });
2655
+ }
2656
+
2657
+ var shell = el('div', 'zs-input-shell');
2658
+ root.appendChild(shell);
2659
+ if (floating && label) shell.appendChild(label);
2660
+
2661
+ var prefixText = opts.prefix || input.getAttribute('data-zidan-prefix');
2662
+ if (prefixText) {
2663
+ shell.appendChild(el('span', 'zs-input-prefix', { 'aria-hidden': 'true' }, prefixText));
2664
+ }
2665
+
2666
+ shell.appendChild(input);
2667
+
2668
+ var suffixText = opts.suffix || input.getAttribute('data-zidan-suffix');
2669
+ if (suffixText) {
2670
+ shell.appendChild(el('span', 'zs-input-suffix', { 'aria-hidden': 'true' }, suffixText));
2671
+ }
2672
+ if (prefixText || suffixText) addClass(root, 'zs-field--adorned');
2673
+
2674
+ var reveal = null;
2675
+ if (type === 'password' && (opts.reveal || input.hasAttribute('data-zidan-reveal'))) {
2676
+ reveal = el('button', 'zs-input-action zs-input-reveal', {
2677
+ type: 'button',
2678
+ 'aria-label': opts.showPasswordLabel || 'Show password',
2679
+ 'aria-pressed': 'false'
2680
+ });
2681
+ reveal.textContent = opts.showPasswordLabel || 'Show';
2682
+ shell.appendChild(reveal);
2683
+ this.on(reveal, 'click', function () {
2684
+ var visible = input.type === 'text';
2685
+ input.type = visible ? 'password' : 'text';
2686
+ reveal.setAttribute('aria-pressed', String(!visible));
2687
+ reveal.textContent = !visible ? (opts.hidePasswordLabel || 'Hide') : (opts.showPasswordLabel || 'Show');
2688
+ reveal.setAttribute('aria-label', !visible ? (opts.hidePasswordLabel || 'Hide password') : (opts.showPasswordLabel || 'Show password'));
2689
+ self.emit('reveal', { visible: !visible });
2690
+ });
2691
+ }
2692
+
2693
+ var clearable = opts.clearable;
2694
+ if (clearable === undefined) {
2695
+ clearable = input.hasAttribute('data-zidan-clear') || type === 'search';
2696
+ }
2697
+ var clear = null;
2698
+ if (clearable) {
2699
+ clear = el('button', 'zs-input-action zs-input-clear', {
2700
+ type: 'button',
2701
+ 'aria-label': opts.clearLabel || 'Clear field',
2702
+ hidden: ''
2703
+ });
2704
+ clear.textContent = '\u00d7';
2705
+ shell.appendChild(clear);
2706
+ this.on(clear, 'click', function () {
2707
+ input.value = '';
2708
+ input.dispatchEvent(new Event('input', { bubbles: true }));
2709
+ input.focus();
2710
+ self.update();
2711
+ self.emit('clear', {});
2712
+ });
2713
+ }
2714
+
2715
+ var hintText = opts.hint || input.getAttribute('data-zidan-hint');
2716
+ var counterMax = parseInt(opts.counter, 10) ||
2717
+ parseInt(input.getAttribute('data-zidan-counter'), 10) ||
2718
+ parseInt(input.getAttribute('maxlength'), 10) || 0;
2719
+ var meta = null;
2720
+ var counter = null;
2721
+ if (hintText || counterMax) {
2722
+ meta = el('div', 'zs-field__meta');
2723
+ if (hintText) meta.appendChild(el('p', 'zs-field__hint', { id: this.id + '-hint' }, hintText));
2724
+ else meta.appendChild(el('span', '', null, ''));
2725
+ if (counterMax) {
2726
+ counter = el('span', 'zs-counter', { 'aria-live': 'polite' });
2727
+ meta.appendChild(counter);
2728
+ }
2729
+ root.appendChild(meta);
2730
+ if (hintText) {
2731
+ input.setAttribute('aria-describedby', this.id + '-hint');
2732
+ this._cleanups.push(function () { input.removeAttribute('aria-describedby'); });
2733
+ }
2734
+ }
2735
+
2736
+ this.label = label;
2737
+ this.shell = shell;
2738
+ this.clear = clear;
2739
+ this.counter = counter;
2740
+ this.counterMax = counterMax;
2741
+ this._restoreInput = function () {
2742
+ var parent = root.parentNode || originalParent;
2743
+ parent.insertBefore(input, root.parentNode ? root : null);
2744
+ input.classList.remove('zs-input-native');
2745
+ };
2746
+
2747
+ addClass(input, 'zs-input-native');
2748
+ addClass(root, 'zs-field--' + layout);
2749
+
2750
+ var outputSelector = opts.output || input.getAttribute('data-zidan-output');
2751
+ if (type === 'range' && outputSelector) {
2752
+ var out = doc.querySelector(outputSelector);
2753
+ if (out) {
2754
+ var syncOut = function () {
2755
+ out.textContent = input.value;
2756
+ out.value = input.value;
2757
+ };
2758
+ syncOut();
2759
+ this.on(input, 'input', syncOut);
2760
+ }
2761
+ }
2762
+
2763
+ this.on(input, 'input', function () { self.update(); });
2764
+ this.on(input, 'change', function () {
2765
+ self.update();
2766
+ self.emit('change', { value: input.value });
2767
+ self.call('onChange', { value: input.value, instance: self });
2768
+ });
2769
+ this.on(input, 'focus', function () { root.classList.add('zs-field--focused'); });
2770
+ this.on(input, 'blur', function () { root.classList.remove('zs-field--focused'); });
2771
+
2772
+ this._bindValidity();
2773
+ input.__zidanField = this;
2774
+ this.update();
2775
+ this.emit('init', { type: type });
2776
+ this.call('onInit', { instance: this, type: type });
2777
+ ZidanForm._register(this);
2778
+ }
2779
+
2780
+ ZidanTextField.prototype = Object.create(ZidanFieldBase.prototype);
2781
+ ZidanTextField.prototype.constructor = ZidanTextField;
2782
+
2783
+ ZidanTextField.prototype._sync = function () {
2784
+ var input = this.el;
2785
+ var value = input.value === undefined ? '' : String(input.value);
2786
+ var hasValue = value.length > 0 || (input.type === 'range' && value !== '');
2787
+ this.root.classList.toggle('zs-field--filled', hasValue);
2788
+ this.root.classList.toggle('zs-field--disabled', !!input.disabled);
2789
+ this.root.classList.toggle('zs-field--readonly', !!input.readOnly);
2790
+ if (this.clear) this.clear.hidden = !hasValue || !!input.disabled || !!input.readOnly;
2791
+ if (this.counter) {
2792
+ var length = value.length;
2793
+ this.counter.textContent = length + ' / ' + this.counterMax;
2794
+ this.counter.classList.toggle('zs-counter--limit', length >= this.counterMax);
2795
+ }
2796
+ };
2797
+
2798
+ ZidanTextField.prototype.getValue = function () {
2799
+ return this.el.value;
2800
+ };
2801
+
2802
+ ZidanTextField.prototype.setValue = function (value) {
2803
+ this.el.value = value === null || value === undefined ? '' : String(value);
2804
+ return this.update();
2805
+ };
2806
+
2807
+ ZidanTextField.prototype._teardown = function () {
2808
+ if (this._restoreInput) this._restoreInput();
2809
+ };
2810
+
2811
+ /* ---------------- factory, registry, auto-init ---------------- */
2812
+
2813
+ function fieldKindFor(node) {
2814
+ if (!isElement(node)) return null;
2815
+ var flag = String(node.getAttribute('data-zidan') || '').toLowerCase();
2816
+ if (FIELD_KINDS.indexOf(flag) !== -1) return flag;
2817
+ if (node.hasAttribute('data-zidan-radio-group')) return 'radio-group';
2818
+ if (node.hasAttribute('data-zidan-radio')) return 'radio';
2819
+ if (node.hasAttribute('data-zidan-checkbox') || node.hasAttribute('data-zidan-switch')) return 'checkbox';
2820
+ if (node.hasAttribute('data-zidan-file')) return 'file';
2821
+ if (node.hasAttribute('data-zidan-textarea')) return 'textarea';
2822
+ if (node.hasAttribute('data-zidan-input')) return 'input';
2823
+ var type = String(node.type || '').toLowerCase();
2824
+ if (type === 'checkbox') return 'checkbox';
2825
+ if (type === 'radio') return 'radio';
2826
+ if (type === 'file') return 'file';
2827
+ return null;
2828
+ }
2829
+
2830
+ function createField(node, kind, options) {
2831
+ var opts = options || {};
2832
+ if (node.__zidanField && !opts.force) return node.__zidanField;
2833
+ switch (kind) {
2834
+ case 'checkbox': return new ZidanCheckbox(node, opts);
2835
+ case 'radio': return new ZidanRadioGroup(node, opts);
2836
+ case 'radio-group': return new ZidanRadioGroup(node, opts);
2837
+ case 'file': return new ZidanFileUpload(node, opts);
2838
+ case 'input':
2839
+ case 'textarea':
2840
+ return new ZidanTextField(node, opts);
2841
+ default: return null;
2842
+ }
2843
+ }
2844
+
2845
+ function zidanField(target, options) {
2846
+ var nodes = [];
2847
+ if (typeof target === 'string') {
2848
+ nodes = Array.prototype.slice.call(doc.querySelectorAll(target));
2849
+ } else if (isElement(target)) {
2850
+ nodes = [target];
2851
+ } else if (target && typeof target.length === 'number') {
2852
+ nodes = Array.prototype.slice.call(target);
2853
+ }
2854
+ var created = [];
2855
+ nodes.forEach(function (node) {
2856
+ if (node.__zidanField) return;
2857
+ var kind = fieldKindFor(node);
2858
+ // zidanField() accepts a plain input/textarea too, so JS-only options
2859
+ // (output, counter, clearable, …) work without a data attribute
2860
+ if (!kind && (node.tagName === 'TEXTAREA' ||
2861
+ (node.tagName === 'INPUT' && TEXT_TYPES.indexOf(String(node.type).toLowerCase()) !== -1))) {
2862
+ kind = node.tagName === 'TEXTAREA' ? 'textarea' : 'input';
2863
+ }
2864
+ if (!kind) return;
2865
+ if (kind === 'radio' && !node.hasAttribute('data-zidan-radio')) {
2866
+ kind = 'radio-group';
2867
+ }
2868
+ var instance = createField(node, kind, options || {});
2869
+ if (instance) created.push(instance);
2870
+ });
2871
+ return created.length === 1 ? created[0] : created;
2872
+ }
2873
+
2874
+ function initZidanForms(container, options) {
2875
+ var scope = container || doc;
2876
+ if (!scope || !scope.querySelectorAll) return [];
2877
+ var nodes = Array.prototype.slice.call(scope.querySelectorAll(FIELDS_SELECTOR));
2878
+ if (isElement(scope) && scope.matches && scope.matches(FIELDS_SELECTOR)) nodes.unshift(scope);
2879
+ var instances = [];
2880
+ nodes.forEach(function (node) {
2881
+ if (node.__zidanField) return;
2882
+ var kind = fieldKindFor(node);
2883
+ if (!kind) return;
2884
+ if (kind === 'radio') kind = 'radio-group';
2885
+ var instance = createField(node, kind, options || {});
2886
+ if (instance) instances.push(instance);
2887
+ });
2888
+ return instances;
2889
+ }
2890
+
2891
+ var ZidanForm = {
2892
+ version: VERSION,
2893
+ __zidanFormGuard: VERSION,
2894
+ // live registries: pushing a name here makes it a valid theme/layout
2895
+ themes: THEMES,
2896
+ frameworks: FRAMEWORKS.slice(),
2897
+ fieldLayouts: FIELD_LAYOUTS,
2898
+ fields: [],
2899
+ _register: function (field) {
2900
+ if (ZidanForm.fields.indexOf(field) === -1) ZidanForm.fields.push(field);
2901
+ },
2902
+ _unregister: function (field) {
2903
+ var index = ZidanForm.fields.indexOf(field);
2904
+ if (index !== -1) ZidanForm.fields.splice(index, 1);
2905
+ },
2906
+ get: function (target) {
2907
+ var node = typeof target === 'string' ? doc.querySelector(target) : target;
2908
+ return isElement(node) ? node.__zidanField || null : null;
2909
+ },
2910
+ init: function (scope, options) {
2911
+ return initZidanForms(scope || doc, options || {});
2912
+ },
2913
+ field: zidanField,
2914
+ refresh: function (scope) {
2915
+ initZidanForms(scope || doc, {});
2916
+ ZidanForm.fields.slice().forEach(function (field) { field.update(); });
2917
+ return ZidanForm.fields.slice();
2918
+ },
2919
+ destroyAll: function () {
2920
+ ZidanForm.fields.slice().forEach(function (field) { field.destroy(); });
2921
+ ZidanForm.fields = [];
2922
+ if (ZidanSelect && ZidanSelect.destroyAll) ZidanSelect.destroyAll();
2923
+ return ZidanForm;
2924
+ },
2925
+ /* keep a subtree in sync when it is re-rendered by a framework */
2926
+ observe: function (scope, options) {
2927
+ var root = scope || doc.body;
2928
+ if (!root || !global.MutationObserver) return null;
2929
+ var observer = new global.MutationObserver(function (records) {
2930
+ records.forEach(function (record) {
2931
+ Array.prototype.slice.call(record.addedNodes).forEach(function (node) {
2932
+ if (!isElement(node)) return;
2933
+ if (fieldKindFor(node)) createField(node, fieldKindFor(node) === 'radio' ? 'radio-group' : fieldKindFor(node), options || {});
2934
+ if (node.querySelectorAll) initZidanForms(node, options || {});
2935
+ });
2936
+ });
2937
+ // drop instances whose control left the document
2938
+ ZidanForm.fields.slice().forEach(function (field) {
2939
+ if (!field.el.isConnected) field.destroy();
2940
+ });
2941
+ ZidanSelect.instances.slice().forEach(function (instance) {
2942
+ if (!instance.el.isConnected) instance.destroy();
2943
+ });
2944
+ });
2945
+ observer.observe(root, { childList: true, subtree: true });
2946
+ return observer;
2947
+ }
2948
+ };
2949
+
2950
+ ZidanForm.api = null;
2951
+
2952
+ /* static helpers */
2953
+ ZidanSelect.version = VERSION;
2954
+ ZidanSelect.__zidanSelectGuard = VERSION;
2955
+ ZidanSelect.layouts = LAYOUTS.slice();
2956
+ ZidanSelect.frameworks = FRAMEWORKS.slice();
2957
+ ZidanSelect.scrollbars = SCROLLBARS.slice();
2958
+ ZidanSelect.defaults = DEFAULTS;
2959
+ ZidanSelect.get = function (target) {
2960
+ var element = typeof target === 'string' ? doc.querySelector(target) : target;
2961
+ if (!isElement(element)) return null;
2962
+ return element.__zidanSelect || null;
2963
+ };
2964
+ ZidanSelect.instances = [];
2965
+ ZidanSelect.destroyAll = function () {
2966
+ ZidanSelect.instances.slice().forEach(function (instance) { instance.destroy(); });
2967
+ ZidanSelect.instances = [];
2968
+ };
2969
+
2970
+ /* ------------------------------------------------------------------ *
2971
+ * Factory + auto-init
2972
+ * ------------------------------------------------------------------ */
2973
+
2974
+ function zidanSelect(target, options) {
2975
+ var nodes = [];
2976
+ if (typeof target === 'string') {
2977
+ nodes = Array.prototype.slice.call(doc.querySelectorAll(target));
2978
+ } else if (target && typeof target.length === 'number' && !isElement(target) && target !== global) {
2979
+ nodes = Array.prototype.slice.call(target);
2980
+ } else if (isElement(target)) {
2981
+ nodes = [target];
2982
+ }
2983
+
2984
+ var instances = nodes.map(function (node) {
2985
+ var instance = new ZidanSelect(node, options || {});
2986
+ ZidanSelect.instances.push(instance);
2987
+ return instance;
2988
+ });
2989
+
2990
+ return instances.length === 1 ? instances[0] : instances;
2991
+ }
2992
+
2993
+ function initZidanSelects(container, options) {
2994
+ var scope = container || doc;
2995
+ if (!scope || !scope.querySelectorAll) return [];
2996
+ var nodes = Array.prototype.slice.call(scope.querySelectorAll('[data-zidan-select]'));
2997
+ if (isElement(scope) && scope.hasAttribute('data-zidan-select')) nodes.unshift(scope);
2998
+ return nodes
2999
+ .filter(function (node) { return !node.__zidanSelect; })
3000
+ .map(function (node) {
3001
+ ZidanSelect.instances.push(new ZidanSelect(node, options || {}));
3002
+ return node.__zidanSelect;
3003
+ });
3004
+ }
3005
+
3006
+ function autoInit() {
3007
+ if (!doc) return;
3008
+ var config = global.ZIDAN_SELECT_CONFIG || {};
3009
+ if (config.autoInit === false) return;
3010
+ if (global.ZidanSelect && global.ZidanSelect.autoInit === false) return;
3011
+ if (doc.documentElement.getAttribute('data-zidan-auto-init') === 'false') return;
3012
+ if (config.selector) {
3013
+ Array.prototype.slice.call(doc.querySelectorAll(config.selector)).forEach(function (node) {
3014
+ if (node.__zidanSelect) return;
3015
+ ZidanSelect.instances.push(new ZidanSelect(node, config.options || {}));
3016
+ });
3017
+ return;
3018
+ }
3019
+ initZidanSelects(doc, config.options || {});
3020
+ initZidanForms(doc, config.fields || {});
3021
+ }
3022
+
3023
+ if (doc) {
3024
+ if (doc.readyState === 'loading') {
3025
+ doc.addEventListener('DOMContentLoaded', autoInit);
3026
+ } else {
3027
+ setTimeout(autoInit, 0);
3028
+ }
3029
+ }
3030
+
3031
+ var api = {
3032
+ ZidanForm: ZidanForm,
3033
+ ZidanSelect: ZidanSelect,
3034
+ ZidanCheckbox: ZidanCheckbox,
3035
+ ZidanRadioGroup: ZidanRadioGroup,
3036
+ ZidanFileUpload: ZidanFileUpload,
3037
+ ZidanTextField: ZidanTextField,
3038
+ zidanSelect: zidanSelect,
3039
+ zidanField: zidanField,
3040
+ initZidanSelects: initZidanSelects,
3041
+ initZidanForms: initZidanForms
3042
+ };
3043
+
3044
+ ZidanForm.api = api;
3045
+
3046
+ return api;
3047
+ });