zidan-select 2.2.4 → 2.3.1

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.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * ZidanForm v2.2.4
2
+ * ZidanForm v2.3.1
3
3
  * Zero-dependency form enhancement library: select / combobox / tags,
4
4
  * checkboxes, switches, radio groups, file upload with drag & drop and
5
5
  * upload progress, text / number / phone / date / range inputs and textarea.
@@ -32,7 +32,7 @@
32
32
  })(typeof window !== 'undefined' ? window : this, function (global) {
33
33
  'use strict';
34
34
 
35
- var VERSION = '2.2.4';
35
+ var VERSION = '2.3.1';
36
36
 
37
37
  // Loading the file twice (classic script + module wrapper, or two bundles)
38
38
  // must not replace the classes and orphan the live instances.
@@ -97,6 +97,24 @@
97
97
  return Array.isArray(value) ? value.slice() : [value];
98
98
  }
99
99
 
100
+ function isThenable(value) {
101
+ return !!(value && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function');
102
+ }
103
+
104
+ /* true when the element renders right-to-left, following the nearest dir attribute */
105
+ function isRtl(element) {
106
+ if (!element) return false;
107
+ var host = element.closest ? element.closest('[dir]') : null;
108
+ var dir = host ? host.getAttribute('dir') : '';
109
+ if (!dir && doc && doc.documentElement) dir = doc.documentElement.getAttribute('dir') || '';
110
+ if (dir) return String(dir).toLowerCase() === 'rtl';
111
+ try {
112
+ return !!(global.getComputedStyle && global.getComputedStyle(element).direction === 'rtl');
113
+ } catch (err) {
114
+ return false;
115
+ }
116
+ }
117
+
100
118
  function isElement(value) {
101
119
  return !!(value && typeof value === 'object' && value.nodeType === 1);
102
120
  }
@@ -292,9 +310,9 @@
292
310
  }
293
311
 
294
312
  function registerIcon(name, markup) {
295
- if (!name || typeof markup !== 'string') return ZidanSelect;
296
- ICON_REGISTRY[String(name)] = markup;
297
- return ZidanSelect;
313
+ if (typeof ZidanSelect !== 'undefined' && (!name || typeof markup !== 'string')) return ZidanSelect;
314
+ if (name && typeof markup === 'string') ICON_REGISTRY[String(name)] = markup;
315
+ return typeof ZidanSelect !== 'undefined' ? ZidanSelect : ZidanForm;
298
316
  }
299
317
 
300
318
  /* ---------------- field options (JS options + data-* attributes) ---------------- */
@@ -352,6 +370,7 @@
352
370
  fileType: 'This file type is not allowed.',
353
371
  fileSize: 'This file is too large.',
354
372
  fileCount: 'Too many files.',
373
+ pending: 'Checking…',
355
374
  generic: 'Please check this field.'
356
375
  };
357
376
 
@@ -379,6 +398,20 @@
379
398
  return fillTemplate(map[key] || FIELD_MESSAGES[key] || map.generic, vars);
380
399
  }
381
400
 
401
+ var NATIVE_VALIDITY_FLAGS = ['valueMissing', 'typeMismatch', 'patternMismatch', 'rangeUnderflow',
402
+ 'rangeOverflow', 'stepMismatch', 'tooShort', 'tooLong', 'badInput', 'fileMissing'];
403
+
404
+ /* customError is the library mirroring its own message onto the input, so re-reading it
405
+ would turn a pending/custom check into a phantom native constraint failure */
406
+ function hasNativeValidityError(input) {
407
+ var v = input && input.validity;
408
+ if (!v) return false;
409
+ for (var i = 0; i < NATIVE_VALIDITY_FLAGS.length; i += 1) {
410
+ if (v[NATIVE_VALIDITY_FLAGS[i]]) return true;
411
+ }
412
+ return false;
413
+ }
414
+
382
415
  /* @zidan-build:phone */
383
416
  /* ---------------- phone formatting ---------------- */
384
417
 
@@ -549,6 +582,24 @@
549
582
  return list.indexOf(candidate) === -1 ? fallback : candidate;
550
583
  }
551
584
 
585
+ /* rangeTicks: JS array, JSON array, comma list or a tick count */
586
+ function parseRangeTicks(value) {
587
+ if (Array.isArray(value)) return value.slice();
588
+ if (typeof value === 'string') {
589
+ var raw = value.trim();
590
+ if (raw.charAt(0) === '[') {
591
+ try {
592
+ var parsed = JSON.parse(raw);
593
+ if (Array.isArray(parsed)) return parsed;
594
+ } catch (err) { /* fall back to the tick count */ }
595
+ } else if (raw.indexOf(',') !== -1) {
596
+ return raw.split(',').map(function (part) { return Number(part.trim()); })
597
+ .filter(function (number) { return isFinite(number); });
598
+ }
599
+ }
600
+ return value;
601
+ }
602
+
552
603
  /* theme/framework/layout resolution shared by every field and the select */
553
604
  function resolveScope(node, options) {
554
605
  var opts = options || {};
@@ -616,6 +667,10 @@
616
667
  minChars: 0,
617
668
  allowFreeText: false,
618
669
  searchValues: true,
670
+ fetchPageSize: 0, // >0 enables paged fetchOptions({items, hasMore})
671
+ autoLoadMore: true,
672
+ cacheResults: true,
673
+ loadMoreText: 'Load more',
619
674
  /* tags */
620
675
  maxTags: Infinity,
621
676
  minTagLength: 1,
@@ -644,6 +699,7 @@
644
699
  onClose: null,
645
700
  onTagAdd: null,
646
701
  onTagRemove: null,
702
+ onLoadMore: null,
647
703
  onError: null
648
704
  };
649
705
 
@@ -684,6 +740,14 @@
684
740
  this.rendered = [];
685
741
  this.listeners = new Map();
686
742
  this.asyncController = null;
743
+ this.asyncItems = null;
744
+ this.asyncQuery = '';
745
+ this.asyncPage = 0;
746
+ this.hasMore = false;
747
+ this.fetchingMore = false;
748
+ this.loadMoreError = null;
749
+ this._fetchCache = Object.create(null);
750
+ this._cacheKeys = [];
687
751
  this.timer = null;
688
752
  this.savedInputText = '';
689
753
  this.disabled_ = !!this.opts.disabled;
@@ -760,6 +824,10 @@
760
824
  merged.validation = pick('validation', d.zidanValidation || null);
761
825
  merged.options = pick('options', null);
762
826
  merged.suggestions = pick('suggestions', null);
827
+ merged.fetchPageSize = pick('fetchPageSize', d.zidanFetchPageSize ? parseInt(d.zidanFetchPageSize, 10) || 0 : DEFAULTS.fetchPageSize);
828
+ merged.autoLoadMore = pick('autoLoadMore', readBoolAttr(d.zidanAutoLoadMore, DEFAULTS.autoLoadMore));
829
+ merged.cacheResults = pick('cacheResults', readBoolAttr(d.zidanCacheResults, DEFAULTS.cacheResults));
830
+ merged.loadMoreText = pick('loadMoreText', d.zidanLoadMoreText || DEFAULTS.loadMoreText);
763
831
 
764
832
  // carry over every explicitly-passed option (callbacks, custom classes, ...)
