zidan-select 2.3.1 → 2.4.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.
@@ -12,70 +12,91 @@
12
12
  <meta property="og:url" content="https://akhtar1985.github.io/zidan-select/docs/validation.html">
13
13
  <meta property="og:image" content="https://akhtar1985.github.io/zidan-select/docs/demo-inputs.png">
14
14
  <meta name="twitter:card" content="summary_large_image">
15
+ <meta name="theme-color" content="#4f6bed">
16
+ <meta property="og:site_name" content="ZidanForm">
17
+ <meta property="og:image" content="https://akhtar1985.github.io/zidan-select/docs/demo-inputs.png">
18
+ <meta name="twitter:card" content="summary_large_image">
15
19
  <link rel="stylesheet" href="../plugin-core.css">
16
20
  <link rel="stylesheet" href="../plugin-theme.css">
17
- <style>
18
- * { box-sizing: border-box; }
19
- body {
20
- margin: 0;
21
- padding: 40px 22px 70px;
22
- font-family: "Inter", system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
23
- color: #101324;
24
- background: #f5f6fb;
25
- line-height: 1.55;
26
- }
27
- main { max-width: 900px; margin: 0 auto; }
28
- h1 { margin: 0 0 6px; font-size: 1.9rem; letter-spacing: -0.02em; }
29
- .lead { margin: 0 0 26px; color: #525a70; }
30
- .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(290px, 1fr)); gap: 16px; }
31
- .card {
32
- background: #fff;
33
- border: 1px solid #e4e8f1;
34
- border-radius: 16px;
35
- padding: 20px;
36
- box-shadow: 0 1px 2px rgba(16, 19, 36, 0.05);
37
- }
38
- .card h2 { margin: 0 0 2px; font-size: 1rem; }
39
- .card p { margin: 0 0 16px; font-size: 0.8125rem; color: #6b7385; }
40
- .card form { display: flex; flex-direction: column; gap: 14px; }
41
- .status { margin-top: 12px; font-size: 0.8125rem; color: #067647; min-height: 20px; }
42
- .status[data-state="error"] { color: #b42318; }
43
- .status[data-state="missing"] { color: #b45309; }
44
- button.submit {
45
- align-self: flex-start;
46
- font: inherit;
47
- font-size: 0.85rem;
48
- font-weight: 600;
49
- padding: 9px 16px;
50
- border-radius: 999px;
51
- border: 0;
52
- color: #fff;
53
- background: linear-gradient(140deg, #4f6bed, #6f5cf0);
54
- cursor: pointer;
55
- }
56
- label.error { color: #b42318; font-size: 0.75rem; }
57
- .just-validate-error-label { color: #b42318; font-size: 0.75rem; margin-top: 4px; }
58
- .parsley-errors-list { color: #b42318; font-size: 0.75rem; list-style: none; padding: 0; margin: 4px 0 0; }
59
- .back { display: inline-block; margin-bottom: 18px; font-size: 0.85rem; color: #4f6bed; }
60
- </style>
21
+ <link rel="stylesheet" href="../demo.css">
22
+ <link rel="stylesheet" href="../nav.css">
23
+ <link rel="stylesheet" href="../docs.css">
61
24
  </head>
62
25
  <body>
63
- <main>
64
- <a class="back" href="index.html">← documentation</a>
65
- <h1>Validation-library test bench</h1>
66
- <p class="lead">
67
- The same plugin markup under four validators. Everything is loaded from a CDN, so this
68
- page also works as a smoke test: submit each empty form, then fill it in.
69
- </p>
26
+ <a class="skip-link" href="#docs-main">Skip to content</a>
27
+ <div class="bg-orbs" aria-hidden="true"><span class="orb"></span></div>
70
28
 
71
- <div class="grid">
29
+ <header class="site-header">
30
+ <a class="brand" href="../index.html">
31
+ <span class="logo-mark" aria-hidden="true">Z</span>
32
+ <span>
33
+ <span class="brand-name">ZidanForm</span>
34
+ <span class="brand-sub">v2.4.1 · zero dependencies</span>
35
+ </span>
36
+ </a>
37
+ <button class="nav-toggle" type="button" aria-expanded="false" aria-controls="site-nav">
38
+ <span class="nav-toggle-bars" aria-hidden="true"><span></span><span></span><span></span></span>
39
+ <span>Menu</span>
40
+ </button>
41
+ <nav class="header-nav" id="site-nav" aria-label="Project links">
42
+ <a href="../index.html">Demo</a>
43
+ <a href="../advanced.html">Advanced</a>
44
+ <a href="../playground.html">Playground</a>
45
+ <a href="../ajax.html">AJAX</a>
46
+ <a href="../shopify.html">Shopify</a>
47
+ <a href="../index.html#compare">Compare</a>
48
+ <a href="../index.html#faq">FAQ</a>
49
+ <details class="nav-docs">
50
+ <summary>Docs</summary>
51
+ <div class="nav-docs-panel">
52
+ <a href="index.html">Documentation index</a>
53
+ <a href="options.html">Options &amp; data attributes</a>
54
+ <a href="comparison.html">Why &amp; comparison</a>
55
+ <a href="frameworks.html">Frameworks</a>
56
+ <a href="html-and-wordpress.html">HTML &amp; WordPress</a>
57
+ <a href="validation-guide.html">Validation</a>
58
+ <a href="validation.html" aria-current="page">Validation test bench</a>
59
+ <a href="theming.html">Theming</a>
60
+ <a href="build.html">Build &amp; publish</a>
61
+ </div>
62
+ </details>
63
+ <a href="https://github.com/akhtar1985/zidan-select">GitHub</a>
64
+ <a href="https://www.npmjs.com/package/zidan-select">npm</a>
65
+ <label class="sr-only" for="quick-theme">Page theme</label>
66
+ <select id="quick-theme" aria-label="Page theme">
67
+ <option value="default">Default theme</option>
68
+ <option value="modern">Modern</option>
69
+ <option value="minimal">Minimal</option>
70
+ <option value="dark">Dark</option>
71
+ <option value="glass">Glass</option>
72
+ </select>
73
+ </nav>
74
+ </header>
75
+
76
+ <main id="docs-main" class="wrap docs-main">
77
+ <section class="hero docs-hero" aria-labelledby="docs-title">
78
+ <p class="eyebrow"><span class="eyebrow-dot" aria-hidden="true"></span> Validation · live test bench</p>
79
+ <h1 id="docs-title">One form, <span>four validators.</span></h1>
80
+ <p class="doc-blurb">
81
+ The same plugin markup under native HTML5, jQuery Validation, JustValidate and Parsley.
82
+ Everything is loaded from a CDN, so this page also works as a smoke test: submit each
83
+ empty form, then fill it in.
84
+ </p>
85
+ <div class="hero-actions">
86
+ <a class="btn btn-primary" href="validation-guide.html">Read the validation guide</a>
87
+ <a class="btn" href="index.html">All documentation</a>
88
+ <a class="btn" href="../playground.html">Field playground</a>
89
+ </div>
90
+ </section>
91
+
92
+ <div class="validation-grid">
72
93
  <section class="card">
73
94
  <h2>Native HTML5</h2>
74
95
  <p>Constraint validation and <code>aria-invalid</code> mirroring.</p>
75
96
  <form id="form-native" novalidate>
76
97
  <input name="email" type="email" required data-zidan="input" data-zidan-label="Email">
77
98
  <label><input type="checkbox" name="terms" required data-zidan="checkbox" data-zidan-label="Accept terms"> Accept terms</label>
78
- <button class="submit" type="submit">Submit</button>
99
+ <button class="btn btn-primary" type="submit">Submit</button>
79
100
  </form>
80
101
  <p class="status" id="native-status" role="status"></p>
81
102
  </section>
@@ -86,7 +107,7 @@
86
107
  <form id="form-jquery">
87
108
  <input name="email" id="jq-email" type="email" required data-zidan="input" data-zidan-label="Email">
88
109
  <input name="name" id="jq-name" required minlength="3" data-zidan="input" data-zidan-label="Name">
89
- <button class="submit" type="submit">Submit</button>
110
+ <button class="btn btn-primary" type="submit">Submit</button>
90
111
  </form>
91
112
  <p class="status" id="jquery-status" role="status"></p>
92
113
  </section>
@@ -97,7 +118,7 @@
97
118
  <form id="form-justvalidate">
98
119
  <input name="email" id="jv-email" data-zidan="input" data-zidan-label="Email">
99
120
  <input name="name" id="jv-name" data-zidan="input" data-zidan-label="Name">
100
- <button class="submit" type="submit">Submit</button>
121
+ <button class="btn btn-primary" type="submit">Submit</button>
101
122
  </form>
102
123
  <p class="status" id="justvalidate-status" role="status"></p>
103
124
  </section>
@@ -110,13 +131,32 @@
110
131
  data-zidan="input" data-zidan-label="Email">
111
132
  <input name="name" id="parsley-name" data-parsley-required data-parsley-minlength="3"
112
133
  data-zidan="input" data-zidan-label="Name">
113
- <button class="submit" type="submit">Submit</button>
134
+ <button class="btn btn-primary" type="submit">Submit</button>
114
135
  </form>
115
136
  <p class="status" id="parsley-status" role="status"></p>
116
137
  </section>
117
138
  </div>
139
+
140
+ <p class="doc-source-note">
141
+ The native controls stay reachable for each validator. Read the
142
+ <a href="validation-guide.html">validation compatibility guide</a> for configuration and
143
+ double-submit patterns.
144
+ </p>
118
145
  </main>
119
146
 
147
+ <footer class="site-footer">
148
+ <div class="wrap">
149
+ <p>
150
+ <strong>ZidanForm</strong> — MIT licensed, no dependencies.
151
+ <a href="../index.html">Demo</a> ·
152
+ <a href="../playground.html">Playground</a> ·
153
+ <a href="index.html">Documentation</a> ·
154
+ <a href="https://github.com/akhtar1985/zidan-select">GitHub</a>
155
+ </p>
156
+ </div>
157
+ </footer>
158
+
159
+ <script src="../nav.js"></script>
120
160
  <script src="../zidan-form.js"></script>
121
161
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
122
162
  <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.20.0/dist/jquery.validate.min.js"></script>
@@ -30,12 +30,12 @@ It clears the state on `input`/`change` once validity passes, on `form.reset()`,
30
30
  native validity.
31
31
 
32
32
  A state set through the public `setValidation('invalid')` (and a preset
33
- `data-zidan-validation="invalid"`) is **pinned**: re-rendering the field — `update()`,
34
- `refresh()`, `setValue()`, an option chosen in a select, an async rule that resolves clean —
35
- will not clear it. That is what makes a server-side error survive until the user actually
36
- touches the control. The pin is released by the next `input`, `change` or `blur` from the user,
37
- or by `setValidation(null)` / `setValidation('valid')`. Internal mirrors pass a second argument
38
- (`setValidation(state, true)`) so they never pin a state themselves.
33
+ `data-zidan-validation="invalid"`) is **pinned against re-renders**: `update()`, `refresh()`
34
+ and internal validity mirrors or async re-checks do not clear it. The pin is released by the
35
+ next `input`, `change` or `blur`, or by `setValidation(null)` / `setValidation('valid')`.
36
+ Programmatic value helpers can release it too: field `setValue()` / `setChecked()` dispatch
37
+ `change`, and applying a non-empty select value clears the select's invalid option. Internal
38
+ mirrors pass a second argument (`setValidation(state, true)`) so they never pin a state.
39
39
 
40
40
  ## Built-in rules (written into native validity)
41
41
 
@@ -104,7 +104,7 @@ email.isPending(); // true while the request is in flight
104
104
 
105
105
  Submission is blocked while pending because the native control carries the pending message;
106
106
  listen for `zidan:async-validation` if you need your own spinner or toast. `destroy()` aborts
107
- any in-flight check, and `field.reset()` clears the pending state.
107
+ any in-flight check, and `form.reset()` clears the pending state.
108
108
 
109
109
  ## The hidden-input trap
110
110
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zidan-select",
3
- "version": "2.3.1",
3
+ "version": "2.4.1",
4
4
  "description": "Zero-dependency form enhancement library: select/combobox/tags, checkboxes, switches, radio groups, drag & drop file upload with progress, text/number/phone/date/range inputs and textarea with input icons and steppers. Split core/theme CSS, 5 themes, 11 layouts, framework adapters. Load only the select-only or file-only build if that is all you need, or the full form bundle to enhance every input at once.",
5
5
  "keywords": [
6
6
  "select",
@@ -101,8 +101,9 @@
101
101
  "build": "node scripts/build.mjs",
102
102
  "test": "node scripts/test.mjs",
103
103
  "types": "tsc -p tsconfig.types.json",
104
- "prepublishOnly": "npm run types && npm run build && npm test",
105
- "lint": "node --check zidan-form.js && node --check demo.js && node --check advanced.js && node --check playground.js && node --check nav.js && node --check zidan-form.mjs",
104
+ "prepublishOnly": "npm run build && npm run types && npm test",
105
+ "lint": "node --check zidan-form.js && node --check demo.js && node --check lab.js && node --check advanced.js && node --check ajax.js && node --check playground.js && node --check nav.js && node --check scripts/docs.mjs && node --check zidan-form.mjs",
106
+ "release": "node scripts/release.mjs",
106
107
  "search": "node scripts/exa-search.mjs"
107
108
  },
108
109
  "engines": {
package/plugin-core.css CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * ZidanForm v2.3.1 — plugin-core.css
2
+ * ZidanForm v2.4.1 — plugin-core.css
3
3
  * Structure and mechanics only: layout, positioning, visibility, focus
4
4
  * plumbing and accessible native-input handling. No colours, borders colours,
5
5
  * shadows or decorative skin — load plugin-theme.css (or your own theme) for
package/plugin-theme.css CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * ZidanForm v2.3.1 — plugin-theme.css
2
+ * ZidanForm v2.4.1 — plugin-theme.css
3
3
  * Design tokens, paint, state colours, preset themes (default, modern,
4
4
  * minimal, dark, glass), the five select layouts and framework adapters
5
5
  * (bootstrap, tailwind, bulma, foundation).
package/zidan-form.d.ts CHANGED
@@ -59,19 +59,19 @@ export type FetchOptions = (
59
59
  export interface SelectCallbacks {
60
60
  filterOption?(item: SelectItem, query: string, context: { instance: ZidanSelect; mode: SelectMode; caseSensitive: boolean; selected: boolean }): boolean;
61
61
  renderOption?(item: SelectItem, context: { index: number; selected: boolean; active: boolean; query: string; instance: ZidanSelect }): string | Node | null | undefined;
62
- renderSelected?(item: SelectItem, instance: ZidanSelect): string | Node | null | undefined;
63
- renderTag?(item: SelectItem, instance: ZidanSelect): string | Node | null | undefined;
64
- validateTag?(tag: string, tags: string[], context: { instance: ZidanSelect }): boolean | string | void;
65
- formatTag?(tag: string, instance: ZidanSelect): string;
62
+ renderSelected?(item: Pick<SelectItem, 'value' | 'label'>, context: { index: number; instance: ZidanSelect }): string | Node | null | undefined;
63
+ renderTag?(item: Pick<SelectItem, 'value' | 'label'>, context: { index: number; instance: ZidanSelect; disabled: boolean }): string | Node | null | undefined;
64
+ validateTag?(tag: string, tags: SelectItem[], context: { instance: ZidanSelect }): boolean | string | void;
65
+ formatTag?(tag: string, context: { instance: ZidanSelect; tags: SelectItem[] }): string;
66
66
  onInit?(detail: { instance: ZidanSelect; mode: SelectMode; value: unknown }): void;
67
- onChange?(detail: { value: string | string[]; previousValue?: string | string[]; item?: SelectItem; instance: ZidanSelect }): void;
68
- onSelect?(detail: { value: string | string[]; item: SelectItem; instance: ZidanSelect }): void;
67
+ onChange?(detail: { value: unknown; previousValue?: unknown; item?: SelectItem; instance: ZidanSelect }): void;
68
+ onSelect?(detail: { value: unknown; item: SelectItem; instance: ZidanSelect }): void;
69
69
  onOpen?(detail: { instance: ZidanSelect }): void;
70
70
  onClose?(detail: { instance: ZidanSelect }): void;
71
- onTagAdd?(detail: { tag: string; tags: string[]; instance: ZidanSelect }): void;
72
- onTagRemove?(detail: { tag: string; tags: string[]; instance: ZidanSelect }): void;
71
+ onTagAdd?(detail: { tag: string; value: SelectItem[]; instance: ZidanSelect }): void;
72
+ onTagRemove?(detail: { tag: string; value: SelectItem[]; instance: ZidanSelect }): void;
73
73
  onLoadMore?(detail: { page: number; query: string; instance: ZidanSelect }): void;
74
- onError?(detail: { error: unknown; message: string; instance: ZidanSelect }): void;
74
+ onError?(detail: { error?: unknown; message: string; instance: ZidanSelect }): void;
75
75
  }
76
76
 
77
77
  export interface SelectOptions extends SelectCallbacks {
@@ -86,6 +86,7 @@ export interface SelectOptions extends SelectCallbacks {
86
86
  options?: SelectItemInput[] | null;
87
87
  value?: string | string[] | null;
88
88
  label?: string | null;
89
+ ariaLabel?: string;
89
90
  placeholder?: string | null;
90
91
  multiple?: boolean;
91
92
  searchable?: boolean;
@@ -106,6 +107,24 @@ export interface SelectOptions extends SelectCallbacks {
106
107
  autoLoadMore?: boolean;
107
108
  cacheResults?: boolean;
108
109
  loadMoreText?: string;
110
+ /** AJAX without JS: GET this URL and the select builds its own fetchOptions */
111
+ fetchUrl?: string | null;
112
+ fetchMethod?: string;
113
+ /** Query-string parameter for the search term (set to '' to omit it) */
114
+ fetchQueryParam?: string;
115
+ /** 1-based page parameter (set to '' to omit it) */
116
+ fetchPageParam?: string;
117
+ /** When set, send skip = page * pageSize instead of fetchPageParam */
118
+ fetchSkipParam?: string | null;
119
+ fetchPageSizeParam?: string;
120
+ /** Dot path to the array of rows in the JSON body, e.g. 'data.items' */
121
+ fetchItemsPath?: string | null;
122
+ /** Dot path to the total row count, used to decide hasMore */
123
+ fetchTotalPath?: string | null;
124
+ /** Dot path to a boolean hasMore flag */
125
+ fetchHasMorePath?: string | null;
126
+ fetchHeaders?: Record<string, string> | null;
127
+ fetchCredentials?: RequestCredentials;
109
128
  maxTags?: number;
110
129
  minTagLength?: number;
111
130
  maxTagLength?: number;
@@ -208,16 +227,21 @@ export interface FileFieldOptions extends FieldOptions {
208
227
 
209
228
  export interface TextFieldOptions extends FieldOptions {
210
229
  icon?: string;
211
- iconPosition?: 'start' | 'end';
230
+ iconPosition?: 'left' | 'right';
212
231
  prefix?: string;
213
232
  suffix?: string;
214
233
  clearable?: boolean;
215
- counter?: boolean;
216
- counterMax?: number;
234
+ counter?: number;
217
235
  output?: HTMLOutputElement | string;
218
- stepper?: boolean;
219
- stepperMode?: string;
220
- phone?: boolean;
236
+ stepper?: boolean | string;
237
+ stepperStep?: number;
238
+ phone?: boolean | {
239
+ country?: string;
240
+ format?: PhoneFormat;
241
+ showCountry?: boolean;
242
+ countries?: string[];
243
+ validate?: boolean;
244
+ };
221
245
  phoneCountry?: string;
222
246
  phoneFormat?: PhoneFormat;
223
247
  rangeVariant?: 'default' | 'gradient' | 'stepped' | 'minimal';
@@ -290,8 +314,8 @@ export class ZidanSelect {
290
314
  setValue(value: string | number | Array<string | number> | null, options?: { silent?: boolean }): this;
291
315
  clear(): this;
292
316
  setOptions(options: SelectItemInput[] | null): this;
293
- addTag(label: string, data?: unknown): this;
294
- removeTag(index: number): this;
317
+ addTag(label: string, data?: unknown): boolean;
318
+ removeTag(tagOrIndex: string | number): boolean;
295
319
  getTags(): SelectItem[];
296
320
  enable(): this;
297
321
  disable(): this;
@@ -343,7 +367,7 @@ export class ZidanFileUpload extends ZidanFieldBase {
343
367
  getUploadState(): UploadState[];
344
368
  addFiles(files: File[] | FileList): this;
345
369
  replaceFiles(files: File[] | FileList): this;
346
- removeFile(index: number): this;
370
+ removeFile(index: number | File): this;
347
371
  clear(): this;
348
372
  uploadAll(): this | Promise<boolean>;
349
373
  uploadFile(file: File): this | Promise<unknown>;
@@ -351,7 +375,7 @@ export class ZidanFileUpload extends ZidanFieldBase {
351
375
  cancelAll(): this;
352
376
  retryUpload(file: File): this;
353
377
  setVariant(variant: string): this;
354
- setUploader(handler: UploadHandler | null): this;
378
+ setUploader(handler: UploadHandler | string | null): this;
355
379
  }
356
380
 
357
381
  export class ZidanTextField extends ZidanFieldBase {
@@ -360,8 +384,8 @@ export class ZidanTextField extends ZidanFieldBase {
360
384
  stepUp(times?: number): this;
361
385
  stepDown(times?: number): this;
362
386
  setStepper(enabled: boolean): this;
363
- openPicker(): void;
364
- showPicker(): void;
387
+ openPicker(): this;
388
+ showPicker(): this;
365
389
  getPhoneCountry(): string;
366
390
  setPhoneCountry(iso: string): this;
367
391
  setPhoneFormat(format: PhoneFormat): this;
package/zidan-form.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * ZidanForm v2.3.1
2
+ * ZidanForm v2.4.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.3.1';
35
+ var VERSION = '2.4.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.
@@ -671,6 +671,17 @@
671
671
  autoLoadMore: true,
672
672
  cacheResults: true,
673
673
  loadMoreText: 'Load more',
674
+ fetchUrl: null, // declarative AJAX: GET this endpoint instead of writing fetchOptions
675
+ fetchMethod: 'GET',
676
+ fetchQueryParam: 'q',
677
+ fetchPageParam: 'page', // 1-based page number sent with every request
678
+ fetchSkipParam: null, // when set, send skip = page * pageSize instead of fetchPageParam
679
+ fetchPageSizeParam: 'limit',
680
+ fetchItemsPath: null, // dot path to the array in the JSON body ('data.items')
681
+ fetchTotalPath: null, // dot path to the number of rows available
682
+ fetchHasMorePath: null, // dot path to a boolean
683
+ fetchHeaders: null,
684
+ fetchCredentials: 'same-origin',
674
685
  /* tags */
675
686
  maxTags: Infinity,
676
687
  minTagLength: 1,
@@ -708,6 +719,112 @@
708
719
  * ZidanSelect
709
720
  * ------------------------------------------------------------------ */
710
721
 
722
+ /* ---------------- declarative AJAX (fetchUrl) ---------------- */
723
+
724
+ function readDotPath(source, path) {
725
+ if (!path) return undefined;
726
+ return String(path).split('.').reduce(function (node, key) {
727
+ return node === null || node === undefined ? undefined : node[key];
728
+ }, source);
729
+ }
730
+
731
+ function firstRemoteArray(body) {
732
+ if (Array.isArray(body)) return body;
733
+ if (!body || typeof body !== 'object') return [];
734
+ var keys = ['items', 'data', 'results', 'options', 'rows', 'products', 'records'];
735
+ for (var i = 0; i < keys.length; i++) {
736
+ if (Array.isArray(body[keys[i]])) return body[keys[i]];
737
+ }
738
+ return [];
739
+ }
740
+
741
+ /* Map common API shapes ({id,title}, {value,label}, plain strings) to select items. */
742
+ function remoteItem(raw) {
743
+ if (raw === null || raw === undefined) return null;
744
+ if (typeof raw !== 'object') {
745
+ var text = String(raw);
746
+ return { value: text, label: text };
747
+ }
748
+ var value = raw.value !== undefined ? raw.value
749
+ : raw.id !== undefined ? raw.id
750
+ : raw.slug !== undefined ? raw.slug
751
+ : raw.code !== undefined ? raw.code
752
+ : raw.key !== undefined ? raw.key : undefined;
753
+ var label = raw.label !== undefined ? raw.label
754
+ : raw.name !== undefined ? raw.name
755
+ : raw.title !== undefined ? raw.title
756
+ : raw.full_name !== undefined ? raw.full_name
757
+ : raw.text !== undefined ? raw.text : undefined;
758
+ if (label === undefined) label = value === undefined ? '' : value;
759
+ if (value === undefined) value = label;
760
+ return { value: value, label: label, disabled: !!raw.disabled };
761
+ }
762
+
763
+ /*
764
+ * Turns fetchUrl + fetch* options into the same promise fetchOptions would return:
765
+ * { items, hasMore, total }. Honours AbortSignal and the paging context the
766
+ * select passes in, so caching, debounce and "Load more" work unchanged.
767
+ */
768
+ function createRemoteFetcher(opts) {
769
+ return function (query, signal, context) {
770
+ if (typeof fetch !== 'function') {
771
+ return Promise.reject(new Error('This environment has no fetch().'));
772
+ }
773
+ var page = context && context.page ? context.page : 0;
774
+ var pageSize = opts.fetchPageSize > 0 ? opts.fetchPageSize : 0;
775
+ var url;
776
+ try {
777
+ url = new URL(opts.fetchUrl, (typeof location !== 'undefined' && location.href) || undefined);
778
+ } catch (error) {
779
+ return Promise.reject(new Error('Invalid fetchUrl: ' + opts.fetchUrl));
780
+ }
781
+ if (opts.fetchQueryParam) url.searchParams.set(opts.fetchQueryParam, query || '');
782
+ if (pageSize > 0 && opts.fetchPageSizeParam) {
783
+ url.searchParams.set(opts.fetchPageSizeParam, String(pageSize));
784
+ }
785
+ if (opts.fetchSkipParam) {
786
+ if (pageSize > 0) url.searchParams.set(opts.fetchSkipParam, String(page * pageSize));
787
+ } else if (opts.fetchPageParam) {
788
+ url.searchParams.set(opts.fetchPageParam, String(page + 1));
789
+ }
790
+
791
+ var headers = { Accept: 'application/json' };
792
+ if (opts.fetchHeaders && typeof opts.fetchHeaders === 'object') {
793
+ Object.keys(opts.fetchHeaders).forEach(function (key) {
794
+ headers[key] = opts.fetchHeaders[key];
795
+ });
796
+ }
797
+
798
+ return fetch(url.toString(), {
799
+ method: opts.fetchMethod || 'GET',
800
+ headers: headers,
801
+ signal: signal,
802
+ credentials: opts.fetchCredentials || 'same-origin'
803
+ }).then(function (response) {
804
+ if (!response.ok) {
805
+ throw new Error('Request failed (' + response.status + ' ' + (response.statusText || 'error') + ')');
806
+ }
807
+ return response.json();
808
+ }).then(function (body) {
809
+ var rows = opts.fetchItemsPath ? readDotPath(body, opts.fetchItemsPath) : firstRemoteArray(body);
810
+ if (!Array.isArray(rows)) rows = rows === undefined || rows === null ? [] : [rows];
811
+ var items = rows.map(remoteItem).filter(Boolean);
812
+
813
+ var hasMore;
814
+ if (opts.fetchHasMorePath) hasMore = !!readDotPath(body, opts.fetchHasMorePath);
815
+ var rawTotal = opts.fetchTotalPath ? readDotPath(body, opts.fetchTotalPath)
816
+ : (body && typeof body === 'object' ? body.total : undefined);
817
+ var total = rawTotal === undefined || rawTotal === null ? NaN : Number(rawTotal);
818
+ if (hasMore === undefined && isFinite(total) && pageSize > 0) {
819
+ hasMore = (page + 1) * pageSize < total;
820
+ }
821
+ if (hasMore === undefined) hasMore = pageSize > 0 && items.length >= pageSize;
822
+
823
+ return { items: items, hasMore: hasMore, total: isFinite(total) ? total : undefined };
824
+ });
825
+ };
826
+ }
827
+
711
828
  function ZidanSelect(target, options) {
712
829
  if (!(this instanceof ZidanSelect)) return new ZidanSelect(target, options);
713
830
  if (!doc) throw new Error('ZidanSelect requires a DOM environment.');
@@ -828,6 +945,15 @@
828
945
  merged.autoLoadMore = pick('autoLoadMore', readBoolAttr(d.zidanAutoLoadMore, DEFAULTS.autoLoadMore));
829
946
  merged.cacheResults = pick('cacheResults', readBoolAttr(d.zidanCacheResults, DEFAULTS.cacheResults));
830
947
  merged.loadMoreText = pick('loadMoreText', d.zidanLoadMoreText || DEFAULTS.loadMoreText);
948
+ merged.fetchUrl = pick('fetchUrl', d.zidanFetchUrl || null);
949
+ merged.fetchMethod = pick('fetchMethod', d.zidanFetchMethod || DEFAULTS.fetchMethod);
950
+ merged.fetchQueryParam = pick('fetchQueryParam', d.zidanFetchQueryParam !== undefined ? d.zidanFetchQueryParam : DEFAULTS.fetchQueryParam);
951
+ merged.fetchPageParam = pick('fetchPageParam', d.zidanFetchPageParam !== undefined ? d.zidanFetchPageParam : DEFAULTS.fetchPageParam);
952
+ merged.fetchSkipParam = pick('fetchSkipParam', d.zidanFetchSkipParam || null);
953
+ merged.fetchPageSizeParam = pick('fetchPageSizeParam', d.zidanFetchPageSizeParam !== undefined ? d.zidanFetchPageSizeParam : DEFAULTS.fetchPageSizeParam);
954
+ merged.fetchItemsPath = pick('fetchItemsPath', d.zidanFetchItemsPath || null);
955
+ merged.fetchTotalPath = pick('fetchTotalPath', d.zidanFetchTotalPath || null);
956
+ merged.fetchHasMorePath = pick('fetchHasMorePath', d.zidanFetchHasMorePath || null);
831
957
 
832
958
  // carry over every explicitly-passed option (callbacks, custom classes, ...)
833
959
  Object.keys(options).forEach(function (key) {
@@ -843,6 +969,11 @@
843
969
  if (mode === 'combobox') merged.searchable = true;
844
970
  if (mode === 'tags' && merged.searchable === false) merged.searchable = true;
845
971
  if (mode === 'tags') merged.multiple = true;
972
+
973
+ // declarative AJAX: one URL is enough to opt into remote loading
974
+ if (merged.fetchUrl && typeof merged.fetchOptions !== 'function') {
975
+ merged.fetchOptions = createRemoteFetcher(merged);
976
+ }
846
977
  return merged;
847
978
  };
848
979