zidan-select 2.2.3 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/zidan-form.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * ZidanForm v2.2.3
2
+ * ZidanForm v2.3.0
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.3';
35
+ var VERSION = '2.3.0';
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
 
@@ -616,6 +649,10 @@
616
649
  minChars: 0,
617
650
  allowFreeText: false,
618
651
  searchValues: true,
652
+ fetchPageSize: 0, // >0 enables paged fetchOptions({items, hasMore})
653
+ autoLoadMore: true,
654
+ cacheResults: true,
655
+ loadMoreText: 'Load more',
619
656
  /* tags */
620
657
  maxTags: Infinity,
621
658
  minTagLength: 1,
@@ -644,6 +681,7 @@
644
681
  onClose: null,
645
682
  onTagAdd: null,
646
683
  onTagRemove: null,
684
+ onLoadMore: null,
647
685
  onError: null
648
686
  };
649
687
 
@@ -684,6 +722,14 @@
684
722
  this.rendered = [];
685
723
  this.listeners = new Map();
686
724
  this.asyncController = null;
725
+ this.asyncItems = null;
726
+ this.asyncQuery = '';
727
+ this.asyncPage = 0;
728
+ this.hasMore = false;
729
+ this.fetchingMore = false;
730
+ this.loadMoreError = null;
731
+ this._fetchCache = Object.create(null);
732
+ this._cacheKeys = [];
687
733
  this.timer = null;
688
734
  this.savedInputText = '';
689
735
  this.disabled_ = !!this.opts.disabled;
@@ -760,6 +806,10 @@
760
806
  merged.validation = pick('validation', d.zidanValidation || null);
761
807
  merged.options = pick('options', null);
762
808
  merged.suggestions = pick('suggestions', null);
809
+ merged.fetchPageSize = pick('fetchPageSize', d.zidanFetchPageSize ? parseInt(d.zidanFetchPageSize, 10) || 0 : DEFAULTS.fetchPageSize);
810
+ merged.autoLoadMore = pick('autoLoadMore', readBoolAttr(d.zidanAutoLoadMore, DEFAULTS.autoLoadMore));
811
+ merged.cacheResults = pick('cacheResults', readBoolAttr(d.zidanCacheResults, DEFAULTS.cacheResults));
812
+ merged.loadMoreText = pick('loadMoreText', d.zidanLoadMoreText || DEFAULTS.loadMoreText);
763
813
 
764
814
  // carry over every explicitly-passed option (callbacks, custom classes, ...)