765
833
  Object.keys(options).forEach(function (key) {
@@ -906,6 +974,7 @@
906
974
  rootEl.setAttribute('data-zs-framework', this.framework);
907
975
  rootEl.setAttribute('data-zs-mode', this.mode);
908
976
  rootEl.setAttribute('data-zs-scrollbar', opts.scrollbar || 'default');
977
+ if (isRtl(this.el)) rootEl.setAttribute('dir', 'rtl');
909
978
  rootEl.classList.add('zs-root--' + this.mode);
910
979
  if (this.mode === 'tags') rootEl.classList.add('zs-root--multiple');
911
980
  if (opts.multiple && this.mode === 'select') rootEl.classList.add('zs-root--multiple');
@@ -934,6 +1003,9 @@
934
1003
  input.setAttribute('aria-controls', this.id + '-listbox');
935
1004
  input.setAttribute('aria-autocomplete', (opts.searchable || this.mode !== 'select') ? 'list' : 'none');
936
1005
  input.setAttribute('aria-haspopup', 'listbox');
1006
+ /* a plain select is not type-to-filter: keep its text field read-only so
1007
+ typing cannot filter or hide the options */
1008
+ if (this.mode === 'select' && !opts.searchable) input.readOnly = true;
937
1009
  if (opts.ariaLabel || opts.label) input.setAttribute('aria-label', opts.ariaLabel || opts.label);
938
1010
  if (opts.disabled) input.disabled = true;
939
1011
  this._applyCustomClass(input, 'input');
@@ -943,6 +1015,16 @@
943
1015
  labelEl = el('label', 'zs-label', { for: input.id });
944
1016
  labelEl.textContent = opts.label;
945
1017
  if (this.layout !== 'floating-label') rootEl.classList.add('zs-root--has-static-label');
1018
+
1019
+ // Hide the author's <label>: this label replaces it, and showing both
1020
+ // would print the same text twice above the control.
1021
+ var authorLabel = this.el.labels && this.el.labels[0] ? this.el.labels[0] : null;
1022
+ if (authorLabel && authorLabel.closest && authorLabel.closest('.zs-root')) authorLabel = null;
1023
+ this._authorLabel = authorLabel || null;
1024
+ if (authorLabel) {
1025
+ authorLabel.hidden = true;
1026
+ authorLabel.setAttribute('data-zs-hidden-label', 'true');
1027
+ }
946
1028
  }
947
1029
 
948
1030
  var clearBtn = el('button', 'zs-clear', {
@@ -971,9 +1053,7 @@
971
1053
  var dropdown = el('div', 'zs-dropdown');
972
1054
  dropdown.id = this.id + '-listbox';
973
1055
  dropdown.setAttribute('role', 'listbox');
974
- if (this.mode !== 'tags') {
975
- dropdown.setAttribute('aria-multiselectable', String(!!(opts.multiple || this.mode === 'tags')));
976
- }
1056
+ dropdown.setAttribute('aria-multiselectable', String(!!(opts.multiple || this.mode === 'tags')));
977
1057
  this._applyCustomClass(dropdown, 'dropdown');
978
1058
 
979
1059
  var live = el('div', 'zs-live', { 'aria-live': 'polite', 'aria-atomic': 'true' });
@@ -1051,6 +1131,22 @@
1051
1131
  };
1052
1132
  this.form.addEventListener('reset', this.onFormReset);
1053
1133
  }
1134
+
1135
+ /* `required` is a JS-only option as well as a native attribute. A native
1136
+ select can carry it directly; a mount-mode div needs a submit guard. */
1137
+ if (opts.required && this.native && this.native.tagName === 'SELECT' && !this.native.required) {
1138
+ this.native.required = true;
1139
+ this._nativeRequiredAdded = true;
1140
+ } else if (opts.required && !this.native && this.form) {
1141
+ this.onFormSubmit = function (event) {
1142
+ if (self.value_.length) return;
1143
+ event.preventDefault();
1144
+ self.setValidation('invalid');
1145
+ if (self.input && self.input.focus) self.input.focus();
1146
+ self.announce('Please select an option.');
1147
+ };
1148
+ this.form.addEventListener('submit', this.onFormSubmit);
1149
+ }
1054
1150
  return this.syncEl;
1055
1151
  };
1056
1152
 
@@ -1151,7 +1247,9 @@
1151
1247
 
1152
1248
  if (!this.opts.multiple && this.mode !== 'tags') next = next.slice(0, 1);
1153
1249
  this.value_ = next;
1154
- if (next.length && this.opts.validation === 'invalid') this.opts.validation = null;
1250
+ /* a preset/manual invalid state is only cleared by a real value change, not
1251
+ by the initial value applied during construction */
1252
+ if (next.length && this.opts.validation === 'invalid' && !cfg.silent) this.opts.validation = null;
1155
1253
  this._render();
1156
1254
  this._syncNative();
1157
1255
  if (!cfg.silent) {
@@ -1341,8 +1439,11 @@
1341
1439
  var query = this.query.trim();
1342
1440
  var source = this._sourceItems();
1343
1441
  var isCaseSensitive = !!this.opts.caseSensitive;
1442
+ var remote = typeof this.opts.fetchOptions === 'function' && !!this.asyncItems;
1344
1443
 
1345
1444
  if (!query) return source.slice();
1445
+ // the server already filtered this page; only an explicit filterOption re-checks it
1446
+ if (remote && typeof this.opts.filterOption !== 'function') return source.slice();
1346
1447
 
1347
1448
  return source.filter(function (item) {
1348
1449
  if (typeof self.opts.filterOption === 'function') {
@@ -1440,6 +1541,20 @@
1440
1541
  self.dropdown.appendChild(option);
1441
1542
  });
1442
1543
  }
1544
+
1545
+ if (this.hasMore) {
1546
+ var more = el('button', 'zs-more', { type: 'button' });
1547
+ if (this.fetchingMore) {
1548
+ more.appendChild(el('span', 'zs-spinner', { 'aria-hidden': 'true' }));
1549
+ more.appendChild(el('span', null, null, this.opts.loadingText || 'Loading…'));
1550
+ more.disabled = true;
1551
+ more.setAttribute('aria-busy', 'true');
1552
+ } else {
1553
+ more.textContent = this.loadMoreError || this.opts.loadMoreText;
1554
+ if (this.loadMoreError) more.classList.add('zs-more--error');
1555
+ }
1556
+ this.dropdown.appendChild(more);
1557
+ }
1443
1558
  }
1444
1559
 
1445
1560
  this.dropdown.scrollTop = scrollTop;
@@ -1493,6 +1608,8 @@
1493
1608
  this.opened = true;
1494
1609
  this.query = '';
1495
1610
  this.activeIndex = -1;
1611
+ this.loadMoreError = null;
1612
+ this.fetchingMore = false;
1496
1613
  if (this.mode === 'combobox' || (this.mode === 'select' && this.opts.searchable)) {
1497
1614
  this.savedInputText = this.input.value;
1498
1615
  }
@@ -1504,7 +1621,7 @@
1504
1621
  this.emit('open', { instance: this });
1505
1622
  this.call('onOpen', { instance: this });
1506
1623
 
