zidan-select 2.3.0 → 2.4.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.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * ZidanForm Select-only v2.3.0
2
+ * ZidanForm Select-only v2.4.0
3
3
  * Zero-dependency select / combobox / tags enhancement. Every other control family is omitted.
4
4
  * Pairs with plugin-select-core.css and plugin-select-theme.css.
5
5
  *
@@ -29,7 +29,7 @@
29
29
  })(typeof window !== 'undefined' ? window : this, function (global) {
30
30
  'use strict';
31
31
 
32
- var VERSION = '2.3.0';
32
+ var VERSION = '2.4.0';
33
33
 
34
34
  // Loading the file twice (classic script + module wrapper, or two bundles)
35
35
  // must not replace the classes and orphan the live instances.
@@ -426,6 +426,24 @@
426
426
  return list.indexOf(candidate) === -1 ? fallback : candidate;
427
427
  }
428
428
 
429
+ /* rangeTicks: JS array, JSON array, comma list or a tick count */
430
+ function parseRangeTicks(value) {
431
+ if (Array.isArray(value)) return value.slice();
432
+ if (typeof value === 'string') {
433
+ var raw = value.trim();
434
+ if (raw.charAt(0) === '[') {
435
+ try {
436
+ var parsed = JSON.parse(raw);
437
+ if (Array.isArray(parsed)) return parsed;
438
+ } catch (err) { /* fall back to the tick count */ }
439
+ } else if (raw.indexOf(',') !== -1) {
440
+ return raw.split(',').map(function (part) { return Number(part.trim()); })
441
+ .filter(function (number) { return isFinite(number); });
442
+ }
443
+ }
444
+ return value;
445
+ }
446
+
429
447
  /* theme/framework/layout resolution shared by every field and the select */
430
448
  function resolveScope(node, options) {
431
449
  var opts = options || {};
@@ -496,6 +514,17 @@
496
514
  autoLoadMore: true,
497
515
  cacheResults: true,
498
516
  loadMoreText: 'Load more',
517
+ fetchUrl: null, // declarative AJAX: GET this endpoint instead of writing fetchOptions
518
+ fetchMethod: 'GET',
519
+ fetchQueryParam: 'q',
520
+ fetchPageParam: 'page', // 1-based page number sent with every request
521
+ fetchSkipParam: null, // when set, send skip = page * pageSize instead of fetchPageParam
522
+ fetchPageSizeParam: 'limit',
523
+ fetchItemsPath: null, // dot path to the array in the JSON body ('data.items')
524
+ fetchTotalPath: null, // dot path to the number of rows available
525
+ fetchHasMorePath: null, // dot path to a boolean
526
+ fetchHeaders: null,
527
+ fetchCredentials: 'same-origin',
499
528
  /* tags */
500
529
  maxTags: Infinity,
501
530
  minTagLength: 1,
@@ -532,6 +561,112 @@
532
561
  * ZidanSelect
533
562
  * ------------------------------------------------------------------ */
534
563
 
564
+ /* ---------------- declarative AJAX (fetchUrl) ---------------- */
565
+
566
+ function readDotPath(source, path) {
567
+ if (!path) return undefined;
568
+ return String(path).split('.').reduce(function (node, key) {
569
+ return node === null || node === undefined ? undefined : node[key];
570
+ }, source);
571
+ }
572
+
573
+ function firstRemoteArray(body) {
574
+ if (Array.isArray(body)) return body;
575
+ if (!body || typeof body !== 'object') return [];
576
+ var keys = ['items', 'data', 'results', 'options', 'rows', 'products', 'records'];
577
+ for (var i = 0; i < keys.length; i++) {
578
+ if (Array.isArray(body[keys[i]])) return body[keys[i]];
579
+ }
580
+ return [];
581
+ }
582
+
583
+ /* Map common API shapes ({id,title}, {value,label}, plain strings) to select items. */
584
+ function remoteItem(raw) {
585
+ if (raw === null || raw === undefined) return null;
586
+ if (typeof raw !== 'object') {
587
+ var text = String(raw);
588
+ return { value: text, label: text };
589
+ }
590
+ var value = raw.value !== undefined ? raw.value
591
+ : raw.id !== undefined ? raw.id
592
+ : raw.slug !== undefined ? raw.slug
593
+ : raw.code !== undefined ? raw.code
594
+ : raw.key !== undefined ? raw.key : undefined;
595
+ var label = raw.label !== undefined ? raw.label
596
+ : raw.name !== undefined ? raw.name
597
+ : raw.title !== undefined ? raw.title
598
+ : raw.full_name !== undefined ? raw.full_name
599
+ : raw.text !== undefined ? raw.text : undefined;
600
+ if (label === undefined) label = value === undefined ? '' : value;
601
+ if (value === undefined) value = label;
602
+ return { value: value, label: label, disabled: !!raw.disabled };
603
+ }
604
+
605
+ /*
606
+ * Turns fetchUrl + fetch* options into the same promise fetchOptions would return:
607
+ * { items, hasMore, total }. Honours AbortSignal and the paging context the
608
+ * select passes in, so caching, debounce and "Load more" work unchanged.
609
+ */
610
+ function createRemoteFetcher(opts) {
611
+ return function (query, signal, context) {
612
+ if (typeof fetch !== 'function') {
613
+ return Promise.reject(new Error('This environment has no fetch().'));
614
+ }
615
+ var page = context && context.page ? context.page : 0;
616
+ var pageSize = opts.fetchPageSize > 0 ? opts.fetchPageSize : 0;
617
+ var url;
618
+ try {
619
+ url = new URL(opts.fetchUrl, (typeof location !== 'undefined' && location.href) || undefined);
620
+ } catch (error) {
621
+ return Promise.reject(new Error('Invalid fetchUrl: ' + opts.fetchUrl));
622
+ }
623
+ if (opts.fetchQueryParam) url.searchParams.set(opts.fetchQueryParam, query || '');
624
+ if (pageSize > 0 && opts.fetchPageSizeParam) {
625
+ url.searchParams.set(opts.fetchPageSizeParam, String(pageSize));
626
+ }
627
+ if (opts.fetchSkipParam) {
628
+ if (pageSize > 0) url.searchParams.set(opts.fetchSkipParam, String(page * pageSize));
629
+ } else if (opts.fetchPageParam) {
630
+ url.searchParams.set(opts.fetchPageParam, String(page + 1));
631
+ }
632
+
633
+ var headers = { Accept: 'application/json' };
634
+ if (opts.fetchHeaders && typeof opts.fetchHeaders === 'object') {
635
+ Object.keys(opts.fetchHeaders).forEach(function (key) {
636
+ headers[key] = opts.fetchHeaders[key];
637
+ });
638
+ }
639
+
640
+ return fetch(url.toString(), {
641
+ method: opts.fetchMethod || 'GET',
642
+ headers: headers,
643
+ signal: signal,
644
+ credentials: opts.fetchCredentials || 'same-origin'
645
+ }).then(function (response) {
646
+ if (!response.ok) {
647
+ throw new Error('Request failed (' + response.status + ' ' + (response.statusText || 'error') + ')');
648
+ }
649
+ return response.json();
650
+ }).then(function (body) {
651
+ var rows = opts.fetchItemsPath ? readDotPath(body, opts.fetchItemsPath) : firstRemoteArray(body);
652
+ if (!Array.isArray(rows)) rows = rows === undefined || rows === null ? [] : [rows];
653
+ var items = rows.map(remoteItem).filter(Boolean);
654
+
655
+ var hasMore;
656
+ if (opts.fetchHasMorePath) hasMore = !!readDotPath(body, opts.fetchHasMorePath);
657
+ var rawTotal = opts.fetchTotalPath ? readDotPath(body, opts.fetchTotalPath)
658
+ : (body && typeof body === 'object' ? body.total : undefined);
659
+ var total = rawTotal === undefined || rawTotal === null ? NaN : Number(rawTotal);
660
+ if (hasMore === undefined && isFinite(total) && pageSize > 0) {
661
+ hasMore = (page + 1) * pageSize < total;
662
+ }
663
+ if (hasMore === undefined) hasMore = pageSize > 0 && items.length >= pageSize;
664
+
665
+ return { items: items, hasMore: hasMore, total: isFinite(total) ? total : undefined };
666
+ });
667
+ };
668
+ }
669
+
535
670
  function ZidanSelect(target, options) {
536
671
  if (!(this instanceof ZidanSelect)) return new ZidanSelect(target, options);
537
672
  if (!doc) throw new Error('ZidanSelect requires a DOM environment.');
@@ -652,6 +787,15 @@
652
787
  merged.autoLoadMore = pick('autoLoadMore', readBoolAttr(d.zidanAutoLoadMore, DEFAULTS.autoLoadMore));
653
788
  merged.cacheResults = pick('cacheResults', readBoolAttr(d.zidanCacheResults, DEFAULTS.cacheResults));
654
789
  merged.loadMoreText = pick('loadMoreText', d.zidanLoadMoreText || DEFAULTS.loadMoreText);
790
+ merged.fetchUrl = pick('fetchUrl', d.zidanFetchUrl || null);
791
+ merged.fetchMethod = pick('fetchMethod', d.zidanFetchMethod || DEFAULTS.fetchMethod);
792
+ merged.fetchQueryParam = pick('fetchQueryParam', d.zidanFetchQueryParam !== undefined ? d.zidanFetchQueryParam : DEFAULTS.fetchQueryParam);
793
+ merged.fetchPageParam = pick('fetchPageParam', d.zidanFetchPageParam !== undefined ? d.zidanFetchPageParam : DEFAULTS.fetchPageParam);
794
+ merged.fetchSkipParam = pick('fetchSkipParam', d.zidanFetchSkipParam || null);
795
+ merged.fetchPageSizeParam = pick('fetchPageSizeParam', d.zidanFetchPageSizeParam !== undefined ? d.zidanFetchPageSizeParam : DEFAULTS.fetchPageSizeParam);
796
+ merged.fetchItemsPath = pick('fetchItemsPath', d.zidanFetchItemsPath || null);
797
+ merged.fetchTotalPath = pick('fetchTotalPath', d.zidanFetchTotalPath || null);
798
+ merged.fetchHasMorePath = pick('fetchHasMorePath', d.zidanFetchHasMorePath || null);
655
799
 
656
800
  // carry over every explicitly-passed option (callbacks, custom classes, ...)
657
801
  Object.keys(options).forEach(function (key) {
@@ -667,6 +811,11 @@
667
811
  if (mode === 'combobox') merged.searchable = true;
668
812
  if (mode === 'tags' && merged.searchable === false) merged.searchable = true;
669
813
  if (mode === 'tags') merged.multiple = true;
814
+
815
+ // declarative AJAX: one URL is enough to opt into remote loading
816
+ if (merged.fetchUrl && typeof merged.fetchOptions !== 'function') {
817
+ merged.fetchOptions = createRemoteFetcher(merged);
818
+ }
670
819
  return merged;
671
820
  };
672
821
 
@@ -827,6 +976,9 @@
827
976
  input.setAttribute('aria-controls', this.id + '-listbox');
828
977
  input.setAttribute('aria-autocomplete', (opts.searchable || this.mode !== 'select') ? 'list' : 'none');
829
978
  input.setAttribute('aria-haspopup', 'listbox');
979
+ /* a plain select is not type-to-filter: keep its text field read-only so
980
+ typing cannot filter or hide the options */
981
+ if (this.mode === 'select' && !opts.searchable) input.readOnly = true;
830
982
  if (opts.ariaLabel || opts.label) input.setAttribute('aria-label', opts.ariaLabel || opts.label);
831
983
  if (opts.disabled) input.disabled = true;
832
984
  this._applyCustomClass(input, 'input');
@@ -836,6 +988,16 @@
836
988
  labelEl = el('label', 'zs-label', { for: input.id });
837
989
  labelEl.textContent = opts.label;
838
990
  if (this.layout !== 'floating-label') rootEl.classList.add('zs-root--has-static-label');
991
+
992
+ // Hide the author's <label>: this label replaces it, and showing both
993
+ // would print the same text twice above the control.
994
+ var authorLabel = this.el.labels && this.el.labels[0] ? this.el.labels[0] : null;
995
+ if (authorLabel && authorLabel.closest && authorLabel.closest('.zs-root')) authorLabel = null;
996
+ this._authorLabel = authorLabel || null;
997
+ if (authorLabel) {
998
+ authorLabel.hidden = true;
999
+ authorLabel.setAttribute('data-zs-hidden-label', 'true');
1000
+ }
839
1001
  }
840
1002
 
841
1003
  var clearBtn = el('button', 'zs-clear', {
@@ -864,9 +1026,7 @@
864
1026
  var dropdown = el('div', 'zs-dropdown');
865
1027
  dropdown.id = this.id + '-listbox';
866
1028
  dropdown.setAttribute('role', 'listbox');
867
- if (this.mode !== 'tags') {
868
- dropdown.setAttribute('aria-multiselectable', String(!!(opts.multiple || this.mode === 'tags')));
869
- }
1029
+ dropdown.setAttribute('aria-multiselectable', String(!!(opts.multiple || this.mode === 'tags')));
870
1030
  this._applyCustomClass(dropdown, 'dropdown');
871
1031
 
872
1032
  var live = el('div', 'zs-live', { 'aria-live': 'polite', 'aria-atomic': 'true' });
@@ -944,6 +1104,22 @@
944
1104
  };
945
1105
  this.form.addEventListener('reset', this.onFormReset);
946
1106
  }
1107
+
1108
+ /* `required` is a JS-only option as well as a native attribute. A native
1109
+ select can carry it directly; a mount-mode div needs a submit guard. */
1110
+ if (opts.required && this.native && this.native.tagName === 'SELECT' && !this.native.required) {
1111
+ this.native.required = true;
1112
+ this._nativeRequiredAdded = true;
1113
+ } else if (opts.required && !this.native && this.form) {
1114
+ this.onFormSubmit = function (event) {
1115
+ if (self.value_.length) return;
1116
+ event.preventDefault();
1117
+ self.setValidation('invalid');
1118
+ if (self.input && self.input.focus) self.input.focus();
1119
+ self.announce('Please select an option.');
1120
+ };
1121
+ this.form.addEventListener('submit', this.onFormSubmit);
1122
+ }
947
1123
  return this.syncEl;
948
1124
  };
949
1125
 
@@ -1044,7 +1220,9 @@
1044
1220
 
1045
1221
  if (!this.opts.multiple && this.mode !== 'tags') next = next.slice(0, 1);
1046
1222
  this.value_ = next;
1047
- if (next.length && this.opts.validation === 'invalid') this.opts.validation = null;
1223
+ /* a preset/manual invalid state is only cleared by a real value change, not
1224
+ by the initial value applied during construction */
1225
+ if (next.length && this.opts.validation === 'invalid' && !cfg.silent) this.opts.validation = null;
1048
1226
  this._render();
1049
1227
  this._syncNative();
1050
1228
  if (!cfg.silent) {
@@ -1757,6 +1935,22 @@
1757
1935
  return false;
1758
1936
  }
1759
1937
 
1938
+ /* allowFreeText: false limits tags to the supplied option/suggestion list */
1939
+ if (this.mode === 'tags' && !opts.allowFreeText) {
1940
+ var pool = this.suggestions && this.suggestions.length ? this.suggestions : this.items;
1941
+ var needle = opts.caseSensitive ? raw : raw.toLowerCase();
1942
+ var listed = false;
1943
+ for (var s = 0; s < pool.length; s += 1) {
1944
+ var itemValue = opts.caseSensitive ? String(pool[s].value) : String(pool[s].value).toLowerCase();
1945
+ var itemLabel = opts.caseSensitive ? String(pool[s].label) : String(pool[s].label).toLowerCase();
1946
+ if (itemValue === needle || itemLabel === needle) { listed = true; break; }
1947
+ }
1948
+ if (!listed) {
1949
+ if (!cfg.silent) this._tagError('"' + raw + '" is not in the list.');
1950
+ return false;
1951
+ }
1952
+ }
1953
+
1760
1954
  var formatted = raw;
1761
1955
  if (typeof opts.formatTag === 'function') {
1762
1956
  var formattedResult = opts.formatTag(raw, { instance: this, tags: this.getTags() });
@@ -1833,6 +2027,14 @@
1833
2027
  var key = event.key;
1834
2028
  var items = this._visibleItems();
1835
2029
 
2030
+ /* Space opens a closed combobox/listbox (WAI-ARIA), unless the user is
2031
+ already typing a search or tag query in an open control. */
2032
+ if ((key === ' ' || key === 'Spacebar') && !this.opened) {
2033
+ event.preventDefault();
2034
+ this.open();
2035
+ return;
2036
+ }
2037
+
1836
2038
  if (key === 'ArrowDown' || key === 'ArrowUp') {
1837
2039
  event.preventDefault();
1838
2040
  if (!this.opened) {
@@ -1968,6 +2170,8 @@
1968
2170
 
1969
2171
  this.onInput = function () {
1970
2172
  var value = self.input.value;
2173
+ /* plain selects are not searchable: typing must not filter the list */
2174
+ if (self.mode === 'select' && !self.opts.searchable) return;
1971
2175
  self.query = value;
1972
2176
  if (self.opened) {
1973
2177
  if (typeof self.opts.fetchOptions === 'function' && self.query.length >= (self.opts.minChars || 0)) {
@@ -2361,6 +2565,11 @@
2361
2565
  this.clearCache();
2362
2566
  if (this.resizeObserver) this.resizeObserver.disconnect();
2363
2567
  if (this.form && this.onFormReset) this.form.removeEventListener('reset', this.onFormReset);
2568
+ if (this.form && this.onFormSubmit) this.form.removeEventListener('submit', this.onFormSubmit);
2569
+ if (this._nativeRequiredAdded && this.native) {
2570
+ this.native.required = false;
2571
+ this._nativeRequiredAdded = false;
2572
+ }
2364
2573
 
2365
2574
  doc.removeEventListener('pointerdown', this.onDocumentPointerDown, true);
2366
2575
  global.removeEventListener('resize', this.onWindowResize);
@@ -2370,6 +2579,12 @@
2370
2579
 
2371
2580
  if (this.root && this.root.parentNode) this.root.parentNode.removeChild(this.root);
2372
2581
 
2582
+ if (this._authorLabel) {
2583
+ this._authorLabel.hidden = false;
2584
+ this._authorLabel.removeAttribute('data-zs-hidden-label');
2585
+ this._authorLabel = null;
2586
+ }
2587
+
2373
2588
  if (this.native) {
2374
2589
  this.native.hidden = false;
2375
2590
  this.native.classList.remove('zs-native');
@@ -2457,7 +2672,11 @@
2457
2672
  // (output, counter, clearable, …) work without a data attribute
2458
2673
  var kind = fieldKindFor(node) || inferredTextKind(node);
2459
2674
  if (!kind) return;
2460
- if (kind === 'radio' && !node.hasAttribute('data-zidan-radio')) {
2675
+ if (kind === 'radio' || kind === 'radio-group') {
2676
+ if (/^INPUT$/i.test(node.tagName)) {
2677
+ node = node.closest ? node.closest('fieldset, [data-zidan-radio-group]') : null;
2678
+ if (!node) return;
2679
+ }
2461
2680
  kind = 'radio-group';
2462
2681
  }
2463
2682
  var instance = createField(node, kind, options || {});
@@ -2472,7 +2691,13 @@
2472
2691
  if (!isElement(node) || node.__zidanField) return;
2473
2692
  var kind = fieldKindFor(node);
2474
2693
  if (!kind) return;
2475
- if (kind === 'radio') kind = 'radio-group';
2694
+ if (kind === 'radio' || kind === 'radio-group') {
2695
+ if (/^INPUT$/i.test(node.tagName)) {
2696
+ node = node.closest ? node.closest('fieldset, [data-zidan-radio-group]') : null;
2697
+ if (!node) return;
2698
+ }
2699
+ kind = 'radio-group';
2700
+ }
2476
2701
  var instance = createField(node, kind, options || {});
2477
2702
  if (instance) instances.push(instance);
2478
2703
  });