765
815
  Object.keys(options).forEach(function (key) {
@@ -906,6 +956,7 @@
906
956
  rootEl.setAttribute('data-zs-framework', this.framework);
907
957
  rootEl.setAttribute('data-zs-mode', this.mode);
908
958
  rootEl.setAttribute('data-zs-scrollbar', opts.scrollbar || 'default');
959
+ if (isRtl(this.el)) rootEl.setAttribute('dir', 'rtl');
909
960
  rootEl.classList.add('zs-root--' + this.mode);
910
961
  if (this.mode === 'tags') rootEl.classList.add('zs-root--multiple');
911
962
  if (opts.multiple && this.mode === 'select') rootEl.classList.add('zs-root--multiple');
@@ -1341,8 +1392,11 @@
1341
1392
  var query = this.query.trim();
1342
1393
  var source = this._sourceItems();
1343
1394
  var isCaseSensitive = !!this.opts.caseSensitive;
1395
+ var remote = typeof this.opts.fetchOptions === 'function' && !!this.asyncItems;
1344
1396
 
1345
1397
  if (!query) return source.slice();
1398
+ // the server already filtered this page; only an explicit filterOption re-checks it
1399
+ if (remote && typeof this.opts.filterOption !== 'function') return source.slice();
1346
1400
 
1347
1401
  return source.filter(function (item) {
1348
1402
  if (typeof self.opts.filterOption === 'function') {
@@ -1440,6 +1494,20 @@
1440
1494
  self.dropdown.appendChild(option);
1441
1495
  });
1442
1496
  }
1497
+
1498
+ if (this.hasMore) {
1499
+ var more = el('button', 'zs-more', { type: 'button' });
1500
+ if (this.fetchingMore) {
1501
+ more.appendChild(el('span', 'zs-spinner', { 'aria-hidden': 'true' }));
1502
+ more.appendChild(el('span', null, null, this.opts.loadingText || 'Loading…'));
1503
+ more.disabled = true;
1504
+ more.setAttribute('aria-busy', 'true');
1505
+ } else {
1506
+ more.textContent = this.loadMoreError || this.opts.loadMoreText;
1507
+ if (this.loadMoreError) more.classList.add('zs-more--error');
1508
+ }
1509
+ this.dropdown.appendChild(more);
1510
+ }
1443
1511
  }
1444
1512
 
1445
1513
  this.dropdown.scrollTop = scrollTop;
@@ -1493,6 +1561,8 @@
1493
1561
  this.opened = true;
1494
1562
  this.query = '';
1495
1563
  this.activeIndex = -1;
1564
+ this.loadMoreError = null;
1565
+ this.fetchingMore = false;
1496
1566
  if (this.mode === 'combobox' || (this.mode === 'select' && this.opts.searchable)) {
1497
1567
  this.savedInputText = this.input.value;
1498
1568
  }
@@ -1504,7 +1574,7 @@
1504
1574
  this.emit('open', { instance: this });
1505
1575
  this.call('onOpen', { instance: this });
1506
1576
 
1507
- if (typeof this.opts.fetchOptions === 'function' && !this.asyncItems) {
1577
+ if (typeof this.opts.fetchOptions === 'function' && (!this.asyncItems || this.asyncQuery !== '')) {
1508
1578
  this._fetch('');
1509
1579
  } else if (this.mode !== 'tags') {
1510
1580
  var first = this._firstEnabledIndex();
@@ -1532,6 +1602,15 @@
1532
1602
  this.dropdown.removeAttribute('data-zs-visible');
1533
1603
  this.activeIndex = -1;
1534
1604
  this.query = '';
1605
+ if (typeof this.opts.fetchOptions === 'function') {
1606
+ if (this.asyncController) {
1607
+ this.asyncController.abort();
1608
+ this.asyncController = null;
1609
+ }
1610
+ this.loading = false;
1611
+ this.fetchingMore = false;
1612
+ this.loadMoreError = null;
1613
+ }
1535
1614
  this._render();
1536
1615
  this.emit('close', { instance: this });
1537
1616
  this.call('onClose', { instance: this });
@@ -1601,54 +1680,205 @@
1601
1680
 
1602
1681
  /* ---------------- async loading ---------------- */
1603
1682
 
1604
- ZidanSelect.prototype._fetch = function (query) {
1683
+ ZidanSelect.prototype._cacheKey = function (query, page) {
1684
+ return query + '\u0000' + page;
1685
+ };
1686
+
1687
+ ZidanSelect.prototype._cacheGet = function (query, page) {
1688
+ if (!this.opts.cacheResults) return null;
1689
+ var key = this._cacheKey(query, page);
1690
+ var entry = this._fetchCache[key];
1691
+ if (!entry) return null;
1692
+ var index = this._cacheKeys.indexOf(key);
1693
+ if (index !== -1) {
1694
+ this._cacheKeys.splice(index, 1);
1695
+ this._cacheKeys.push(key);
1696
+ }
1697
+ return entry;
1698
+ };
1699
+
1700
+ ZidanSelect.prototype._cacheSet = function (query, page, entry) {
1701
+ if (!this.opts.cacheResults) return;
1702
+ var key = this._cacheKey(query, page);
1703
+ this._fetchCache[key] = entry;
1704
+ var index = this._cacheKeys.indexOf(key);
1705
+ if (index !== -1) this._cacheKeys.splice(index, 1);
1706
+ this._cacheKeys.push(key);
1707
+ var limit = ZidanSelect.cacheLimit || 50;
1708
+ while (this._cacheKeys.length > limit) {
1709
+ delete this._fetchCache[this._cacheKeys.shift()];
1710
+ }
1711
+ };
1712
+
1713
+ ZidanSelect.prototype.clearCache = function () {
1714
+ this._fetchCache = Object.create(null);
1715
+ this._cacheKeys = [];
1716
+ return this;
1717
+ };
1718
+
1719
+ ZidanSelect.prototype._readFetchPayload = function (result, page, pageSize) {
1720
+ var rows = result;
1721
+ var hasMore = false;
1722
+ if (result && !Array.isArray(result) && typeof result === 'object') {
1723
+ rows = result.items || result.options || result.results || [];
1724
+ if (result.hasMore !== undefined) {
1725
+ hasMore = !!result.hasMore;
1726
+ } else if (result.total !== undefined && pageSize > 0) {
1727
+ hasMore = (page + 1) * pageSize < Number(result.total);
1728
+ } else if (pageSize > 0) {
1729
+ hasMore = toArray(rows).length >= pageSize;
1730
+ }
1731
+ } else if (pageSize > 0) {
1732
+ hasMore = toArray(rows).length >= pageSize;
1733
+ }
1734
+ return { items: this._normalizeItems(rows), hasMore: hasMore };
1735
+ };
1736
+
1737
+ ZidanSelect.prototype._applyCachedPage = function (query, page, append) {
1738
+ var cached = this._cacheGet(query, page);
1739
+ if (!cached) return false;
1740
+ this.loading = false;
1741
+ this.fetchingMore = false;
1742
+ this.loadMoreError = null;
1743
+ this.error = null;
1744
+ this.asyncQuery = query;
1745
+ this.asyncPage = page;
1746
+ this.asyncItems = append ? (this.asyncItems || []).concat(cached.items) : cached.items.slice();
1747
+ this.hasMore = !!cached.hasMore;
1748
+ if (!append) this.activeIndex = -1;
1749
+ this._renderDropdown();
1750
+ return true;
1751
+ };
1752
+
1753
+ /* page 0 replaces the result set; later pages append (remote pagination) */
1754
+ ZidanSelect.prototype._fetch = function (query, page, append) {
1605
1755
  var self = this;
1606
- if (typeof this.opts.fetchOptions !== 'function') return;
1756
+ if (typeof this.opts.fetchOptions !== 'function') return Promise.resolve([]);
1607
1757
  query = query === undefined || query === null ? '' : String(query);
1758
+ page = page === undefined || page === null ? 0 : parseInt(page, 10) || 0;
1759
+ append = !!append;
1760
+ if (append && (this.loading || this.fetchingMore || !this.hasMore)) return Promise.resolve([]);
1761
+
1762
+ var cached = this._cacheGet(query, page);
1763
+ if (cached && (append ? this.hasMore : true)) {
1764
+ if (this.asyncController) this.asyncController.abort();
1765
+ this.asyncController = null;
1766
+ this._applyCachedPage(query, page, append);
1767
+ return Promise.resolve(this._visibleItems());
1768
+ }
1608
1769
 
1609
1770
  if (this.asyncController) this.asyncController.abort();
1610
1771
  var controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
1611
1772
  this.asyncController = controller;
1612
- this.loading = true;
1773
+ this.loading = !append;
1774
+ this.fetchingMore = append;
1613
1775
  this.error = null;
1776
+ this.loadMoreError = null;
1777
+ if (!append) {
1778
+ this.hasMore = false;
1779
+ this.asyncPage = 0;
1780
+ this.announce(this.opts.loadingText);
1781
+ }
1614
1782
  this._renderDropdown();
1615
- this.announce(this.opts.loadingText);
1616
1783
 
1784
+ var settleFetch;
1785
+ var fetchPromise = new Promise(function (resolve) { settleFetch = resolve; });
1786
+ if (controller && controller.signal.addEventListener) {
1787
+ controller.signal.addEventListener('abort', function () { settleFetch([]); });
1788
+ }
1789
+
1790
+ if (append) {
1791
+ this.emit('load-more', { page: page, query: query, instance: this });
1792
+ this.call('onLoadMore', { page: page, query: query, instance: this });
1793
+ }
1794
+
1795
+ var pageSize = this.opts.fetchPageSize > 0 ? this.opts.fetchPageSize : 0;
1617
1796
  var done = function (result) {
1797
+ if (controller && controller.signal.aborted) return;
1618
1798
  self.loading = false;
1619
- self.asyncItems = self._normalizeItems(result || []);
1620
- self.activeIndex = -1;
1799
+ self.fetchingMore = false;
1800
+ self.loadMoreError = null;
1801
+ self.error = null;
1802
+ var payload = self._readFetchPayload(result, page, pageSize);
1803
+ self.asyncQuery = query;
1804
+ self.asyncPage = page;
1805
+ self.asyncItems = append ? (self.asyncItems || []).concat(payload.items) : payload.items;
1806
+ self.hasMore = payload.hasMore;
1807
+ self._cacheSet(query, page, { items: payload.items, hasMore: payload.hasMore });
1808
+ if (!append) self.activeIndex = -1;
1621
1809
  self._renderDropdown();
1622
1810
  var count = self._visibleItems().length;
1623
1811
  self.announce(count + ' result' + (count === 1 ? '' : 's'));
1812
+ settleFetch(self._visibleItems());
1624
1813
  };
1625
1814
  var fail = function (err) {
1815
+ if (err && err.name === 'AbortError') {
1816
+ settleFetch([]);
1817
+ return;
1818
+ }
1819
+ if (controller && controller.signal.aborted) {
1820
+ settleFetch([]);
1821
+ return;
1822
+ }
1823
+ var message = (err && err.message) || 'Unable to load options.';
1626
1824
  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 });
1825
+ self.fetchingMore = false;
1826
+ if (append) self.loadMoreError = message;
1827
+ else self.error = { message: message };
1828
+ self.emit('error', { error: err, message: message, instance: self });
1829
+ self.call('onError', { error: err, message: message, instance: self });
1630
1830
  self._renderDropdown();
1831
+ settleFetch([]);
1631
1832
  };
1632
1833
 
1633
1834
  try {
1634
- var result = this.opts.fetchOptions(query, controller ? controller.signal : undefined);
1835
+ var result = this.opts.fetchOptions(query, controller ? controller.signal : undefined, {
1836
+ page: page,
1837
+ pageSize: pageSize,
1838
+ append: append,
1839
+ instance: this
1840
+ });
1635
1841
  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
- });
1842
+ result.then(done).catch(fail);
1644
1843
  } else {
1645
1844
  done(result);
1646
1845
  }
1647
1846
  } catch (err) {
1648
- if (err && err.name === 'AbortError') return;
1649
1847
  fail(err);
1650
1848
  }