1507
- if (typeof this.opts.fetchOptions === 'function' && !this.asyncItems) {
1624
+ if (typeof this.opts.fetchOptions === 'function' && (!this.asyncItems || this.asyncQuery !== '')) {
1508
1625
  this._fetch('');
1509
1626
  } else if (this.mode !== 'tags') {
1510
1627
  var first = this._firstEnabledIndex();
@@ -1532,6 +1649,15 @@
1532
1649
  this.dropdown.removeAttribute('data-zs-visible');
1533
1650
  this.activeIndex = -1;
1534
1651
  this.query = '';
1652
+ if (typeof this.opts.fetchOptions === 'function') {
1653
+ if (this.asyncController) {
1654
+ this.asyncController.abort();
1655
+ this.asyncController = null;
1656
+ }
1657
+ this.loading = false;
1658
+ this.fetchingMore = false;
1659
+ this.loadMoreError = null;
1660
+ }
1535
1661
  this._render();
1536
1662
  this.emit('close', { instance: this });
1537
1663
  this.call('onClose', { instance: this });
@@ -1601,54 +1727,205 @@
1601
1727
 
1602
1728
  /* ---------------- async loading ---------------- */
1603
1729
 
1604
- ZidanSelect.prototype._fetch = function (query) {
1730
+ ZidanSelect.prototype._cacheKey = function (query, page) {
1731
+ return query + '\u0000' + page;
1732
+ };
1733
+
1734
+ ZidanSelect.prototype._cacheGet = function (query, page) {
1735
+ if (!this.opts.cacheResults) return null;
1736
+ var key = this._cacheKey(query, page);
1737
+ var entry = this._fetchCache[key];
1738
+ if (!entry) return null;
1739
+ var index = this._cacheKeys.indexOf(key);
1740
+ if (index !== -1) {
1741
+ this._cacheKeys.splice(index, 1);
1742
+ this._cacheKeys.push(key);
1743
+ }
1744
+ return entry;
1745
+ };
1746
+
1747
+ ZidanSelect.prototype._cacheSet = function (query, page, entry) {
1748
+ if (!this.opts.cacheResults) return;
1749
+ var key = this._cacheKey(query, page);
1750
+ this._fetchCache[key] = entry;
1751
+ var index = this._cacheKeys.indexOf(key);
1752
+ if (index !== -1) this._cacheKeys.splice(index, 1);
1753
+ this._cacheKeys.push(key);
1754
+ var limit = ZidanSelect.cacheLimit || 50;
1755
+ while (this._cacheKeys.length > limit) {
1756
+ delete this._fetchCache[this._cacheKeys.shift()];
1757
+ }
1758
+ };
1759
+
1760
+ ZidanSelect.prototype.clearCache = function () {
1761
+ this._fetchCache = Object.create(null);
1762
+ this._cacheKeys = [];
1763
+ return this;
1764
+ };
1765
+
1766
+ ZidanSelect.prototype._readFetchPayload = function (result, page, pageSize) {
1767
+ var rows = result;
1768
+ var hasMore = false;
1769
+ if (result && !Array.isArray(result) && typeof result === 'object') {
1770
+ rows = result.items || result.options || result.results || [];
1771
+ if (result.hasMore !== undefined) {
1772
+ hasMore = !!result.hasMore;
1773
+ } else if (result.total !== undefined && pageSize > 0) {
1774
+ hasMore = (page + 1) * pageSize < Number(result.total);
1775
+ } else if (pageSize > 0) {
1776
+ hasMore = toArray(rows).length >= pageSize;
1777
+ }
1778
+ } else if (pageSize > 0) {
1779
+ hasMore = toArray(rows).length >= pageSize;
1780
+ }
1781
+ return { items: this._normalizeItems(rows), hasMore: hasMore };
1782
+ };
1783
+
1784
+ ZidanSelect.prototype._applyCachedPage = function (query, page, append) {
1785
+ var cached = this._cacheGet(query, page);
1786
+ if (!cached) return false;
1787
+ this.loading = false;
1788
+ this.fetchingMore = false;
1789
+ this.loadMoreError = null;
1790
+ this.error = null;
1791
+ this.asyncQuery = query;
1792
+ this.asyncPage = page;
1793
+ this.asyncItems = append ? (this.asyncItems || []).concat(cached.items) : cached.items.slice();
1794
+ this.hasMore = !!cached.hasMore;
1795
+ if (!append) this.activeIndex = -1;
1796
+ this._renderDropdown();
1797
+ return true;
1798
+ };
1799
+
1800
+ /* page 0 replaces the result set; later pages append (remote pagination) */
1801
+ ZidanSelect.prototype._fetch = function (query, page, append) {
1605
1802
  var self = this;
1606
- if (typeof this.opts.fetchOptions !== 'function') return;
1803
+ if (typeof this.opts.fetchOptions !== 'function') return Promise.resolve([]);
1607
1804
  query = query === undefined || query === null ? '' : String(query);
1805
+ page = page === undefined || page === null ? 0 : parseInt(page, 10) || 0;
1806
+ append = !!append;
1807
+ if (append && (this.loading || this.fetchingMore || !this.hasMore)) return Promise.resolve([]);
1808
+
1809
+ var cached = this._cacheGet(query, page);
1810
+ if (cached && (append ? this.hasMore : true)) {
1811
+ if (this.asyncController) this.asyncController.abort();
1812
+ this.asyncController = null;
1813
+ this._applyCachedPage(query, page, append);
1814
+ return Promise.resolve(this._visibleItems());
1815
+ }
1608
1816
 
1609
1817
  if (this.asyncController) this.asyncController.abort();
1610
1818
  var controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
1611
1819
  this.asyncController = controller;
1612
- this.loading = true;
1820
+ this.loading = !append;
1821
+ this.fetchingMore = append;
1613
1822
  this.error = null;
1823
+ this.loadMoreError = null;
1824
+ if (!append) {
1825
+ this.hasMore = false;
1826
+ this.asyncPage = 0;
1827
+ this.announce(this.opts.loadingText);
1828
+ }
1614
1829
  this._renderDropdown();
1615
- this.announce(this.opts.loadingText);
1616
1830
 
1831
+ var settleFetch;
1832
+ var fetchPromise = new Promise(function (resolve) { settleFetch = resolve; });
1833
+ if (controller && controller.signal.addEventListener) {
1834
+ controller.signal.addEventListener('abort', function () { settleFetch([]); });
1835
+ }
1836
+
1837
+ if (append) {
1838
+ this.emit('load-more', { page: page, query: query, instance: this });
1839
+ this.call('onLoadMore', { page: page, query: query, instance: this });
1840
+ }
1841
+
1842
+ var pageSize = this.opts.fetchPageSize > 0 ? this.opts.fetchPageSize : 0;
1617
1843
  var done = function (result) {
1844
+ if (controller && controller.signal.aborted) return;
1618
1845
  self.loading = false;
1619
- self.asyncItems = self._normalizeItems(result || []);
1620
- self.activeIndex = -1;
1846
+ self.fetchingMore = false;
1847
+ self.loadMoreError = null;
1848
+ self.error = null;
1849
+ var payload = self._readFetchPayload(result, page, pageSize);
1850
+ self.asyncQuery = query;
1851
+ self.asyncPage = page;
1852
+ self.asyncItems = append ? (self.asyncItems || []).concat(payload.items) : payload.items;
1853
+ self.hasMore = payload.hasMore;
1854
+ self._cacheSet(query, page, { items: payload.items, hasMore: payload.hasMore });
1855
+ if (!append) self.activeIndex = -1;
1621
1856
  self._renderDropdown();
1622
1857
  var count = self._visibleItems().length;
1623
1858
  self.announce(count + ' result' + (count === 1 ? '' : 's'));
1859
+ settleFetch(self._visibleItems());
1624
1860
  };
1625
1861
  var fail = function (err) {
1862
+ if (err && err.name === 'AbortError') {
1863
+ settleFetch([]);
1864
+ return;
1865
+ }
1866
+ if (controller && controller.signal.aborted) {
1867
+ settleFetch([]);
1868
+ return;
1869
+ }
1870
+ var message = (err && err.message) || 'Unable to load options.';
1626
1871
  self.loading = false;
1627
- self.error = { message: (err && err.message) || 'Unable to load options.' };
1628
- self.emit('error', { error: err, message: self.error.message, instance: self });
1629
- self.call('onError', { error: err, message: self.error.message, instance: self });
1872
+ self.fetchingMore = false;
1873
+ if (append) self.loadMoreError = message;
1874
+ else self.error = { message: message };
1875
+ self.emit('error', { error: err, message: message, instance: self });
1876
+ self.call('onError', { error: err, message: message, instance: self });
1630
1877
  self._renderDropdown();
1878
+ settleFetch([]);
1631
1879
  };
1632
1880
 
1633
1881
  try {
1634
- var result = this.opts.fetchOptions(query, controller ? controller.signal : undefined);
1882
+ var result = this.opts.fetchOptions(query, controller ? controller.signal : undefined, {
1883
+ page: page,
1884
+ pageSize: pageSize,
1885
+ append: append,
1886
+ instance: this
1887
+ });
1635
1888
  if (result && typeof result.then === 'function') {
1636
- result.then(function (data) {
1637
- if (controller && controller.signal.aborted) return;
1638
- done(data);
1639
- }).catch(function (err) {
1640
- if (err && err.name === 'AbortError') return;
1641
- if (controller && controller.signal.aborted) return;
1642
- fail(err);
1643
- });
1889
+ result.then(done).catch(fail);
1644
1890
  } else {
1645
1891
  done(result);
1646
1892
  }
1647
1893
  } catch (err) {
1648
- if (err && err.name === 'AbortError') return;
1649
1894
  fail(err);
1650
1895
  }
1651
- void self;
1896
+ return fetchPromise;
1897
+ };
1898
+
1899
+ ZidanSelect.prototype.loadMore = function () {
1900
+ if (typeof this.opts.fetchOptions !== 'function') return this;
1901
+ if (this.loading || this.fetchingMore || !this.hasMore) return this;
1902
+ return this._fetch(this.asyncQuery || this.query || '', this.asyncPage + 1, true);
1903
+ };
1904
+
1905
+ ZidanSelect.prototype.hasMoreResults = function () {
1906
+ return !!this.hasMore;
1907
+ };
1908
+
1909
+ ZidanSelect.prototype.getAsyncState = function () {
1910
+ return {
1911
+ query: this.asyncQuery,
1912
+ page: this.asyncPage,
1913
+ hasMore: !!this.hasMore,
1914
+ loading: !!this.loading,
1915
+ fetchingMore: !!this.fetchingMore,
1916
+ error: this.error ? this.error.message : null
1917
+ };
1918
+ };
1919
+
1920
+ ZidanSelect.prototype.refreshOptions = function () {
1921
+ this.clearCache();
1922
+ if (typeof this.opts.fetchOptions !== 'function') return this;
1923
+ this.asyncItems = null;
1924
+ this.asyncQuery = '';
1925
+ this.asyncPage = 0;
1926
+ this.hasMore = false;
1927
+ if (this.opened) return this._fetch(this.query, 0, false);
1928
+ return this;
1652
1929
  };
1653
1930
 
1654
1931
  /* ---------------- tags ---------------- */
@@ -1685,6 +1962,22 @@
1685
1962
  return false;
1686
1963
  }
1687
1964
 
1965
+ /* allowFreeText: false limits tags to the supplied option/suggestion list */
1966
+ if (this.mode === 'tags' && !opts.allowFreeText) {
1967
+ var pool = this.suggestions && this.suggestions.length ? this.suggestions : this.items;
1968
+ var needle = opts.caseSensitive ? raw : raw.toLowerCase();
1969
+ var listed = false;
1970
+ for (var s = 0; s < pool.length; s += 1) {
1971
+ var itemValue = opts.caseSensitive ? String(pool[s].value) : String(pool[s].value).toLowerCase();
1972
+ var itemLabel = opts.caseSensitive ? String(pool[s].label) : String(pool[s].label).toLowerCase();
1973
+ if (itemValue === needle || itemLabel === needle) { listed = true; break; }
1974
+ }
1975
+ if (!listed) {
1976
+ if (!cfg.silent) this._tagError('"' + raw + '" is not in the list.');
1977
+ return false;
1978
+ }
1979
+ }
1980
+
1688
1981
  var formatted = raw;
1689
1982
  if (typeof opts.formatTag === 'function') {
1690
1983
  var formattedResult = opts.formatTag(raw, { instance: this, tags: this.getTags() });
@@ -1761,6 +2054,14 @@
1761
2054
  var key = event.key;
1762
2055
  var items = this._visibleItems();
1763
2056
 
2057
+ /* Space opens a closed combobox/listbox (WAI-ARIA), unless the user is
2058
+ already typing a search or tag query in an open control. */
2059
+ if ((key === ' ' || key === 'Spacebar') && !this.opened) {
2060
+ event.preventDefault();
2061
+ this.open();
2062
+ return;
2063
+ }
2064
+
1764
2065
  if (key === 'ArrowDown' || key === 'ArrowUp') {
1765
2066
  event.preventDefault();
1766
2067
  if (!this.opened) {
@@ -1896,6 +2197,8 @@
1896
2197
 
1897
2198
  this.onInput = function () {
1898
2199
  var value = self.input.value;
2200
+ /* plain selects are not searchable: typing must not filter the list */
2201
+ if (self.mode === 'select' && !self.opts.searchable) return;
1899
2202
  self.query = value;
1900
2203
  if (self.opened) {
1901
2204
  if (typeof self.opts.fetchOptions === 'function' && self.query.length >= (self.opts.minChars || 0)) {
@@ -2005,6 +2308,13 @@
2005
2308
  };
2006
2309
 
2007
2310
  this.onDropdownClick = function (event) {
2311
+ var more = event.target.closest ? event.target.closest('.zs-more') : null;
2312
+ if (more) {
2313
+ event.preventDefault();
2314
+ event.stopPropagation();
2315
+ self.loadMore();
2316
+ return;
2317
+ }
2008
2318
  var option = event.target.closest ? event.target.closest('[data-zs-option]') : null;
2009
2319
  if (!option) return;
2010
2320
  event.preventDefault();
@@ -2028,6 +2338,13 @@
2028
2338
  if (self.opened) self._position();
2029
2339
  };
2030
2340
 
2341
+ this.onDropdownScroll = function () {
2342
+ if (!self.opts.autoLoadMore || !self.opened || !self.hasMore) return;
2343
+ if (self.loading || self.fetchingMore) return;
2344
+ var node = self.dropdown;
2345
+ if (node.scrollTop + node.clientHeight >= node.scrollHeight - 24) self.loadMore();
2346
+ };
2347
+
2031
2348
  this.debouncedFetch = debounce(function (query) { self._fetch(query); }, this.opts.debounce);
2032
2349
 
2033
2350
  if (this.el && this.el.addEventListener) {
@@ -2048,6 +2365,7 @@
2048
2365
  this.clearBtn.addEventListener('click', this.onClearClick);
2049
2366
  this.dropdown.addEventListener('mousedown', this.onDropdownMouseDown);
2050
2367
  this.dropdown.addEventListener('click', this.onDropdownClick);
2368
+ this.dropdown.addEventListener('scroll', this.onDropdownScroll);
2051
2369
  doc.addEventListener('pointerdown', this.onDocumentPointerDown, true);
2052
2370
  global.addEventListener('resize', this.onWindowResize);
2053
2371
  };
@@ -2135,6 +2453,10 @@
2135
2453
  }
2136
2454
  }
2137
2455
  this.asyncItems = null;
2456
+ this.asyncPage = 0;
2457
+ this.hasMore = false;
2458
+ this.loadMoreError = null;
2459
+ this.clearCache();
2138
2460
  this.activeIndex = -1;
2139
2461
  this._render();
2140
2462
  this._syncNative();
@@ -2267,8 +2589,14 @@
2267
2589
 
2268
2590
  if (this.debouncedFetch) this.debouncedFetch.cancel();
2269
2591
  if (this.asyncController) this.asyncController.abort();
2592
+ this.clearCache();
2270
2593
  if (this.resizeObserver) this.resizeObserver.disconnect();
2271
2594
  if (this.form && this.onFormReset) this.form.removeEventListener('reset', this.onFormReset);
2595
+ if (this.form && this.onFormSubmit) this.form.removeEventListener('submit', this.onFormSubmit);
2596
+ if (this._nativeRequiredAdded && this.native) {
2597
+ this.native.required = false;
2598
+ this._nativeRequiredAdded = false;
2599
+ }
2272
2600
 
2273
2601
  doc.removeEventListener('pointerdown', this.onDocumentPointerDown, true);
2274
2602
  global.removeEventListener('resize', this.onWindowResize);
@@ -2278,6 +2606,12 @@
2278
2606
 
2279
2607
  if (this.root && this.root.parentNode) this.root.parentNode.removeChild(this.root);
2280
2608
 
2609
+ if (this._authorLabel) {
2610
+ this._authorLabel.hidden = false;
2611
+ this._authorLabel.removeAttribute('data-zs-hidden-label');
2612
+ this._authorLabel = null;
2613
+ }
2614
+
2281
2615
  if (this.native) {
2282
2616
  this.native.hidden = false;
2283
2617
  this.native.classList.remove('zs-native');
@@ -2319,6 +2653,8 @@
2319
2653
  var RADIO_VARIANTS = ['stacked', 'inline', 'card', 'button', 'tile'];
2320
2654
  var FILE_VARIANTS = ['dropzone', 'button', 'avatar', 'gallery', 'compact'];
2321
2655
  var RANGE_VARIANTS = ['default', 'gradient', 'stepped', 'minimal'];
2656
+ var RANGE_BUBBLE_MODES = ['always', 'active', 'never'];
2657
+ var RANGE_BUBBLE_POSITIONS = ['top', 'bottom'];
2322
2658
 
2323
2659
  function textWithout(rootNode, skip) {
2324
2660
  var out = '';
@@ -2351,9 +2687,13 @@
2351
2687
  this.validation = null;
2352
2688
  this.errorMessage = null;
2353
2689
  this.errorEl = null;
2690
+ this.pending = false;
2691
+ this._asyncToken = 0;
2692
+ this._asyncController = null;
2354
2693
  this.destroyed = false;
2355
2694
  this._listeners = [];
2356
2695
  this._cleanups = [];
2696
+ this._describedByBefore = [];
2357
2697
  this.formEl = target.form || (target.closest ? target.closest('form') : null);
2358
2698
  var scope = resolveScope(target, this.opts);
2359
2699
  this.theme = scope.theme;
@@ -2391,6 +2731,7 @@
2391
2731
  root.id = this.id + '-field';
2392
2732
  root.setAttribute('data-zs-kind', kind);
2393
2733
  root.classList.add('zs-field--' + kind);
2734
+ if (isRtl(this.el)) root.setAttribute('dir', 'rtl');
2394
2735
  this._applyScope(root);
2395
2736
  this.root = root;
2396
2737
  return root;
@@ -2441,15 +2782,133 @@
2441
2782
  var targets = this.validationTargets();
2442
2783
  for (var i = 0; i < targets.length; i += 1) {
2443
2784
  var input = targets[i];
2444
- if (input && input.validity && !input.validity.valid) return this._messageFor(input);
2785
+ if (hasNativeValidityError(input)) return this._messageFor(input);
2445
2786
  }
2446
2787
  return '';
2447
2788
  };
2448
2789
 
2449
- ZidanFieldBase.prototype._evaluateError = function () {
2790
+ /* subclasses forward this context to async validators so they can abort */
2791
+ ZidanFieldBase.prototype._asyncSignal = function () {
2792
+ return this._asyncController ? this._asyncController.signal : undefined;
2793
+ };
2794
+
2795
+ ZidanFieldBase.prototype._asyncContext = function () {
2796
+ return { signal: this._asyncSignal(), field: this, instance: this };
2797
+ };
2798
+
2799
+ /* text inputs override this to block form submission while pending/invalid */
2800
+ ZidanFieldBase.prototype._setCustomValidity = function () {};
2801
+
2802
+ ZidanFieldBase.prototype._abortAsync = function () {
2803
+ this._asyncToken += 1;
2804
+ if (this._asyncController) {
2805
+ try { this._asyncController.abort(); } catch (err) { /* already settled */ }
2806
+ this._asyncController = null;
2807
+ }
2808
+ };
2809
+
2810
+ /* returns { pending: promise } for async checks, otherwise { error, custom } */
2811
+ ZidanFieldBase.prototype._evaluate = function () {
2812
+ this._abortAsync();
2813
+ if (typeof AbortController !== 'undefined') this._asyncController = new AbortController();
2450
2814
  var custom = this._customError ? this._customError() : '';
2451
- if (custom) return typeof custom === 'string' ? custom : this.opts.messages.generic;
2452
- return this._nativeError();
2815
+ if (isThenable(custom)) return { pending: custom };
2816
+ this._asyncController = null;
2817
+ if (custom) {
2818
+ return { error: typeof custom === 'string' ? custom : this.opts.messages.generic, custom: true };
2819
+ }
2820
+ var native = this._nativeError();
2821
+ return native ? { error: native, custom: false } : {};
2822
+ };
2823
+
2824
+ ZidanFieldBase.prototype._applyValidity = function (message, show, custom) {
2825
+ this._setCustomValidity(message && custom ? message : '');
2826
+ if (message) {
2827
+ if (show) this.setError(message);
2828
+ else this.setValidation('invalid', true);
2829
+ return this;
2830
+ }
2831
+ if (this.errorMessage) this.setError(null);
2832
+ /* keep an initial or manually set invalid state until the user interacts */
2833
+ if (this.validation === 'invalid' && !this._presetValidation) this.setValidation(null, true);
2834
+ return this;
2835
+ };
2836
+
2837
+ ZidanFieldBase.prototype._setPending = function (on) {
2838
+ on = !!on;
2839
+ this.pending = on;
2840
+ if (this.root) {
2841
+ this.root.classList.toggle('zs-field--pending', on);
2842
+ if (on) {
2843
+ this.root.setAttribute('data-zs-validation', 'pending');
2844
+ } else if (this.root.getAttribute('data-zs-validation') === 'pending') {
2845
+ this.root.removeAttribute('data-zs-validation');
2846
+ }
2847
+ }
2848
+ this.validationTargets().forEach(function (input) {
2849
+ if (!input || !input.setAttribute) return;
2850
+ if (on) input.setAttribute('aria-busy', 'true');
2851
+ else input.removeAttribute('aria-busy');
2852
+ }, this);
2853
+ if (on) {
2854
+ if (this.errorMessage) this.setError(null);
2855
+ this._setCustomValidity(this.opts.messages.pending || FIELD_MESSAGES.pending);
2856
+ } else {
2857
+ this._setCustomValidity('');
2858
+ }
2859
+ return this;
2860
+ };
2861
+
2862
+ ZidanFieldBase.prototype._runAsync = function (promise) {
2863
+ var self = this;
2864
+ if (self.destroyed) return Promise.resolve(false);
2865
+ var token = self._asyncToken;
2866
+ self._setPending(true);
2867
+ return Promise.resolve(promise).then(function (value) {
2868
+ if (self.destroyed || token !== self._asyncToken) return false;
2869
+ self._asyncController = null;
2870
+ self._setPending(false);
2871
+ var message = '';
2872
+ if (value === false) message = self.opts.messages.generic;
2873
+ else if (typeof value === 'string') message = value;
2874
+ else if (value instanceof Error) message = value.message || self.opts.messages.generic;
2875
+ self._applyValidity(message, self.touched || self.opts.alwaysValidate || !!message, true);
2876
+ if (!message && self.opts.showValidState) self.setValidation('valid');
2877
+ self.emit('async-validation', { valid: !message, message: message });
2878
+ return !message;
2879
+ }, function (err) {
2880
+ if (self.destroyed || token !== self._asyncToken || (err && err.name === 'AbortError')) return false;
2881
+ self._asyncController = null;
2882
+ self._setPending(false);
2883
+ var message = (err && (err.message || err.error)) || self.opts.messages.generic;
2884
+ if (typeof message !== 'string') message = self.opts.messages.generic;
2885
+ self._applyValidity(message, true, true);
2886
+ self.emit('async-validation', { valid: false, message: message, error: err });
2887
+ return false;
2888
+ });
2889
+ };
2890
+
2891
+ /* convenience: resolves with the async result, false when sync-invalid, true when sync-valid */
2892
+ ZidanFieldBase.prototype.checkAsync = function () {
2893
+ var result = this._evaluate();
2894
+ if (result.pending) return this._runAsync(result.pending);
2895
+ return Promise.resolve(!result.error);
2896
+ };
2897
+
2898
+ ZidanFieldBase.prototype._trackDescribedBy = function (input) {
2899
+ if (!input || !input.getAttribute) return;
2900
+ for (var i = 0; i < this._describedByBefore.length; i += 1) {
2901
+ if (this._describedByBefore[i][0] === input) return;
2902
+ }
2903
+ this._describedByBefore.push([input, input.getAttribute('aria-describedby')]);
2904
+ };
2905
+
2906
+ ZidanFieldBase.prototype._addDescribedBy = function (input, id) {
2907
+ if (!input || !input.getAttribute || !id) return;
2908
+ this._trackDescribedBy(input);
2909
+ var current = (input.getAttribute('aria-describedby') || '').split(/\s+/).filter(Boolean);
2910
+ if (current.indexOf(id) === -1) current.push(id);
2911
+ input.setAttribute('aria-describedby', current.join(' '));
2453
2912
  };
2454
2913
 
2455
2914
  ZidanFieldBase.prototype._syncDescribedBy = function () {
@@ -2460,6 +2919,7 @@
2460
2919
  var targets = this.validationTargets();
2461
2920
  targets.forEach(function (input) {
2462
2921
  if (!input || !input.getAttribute) return;
2922
+ this._trackDescribedBy(input);
2463
2923
  var current = (input.getAttribute('aria-describedby') || '').split(/\s+/).filter(Boolean);
2464
2924
  var next = current.filter(function (id) { return id !== errorId && id !== hintId; });
2465
2925
  if (hintId) next.push(hintId);
@@ -2517,22 +2977,35 @@
2517
2977
  this.validationTargets().forEach(function (input) {
2518
2978
  self.on(input, 'invalid', function () {
2519
2979
  self.touched = true;
2520
- var message = self._evaluateError();
2521
- if (message) self.setError(message);
2980
+ var result = self._evaluate();
2981
+ if (result.pending) {
2982
+ self._runAsync(result.pending);
2983
+ return;
2984
+ }
2985
+ if (result.error) self.setError(result.error);
2522
2986
  else self.setValidation('invalid');
2523
2987
  });
2524
2988
  self.on(input, 'blur', function () {
2525
2989
  self.touched = true;
2990
+ self._presetValidation = false;
2991
+ self._mirrorValidity();
2992
+ });
2993
+ self.on(input, 'input', function () {
2994
+ self._presetValidation = false;
2995
+ self._mirrorValidity();
2996
+ });
2997
+ self.on(input, 'change', function () {
2998
+ self._presetValidation = false;
2526
2999
  self._mirrorValidity();
2527
3000
  });
2528
- self.on(input, 'input', function () { self._mirrorValidity(); });
2529
- self.on(input, 'change', function () { self._mirrorValidity(); });
2530
3001
  });
2531
3002
  this.on(this.formEl, 'reset', function () {
2532
3003
  global.setTimeout(function () {
2533
3004
  if (self.destroyed) return;
3005
+ self._abortAsync();
2534
3006
  self.touched = false;
2535
3007
  self.errorMessage = null;
3008
+ self._setPending(false);
2536
3009
  if (self.errorEl) {
2537
3010
  self.errorEl.textContent = '';
2538
3011
  self.errorEl.hidden = true;
@@ -2548,31 +3021,35 @@
2548
3021
  };
2549
3022
 
2550
3023
  ZidanFieldBase.prototype._mirrorValidity = function () {
2551
- var error = this._evaluateError();
2552
- if (error) {
2553
- if (this.touched || this.opts.alwaysValidate) this.setError(error);
2554
- else this.setValidation('invalid');
3024
+ var result = this._evaluate();
3025
+ if (result.pending) {
3026
+ this._runAsync(result.pending);
2555
3027
  return this;
2556
3028
  }
2557
- if (this.errorMessage) this.setError(null);
2558
- if (this.validation === 'invalid') this.setValidation(null);
3029
+ if (this.pending) this._setPending(false);
3030
+ this._applyValidity(result.error || '', this.touched || this.opts.alwaysValidate, result.custom);
2559
3031
  return this;
2560
3032
  };
2561
3033
 
3034
+ /* returns a boolean for sync rules and a Promise<boolean> when an async rule runs */
2562
3035
  ZidanFieldBase.prototype.validate = function () {
2563
3036
  this.touched = true;
2564
- var error = this._evaluateError();
2565
- if (error) {
2566
- this.setError(error);
3037
+ var result = this._evaluate();
3038
+ if (result.pending) return this._runAsync(result.pending);
3039
+ if (this.pending) this._setPending(false);
3040
+ if (result.error) {
3041
+ this._applyValidity(result.error, true, result.custom);
2567
3042
  return false;
2568
3043
  }
2569
- this.setError(null);
3044
+ this._applyValidity('', true, false);
2570
3045
  if (this.opts.showValidState) this.setValidation('valid');
2571
3046
  return true;
2572
3047
  };
2573
3048
 
2574
- ZidanFieldBase.prototype.setValidation = function (state) {
3049
+ ZidanFieldBase.prototype.setValidation = function (state, internal) {
2575
3050
  this.validation = VALIDATION_STATES.indexOf(state) === -1 ? null : state;
3051
+ /* public calls pin the state; internal mirrors may clear it again */
3052
+ if (!internal) this._presetValidation = this.validation === 'invalid';
2576
3053
  var invalid = this.validation === 'invalid' || !!this.errorMessage;
2577
3054
  if (this.root) {
2578
3055
  this.root.classList.toggle('zs-field--invalid', invalid);
@@ -2596,6 +3073,10 @@
2596
3073
  return this.validation;
2597
3074
  };
2598
3075
 
3076
+ ZidanFieldBase.prototype.isPending = function () {
3077
+ return this.pending;
3078
+ };
3079
+
2599
3080
  ZidanFieldBase.prototype.getValue = function () {
2600
3081
  var el = this.el;
2601
3082
  if (!el) return null;
@@ -2650,6 +3131,7 @@
2650
3131
  ZidanFieldBase.prototype.destroy = function () {
2651
3132
  if (this.destroyed) return this;
2652
3133
  this.destroyed = true;
3134
+ this._abortAsync();
2653
3135
  this._listeners.forEach(function (entry) {
2654
3136
  entry[0].removeEventListener(entry[1], entry[2], entry[3]);
2655
3137
  });
@@ -2658,7 +3140,16 @@
2658
3140
  this._cleanups.forEach(function (fn) { fn(); });
2659
3141
  this._cleanups.length = 0;
2660
3142
  this.emit('destroy', {});
2661
- if (this.root && this.root.parentNode) this.root.parentNode.removeChild(this.root);
3143
+ /* radio groups use the author's <fieldset> as their root: removing it would
3144
+ delete the original radios too, so only remove roots the field created. */
3145
+ if (this.root && this.root !== this.el && this.root.parentNode) this.root.parentNode.removeChild(this.root);
3146
+ this._describedByBefore.forEach(function (entry) {
3147
+ var input = entry[0];
3148
+ if (!input || !input.getAttribute) return;
3149
+ if (entry[1] === null || entry[1] === undefined) input.removeAttribute('aria-describedby');
3150
+ else input.setAttribute('aria-describedby', entry[1]);
3151
+ });
3152
+ this._describedByBefore = [];
2662
3153
  if (this.el.__zidanField === this) delete this.el.__zidanField;
2663
3154
  ZidanForm._unregister(this);
2664
3155
  return this;
@@ -2762,8 +3253,7 @@
2762
3253
  if (hintText) {
2763
3254
  var hint = el('p', 'zs-field__hint', { id: this.id + '-hint' }, hintText);
2764
3255
  root.appendChild(hint);
2765
- input.setAttribute('aria-describedby', this.id + '-hint');
2766
- this._cleanups.push(function () { input.removeAttribute('aria-describedby'); });
3256
+ this._addDescribedBy(input, this.id + '-hint');
2767
3257
  }
2768
3258
 
2769
3259
  this.check = check;
@@ -2835,9 +3325,10 @@
2835
3325
 
2836
3326
  ZidanCheckbox.prototype._customError = function () {
2837
3327
  if (typeof this.opts.validate === 'function') {
2838
- var result = this.opts.validate(this.el.checked, this);
3328
+ var result = this.opts.validate(this.el.checked, this, this._asyncContext());
2839
3329
  if (result === false) return this.opts.messages.generic;
2840
3330
  if (typeof result === 'string' && result) return result;
3331
+ if (isThenable(result)) return result;
2841
3332
  }
2842
3333
  return '';
2843
3334
  };
@@ -2851,6 +3342,12 @@
2851
3342
 
2852
3343
  function ZidanRadioGroup(target, options) {
2853
3344
  if (!(this instanceof ZidanRadioGroup)) return new ZidanRadioGroup(target, options);
3345
+ /* radios are enhanced as a group, never one input at a time */
3346
+ if (isElement(target) && /^INPUT$/i.test(target.tagName)) {
3347
+ var group = target.closest ? target.closest('fieldset, [data-zidan-radio-group]') : null;
3348
+ if (!group) throw new Error('ZidanRadioGroup: expected a <fieldset> containing the radio inputs.');
3349
+ target = group;
3350
+ }
2854
3351
  ZidanFieldBase.call(this, target, options, 'radio-group');
2855
3352
  var variant = pickList(this.opts.variant || target.getAttribute('data-zidan-variant'), RADIO_VARIANTS, 'stacked');
2856
3353
  this.variant = variant;
@@ -2860,7 +3357,14 @@
2860
3357
  target.setAttribute('data-zs-kind', 'radio-group');
2861
3358
  target.setAttribute('data-zs-variant', variant);
2862
3359
  this._applyScope(target);
2863
- if (!target.hasAttribute('role')) target.setAttribute('role', 'radiogroup');
3360
+ var hadRole = target.hasAttribute('role');
3361
+ if (!hadRole) target.setAttribute('role', 'radiogroup');
3362
+ this._teardown = function () {
3363
+ target.classList.remove('zs-radio-group');
3364
+ ['data-zs-kind', 'data-zs-variant', 'data-zs-theme', 'data-zs-framework', 'data-zs-layout']
3365
+ .forEach(function (name) { target.removeAttribute(name); });
3366
+ if (!hadRole) target.removeAttribute('role');
3367
+ };
2864
3368
  this._labels = [];
2865
3369
  this._enhance();
2866
3370
  this._bindValidity();
@@ -3012,9 +3516,10 @@
3012
3516
 
3013
3517
  ZidanRadioGroup.prototype._customError = function () {
3014
3518
  if (typeof this.opts.validate === 'function') {
3015
- var result = this.opts.validate(this.getValue(), this);
3519
+ var result = this.opts.validate(this.getValue(), this, this._asyncContext());
3016
3520
  if (result === false) return this.opts.messages.generic;
3017
3521
  if (typeof result === 'string' && result) return result;
3522
+ if (isThenable(result)) return result;
3018
3523
  }
3019
3524
  return '';
3020
3525
  };
@@ -3189,6 +3694,22 @@
3189
3694
 
3190
3695
  self.on(clearBtn, 'click', function () { self.clear(); });
3191
3696
 
3697
+ /* Delegated once: the list is rebuilt on every upload progress tick, so
3698
+ per-item listeners would grow without bound. */
3699
+ self.on(list, 'click', function (event) {
3700
+ var button = event.target && event.target.closest ? event.target.closest('button') : null;
3701
+ if (!button || !list.contains(button)) return;
3702
+ var item = button.closest('.zs-file-item');
3703
+ var index = item ? parseInt(item.getAttribute('data-zs-file-index'), 10) : -1;
3704
+ var file = index >= 0 ? self.getFiles()[index] : null;
3705
+ if (!file) return;
3706
+ event.preventDefault();
3707
+ event.stopPropagation();
3708
+ if (button.classList.contains('zs-file-cancel')) self.cancelUpload(file);
3709
+ else if (button.classList.contains('zs-file-retry')) self.retryUpload(file);
3710
+ else if (button.classList.contains('zs-file-remove')) self.removeFile(file);
3711
+ });
3712
+
3192
3713
  this._bindValidity();
3193
3714
  this.on(this.formEl, 'reset', function () {
3194
3715
  global.setTimeout(function () {
@@ -3346,8 +3867,19 @@
3346
3867
  };
3347
3868
  };
3348
3869
 
3870
+ ZidanFileUpload.prototype._setCustomValidity = function (message) {
3871
+ if (this.el && this.el.setCustomValidity) this.el.setCustomValidity(message || '');
3872
+ };
3873
+
3349
3874
  ZidanFileUpload.prototype._customError = function () {
3350
- return this.fileError || '';
3875
+ if (this.fileError) return this.fileError;
3876
+ if (typeof this.opts.validate === 'function') {
3877
+ var result = this.opts.validate(this.getFiles(), this, this._asyncContext());
3878
+ if (result === false) return this.opts.messages.generic;
3879
+ if (typeof result === 'string' && result) return result;
3880
+ if (isThenable(result)) return result;
3881
+ }
3882
+ return '';
3351
3883
  };
3352
3884
 
3353
3885
  ZidanFileUpload.prototype._validate = function () {
@@ -3384,7 +3916,9 @@
3384
3916
  }
3385
3917
 
3386
3918
  this.fileError = error;
3387
- if (input.setCustomValidity) input.setCustomValidity(error || '');
3919
+ if (input.setCustomValidity) {
3920
+ input.setCustomValidity(this.pending ? (messages.pending || FIELD_MESSAGES.pending) : (error || ''));
3921
+ }
3388
3922
  var shown = error || this._nativeError();
3389
3923
  if (shown) this.setError(shown);
3390
3924
  else if (this.errorMessage) this.setError(null);
@@ -3472,6 +4006,7 @@
3472
4006
  var state = self._stateFor(file, false) || { status: 'idle', progress: 0, error: '', result: null };
3473
4007
  var item = el('li', 'zs-file-item');
3474
4008
  item.setAttribute('data-zs-upload-state', state.status);
4009
+ item.setAttribute('data-zs-file-index', String(index));
3475
4010
 
3476
4011
  var thumb = el('span', 'zs-file-thumb');
3477
4012
  if (/^image\//.test(file.type)) {
@@ -3521,30 +4056,15 @@
3521
4056
  if (state.status === 'uploading') {
3522
4057
  var cancel = el('button', 'zs-file-cancel', { type: 'button', 'aria-label': 'Cancel upload of ' + file.name });
3523
4058
  cancel.textContent = opts.cancelLabel || 'Cancel';
3524
- self.on(cancel, 'click', function (event) {
3525
- event.preventDefault();
3526
- event.stopPropagation();
3527
- self.cancelUpload(file);
3528
- });
3529
4059
  actions.appendChild(cancel);
3530
4060
  } else if (state.status === 'error' || state.status === 'canceled') {
3531
4061
  var retry = el('button', 'zs-file-retry', { type: 'button', 'aria-label': 'Retry upload of ' + file.name });
3532
4062
  retry.textContent = opts.retryLabel || 'Retry';
3533
- self.on(retry, 'click', function (event) {
3534
- event.preventDefault();
3535
- event.stopPropagation();
3536
- self.retryUpload(file);
3537
- });
3538
4063
  actions.appendChild(retry);
3539
4064
  }
3540
4065
 
3541
4066
  var remove = el('button', 'zs-file-remove', { type: 'button', 'aria-label': 'Remove ' + file.name });
3542
4067
  remove.textContent = '\u00d7';
3543
- self.on(remove, 'click', function (event) {
3544
- event.preventDefault();
3545
- event.stopPropagation();
3546
- self.removeFile(file);
3547
- });
3548
4068
  actions.appendChild(remove);
3549
4069
 
3550
4070
  item.appendChild(thumb);
@@ -3611,6 +4131,14 @@
3611
4131
  var self = this;
3612
4132
  if (!this.hasUploader) return this;
3613
4133
  if (!this._validate()) return this;
4134
+ var check = this.validate();
4135
+ if (isThenable(check)) {
4136
+ return check.then(function (valid) {
4137
+ if (valid && !self.destroyed) self.getFiles().forEach(function (file) { self.uploadFile(file); });
4138
+ return valid;
4139
+ });
4140
+ }
4141
+ if (!check) return this;
3614
4142
  this.getFiles().forEach(function (file) { self.uploadFile(file); });
3615
4143
  return this;
3616
4144
  };
@@ -3893,8 +4421,10 @@
3893
4421
  iso = String(iso).toUpperCase();
3894
4422
  var country = PHONE_COUNTRIES[iso];
3895
4423
  if (!country) return;
4424
+ /* ISO + dial only: Windows renders flag emoji as the two ISO letters,
4425
+ which duplicated the code ("GB GB +44"). */
3896
4426
  var optionNode = el('option', null, { value: iso },
3897
- (country.flag ? country.flag + ' ' : '') + iso + ' +' + country.dial);
4427
+ iso + ' +' + country.dial);
3898
4428
  countrySelect.appendChild(optionNode);
3899
4429
  });
3900
4430
  countrySelect.value = phoneCountry;
@@ -3979,12 +4509,23 @@
3979
4509
  if (isRange) {
3980
4510
  var rangeVariant = pickList(fieldOption(input, opts, 'rangeVariant', 'range-variant', 'default'), RANGE_VARIANTS, 'default');
3981
4511
  var rangeBubbleOn = fieldBool(input, opts, 'rangeBubble', 'range-bubble', true);
4512
+ var rangeBubbleMode = pickList(fieldOption(input, opts, 'rangeBubbleMode', 'range-bubble-mode', 'always'), RANGE_BUBBLE_MODES, 'always');
4513
+ var rangeBubblePosition = pickList(fieldOption(input, opts, 'rangeBubblePosition', 'range-bubble-position', 'top'), RANGE_BUBBLE_POSITIONS, 'top');
4514
+ var rangeFillOn = fieldBool(input, opts, 'rangeFill', 'range-fill', true);
3982
4515
  var rangeScaleOn = fieldBool(input, opts, 'rangeMinMax', 'range-minmax', true);
4516
+ var showBubble = rangeBubbleOn && rangeBubbleMode !== 'never';
4517
+ var bubbleVisible = showBubble && rangeVariant !== 'minimal';
3983
4518
  rangeWrap = el('div', 'zs-range');
3984
4519
  rangeWrap.setAttribute('data-zs-range', rangeVariant);
3985
- if (rangeBubbleOn) {
4520
+ rangeWrap.classList.toggle('zs-range--fill-off', !rangeFillOn);
4521
+ rangeWrap.classList.toggle('zs-range--no-bubble', !bubbleVisible);
4522
+ if (showBubble) {
3986
4523
  rangeBubble = el('output', 'zs-range-bubble', { for: this.id, 'aria-hidden': 'true' });
3987
4524
  rangeWrap.appendChild(rangeBubble);
4525
+ if (bubbleVisible) {
4526
+ rangeWrap.classList.toggle('zs-range--bubble-active', rangeBubbleMode === 'active');
4527
+ rangeWrap.classList.toggle('zs-range--bubble-bottom', rangeBubblePosition === 'bottom');
4528
+ }
3988
4529
  }
3989
4530
  rangeWrap.appendChild(input);
3990
4531
  rangeTicksEl = el('div', 'zs-range-ticks', { 'aria-hidden': 'true' });
@@ -4002,7 +4543,11 @@
4002
4543
  this.rangeTicksEl = rangeTicksEl;
4003
4544
  this.rangeScale = rangeScale;
4004
4545
  this.rangeFormat = opts.rangeFormat || input.getAttribute('data-zidan-range-format') || null;
4005
- this.rangeTicksOption = fieldOption(input, opts, 'rangeTicks', 'range-ticks', 0);
4546
+ this.rangeBubbleMode = rangeBubbleMode;
4547
+ this.rangeBubblePosition = rangeBubblePosition;
4548
+ this.rangeMinLabel = String(fieldOption(input, opts, 'rangeMinLabel', 'range-min-label', ''));
4549
+ this.rangeMaxLabel = String(fieldOption(input, opts, 'rangeMaxLabel', 'range-max-label', ''));
4550
+ this.rangeTicksOption = parseRangeTicks(fieldOption(input, opts, 'rangeTicks', 'range-ticks', 0));
4006
4551
  this.rangeTickLabels = fieldBool(input, opts, 'rangeTickLabels', 'range-tick-labels', false);
4007
4552
  this.rangeLabelMap = opts.rangeLabels || null;
4008
4553
  this.rangeSignature = '';
@@ -4222,7 +4767,8 @@
4222
4767
 
4223
4768
  var outputSelector = opts.output || input.getAttribute('data-zidan-output');
4224
4769
  if (isRange && outputSelector) {
4225
- var out = doc.querySelector(outputSelector);
4770
+ var out = null;
4771
+ try { out = doc.querySelector(outputSelector); } catch (err) { out = null; }
4226
4772
  if (out) {
4227
4773
  this.rangeOutput = out;
4228
4774
  }
@@ -4260,17 +4806,13 @@
4260
4806
  ZidanTextField.prototype.constructor = ZidanTextField;
4261
4807
 
4262
4808
  // phone/date/custom rules must also block native form submission
4263
- ZidanTextField.prototype._mirrorValidity = function () {
4809
+ ZidanTextField.prototype._setCustomValidity = function (message) {
4264
4810
  var input = this.el;
4265
- if (input.setCustomValidity) {
4266
- var custom = this._customError();
4267
- var message = typeof custom === 'string' ? custom : (custom ? this.opts.messages.generic : '');
4268
- if (input.__zidanCustomError !== message) {
4269
- input.setCustomValidity(message);
4270
- input.__zidanCustomError = message;
4271
- }
4811
+ if (!input.setCustomValidity) return;
4812
+ if (input.__zidanCustomError !== message) {
4813
+ input.setCustomValidity(message);
4814
+ input.__zidanCustomError = message;
4272
4815
  }
4273
- return ZidanFieldBase.prototype._mirrorValidity.call(this);
4274
4816
  };
4275
4817
 
4276
4818
  ZidanTextField.prototype._formatRangeValue = function (value) {
@@ -4298,28 +4840,45 @@
4298
4840
  return { min: min, max: max };
4299
4841
  };
4300
4842
 
4843
+ ZidanTextField.prototype._rangeLabelFor = function (value) {
4844
+ if (this.rangeLabelMap && this.rangeLabelMap[value] !== undefined) {
4845
+ return String(this.rangeLabelMap[value]);
4846
+ }
4847
+ return this._formatRangeValue(value);
4848
+ };
4849
+
4301
4850
  ZidanTextField.prototype._renderRangeTicks = function () {
4302
4851
  if (!this.rangeTicksEl) return;
4303
4852
  var bounds = this._rangeBounds();
4304
4853
  var option = this.rangeTicksOption;
4854
+ var labelsOn = !!this.rangeTickLabels;
4855
+ this.rangeTicksEl.textContent = '';
4305
4856
  var values = [];
4306
- if (Array.isArray(option)) values = option.map(Number).filter(function (n) { return isFinite(n); });
4307
- else {
4857
+ if (Array.isArray(option)) {
4858
+ values = option.map(Number).filter(function (n) { return isFinite(n); });
4859
+ } else {
4308
4860
  var count = parseInt(option, 10);
4309
- if (!(count > 1)) return;
4310
- for (var i = 0; i < count; i += 1) values.push(bounds.min + ((bounds.max - bounds.min) * i) / (count - 1));
4861
+ if (count > 1) {
4862
+ for (var i = 0; i < count; i += 1) values.push(bounds.min + ((bounds.max - bounds.min) * i) / (count - 1));
4863
+ }
4311
4864
  }
4312
- this.rangeTicksEl.textContent = '';
4865
+ /* Labeled ticks at both ends replace the min/max scale, so the start and end
4866
+ numbers are printed once instead of twice. */
4867
+ var coversEnds = labelsOn && !!this.rangeScale && values.length > 0 &&
4868
+ values.indexOf(bounds.min) !== -1 && values.indexOf(bounds.max) !== -1;
4869
+ if (this.rangeScale) this.rangeScale.classList.toggle('zs-range-scale--hidden', coversEnds);
4870
+ /* with no scale row, tick labels need their own room so they cannot overlap
4871
+ whatever follows the range */
4872
+ this.range.classList.toggle('zs-range--labels-no-scale', labelsOn && !this.rangeScale && values.length > 0);
4313
4873
  values.forEach(function (value) {
4314
4874
  var pct = bounds.max > bounds.min ? (value - bounds.min) / (bounds.max - bounds.min) : 0;
4315
4875
  var tick = el('span', 'zs-range-tick');
4316
- tick.style.left = (clamp(pct, 0, 1) * 100).toFixed(2) + '%';
4317
- if (this.rangeTickLabels) {
4318
- var label = this.rangeLabelMap && this.rangeLabelMap[value] !== undefined
4319
- ? this.rangeLabelMap[value]
4320
- : this._formatRangeValue(value);
4321
- tick.textContent = label;
4876
+ tick.style.setProperty('--zs-range-tick-pct', (clamp(pct, 0, 1) * 100).toFixed(2) + '%');
4877
+ if (labelsOn) {
4878
+ tick.textContent = this._rangeLabelFor(value);
4322
4879
  tick.classList.add('zs-range-tick--labeled');
4880
+ if (pct <= 0) tick.classList.add('zs-range-tick--start');
4881
+ else if (pct >= 1) tick.classList.add('zs-range-tick--end');
4323
4882
  }
4324
4883
  this.rangeTicksEl.appendChild(tick);
4325
4884
  }, this);
@@ -4334,12 +4893,24 @@
4334
4893
  pct = clamp(pct, 0, 1);
4335
4894
  this.range.style.setProperty('--zs-range-pct', pct.toFixed(4));
4336
4895
  this.range.style.setProperty('--zs-range-fill', (pct * 100).toFixed(2) + '%');
4337
- if (this.rangeBubble) this.rangeBubble.textContent = this._formatRangeValue(numeric);
4338
- if (this.rangeScale) {
4339
- this.rangeScale.firstChild.textContent = this._formatRangeValue(bounds.min);
4340
- this.rangeScale.lastChild.textContent = this._formatRangeValue(bounds.max);
4896
+ if (this.rangeBubble) {
4897
+ this.rangeBubble.textContent = this._formatRangeValue(numeric);
4898
+ /* at the ends, align the bubble inside the track instead of half outside it */
4899
+ this.rangeBubble.classList.toggle('zs-range-bubble--start', pct <= 0);
4900
+ this.rangeBubble.classList.toggle('zs-range-bubble--end', pct >= 1);
4341
4901
  }
4342
- var signature = [bounds.min, bounds.max, this.el.step, JSON.stringify(this.rangeTicksOption), this.rangeTickLabels].join('|');
4902
+ if (this.rangeScale) {
4903
+ this.rangeScale.firstChild.textContent = this.rangeMinLabel || this._formatRangeValue(bounds.min);
4904
+ this.rangeScale.lastChild.textContent = this.rangeMaxLabel || this._formatRangeValue(bounds.max);
4905
+ }
4906
+ /* the formatted value is what the user sees and what assistive tech should read */
4907
+ if (this.rangeFormat) this.el.setAttribute('aria-valuetext', this._formatRangeValue(numeric));
4908
+ else this.el.removeAttribute('aria-valuetext');
4909
+ var signature = [
4910
+ bounds.min, bounds.max, this.el.step, JSON.stringify(this.rangeTicksOption), this.rangeTickLabels,
4911
+ JSON.stringify(this.rangeLabelMap || null), this.rangeMinLabel, this.rangeMaxLabel,
4912
+ String(this.rangeFormat || '')
4913
+ ].join('|');
4343
4914
  if (signature !== this.rangeSignature) {
4344
4915
  this.rangeSignature = signature;
4345
4916
  this._renderRangeTicks();
@@ -4349,8 +4920,9 @@
4349
4920
  ZidanTextField.prototype._syncRangeOutput = function (value) {
4350
4921
  if (this.range) this._syncRange(value);
4351
4922
  if (this.rangeOutput) {
4352
- this.rangeOutput.textContent = value;
4353
- this.rangeOutput.value = value;
4923
+ var display = this.range ? this._formatRangeValue(value) : value;
4924
+ this.rangeOutput.textContent = display;
4925
+ this.rangeOutput.value = display;
4354
4926
  }
4355
4927
  };
4356
4928
 
@@ -4514,16 +5086,18 @@
4514
5086
  if (blocked) return messages.dateDisabled;
4515
5087
  }
4516
5088
  if (typeof opts.validateDate === 'function') {
4517
- var dateResult = opts.validateDate(input.value, date, this);
5089
+ var dateResult = opts.validateDate(input.value, date, this, this._asyncContext());
4518
5090
  if (dateResult === false) return messages.date;
4519
5091
  if (typeof dateResult === 'string' && dateResult) return dateResult;
5092
+ if (isThenable(dateResult)) return dateResult;
4520
5093
  }
4521
5094
  }
4522
5095
 
4523
5096
  if (typeof opts.validate === 'function') {
4524
- var result = opts.validate(input.value, this);
5097
+ var result = opts.validate(input.value, this, this._asyncContext());
4525
5098
  if (result === false) return messages.generic;
4526
5099
  if (typeof result === 'string' && result) return result;
5100
+ if (isThenable(result)) return result;
4527
5101
  }
4528
5102
  return '';
4529
5103
  };
@@ -4543,8 +5117,9 @@
4543
5117
  }
4544
5118
  if (this.range) this._syncRange(value);
4545
5119
  if (this.rangeOutput) {
4546
- this.rangeOutput.textContent = value;
4547
- this.rangeOutput.value = value;
5120
+ var display = this.range ? this._formatRangeValue(value) : value;
5121
+ this.rangeOutput.textContent = display;
5122
+ this.rangeOutput.value = display;
4548
5123
  }
4549
5124
  if (this.stepper) {
4550
5125
  var min = parseFloat(input.min);
@@ -4568,6 +5143,7 @@
4568
5143
  };
4569
5144
 
4570
5145
  ZidanTextField.prototype._teardown = function () {
5146
+ if (this.range) this.el.removeAttribute('aria-valuetext');
4571
5147
  if (this._restoreInput) this._restoreInput();
4572
5148
  };
4573
5149
 
@@ -4633,7 +5209,11 @@
4633
5209
  // (output, counter, clearable, …) work without a data attribute
4634
5210
  var kind = fieldKindFor(node) || inferredTextKind(node);
4635
5211
  if (!kind) return;
4636
- if (kind === 'radio' && !node.hasAttribute('data-zidan-radio')) {
5212
+ if (kind === 'radio' || kind === 'radio-group') {
5213
+ if (/^INPUT$/i.test(node.tagName)) {
5214
+ node = node.closest ? node.closest('fieldset, [data-zidan-radio-group]') : null;
5215
+ if (!node) return;
5216
+ }
4637
5217
  kind = 'radio-group';
4638
5218
  }
4639
5219
  var instance = createField(node, kind, options || {});
@@ -4648,7 +5228,13 @@
4648
5228
  if (!isElement(node) || node.__zidanField) return;
4649
5229
  var kind = fieldKindFor(node);
4650
5230
  if (!kind) return;
4651
- if (kind === 'radio') kind = 'radio-group';
5231
+ if (kind === 'radio' || kind === 'radio-group') {
5232
+ if (/^INPUT$/i.test(node.tagName)) {
5233
+ node = node.closest ? node.closest('fieldset, [data-zidan-radio-group]') : null;
5234
+ if (!node) return;
5235
+ }
5236
+ kind = 'radio-group';
5237
+ }
4652
5238
  var instance = createField(node, kind, options || {});
4653
5239
  if (instance) instances.push(instance);
4654
5240
  });
@@ -4753,6 +5339,7 @@
4753
5339
  ZidanSelect.frameworks = FRAMEWORKS.slice();
4754
5340
  ZidanSelect.scrollbars = SCROLLBARS.slice();
4755
5341
  ZidanSelect.defaults = DEFAULTS;
5342
+ ZidanSelect.cacheLimit = 50;
4756
5343
  ZidanSelect.get = function (target) {
4757
5344
  var element = typeof target === 'string' ? doc.querySelector(target) : target;
4758
5345
  if (!isElement(element)) return null;