1651
- void self;
1849
+ return fetchPromise;
1850
+ };
1851
+
1852
+ ZidanSelect.prototype.loadMore = function () {
1853
+ if (typeof this.opts.fetchOptions !== 'function') return this;
1854
+ if (this.loading || this.fetchingMore || !this.hasMore) return this;
1855
+ return this._fetch(this.asyncQuery || this.query || '', this.asyncPage + 1, true);
1856
+ };
1857
+
1858
+ ZidanSelect.prototype.hasMoreResults = function () {
1859
+ return !!this.hasMore;
1860
+ };
1861
+
1862
+ ZidanSelect.prototype.getAsyncState = function () {
1863
+ return {
1864
+ query: this.asyncQuery,
1865
+ page: this.asyncPage,
1866
+ hasMore: !!this.hasMore,
1867
+ loading: !!this.loading,
1868
+ fetchingMore: !!this.fetchingMore,
1869
+ error: this.error ? this.error.message : null
1870
+ };
1871
+ };
1872
+
1873
+ ZidanSelect.prototype.refreshOptions = function () {
1874
+ this.clearCache();
1875
+ if (typeof this.opts.fetchOptions !== 'function') return this;
1876
+ this.asyncItems = null;
1877
+ this.asyncQuery = '';
1878
+ this.asyncPage = 0;
1879
+ this.hasMore = false;
1880
+ if (this.opened) return this._fetch(this.query, 0, false);
1881
+ return this;
1652
1882
  };
1653
1883
 
1654
1884
  /* ---------------- tags ---------------- */
@@ -2005,6 +2235,13 @@
2005
2235
  };
2006
2236
 
2007
2237
  this.onDropdownClick = function (event) {
2238
+ var more = event.target.closest ? event.target.closest('.zs-more') : null;
2239
+ if (more) {
2240
+ event.preventDefault();
2241
+ event.stopPropagation();
2242
+ self.loadMore();
2243
+ return;
2244
+ }
2008
2245
  var option = event.target.closest ? event.target.closest('[data-zs-option]') : null;
2009
2246
  if (!option) return;
2010
2247
  event.preventDefault();
@@ -2028,6 +2265,13 @@
2028
2265
  if (self.opened) self._position();
2029
2266
  };
2030
2267
 
2268
+ this.onDropdownScroll = function () {
2269
+ if (!self.opts.autoLoadMore || !self.opened || !self.hasMore) return;
2270
+ if (self.loading || self.fetchingMore) return;
2271
+ var node = self.dropdown;
2272
+ if (node.scrollTop + node.clientHeight >= node.scrollHeight - 24) self.loadMore();
2273
+ };
2274
+
2031
2275
  this.debouncedFetch = debounce(function (query) { self._fetch(query); }, this.opts.debounce);
2032
2276
 
2033
2277
  if (this.el && this.el.addEventListener) {
@@ -2048,6 +2292,7 @@
2048
2292
  this.clearBtn.addEventListener('click', this.onClearClick);
2049
2293
  this.dropdown.addEventListener('mousedown', this.onDropdownMouseDown);
2050
2294
  this.dropdown.addEventListener('click', this.onDropdownClick);
2295
+ this.dropdown.addEventListener('scroll', this.onDropdownScroll);
2051
2296
  doc.addEventListener('pointerdown', this.onDocumentPointerDown, true);
2052
2297
  global.addEventListener('resize', this.onWindowResize);
2053
2298
  };
@@ -2135,6 +2380,10 @@
2135
2380
  }
2136
2381
  }
2137
2382
  this.asyncItems = null;
2383
+ this.asyncPage = 0;
2384
+ this.hasMore = false;
2385
+ this.loadMoreError = null;
2386
+ this.clearCache();
2138
2387
  this.activeIndex = -1;
2139
2388
  this._render();
2140
2389
  this._syncNative();
@@ -2267,6 +2516,7 @@
2267
2516
 
2268
2517
  if (this.debouncedFetch) this.debouncedFetch.cancel();
2269
2518
  if (this.asyncController) this.asyncController.abort();
2519
+ this.clearCache();
2270
2520
  if (this.resizeObserver) this.resizeObserver.disconnect();
2271
2521
  if (this.form && this.onFormReset) this.form.removeEventListener('reset', this.onFormReset);
2272
2522
 
@@ -2351,6 +2601,9 @@
2351
2601
  this.validation = null;
2352
2602
  this.errorMessage = null;
2353
2603
  this.errorEl = null;
2604
+ this.pending = false;
2605
+ this._asyncToken = 0;
2606
+ this._asyncController = null;
2354
2607
  this.destroyed = false;
2355
2608
  this._listeners = [];
2356
2609
  this._cleanups = [];
@@ -2391,6 +2644,7 @@
2391
2644
  root.id = this.id + '-field';
2392
2645
  root.setAttribute('data-zs-kind', kind);
2393
2646
  root.classList.add('zs-field--' + kind);
2647
+ if (isRtl(this.el)) root.setAttribute('dir', 'rtl');
2394
2648
  this._applyScope(root);
2395
2649
  this.root = root;
2396
2650
  return root;
@@ -2441,15 +2695,116 @@
2441
2695
  var targets = this.validationTargets();
2442
2696
  for (var i = 0; i < targets.length; i += 1) {
2443
2697
  var input = targets[i];
2444
- if (input && input.validity && !input.validity.valid) return this._messageFor(input);
2698
+ if (hasNativeValidityError(input)) return this._messageFor(input);
2445
2699
  }
2446
2700
  return '';
2447
2701
  };
2448
2702
 
2449
- ZidanFieldBase.prototype._evaluateError = function () {
2703
+ /* subclasses forward this context to async validators so they can abort */
2704
+ ZidanFieldBase.prototype._asyncSignal = function () {
2705
+ return this._asyncController ? this._asyncController.signal : undefined;
2706
+ };
2707
+
2708
+ ZidanFieldBase.prototype._asyncContext = function () {
2709
+ return { signal: this._asyncSignal(), field: this, instance: this };
2710
+ };
2711
+
2712
+ /* text inputs override this to block form submission while pending/invalid */
2713
+ ZidanFieldBase.prototype._setCustomValidity = function () {};
2714
+
2715
+ ZidanFieldBase.prototype._abortAsync = function () {
2716
+ this._asyncToken += 1;
2717
+ if (this._asyncController) {
2718
+ try { this._asyncController.abort(); } catch (err) { /* already settled */ }
2719
+ this._asyncController = null;
2720
+ }
2721
+ };
2722
+
2723
+ /* returns { pending: promise } for async checks, otherwise { error, custom } */
2724
+ ZidanFieldBase.prototype._evaluate = function () {
2725
+ this._abortAsync();
2726
+ if (typeof AbortController !== 'undefined') this._asyncController = new AbortController();
2450
2727
  var custom = this._customError ? this._customError() : '';
2451
- if (custom) return typeof custom === 'string' ? custom : this.opts.messages.generic;
2452
- return this._nativeError();
2728
+ if (isThenable(custom)) return { pending: custom };
2729
+ this._asyncController = null;
2730
+ if (custom) {
2731
+ return { error: typeof custom === 'string' ? custom : this.opts.messages.generic, custom: true };
2732
+ }
2733
+ var native = this._nativeError();
2734
+ return native ? { error: native, custom: false } : {};
2735
+ };
2736
+
2737
+ ZidanFieldBase.prototype._applyValidity = function (message, show, custom) {
2738
+ this._setCustomValidity(message && custom ? message : '');
2739
+ if (message) {
2740
+ if (show) this.setError(message);
2741
+ else this.setValidation('invalid');
2742
+ return this;
2743
+ }
2744
+ if (this.errorMessage) this.setError(null);
2745
+ if (this.validation === 'invalid') this.setValidation(null);
2746
+ return this;
2747
+ };
2748
+
2749
+ ZidanFieldBase.prototype._setPending = function (on) {
2750
+ on = !!on;
2751
+ this.pending = on;
2752
+ if (this.root) {
2753
+ this.root.classList.toggle('zs-field--pending', on);
2754
+ if (on) {
2755
+ this.root.setAttribute('data-zs-validation', 'pending');
2756
+ } else if (this.root.getAttribute('data-zs-validation') === 'pending') {
2757
+ this.root.removeAttribute('data-zs-validation');
2758
+ }
2759
+ }
2760
+ this.validationTargets().forEach(function (input) {
2761
+ if (!input || !input.setAttribute) return;
2762
+ if (on) input.setAttribute('aria-busy', 'true');
2763
+ else input.removeAttribute('aria-busy');
2764
+ }, this);
2765
+ if (on) {
2766
+ if (this.errorMessage) this.setError(null);
2767
+ this._setCustomValidity(this.opts.messages.pending || FIELD_MESSAGES.pending);
2768
+ } else {
2769
+ this._setCustomValidity('');
2770
+ }
2771
+ return this;
2772
+ };
2773
+
2774
+ ZidanFieldBase.prototype._runAsync = function (promise) {
2775
+ var self = this;
2776
+ if (self.destroyed) return Promise.resolve(false);
2777
+ var token = self._asyncToken;
2778
+ self._setPending(true);
2779
+ return Promise.resolve(promise).then(function (value) {
2780
+ if (self.destroyed || token !== self._asyncToken) return false;
2781
+ self._asyncController = null;
2782
+ self._setPending(false);
2783
+ var message = '';
2784
+ if (value === false) message = self.opts.messages.generic;
2785
+ else if (typeof value === 'string') message = value;
2786
+ else if (value instanceof Error) message = value.message || self.opts.messages.generic;
2787
+ self._applyValidity(message, self.touched || self.opts.alwaysValidate || !!message, true);
2788
+ if (!message && self.opts.showValidState) self.setValidation('valid');
2789
+ self.emit('async-validation', { valid: !message, message: message });
2790
+ return !message;
2791
+ }, function (err) {
2792
+ if (self.destroyed || token !== self._asyncToken || (err && err.name === 'AbortError')) return false;
2793
+ self._asyncController = null;
2794
+ self._setPending(false);
2795
+ var message = (err && (err.message || err.error)) || self.opts.messages.generic;
2796
+ if (typeof message !== 'string') message = self.opts.messages.generic;
2797
+ self._applyValidity(message, true, true);
2798
+ self.emit('async-validation', { valid: false, message: message, error: err });
2799
+ return false;
2800
+ });
2801
+ };
2802
+
2803
+ /* convenience: resolves with the async result, false when sync-invalid, true when sync-valid */
2804
+ ZidanFieldBase.prototype.checkAsync = function () {
2805
+ var result = this._evaluate();
2806
+ if (result.pending) return this._runAsync(result.pending);
2807
+ return Promise.resolve(!result.error);
2453
2808
  };
2454
2809
 
2455
2810
  ZidanFieldBase.prototype._syncDescribedBy = function () {
@@ -2517,8 +2872,12 @@
2517
2872
  this.validationTargets().forEach(function (input) {
2518
2873
  self.on(input, 'invalid', function () {
2519
2874
  self.touched = true;
2520
- var message = self._evaluateError();
2521
- if (message) self.setError(message);
2875
+ var result = self._evaluate();
2876
+ if (result.pending) {
2877
+ self._runAsync(result.pending);
2878
+ return;
2879
+ }
2880
+ if (result.error) self.setError(result.error);
2522
2881
  else self.setValidation('invalid');
2523
2882
  });
2524
2883
  self.on(input, 'blur', function () {
@@ -2531,8 +2890,10 @@
2531
2890
  this.on(this.formEl, 'reset', function () {
2532
2891
  global.setTimeout(function () {
2533
2892
  if (self.destroyed) return;
2893
+ self._abortAsync();
2534
2894
  self.touched = false;
2535
2895
  self.errorMessage = null;
2896
+ self._setPending(false);
2536
2897
  if (self.errorEl) {
2537
2898
  self.errorEl.textContent = '';
2538
2899
  self.errorEl.hidden = true;
@@ -2548,25 +2909,27 @@
2548
2909
  };
2549
2910
 
2550
2911
  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');
2912
+ var result = this._evaluate();
2913
+ if (result.pending) {
2914
+ this._runAsync(result.pending);
2555
2915
  return this;
2556
2916
  }
2557
- if (this.errorMessage) this.setError(null);
2558
- if (this.validation === 'invalid') this.setValidation(null);
2917
+ if (this.pending) this._setPending(false);
2918
+ this._applyValidity(result.error || '', this.touched || this.opts.alwaysValidate, result.custom);
2559
2919
  return this;
2560
2920
  };
2561
2921
 
2922
+ /* returns a boolean for sync rules and a Promise<boolean> when an async rule runs */
2562
2923
  ZidanFieldBase.prototype.validate = function () {
2563
2924
  this.touched = true;
2564
- var error = this._evaluateError();
2565
- if (error) {
2566
- this.setError(error);
2925
+ var result = this._evaluate();
2926
+ if (result.pending) return this._runAsync(result.pending);
2927
+ if (this.pending) this._setPending(false);
2928
+ if (result.error) {
2929
+ this._applyValidity(result.error, true, result.custom);
2567
2930
  return false;
2568
2931
  }
2569
- this.setError(null);
2932
+ this._applyValidity('', true, false);
2570
2933
  if (this.opts.showValidState) this.setValidation('valid');
2571
2934
  return true;
2572
2935
  };
@@ -2596,6 +2959,10 @@
2596
2959
  return this.validation;
2597
2960
  };
2598
2961
 
2962
+ ZidanFieldBase.prototype.isPending = function () {
2963
+ return this.pending;
2964
+ };
2965
+
2599
2966
  ZidanFieldBase.prototype.getValue = function () {
2600
2967
  var el = this.el;
2601
2968
  if (!el) return null;
@@ -2650,6 +3017,7 @@
2650
3017
  ZidanFieldBase.prototype.destroy = function () {
2651
3018
  if (this.destroyed) return this;
2652
3019
  this.destroyed = true;
3020
+ this._abortAsync();
2653
3021
  this._listeners.forEach(function (entry) {
2654
3022
  entry[0].removeEventListener(entry[1], entry[2], entry[3]);
2655
3023
  });
@@ -2835,9 +3203,10 @@
2835
3203
 
2836
3204
  ZidanCheckbox.prototype._customError = function () {
2837
3205
  if (typeof this.opts.validate === 'function') {
2838
- var result = this.opts.validate(this.el.checked, this);
3206
+ var result = this.opts.validate(this.el.checked, this, this._asyncContext());
2839
3207
  if (result === false) return this.opts.messages.generic;
2840
3208
  if (typeof result === 'string' && result) return result;
3209
+ if (isThenable(result)) return result;
2841
3210
  }
2842
3211
  return '';
2843
3212
  };
@@ -3012,9 +3381,10 @@
3012
3381
 
3013
3382
  ZidanRadioGroup.prototype._customError = function () {
3014
3383
  if (typeof this.opts.validate === 'function') {
3015
- var result = this.opts.validate(this.getValue(), this);
3384
+ var result = this.opts.validate(this.getValue(), this, this._asyncContext());
3016
3385
  if (result === false) return this.opts.messages.generic;
3017
3386
  if (typeof result === 'string' && result) return result;
3387
+ if (isThenable(result)) return result;
3018
3388
  }
3019
3389
  return '';
3020
3390
  };
@@ -3346,8 +3716,19 @@
3346
3716
  };
3347
3717
  };
3348
3718
 
3719
+ ZidanFileUpload.prototype._setCustomValidity = function (message) {
3720
+ if (this.el && this.el.setCustomValidity) this.el.setCustomValidity(message || '');
3721
+ };
3722
+
3349
3723
  ZidanFileUpload.prototype._customError = function () {
3350
- return this.fileError || '';
3724
+ if (this.fileError) return this.fileError;
3725
+ if (typeof this.opts.validate === 'function') {
3726
+ var result = this.opts.validate(this.getFiles(), this, this._asyncContext());
3727
+ if (result === false) return this.opts.messages.generic;
3728
+ if (typeof result === 'string' && result) return result;
3729
+ if (isThenable(result)) return result;
3730
+ }
3731
+ return '';
3351
3732
  };
3352
3733
 
3353
3734
  ZidanFileUpload.prototype._validate = function () {
@@ -3384,7 +3765,9 @@
3384
3765
  }
3385
3766
 
3386
3767
  this.fileError = error;
3387
- if (input.setCustomValidity) input.setCustomValidity(error || '');
3768
+ if (input.setCustomValidity) {
3769
+ input.setCustomValidity(this.pending ? (messages.pending || FIELD_MESSAGES.pending) : (error || ''));
3770
+ }
3388
3771
  var shown = error || this._nativeError();
3389
3772
  if (shown) this.setError(shown);
3390
3773
  else if (this.errorMessage) this.setError(null);
@@ -3611,6 +3994,14 @@
3611
3994
  var self = this;
3612
3995
  if (!this.hasUploader) return this;
3613
3996
  if (!this._validate()) return this;
3997
+ var check = this.validate();
3998
+ if (isThenable(check)) {
3999
+ return check.then(function (valid) {
4000
+ if (valid && !self.destroyed) self.getFiles().forEach(function (file) { self.uploadFile(file); });
4001
+ return valid;
4002
+ });
4003
+ }
4004
+ if (!check) return this;
3614
4005
  this.getFiles().forEach(function (file) { self.uploadFile(file); });
3615
4006
  return this;
3616
4007
  };
@@ -4260,17 +4651,13 @@
4260
4651
  ZidanTextField.prototype.constructor = ZidanTextField;
4261
4652
 
4262
4653
  // phone/date/custom rules must also block native form submission
4263
- ZidanTextField.prototype._mirrorValidity = function () {
4654
+ ZidanTextField.prototype._setCustomValidity = function (message) {
4264
4655
  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
- }
4656
+ if (!input.setCustomValidity) return;
4657
+ if (input.__zidanCustomError !== message) {
4658
+ input.setCustomValidity(message);
4659
+ input.__zidanCustomError = message;
4272
4660
  }
4273
- return ZidanFieldBase.prototype._mirrorValidity.call(this);
4274
4661
  };
4275
4662
 
4276
4663
  ZidanTextField.prototype._formatRangeValue = function (value) {
@@ -4313,7 +4700,7 @@
4313
4700
  values.forEach(function (value) {
4314
4701
  var pct = bounds.max > bounds.min ? (value - bounds.min) / (bounds.max - bounds.min) : 0;
4315
4702
  var tick = el('span', 'zs-range-tick');
4316
- tick.style.left = (clamp(pct, 0, 1) * 100).toFixed(2) + '%';
4703
+ tick.style.setProperty('--zs-range-tick-pct', (clamp(pct, 0, 1) * 100).toFixed(2) + '%');
4317
4704
  if (this.rangeTickLabels) {
4318
4705
  var label = this.rangeLabelMap && this.rangeLabelMap[value] !== undefined
4319
4706
  ? this.rangeLabelMap[value]
@@ -4514,16 +4901,18 @@
4514
4901
  if (blocked) return messages.dateDisabled;
4515
4902
  }
4516
4903
  if (typeof opts.validateDate === 'function') {
4517
- var dateResult = opts.validateDate(input.value, date, this);
4904
+ var dateResult = opts.validateDate(input.value, date, this, this._asyncContext());
4518
4905
  if (dateResult === false) return messages.date;
4519
4906
  if (typeof dateResult === 'string' && dateResult) return dateResult;
4907
+ if (isThenable(dateResult)) return dateResult;
4520
4908
  }
4521
4909
  }
4522
4910
 
4523
4911
  if (typeof opts.validate === 'function') {
4524
- var result = opts.validate(input.value, this);
4912
+ var result = opts.validate(input.value, this, this._asyncContext());
4525
4913
  if (result === false) return messages.generic;
4526
4914
  if (typeof result === 'string' && result) return result;
4915
+ if (isThenable(result)) return result;
4527
4916
  }
4528
4917
  return '';
4529
4918
  };
@@ -4753,6 +5142,7 @@
4753
5142
  ZidanSelect.frameworks = FRAMEWORKS.slice();
4754
5143
  ZidanSelect.scrollbars = SCROLLBARS.slice();
4755
5144
  ZidanSelect.defaults = DEFAULTS;
5145
+ ZidanSelect.cacheLimit = 50;
4756
5146
  ZidanSelect.get = function (target) {
4757
5147
  var element = typeof target === 'string' ? doc.querySelector(target) : target;
4758
5148
  if (!isElement(element)) return null;