zidan-select 2.1.2 → 2.2.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.
@@ -0,0 +1,1946 @@
1
+ /*!
2
+ * ZidanForm File-only v2.2.0
3
+ * Zero-dependency drag & drop file upload with variants, previews, limits and progress.
4
+ * Pairs with plugin-file-core.css and plugin-file-theme.css.
5
+ *
6
+ * Generated by scripts/build.mjs — edit zidan-form.js instead.
7
+ * https://github.com/akhtar1985/zidan-select
8
+ * MIT License © akhtar1985
9
+ *
10
+ * Classic <script> adds window.ZidanForm plus window.zidanField / initZidanForms.
11
+ */
12
+ (function (root, factory) {
13
+ 'use strict';
14
+ var api = factory(root);
15
+ if (typeof window !== 'undefined') {
16
+ window.ZidanForm = api.ZidanForm;
17
+ if (api.ZidanSelect) {
18
+ window.ZidanSelect = api.ZidanSelect;
19
+ window.zidanSelect = api.zidanSelect;
20
+ window.initZidanSelects = api.initZidanSelects;
21
+ }
22
+ if (api.zidanField) window.zidanField = api.zidanField;
23
+ if (api.initZidanForms) window.initZidanForms = api.initZidanForms;
24
+ if (api.registerIcon) window.registerZidanIcon = api.registerIcon;
25
+ }
26
+ if (typeof module !== 'undefined' && module.exports) {
27
+ module.exports = api;
28
+ }
29
+ })(typeof window !== 'undefined' ? window : this, function (global) {
30
+ 'use strict';
31
+
32
+ var VERSION = '2.2.0';
33
+
34
+ // Loading the file twice (classic script + module wrapper, or two bundles)
35
+ // must not replace the classes and orphan the live instances.
36
+ if (global && global.ZidanForm && global.ZidanForm.__zidanFormGuard === VERSION) {
37
+ return global.ZidanForm.api;
38
+ }
39
+
40
+ var doc = typeof document !== 'undefined' ? document : null;
41
+
42
+ /* ------------------------------------------------------------------ *
43
+ * Constants & tiny helpers
44
+ * ------------------------------------------------------------------ */
45
+
46
+ var LAYOUTS = ['classic-clean', 'floating-label', 'soft-pill', 'bordered-brutalist', 'glass-elevated'];
47
+ var FRAMEWORKS = ['auto', 'none', 'vanilla', 'bootstrap', 'tailwind', 'bulma', 'foundation'];
48
+ var THEMES = ['default', 'modern', 'minimal', 'dark', 'glass'];
49
+ var FIELD_LAYOUTS = ['stacked', 'inline', 'card', 'compact', 'floating', 'outlined'];
50
+ var FIELD_KINDS = ['checkbox', 'radio', 'radio-group', 'file', 'input', 'textarea'];
51
+ var FIELDS_SELECTOR = '[data-zidan], [data-zidan-checkbox], [data-zidan-switch], [data-zidan-radio], ' +
52
+ '[data-zidan-radio-group], [data-zidan-file], [data-zidan-input], [data-zidan-textarea], .zidan-field';
53
+ var SELECT_SELECTOR = '[data-zidan-select], .zidan-select';
54
+ var FORM_SCOPE_SELECTOR = '[data-zidan-form], .zidan-form';
55
+ var SCROLLBARS = ['default', 'thin', 'fancy', 'hover', 'hidden'];
56
+ var EVENT_PREFIX = 'zidan:';
57
+ var uidSeq = 0;
58
+
59
+ function uid(prefix) {
60
+ uidSeq += 1;
61
+ return (prefix || 'zs') + '-' + uidSeq.toString(36) + Math.random().toString(36).slice(2, 6);
62
+ }
63
+
64
+ function hasClass(node, cls) {
65
+ return !!(node && node.classList && node.classList.contains(cls));
66
+ }
67
+
68
+ function addClass(node, cls) {
69
+ if (!node || !cls) return node;
70
+ cls.split(/\s+/).forEach(function (c) {
71
+ if (c) node.classList.add(c);
72
+ });
73
+ return node;
74
+ }
75
+
76
+ function el(tag, className, attrs, text) {
77
+ var node = doc.createElement(tag);
78
+ if (className) node.className = className;
79
+ if (attrs) {
80
+ Object.keys(attrs).forEach(function (key) {
81
+ var value = attrs[key];
82
+ if (value === null || value === undefined || value === false) return;
83
+ if (key === 'text') node.textContent = String(value);
84
+ else node.setAttribute(key, value === true ? '' : String(value));
85
+ });
86
+ }
87
+ if (text !== undefined && text !== null) node.textContent = String(text);
88
+ return node;
89
+ }
90
+
91
+ function toArray(value) {
92
+ if (value === null || value === undefined || value === '') return [];
93
+ return Array.isArray(value) ? value.slice() : [value];
94
+ }
95
+
96
+ function isElement(value) {
97
+ return !!(value && typeof value === 'object' && value.nodeType === 1);
98
+ }
99
+
100
+ function readBoolAttr(value, fallback) {
101
+ if (value === undefined || value === null || value === '') return fallback;
102
+ var v = String(value).toLowerCase();
103
+ return !(v === 'false' || v === '0' || v === 'no' || v === 'off');
104
+ }
105
+
106
+ /* copy own keys from each source; later sources win */
107
+ function mergeOptions() {
108
+ var out = {};
109
+ for (var i = 0; i < arguments.length; i++) {
110
+ (function (source) {
111
+ if (!source || typeof source !== 'object') return;
112
+ Object.keys(source).forEach(function (key) {
113
+ if (source[key] !== undefined) out[key] = source[key];
114
+ });
115
+ })(arguments[i]);
116
+ }
117
+ return out;
118
+ }
119
+
120
+ /* data-zidan-options='{"mode":"tags",...}' — options for CMS/JSON-only setups */
121
+ function parseOptionsAttr(node) {
122
+ if (!node || !node.getAttribute) return null;
123
+ var raw = node.getAttribute('data-zidan-options');
124
+ if (!raw) return null;
125
+ try {
126
+ var parsed = JSON.parse(raw);
127
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
128
+ } catch (error) {
129
+ if (typeof console !== 'undefined' && console.warn) {
130
+ console.warn('[ZidanForm] ignoring invalid data-zidan-options JSON on', node, error);
131
+ }
132
+ return null;
133
+ }
134
+ }
135
+
136
+ function clamp(value, min, max) {
137
+ return Math.min(max, Math.max(min, value));
138
+ }
139
+
140
+ function fillTemplate(template, vars) {
141
+ return String(template).replace(/\{(\w+)\}/g, function (match, key) {
142
+ return vars && vars[key] !== undefined && vars[key] !== null ? String(vars[key]) : match;
143
+ });
144
+ }
145
+
146
+ /* ---------------- opt-in icon presets ---------------- */
147
+
148
+ var ICON_PATHS = {
149
+ text: '<path d="M4 7h16M4 12h10M4 17h13"/>',
150
+ mail: '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/>',
151
+ phone: '<path d="M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1 1 .4 1.9.7 2.8a2 2 0 0 1-.5 2.1L8.1 9.9a16 16 0 0 0 6 6l1.3-1.2a2 2 0 0 1 2.1-.5c.9.3 1.8.6 2.8.7a2 2 0 0 1 1.7 2Z"/>',
152
+ user: '<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>',
153
+ lock: '<rect x="4" y="10" width="16" height="11" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/>',
154
+ search: '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',
155
+ calendar: '<rect x="3" y="5" width="18" height="16" rx="2"/><path d="M16 3v4M8 3v4M3 11h18"/>',
156
+ clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
157
+ link: '<path d="M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1.5 1.5"/><path d="M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1.5-1.5"/>',
158
+ hash: '<path d="M4 9h16M4 15h16M10 3 8 21M16 3l-2 18"/>',
159
+ palette: '<path d="M12 3a9 9 0 0 0 0 18h1.5a2.5 2.5 0 0 0 0-5H12a2 2 0 0 1 0-4h4a5 5 0 0 0 0-10Z"/><circle cx="8.5" cy="8.5" r="1"/><circle cx="8" cy="14" r="1"/>',
160
+ sliders: '<path d="M4 7h16M4 17h16"/><circle cx="9" cy="7" r="2.5"/><circle cx="15" cy="17" r="2.5"/>',
161
+ file: '<path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/>',
162
+ upload: '<path d="M12 16V4"/><path d="m7 9 5-5 5 5"/><path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"/>',
163
+ eye: '<path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6-10-6-10-6Z"/><circle cx="12" cy="12" r="3"/>',
164
+ 'eye-off': '<path d="m3 3 18 18"/><path d="M10.6 6.2A9.9 9.9 0 0 1 12 6c6.5 0 10 6 10 6a17 17 0 0 1-3.1 3.6"/><path d="M6.4 6.7C3.5 8.4 2 12 2 12s3.5 6 10 6c1.7 0 3.2-.4 4.5-1"/><path d="M9.9 9.9a3 3 0 0 0 4.2 4.2"/>',
165
+ check: '<path d="m4 12.5 5 5L20 6.5"/>',
166
+ x: '<path d="M6 6l12 12M18 6 6 18"/>',
167
+ plus: '<path d="M12 5v14M5 12h14"/>',
168
+ minus: '<path d="M5 12h14"/>',
169
+ 'chevron-down': '<path d="m6 9 6 6 6-6"/>',
170
+ 'chevron-up': '<path d="m6 15 6-6 6 6"/>',
171
+ 'chevron-left': '<path d="m15 6-6 6 6 6"/>',
172
+ 'chevron-right': '<path d="m9 6 6 6-6 6"/>',
173
+ alert: '<path d="M12 9v4"/><path d="M12 17h.01"/><path d="M10.3 3.9 2.6 17.4A2 2 0 0 0 4.3 20h15.4a2 2 0 0 0 1.7-2.6L13.7 3.9a2 2 0 0 0-3.4 0Z"/>',
174
+ info: '<circle cx="12" cy="12" r="9"/><path d="M12 11v5"/><path d="M12 8h.01"/>',
175
+ globe: '<circle cx="12" cy="12" r="9"/><path d="M3 12h18"/><path d="M12 3a15 15 0 0 1 0 18 15 15 0 0 1 0-18Z"/>',
176
+ 'map-pin': '<path d="M20 10c0 6-8 12-8 12S4 16 4 10a8 8 0 1 1 16 0Z"/><circle cx="12" cy="10" r="3"/>',
177
+ image: '<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/>',
178
+ refresh: '<path d="M20 11a8 8 0 0 0-14.9-3.9L3 10"/><path d="M3 5v5h5"/><path d="M4 13a8 8 0 0 0 14.9 3.9L21 14"/><path d="M21 19v-5h-5"/>',
179
+ trash: '<path d="M4 7h16"/><path d="M9 7V4h6v3"/><path d="M6 7l1 13h10l1-13"/><path d="M10 11v5M14 11v5"/>'
180
+ };
181
+
182
+ var ICON_REGISTRY = {};
183
+ Object.keys(ICON_PATHS).forEach(function (key) { ICON_REGISTRY[key] = ICON_PATHS[key]; });
184
+ var ICON_NAMESPACE = 'http://www.w3.org/2000/svg';
185
+
186
+ var ICON_ALLOWED = {
187
+ svg: 1, g: 1, path: 1, circle: 1, rect: 1, line: 1, polyline: 1,
188
+ polygon: 1, ellipse: 1, title: 1, defs: 1, clipPath: 1, clippath: 1, mask: 1
189
+ };
190
+
191
+ function sanitizeIcon(markup) {
192
+ if (typeof markup !== 'string' || !markup.trim()) return '';
193
+ var parsed;
194
+ try {
195
+ if (typeof global.DOMParser === 'undefined') return '';
196
+ parsed = new global.DOMParser().parseFromString(markup, 'image/svg+xml');
197
+ } catch (err) {
198
+ return '';
199
+ }
200
+ if (!parsed || !parsed.documentElement) return '';
201
+ var svg = parsed.documentElement;
202
+ if (String(svg.nodeName).toLowerCase() !== 'svg') return '';
203
+ if (parsed.getElementsByTagName('parsererror').length) return '';
204
+ var walk = function (node) {
205
+ Array.prototype.slice.call(node.children || []).forEach(function (child) {
206
+ var tag = String(child.nodeName);
207
+ if (tag !== tag.toLowerCase()) tag = tag.toLowerCase();
208
+ if (!ICON_ALLOWED[tag]) {
209
+ child.parentNode.removeChild(child);
210
+ return;
211
+ }
212
+ Array.prototype.slice.call(child.attributes || []).forEach(function (attr) {
213
+ var name = String(attr.name).toLowerCase();
214
+ if (name.indexOf('on') === 0) child.removeAttribute(attr.name);
215
+ if ((name === 'href' || name === 'xlink:href') && !/^#/.test(attr.value)) child.removeAttribute(attr.name);
216
+ if (/url\s*\(\s*['"]?\s*(?:https?:|\/\/)/i.test(attr.value)) child.removeAttribute(attr.name);
217
+ });
218
+ walk(child);
219
+ });
220
+ };
221
+ walk(svg);
222
+ return svg.outerHTML;
223
+ }
224
+
225
+ function iconSvgFromMarkup(markup) {
226
+ var paths = markup;
227
+ if (/^\s*</.test(paths) && !/^\s*<svg/i.test(paths)) {
228
+ paths = '<svg xmlns="' + ICON_NAMESPACE + '" viewBox="0 0 24 24" fill="none" stroke="currentColor" ' +
229
+ 'stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' + paths + '</svg>';
230
+ } else if (!/^\s*<svg/i.test(paths)) {
231
+ paths = '';
232
+ }
233
+ return sanitizeIcon(paths);
234
+ }
235
+
236
+ function iconNode(spec, className) {
237
+ var markup = '';
238
+ var name = '';
239
+ if (typeof spec === 'string' && spec) {
240
+ name = spec;
241
+ if (/^\s*</.test(spec)) {
242
+ markup = iconSvgFromMarkup(spec) || iconSvgFromMarkup('<path d="M4 12h16"/>');
243
+ } else if (ICON_REGISTRY[spec]) {
244
+ markup = iconSvgFromMarkup(ICON_REGISTRY[spec]) || '';
245
+ }
246
+ } else if (spec && typeof spec === 'object' && spec.name) {
247
+ name = spec.name;
248
+ markup = iconSvgFromMarkup(ICON_REGISTRY[spec.name] || '');
249
+ }
250
+ if (!markup) return null;
251
+ var node = doc.createElement('span');
252
+ if (className) node.className = className;
253
+ node.setAttribute('data-zs-icon', name || 'custom');
254
+ try {
255
+ node.innerHTML = markup;
256
+ } catch (err) {
257
+ return null;
258
+ }
259
+ var svg = node.firstChild;
260
+ if (svg) {
261
+ svg.setAttribute('focusable', 'false');
262
+ svg.setAttribute('aria-hidden', 'true');
263
+ svg.setAttribute('width', '18');
264
+ svg.setAttribute('height', '18');
265
+ }
266
+ return node;
267
+ }
268
+
269
+ var TYPE_ICONS = {
270
+ text: 'text',
271
+ email: 'mail',
272
+ password: 'lock',
273
+ number: 'hash',
274
+ tel: 'phone',
275
+ url: 'link',
276
+ search: 'search',
277
+ date: 'calendar',
278
+ time: 'clock',
279
+ 'datetime-local': 'calendar',
280
+ month: 'calendar',
281
+ week: 'calendar',
282
+ range: 'sliders',
283
+ color: 'palette'
284
+ };
285
+
286
+ function iconForType(type) {
287
+ return TYPE_ICONS[type] || '';
288
+ }
289
+
290
+ function registerIcon(name, markup) {
291
+ if (!name || typeof markup !== 'string') return ZidanSelect;
292
+ ICON_REGISTRY[String(name)] = markup;
293
+ return ZidanSelect;
294
+ }
295
+
296
+ /* ---------------- field options (JS options + data-* attributes) ---------------- */
297
+
298
+ function fieldOption(node, options, key, attr, fallback) {
299
+ if (options && options[key] !== undefined && options[key] !== null) return options[key];
300
+ if (node && attr && node.getAttribute) {
301
+ var value = node.getAttribute('data-zidan-' + attr);
302
+ if (value !== null && value !== '') return value;
303
+ }
304
+ return fallback;
305
+ }
306
+
307
+ function fieldBool(node, options, key, attr, fallback) {
308
+ if (options && options[key] !== undefined && options[key] !== null) return !!options[key];
309
+ if (node && attr && node.getAttribute) {
310
+ var value = node.getAttribute('data-zidan-' + attr);
311
+ if (value !== null) return readBoolAttr(value, fallback);
312
+ }
313
+ return fallback;
314
+ }
315
+
316
+ function fieldNumber(node, options, key, attr, fallback) {
317
+ var value = fieldOption(node, options, key, attr, fallback);
318
+ if (value === null || value === undefined || value === '') return fallback;
319
+ var number = parseFloat(value);
320
+ return isFinite(number) ? number : fallback;
321
+ }
322
+
323
+ function fieldList(node, options, key, attr, fallback) {
324
+ var value = fieldOption(node, options, key, attr, null);
325
+ if (value === null || value === undefined || value === '') return fallback;
326
+ if (Array.isArray(value)) return value.slice();
327
+ return String(value).split(',').map(function (item) { return item.trim(); }).filter(Boolean);
328
+ }
329
+
330
+ /* ---------------- validation messages ---------------- */
331
+
332
+ var FIELD_MESSAGES = {
333
+ required: 'This field is required.',
334
+ email: 'Enter a valid email address.',
335
+ url: 'Enter a valid URL.',
336
+ pattern: 'The value does not match the expected format.',
337
+ min: 'Value must be at least {min}.',
338
+ max: 'Value must be at most {max}.',
339
+ step: 'Value must be a multiple of {step}.',
340
+ minlength: 'Use at least {minlength} characters.',
341
+ maxlength: 'Use at most {maxlength} characters.',
342
+ badInput: 'Enter a valid value.',
343
+ phone: 'Enter a valid phone number for {country}.',
344
+ integer: 'Enter a whole number.',
345
+ date: 'Enter a valid date.',
346
+ weekend: 'Weekends are not available — pick a weekday.',
347
+ dateDisabled: 'This date is not available.',
348
+ fileType: 'This file type is not allowed.',
349
+ fileSize: 'This file is too large.',
350
+ fileCount: 'Too many files.',
351
+ generic: 'Please check this field.'
352
+ };
353
+
354
+ function validityMessage(input, messages) {
355
+ if (!input || !input.validity || input.validity.valid) return '';
356
+ var v = input.validity;
357
+ var map = messages || FIELD_MESSAGES;
358
+ var type = String(input.type || '').toLowerCase();
359
+ var key = '';
360
+ var vars = { min: input.getAttribute('min'), max: input.getAttribute('max'), step: input.getAttribute('step') };
361
+ if (v.valueMissing) key = 'required';
362
+ else if (v.typeMismatch) key = type === 'email' ? 'email' : (type === 'url' ? 'url' : 'generic');
363
+ else if (v.patternMismatch) key = 'pattern';
364
+ else if (v.rangeUnderflow) key = 'min';
365
+ else if (v.rangeOverflow) key = 'max';
366
+ else if (v.stepMismatch) key = 'step';
367
+ else if (v.tooShort) {
368
+ key = 'minlength';
369
+ vars.minlength = input.getAttribute('minlength');
370
+ } else if (v.tooLong) {
371
+ key = 'maxlength';
372
+ vars.maxlength = input.getAttribute('maxlength');
373
+ } else if (v.badInput || v.customError) key = 'badInput';
374
+ if (!key) return input.validationMessage || map.generic;
375
+ return fillTemplate(map[key] || FIELD_MESSAGES[key] || map.generic, vars);
376
+ }
377
+
378
+ /* first non-empty value of any of `names`, walking up the tree */
379
+ function inheritedAttr(node, names) {
380
+ var current = node;
381
+ while (current && current.nodeType === 1) {
382
+ for (var i = 0; i < names.length; i += 1) {
383
+ var value = current.getAttribute(names[i]);
384
+ if (value) return value;
385
+ }
386
+ current = current.parentElement;
387
+ }
388
+ return '';
389
+ }
390
+
391
+ function pickList(value, list, fallback) {
392
+ var candidate = String(value || '').toLowerCase();
393
+ return list.indexOf(candidate) === -1 ? fallback : candidate;
394
+ }
395
+
396
+ /* theme/framework/layout resolution shared by every field and the select */
397
+ function resolveScope(node, options) {
398
+ var opts = options || {};
399
+ var theme = opts.theme || inheritedAttr(node, ['data-zidan-theme', 'data-zs-theme']);
400
+ if (!theme && doc) theme = doc.documentElement.getAttribute('data-zs-theme') || '';
401
+ var framework = opts.framework || inheritedAttr(node, ['data-zidan-framework', 'data-zs-framework']);
402
+ if (!framework && doc) framework = doc.documentElement.getAttribute('data-zs-framework') || '';
403
+ var layout = opts.layout || inheritedAttr(node, ['data-zidan-layout', 'data-zs-layout']);
404
+ return {
405
+ theme: pickList(theme, THEMES, 'default'),
406
+ framework: pickList(framework, FRAMEWORKS, 'none'),
407
+ layout: layout ? String(layout).toLowerCase() : ''
408
+ };
409
+ }
410
+
411
+ function debounce(fn, wait) {
412
+ var timer = null;
413
+ function debounced() {
414
+ var args = arguments;
415
+ clearTimeout(timer);
416
+ timer = setTimeout(function () {
417
+ timer = null;
418
+ fn.apply(null, args);
419
+ }, wait);
420
+ }
421
+ debounced.cancel = function () {
422
+ clearTimeout(timer);
423
+ timer = null;
424
+ };
425
+ return debounced;
426
+ }
427
+
428
+ /* ================================================================== *
429
+ * Part 2 — opt-in form fields
430
+ *
431
+ * The real control always stays in the DOM (1×1px, never display:none),
432
+ * so FormData, form.reset(), constraint validation and jQuery Validation's
433
+ * ":hidden" ignore all keep working. Wrappers only mirror its state.
434
+ * ================================================================== */
435
+
436
+ var VALIDATION_STATES = ['valid', 'invalid'];
437
+ var CHECKBOX_VARIANTS = ['default', 'switch', 'card', 'button', 'minimal'];
438
+ var SWITCH_STYLES = ['ios', 'material', 'square', 'labeled', 'icon'];
439
+ var RADIO_VARIANTS = ['stacked', 'inline', 'card', 'button', 'tile'];
440
+ var FILE_VARIANTS = ['dropzone', 'button', 'avatar', 'gallery', 'compact'];
441
+ var RANGE_VARIANTS = ['default', 'gradient', 'stepped', 'minimal'];
442
+
443
+ function textWithout(rootNode, skip) {
444
+ var out = '';
445
+ Array.prototype.slice.call(rootNode.childNodes).forEach(function (node) {
446
+ if (node === skip || node.nodeType !== 3) return;
447
+ out += node.nodeValue;
448
+ });
449
+ return out.replace(/\s+/g, ' ').trim();
450
+ }
451
+
452
+ function moveTextInto(label, target) {
453
+ Array.prototype.slice.call(label.childNodes).forEach(function (node) {
454
+ if (node.nodeType === 3 && node.nodeValue.trim()) target.appendChild(node);
455
+ });
456
+ return target;
457
+ }
458
+
459
+ /* ---------------- shared base ---------------- */
460
+
461
+ function ZidanFieldBase(target, options, kind) {
462
+ if (!doc) throw new Error('ZidanForm requires a DOM environment.');
463
+ if (!isElement(target)) throw new Error('ZidanForm: target element not found.');
464
+ this.el = target;
465
+ this.kind = kind;
466
+ this.opts = options || {};
467
+ this.opts.messages = Object.assign({}, FIELD_MESSAGES, this.opts.messages || {});
468
+ this.id = target.id || (target.id = uid('zf'));
469
+ this.root = null;
470
+ this.touched = false;
471
+ this.validation = null;
472
+ this.errorMessage = null;
473
+ this.errorEl = null;
474
+ this.destroyed = false;
475
+ this._listeners = [];
476
+ this._cleanups = [];
477
+ this.formEl = target.form || (target.closest ? target.closest('form') : null);
478
+ var scope = resolveScope(target, this.opts);
479
+ this.theme = scope.theme;
480
+ this.framework = scope.framework;
481
+ this.layout = this.opts.layout || scope.layout;
482
+ }
483
+
484
+ ZidanFieldBase.prototype.on = function (node, type, handler, config) {
485
+ if (!node || !node.addEventListener) return this;
486
+ node.addEventListener(type, handler, config);
487
+ this._listeners.push([node, type, handler, config]);
488
+ return this;
489
+ };
490
+
491
+ ZidanFieldBase.prototype.emit = function (name, detail) {
492
+ if (!this.root) return this;
493
+ var payload = detail || {};
494
+ payload.instance = this;
495
+ payload.kind = this.kind;
496
+ try {
497
+ this.root.dispatchEvent(new CustomEvent(EVENT_PREFIX + name, { detail: payload, bubbles: true }));
498
+ } catch (err) { /* CustomEvent unsupported: events are optional */ }
499
+ return this;
500
+ };
501
+
502
+ ZidanFieldBase.prototype.call = function (name, payload) {
503
+ var fn = this.opts[name];
504
+ if (typeof fn !== 'function') return undefined;
505
+ try { return fn(payload); } catch (err) { this.emit('error', { error: err, callback: name }); }
506
+ return undefined;
507
+ };
508
+
509
+ ZidanFieldBase.prototype._scope = function (kind) {
510
+ var root = el('div', 'zs-field');
511
+ root.id = this.id + '-field';
512
+ root.setAttribute('data-zs-kind', kind);
513
+ root.classList.add('zs-field--' + kind);
514
+ this._applyScope(root);
515
+ this.root = root;
516
+ return root;
517
+ };
518
+
519
+ ZidanFieldBase.prototype._applyScope = function (root) {
520
+ root.setAttribute('data-zs-theme', this.theme);
521
+ root.setAttribute('data-zs-framework', this.framework);
522
+ if (this.layout) root.setAttribute('data-zs-layout', this.layout);
523
+ return root;
524
+ };
525
+
526
+ ZidanFieldBase.prototype.setTheme = function (name) {
527
+ this.theme = pickList(name, THEMES, this.theme);
528
+ if (this.root) this.root.setAttribute('data-zs-theme', this.theme);
529
+ return this;
530
+ };
531
+
532
+ ZidanFieldBase.prototype.setFramework = function (name) {
533
+ this.framework = pickList(name, FRAMEWORKS, this.framework);
534
+ if (this.root) this.root.setAttribute('data-zs-framework', this.framework);
535
+ return this;
536
+ };
537
+
538
+ ZidanFieldBase.prototype.setLayout = function (name) {
539
+ this.layout = pickList(name, FIELD_LAYOUTS, this.layout || 'stacked');
540
+ if (this.root) this.root.setAttribute('data-zs-layout', this.layout);
541
+ return this;
542
+ };
543
+
544
+ ZidanFieldBase.prototype.validationTargets = function () {
545
+ return [this.el];
546
+ };
547
+
548
+ /* field-specific cross-field / format checks; subclasses override */
549
+ ZidanFieldBase.prototype._customError = function () {
550
+ return '';
551
+ };
552
+
553
+ ZidanFieldBase.prototype._messageFor = function (input) {
554
+ var message = validityMessage(input, this.opts.messages);
555
+ if (message) return message;
556
+ if (input && input.validationMessage) return input.validationMessage;
557
+ return this.opts.messages.generic || FIELD_MESSAGES.generic;
558
+ };
559
+
560
+ ZidanFieldBase.prototype._nativeError = function () {
561
+ var targets = this.validationTargets();
562
+ for (var i = 0; i < targets.length; i += 1) {
563
+ var input = targets[i];
564
+ if (input && input.validity && !input.validity.valid) return this._messageFor(input);
565
+ }
566
+ return '';
567
+ };
568
+
569
+ ZidanFieldBase.prototype._evaluateError = function () {
570
+ var custom = this._customError ? this._customError() : '';
571
+ if (custom) return typeof custom === 'string' ? custom : this.opts.messages.generic;
572
+ return this._nativeError();
573
+ };
574
+
575
+ ZidanFieldBase.prototype._syncDescribedBy = function () {
576
+ if (!this.el || !this.el.getAttribute) return;
577
+ var errorId = this.id + '-error';
578
+ var hint = this.root && this.root.querySelector ? this.root.querySelector('.zs-field__hint[id]') : null;
579
+ var hintId = hint ? hint.id : '';
580
+ var targets = this.validationTargets();
581
+ targets.forEach(function (input) {
582
+ if (!input || !input.getAttribute) return;
583
+ var current = (input.getAttribute('aria-describedby') || '').split(/\s+/).filter(Boolean);
584
+ var next = current.filter(function (id) { return id !== errorId && id !== hintId; });
585
+ if (hintId) next.push(hintId);
586
+ if (this.errorMessage) next.push(errorId);
587
+ if (next.length) input.setAttribute('aria-describedby', next.join(' '));
588
+ else input.removeAttribute('aria-describedby');
589
+ }, this);
590
+ };
591
+
592
+ ZidanFieldBase.prototype._renderError = function () {
593
+ if (!this.root) return;
594
+ if (!this.errorEl) {
595
+ this.errorEl = el('p', 'zs-field__error', {
596
+ id: this.id + '-error',
597
+ role: 'status',
598
+ 'aria-live': 'polite'
599
+ });
600
+ this.root.appendChild(this.errorEl);
601
+ }
602
+ this.errorEl.textContent = this.errorMessage || '';
603
+ this.errorEl.hidden = !this.errorMessage;
604
+ this._syncDescribedBy();
605
+ };
606
+
607
+ ZidanFieldBase.prototype.setError = function (message) {
608
+ this.errorMessage = message || null;
609
+ if (this.errorMessage) this.validation = 'invalid';
610
+ else if (this.validation === 'invalid') this.validation = null;
611
+ var invalid = !!this.errorMessage || this.validation === 'invalid';
612
+ if (this.root) {
613
+ this.root.classList.toggle('zs-field--invalid', invalid);
614
+ this.root.classList.toggle('zs-field--valid', this.validation === 'valid' && !this.errorMessage);
615
+ if (invalid || this.validation) this.root.setAttribute('data-zs-validation', invalid ? 'invalid' : this.validation);
616
+ else this.root.removeAttribute('data-zs-validation');
617
+ }
618
+ this._renderError();
619
+ this.validationTargets().forEach(function (input) {
620
+ if (!input || !input.setAttribute) return;
621
+ if (invalid) input.setAttribute('aria-invalid', 'true');
622
+ else if (this.validation === 'valid') input.setAttribute('aria-invalid', 'false');
623
+ else input.removeAttribute('aria-invalid');
624
+ }, this);
625
+ this.emit('validation', { state: invalid ? 'invalid' : this.validation, message: this.errorMessage });
626
+ this.call('onValidation', { state: invalid ? 'invalid' : this.validation, message: this.errorMessage, instance: this });
627
+ return this;
628
+ };
629
+
630
+ ZidanFieldBase.prototype.clearError = function () {
631
+ return this.setError(null);
632
+ };
633
+
634
+ /* mirror native constraint validity + custom rules into classes and aria */
635
+ ZidanFieldBase.prototype._bindValidity = function () {
636
+ var self = this;
637
+ this.validationTargets().forEach(function (input) {
638
+ self.on(input, 'invalid', function () {
639
+ self.touched = true;
640
+ var message = self._evaluateError();
641
+ if (message) self.setError(message);
642
+ else self.setValidation('invalid');
643
+ });
644
+ self.on(input, 'blur', function () {
645
+ self.touched = true;
646
+ self._mirrorValidity();
647
+ });
648
+ self.on(input, 'input', function () { self._mirrorValidity(); });
649
+ self.on(input, 'change', function () { self._mirrorValidity(); });
650
+ });
651
+ this.on(this.formEl, 'reset', function () {
652
+ global.setTimeout(function () {
653
+ if (self.destroyed) return;
654
+ self.touched = false;
655
+ self.errorMessage = null;
656
+ if (self.errorEl) {
657
+ self.errorEl.textContent = '';
658
+ self.errorEl.hidden = true;
659
+ }
660
+ self.setValidation(null);
661
+ self.update();
662
+ }, 0);
663
+ });
664
+ var preset = this.opts.validation || this.el.getAttribute('data-zidan-validation') ||
665
+ this.el.getAttribute('data-zs-validation');
666
+ if (preset === 'valid' || preset === 'invalid') this.setValidation(preset);
667
+ this._syncDescribedBy();
668
+ };
669
+
670
+ ZidanFieldBase.prototype._mirrorValidity = function () {
671
+ var error = this._evaluateError();
672
+ if (error) {
673
+ if (this.touched || this.opts.alwaysValidate) this.setError(error);
674
+ else this.setValidation('invalid');
675
+ return this;
676
+ }
677
+ if (this.errorMessage) this.setError(null);
678
+ if (this.validation === 'invalid') this.setValidation(null);
679
+ return this;
680
+ };
681
+
682
+ ZidanFieldBase.prototype.validate = function () {
683
+ this.touched = true;
684
+ var error = this._evaluateError();
685
+ if (error) {
686
+ this.setError(error);
687
+ return false;
688
+ }
689
+ this.setError(null);
690
+ if (this.opts.showValidState) this.setValidation('valid');
691
+ return true;
692
+ };
693
+
694
+ ZidanFieldBase.prototype.setValidation = function (state) {
695
+ this.validation = VALIDATION_STATES.indexOf(state) === -1 ? null : state;
696
+ var invalid = this.validation === 'invalid' || !!this.errorMessage;
697
+ if (this.root) {
698
+ this.root.classList.toggle('zs-field--invalid', invalid);
699
+ this.root.classList.toggle('zs-field--valid', this.validation === 'valid' && !this.errorMessage);
700
+ if (invalid) this.root.setAttribute('data-zs-validation', 'invalid');
701
+ else if (this.validation) this.root.setAttribute('data-zs-validation', this.validation);
702
+ else this.root.removeAttribute('data-zs-validation');
703
+ }
704
+ this.validationTargets().forEach(function (input) {
705
+ if (!input || !input.setAttribute) return;
706
+ if (invalid) input.setAttribute('aria-invalid', 'true');
707
+ else if (this.validation === 'valid') input.setAttribute('aria-invalid', 'false');
708
+ else input.removeAttribute('aria-invalid');
709
+ }, this);
710
+ this.emit('validation', { state: invalid ? 'invalid' : this.validation, message: this.errorMessage });
711
+ this.call('onValidation', { state: invalid ? 'invalid' : this.validation, message: this.errorMessage, instance: this });
712
+ return this;
713
+ };
714
+
715
+ ZidanFieldBase.prototype.getValidation = function () {
716
+ return this.validation;
717
+ };
718
+
719
+ ZidanFieldBase.prototype.getValue = function () {
720
+ var el = this.el;
721
+ if (!el) return null;
722
+ if (this.kind === 'file') {
723
+ return this.getFiles ? this.getFiles() : Array.prototype.slice.call(el.files || []);
724
+ }
725
+ if (el.type === 'checkbox') return !!el.checked;
726
+ if (el.multiple && el.options) {
727
+ return Array.prototype.filter.call(el.options, function (option) { return option.selected; })
728
+ .map(function (option) { return option.value; });
729
+ }
730
+ return el.value;
731
+ };
732
+
733
+ ZidanFieldBase.prototype.setValue = function (value) {
734
+ var el = this.el;
735
+ if (!el) return this;
736
+ if (this.kind === 'file') {
737
+ var files = value === null || value === undefined ? [] : (Array.isArray(value) ? value : [value]);
738
+ if (!files.length) return this.clear ? this.clear() : this;
739
+ if (this.addFiles) this.addFiles(files);
740
+ return this;
741
+ }
742
+ if (el.type === 'checkbox') {
743
+ if (this.setChecked) return this.setChecked(!!value);
744
+ el.checked = !!value;
745
+ el.dispatchEvent(new Event('change', { bubbles: true }));
746
+ return this.update();
747
+ }
748
+ if (el.multiple && el.options) {
749
+ var wanted = (Array.isArray(value) ? value : [value]).map(String);
750
+ Array.prototype.forEach.call(el.options, function (option) {
751
+ option.selected = wanted.indexOf(option.value) !== -1;
752
+ });
753
+ } else {
754
+ el.value = value === null || value === undefined ? '' : String(value);
755
+ }
756
+ el.dispatchEvent(new Event('change', { bubbles: true }));
757
+ return this.update();
758
+ };
759
+
760
+ ZidanFieldBase.prototype.update = function () {
761
+ if (this._sync) this._sync();
762
+ this._mirrorValidity();
763
+ return this;
764
+ };
765
+
766
+ ZidanFieldBase.prototype.refresh = function () {
767
+ return this.update();
768
+ };
769
+
770
+ ZidanFieldBase.prototype.destroy = function () {
771
+ if (this.destroyed) return this;
772
+ this.destroyed = true;
773
+ this._listeners.forEach(function (entry) {
774
+ entry[0].removeEventListener(entry[1], entry[2], entry[3]);
775
+ });
776
+ this._listeners.length = 0;
777
+ if (this._teardown) this._teardown();
778
+ this._cleanups.forEach(function (fn) { fn(); });
779
+ this._cleanups.length = 0;
780
+ this.emit('destroy', {});
781
+ if (this.root && this.root.parentNode) this.root.parentNode.removeChild(this.root);
782
+ if (this.el.__zidanField === this) delete this.el.__zidanField;
783
+ ZidanForm._unregister(this);
784
+ return this;
785
+ };
786
+
787
+ /* ---------------- file upload ---------------- */
788
+
789
+ function formatBytes(bytes) {
790
+ if (!bytes && bytes !== 0) return '';
791
+ if (bytes < 1024) return bytes + ' B';
792
+ if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(bytes < 10240 ? 1 : 0) + ' KB';
793
+ return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
794
+ }
795
+
796
+ function fileExtension(name) {
797
+ var match = /\.([a-z0-9]+)$/i.exec(String(name || ''));
798
+ return match ? '.' + match[1].toLowerCase() : '';
799
+ }
800
+
801
+ function matchesAccept(file, accept) {
802
+ if (!accept) return true;
803
+ return String(accept).split(',').some(function (raw) {
804
+ var token = raw.trim().toLowerCase();
805
+ if (!token) return false;
806
+ if (token.indexOf('.') === 0) return fileExtension(file.name) === token;
807
+ if (token.indexOf('/*') !== -1) return String(file.type).toLowerCase().indexOf(token.split('/')[0] + '/') === 0;
808
+ return String(file.type).toLowerCase() === token;
809
+ });
810
+ }
811
+
812
+ function fileKey(file) {
813
+ return [file.name, file.size, file.lastModified || 0, file.type || ''].join('|');
814
+ }
815
+
816
+ function uploadErrorText(err, fallback) {
817
+ if (err && typeof err === 'string') return err;
818
+ if (err && err.message) return err.message;
819
+ if (err && err.status) return 'Upload failed (HTTP ' + err.status + ').';
820
+ return fallback || 'Upload failed.';
821
+ }
822
+
823
+ function ZidanFileUpload(target, options) {
824
+ if (!(this instanceof ZidanFileUpload)) return new ZidanFileUpload(target, options);
825
+ if (!/^file$/i.test(target.type)) {
826
+ throw new Error('ZidanFileUpload: expected an <input type="file">.');
827
+ }
828
+ ZidanFieldBase.call(this, target, options, 'file');
829
+ var self = this;
830
+ var input = target;
831
+ var opts = this.opts;
832
+
833
+ var variant = pickList(
834
+ fieldOption(input, opts, 'fileVariant', 'file-variant',
835
+ fieldOption(input, opts, 'variant', 'variant', 'dropzone')),
836
+ FILE_VARIANTS, 'dropzone');
837
+
838
+ var originalParent = input.parentNode;
839
+ var root = this._scope('file');
840
+ root.setAttribute('data-zs-file-variant', variant);
841
+ originalParent.insertBefore(root, input);
842
+
843
+ var drop = el('label', 'zs-file-drop zs-file-drop--' + variant);
844
+ drop.setAttribute('for', this.id);
845
+
846
+ var avatar = el('span', 'zs-file-avatar', { hidden: true });
847
+ var avatarImg = doc.createElement('img');
848
+ avatarImg.alt = '';
849
+ avatar.appendChild(avatarImg);
850
+
851
+ var icon = el('span', 'zs-file-icon', { 'aria-hidden': 'true' });
852
+ var iconSpec = fieldOption(input, opts, 'uploadIcon', 'upload-icon',
853
+ fieldOption(input, opts, 'icon', 'icon', 'upload'));
854
+ var glyph = iconNode(iconSpec, 'zs-file-icon-svg');
855
+ if (glyph) icon.appendChild(glyph);
856
+
857
+ var fallbackTitle = opts.title || input.getAttribute('data-zidan-title') ||
858
+ (variant === 'avatar' ? 'Upload an image' : (variant === 'gallery' ? 'Add images' : 'Choose a file'));
859
+ var title = el('span', 'zs-file-drop-title', null, fallbackTitle);
860
+ var hint = el('span', 'zs-file-drop-hint', null,
861
+ opts.dropHint || input.getAttribute('data-zidan-drop-hint') ||
862
+ (input.multiple ? 'or drop files here — multiple allowed' : 'or drop it here'));
863
+ drop.appendChild(avatar);
864
+ drop.appendChild(icon);
865
+ drop.appendChild(title);
866
+ drop.appendChild(hint);
867
+ drop.appendChild(input);
868
+ root.appendChild(drop);
869
+
870
+ var list = el('ul', 'zs-file-list');
871
+ root.appendChild(list);
872
+
873
+ var footer = el('div', 'zs-file-meta-row');
874
+ var status = el('span', 'zs-file-status', { 'role': 'status', 'aria-live': 'polite' });
875
+ var clearBtn = el('button', 'zs-file-clear', { type: 'button' });
876
+ clearBtn.textContent = opts.clearLabel || 'Clear all';
877
+ clearBtn.hidden = true;
878
+ footer.appendChild(status);
879
+ footer.appendChild(clearBtn);
880
+ root.appendChild(footer);
881
+
882
+ var acceptHint = opts.accept || input.accept;
883
+ if (acceptHint) hint.textContent = hint.textContent + ' · ' + acceptHint;
884
+
885
+ this.variant = variant;
886
+ this.drop = drop;
887
+ this.list = list;
888
+ this.status = status;
889
+ this.clearBtn = clearBtn;
890
+ this.titleEl = title;
891
+ this.hintEl = hint;
892
+ this._fallbackTitle = fallbackTitle;
893
+ this.avatarEl = avatar;
894
+ this.avatarImg = avatarImg;
895
+
896
+ this.uploadHandler = typeof opts.upload === 'function' ? opts.upload :
897
+ (typeof opts.uploadHandler === 'function' ? opts.uploadHandler : null);
898
+ this.uploadUrl = fieldOption(input, opts, 'uploadUrl', 'upload-url', '');
899
+ this.uploadField = fieldOption(input, opts, 'uploadField', 'upload-field', 'file');
900
+ this.withCredentials = fieldBool(input, opts, 'withCredentials', 'with-credentials', false);
901
+ this.uploadHeaders = opts.uploadHeaders || opts.headers || null;
902
+ this.simulateUpload = fieldBool(input, opts, 'simulateUpload', 'simulate-upload', false);
903
+ this.simulateDuration = Math.max(120, fieldNumber(input, opts, 'simulateDuration', 'simulate-duration', 900));
904
+ this.autoUpload = fieldBool(input, opts, 'autoUpload', 'auto-upload', true);
905
+ this.showFileMeta = fieldBool(input, opts, 'showFileMeta', 'show-file-meta', true);
906
+ this.showPreview = fieldBool(input, opts, 'showPreview', 'preview', true);
907
+ this.hasUploader = !!(this.uploadHandler || this.uploadUrl || this.simulateUpload);
908
+ root.setAttribute('data-zs-upload', this.hasUploader ? 'true' : 'false');
909
+
910
+ this._uploads = Object.create(null);
911
+ this._active = Object.create(null);
912
+ this._urls = [];
913
+ this._renderQueued = false;
914
+ this.fileError = '';
915
+ this._restoreInput = function () {
916
+ var parent = root.parentNode || originalParent;
917
+ parent.insertBefore(input, root.parentNode ? root : null);
918
+ input.classList.remove('zs-native-input', 'zs-file-input');
919
+ };
920
+
921
+ addClass(input, 'zs-native-input');
922
+ addClass(input, 'zs-file-input');
923
+
924
+ this.on(input, 'change', function () {
925
+ var ok = self._validate();
926
+ self._render();
927
+ self.emit('change', { files: self.getFiles() });
928
+ self.call('onChange', { files: self.getFiles(), instance: self });
929
+ if (ok && self.autoUpload && self.hasUploader) self.uploadAll();
930
+ });
931
+
932
+ var dragDepth = 0;
933
+ ['dragenter', 'dragover'].forEach(function (type) {
934
+ self.on(drop, type, function (event) {
935
+ event.preventDefault();
936
+ if (type === 'dragenter') dragDepth += 1;
937
+ drop.classList.add('zs-file-drop--over');
938
+ });
939
+ });
940
+ self.on(drop, 'dragleave', function () {
941
+ dragDepth = Math.max(0, dragDepth - 1);
942
+ if (!dragDepth) drop.classList.remove('zs-file-drop--over');
943
+ });
944
+ self.on(drop, 'drop', function (event) {
945
+ event.preventDefault();
946
+ dragDepth = 0;
947
+ drop.classList.remove('zs-file-drop--over');
948
+ if (!event.dataTransfer || !event.dataTransfer.files || !event.dataTransfer.files.length) return;
949
+ var incoming = Array.prototype.slice.call(event.dataTransfer.files);
950
+ if (!input.multiple) incoming = incoming.slice(0, 1);
951
+ self.addFiles(incoming);
952
+ });
953
+
954
+ self.on(clearBtn, 'click', function () { self.clear(); });
955
+
956
+ this._bindValidity();
957
+ this.on(this.formEl, 'reset', function () {
958
+ global.setTimeout(function () {
959
+ if (self.destroyed) return;
960
+ self.cancelAll();
961
+ self._uploads = Object.create(null);
962
+ self.fileError = '';
963
+ if (input.setCustomValidity) input.setCustomValidity('');
964
+ self._render();
965
+ }, 0);
966
+ });
967
+
968
+ input.__zidanField = this;
969
+ this._render();
970
+ this.emit('init', {});
971
+ ZidanForm._register(this);
972
+ }
973
+
974
+ ZidanFileUpload.prototype = Object.create(ZidanFieldBase.prototype);
975
+ ZidanFileUpload.prototype.constructor = ZidanFileUpload;
976
+
977
+ ZidanFileUpload.prototype.getFiles = function () {
978
+ return this.el.files ? Array.prototype.slice.call(this.el.files) : [];
979
+ };
980
+
981
+ ZidanFileUpload.prototype.getUploadState = function () {
982
+ var self = this;
983
+ return this.getFiles().map(function (file) {
984
+ var state = self._stateFor(file, false) || { status: 'idle', progress: 0, error: '', result: null };
985
+ return {
986
+ file: file,
987
+ name: file.name,
988
+ size: file.size,
989
+ status: state.status,
990
+ progress: state.progress,
991
+ error: state.error,
992
+ result: state.result
993
+ };
994
+ });
995
+ };
996
+
997
+ ZidanFileUpload.prototype._stateFor = function (file, create) {
998
+ var key = fileKey(file);
999
+ var state = this._uploads[key];
1000
+ if (!state && create) {
1001
+ state = this._uploads[key] = {
1002
+ status: 'idle', progress: 0, error: '', result: null
1003
+ };
1004
+ }
1005
+ return state;
1006
+ };
1007
+
1008
+ ZidanFileUpload.prototype._setFiles = function (files) {
1009
+ try {
1010
+ var Ctor = typeof DataTransfer !== 'undefined' ? DataTransfer : global.DataTransfer;
1011
+ if (!Ctor) return false;
1012
+ var dt = new Ctor();
1013
+ files.forEach(function (file) { dt.items.add(file); });
1014
+ this.el.files = dt.files;
1015
+ return true;
1016
+ } catch (err) {
1017
+ return false;
1018
+ }
1019
+ };
1020
+
1021
+ /* keeps native input.files authoritative; `source: 'user'` mirrors a pick/drop */
1022
+ ZidanFileUpload.prototype._applyFiles = function (files, fromDrop) {
1023
+ if (!this._setFiles(files)) {
1024
+ this.emit('error', { error: new Error('This browser cannot assign files programmatically.'), action: 'setFiles' });
1025
+ return this;
1026
+ }
1027
+ if (fromDrop) {
1028
+ try { this.el.dispatchEvent(new Event('change', { bubbles: true })); } catch (err) { /* old browsers */ }
1029
+ } else {
1030
+ this._validate();
1031
+ this._render();
1032
+ }
1033
+ return this;
1034
+ };
1035
+
1036
+ ZidanFileUpload.prototype.addFiles = function (files) {
1037
+ var incoming = files && files.length !== undefined ? Array.prototype.slice.call(files) : toArray(files);
1038
+ if (!incoming.length) return this;
1039
+ var current = this.el.multiple ? this.getFiles() : [];
1040
+ var seen = Object.create(null);
1041
+ var next = current.concat(incoming).filter(function (file) {
1042
+ var key = fileKey(file);
1043
+ if (seen[key]) return false;
1044
+ seen[key] = true;
1045
+ return true;
1046
+ });
1047
+ if (!this.el.multiple) next = next.slice(0, 1);
1048
+ if (!this._setFiles(next)) {
1049
+ this.emit('error', { error: new Error('This browser cannot assign files programmatically.'), action: 'addFiles' });
1050
+ return this;
1051
+ }
1052
+ try { this.el.dispatchEvent(new Event('change', { bubbles: true })); } catch (err) { /* old browsers */ }
1053
+ return this;
1054
+ };
1055
+
1056
+ ZidanFileUpload.prototype.replaceFiles = function (files) {
1057
+ return this._applyFiles(files && files.length !== undefined ? Array.prototype.slice.call(files) : toArray(files), true);
1058
+ };
1059
+
1060
+ ZidanFileUpload.prototype.removeFile = function (target) {
1061
+ var files = this.getFiles();
1062
+ var index = typeof target === 'number' ? target : files.indexOf(target);
1063
+ if (index === -1 || !files[index]) return this;
1064
+ var file = files[index];
1065
+ this.cancelUpload(file);
1066
+ delete this._uploads[fileKey(file)];
1067
+ var next = files.slice();
1068
+ next.splice(index, 1);
1069
+ this._setFiles(next);
1070
+ this._validate();
1071
+ this._render();
1072
+ this.emit('change', { files: next });
1073
+ this.emit('remove', { file: file, index: index });
1074
+ this.call('onChange', { files: next, instance: this });
1075
+ this.call('onRemove', { file: file, index: index, instance: this });
1076
+ return this;
1077
+ };
1078
+
1079
+ ZidanFileUpload.prototype.clear = function () {
1080
+ this.cancelAll();
1081
+ this._uploads = Object.create(null);
1082
+ this.fileError = '';
1083
+ this.el.value = '';
1084
+ if (this.el.setCustomValidity) this.el.setCustomValidity('');
1085
+ this._validate();
1086
+ this._render();
1087
+ this.emit('change', { files: [] });
1088
+ this.emit('clear', {});
1089
+ this.call('onChange', { files: [], instance: this });
1090
+ return this;
1091
+ };
1092
+
1093
+ ZidanFileUpload.prototype._limits = function () {
1094
+ var input = this.el;
1095
+ var opts = this.opts;
1096
+ var maxFiles = parseInt(opts.maxFiles || input.getAttribute('data-zidan-max-files'), 10);
1097
+ var maxSize = parseInt(opts.maxSize || input.getAttribute('data-zidan-max-size'), 10);
1098
+ if (!(maxSize > 0)) {
1099
+ var sizeMb = opts.maxSizeMB;
1100
+ if (sizeMb === undefined || sizeMb === null || sizeMb === '') sizeMb = input.getAttribute('data-zidan-max-size-mb');
1101
+ if (sizeMb !== null && sizeMb !== undefined && sizeMb !== '') {
1102
+ var sizeMbValue = parseFloat(sizeMb);
1103
+ if (sizeMbValue > 0) maxSize = Math.round(sizeMbValue * 1024 * 1024);
1104
+ }
1105
+ }
1106
+ return {
1107
+ maxFiles: maxFiles > 0 ? maxFiles : 0,
1108
+ maxSize: maxSize > 0 ? maxSize : 0,
1109
+ accept: opts.accept || input.accept || ''
1110
+ };
1111
+ };
1112
+
1113
+ ZidanFileUpload.prototype._customError = function () {
1114
+ return this.fileError || '';
1115
+ };
1116
+
1117
+ ZidanFileUpload.prototype._validate = function () {
1118
+ var input = this.el;
1119
+ var messages = this.opts.messages;
1120
+ var limits = this._limits();
1121
+ var files = this.getFiles();
1122
+ var error = '';
1123
+
1124
+ if (limits.maxFiles && files.length > limits.maxFiles) {
1125
+ error = fillTemplate(messages.fileCount, { max: limits.maxFiles });
1126
+ files = files.slice(0, limits.maxFiles);
1127
+ this._setFiles(files);
1128
+ }
1129
+ if (!error && limits.maxSize) {
1130
+ for (var i = 0; i < files.length; i += 1) {
1131
+ if (files[i].size > limits.maxSize) {
1132
+ error = fillTemplate(messages.fileSize, {
1133
+ name: files[i].name,
1134
+ size: formatBytes(files[i].size),
1135
+ limit: formatBytes(limits.maxSize)
1136
+ });
1137
+ break;
1138
+ }
1139
+ }
1140
+ }
1141
+ if (!error && limits.accept) {
1142
+ for (var j = 0; j < files.length; j += 1) {
1143
+ if (!matchesAccept(files[j], limits.accept)) {
1144
+ error = fillTemplate(messages.fileType, { name: files[j].name, accept: limits.accept });
1145
+ break;
1146
+ }
1147
+ }
1148
+ }
1149
+
1150
+ this.fileError = error;
1151
+ if (input.setCustomValidity) input.setCustomValidity(error || '');
1152
+ var shown = error || this._nativeError();
1153
+ if (shown) this.setError(shown);
1154
+ else if (this.errorMessage) this.setError(null);
1155
+ this.root.classList.toggle('zs-field--filled', files.length > 0);
1156
+ this.drop.classList.toggle('zs-file-drop--invalid', !!shown);
1157
+ this._renderStatus();
1158
+ return !shown;
1159
+ };
1160
+
1161
+ ZidanFileUpload.prototype._sync = function () {
1162
+ this._render();
1163
+ };
1164
+
1165
+ ZidanFileUpload.prototype._queueRender = function () {
1166
+ var self = this;
1167
+ if (this._renderQueued || this.destroyed) return;
1168
+ this._renderQueued = true;
1169
+ var run = function () {
1170
+ self._renderQueued = false;
1171
+ if (!self.destroyed) self._render();
1172
+ };
1173
+ if (global.requestAnimationFrame) global.requestAnimationFrame(run);
1174
+ else global.setTimeout(run, 32);
1175
+ };
1176
+
1177
+ ZidanFileUpload.prototype._renderStatus = function () {
1178
+ var files = this.getFiles();
1179
+ var states = this.getUploadState();
1180
+ var total = files.reduce(function (sum, file) { return sum + file.size; }, 0);
1181
+ var uploading = states.filter(function (state) { return state.status === 'uploading'; });
1182
+ var failed = states.filter(function (state) { return state.status === 'error'; });
1183
+ var done = states.filter(function (state) { return state.status === 'done'; });
1184
+ var text = '';
1185
+
1186
+ if (this.fileError) {
1187
+ text = this.fileError;
1188
+ } else if (files.length) {
1189
+ text = files.length + (files.length === 1 ? ' file selected' : ' files selected') + ' · ' + formatBytes(total);
1190
+ if (uploading.length) {
1191
+ var percent = Math.round(uploading.reduce(function (sum, state) { return sum + state.progress; }, 0) / uploading.length);
1192
+ text += ' · Uploading ' + percent + '%';
1193
+ } else if (failed.length) {
1194
+ text += ' · ' + failed.length + ' failed';
1195
+ } else if (done.length === files.length && this.hasUploader) {
1196
+ text += ' · Uploaded';
1197
+ }
1198
+ }
1199
+
1200
+ this.status.textContent = text;
1201
+ this.status.classList.toggle('zs-file-status--error', !!this.fileError);
1202
+ this.status.classList.toggle('zs-file-status--success', !this.fileError && files.length > 0 && done.length === files.length && this.hasUploader);
1203
+ };
1204
+
1205
+ ZidanFileUpload.prototype._render = function () {
1206
+ var self = this;
1207
+ var files = this.getFiles();
1208
+ var opts = this.opts;
1209
+ // detach first, then revoke a tick later: revoking a blob that a live
1210
+ // <img> still points at (or that is mid-decode) makes the browser raise a
1211
+ // failed-resource error
1212
+ this.list.textContent = '';
1213
+ this._revokeLater(this._urls);
1214
+ this._urls = [];
1215
+ this.list.hidden = files.length === 0;
1216
+ this.clearBtn.hidden = files.length === 0;
1217
+ this.root.classList.toggle('zs-field--filled', files.length > 0);
1218
+ this.drop.classList.toggle('zs-file-drop--has-files', files.length > 0);
1219
+
1220
+ var previewFile = this.showPreview ? files.filter(function (file) { return /^image\//.test(file.type); })[0] : null;
1221
+ if (previewFile) {
1222
+ var previewUrl = URL.createObjectURL(previewFile);
1223
+ this._urls.push(previewUrl);
1224
+ this.avatarImg.src = previewUrl;
1225
+ this.avatarEl.hidden = false;
1226
+ this.drop.classList.add('zs-file-drop--has-preview');
1227
+ this.titleEl.textContent = opts.replaceTitle || 'Change image';
1228
+ } else {
1229
+ this.avatarImg.removeAttribute('src');
1230
+ this.avatarEl.hidden = true;
1231
+ this.drop.classList.remove('zs-file-drop--has-preview');
1232
+ this.titleEl.textContent = this._fallbackTitle;
1233
+ }
1234
+
1235
+ files.forEach(function (file, index) {
1236
+ var state = self._stateFor(file, false) || { status: 'idle', progress: 0, error: '', result: null };
1237
+ var item = el('li', 'zs-file-item');
1238
+ item.setAttribute('data-zs-upload-state', state.status);
1239
+
1240
+ var thumb = el('span', 'zs-file-thumb');
1241
+ if (/^image\//.test(file.type)) {
1242
+ var url = URL.createObjectURL(file);
1243
+ self._urls.push(url);
1244
+ var img = doc.createElement('img');
1245
+ img.src = url;
1246
+ img.alt = '';
1247
+ thumb.appendChild(img);
1248
+ } else {
1249
+ thumb.textContent = (fileExtension(file.name) || 'file').replace('.', '').slice(0, 4).toUpperCase();
1250
+ }
1251
+
1252
+ var meta = el('span', 'zs-file-info');
1253
+ var name = el('span', 'zs-file-name', null, file.name);
1254
+ meta.appendChild(name);
1255
+ if (self.showFileMeta) {
1256
+ var sizeText = formatBytes(file.size) + (file.type ? ' · ' + file.type : '');
1257
+ meta.appendChild(el('span', 'zs-file-size', null, sizeText));
1258
+ }
1259
+
1260
+ if (self.hasUploader) {
1261
+ var stateLine = el('span', 'zs-file-upload-state');
1262
+ if (state.status === 'uploading') {
1263
+ stateLine.textContent = fillTemplate(opts.progressTemplate || 'Uploading {percent}%', { percent: state.progress });
1264
+ var bar = el('span', 'zs-file-progress');
1265
+ bar.setAttribute('role', 'progressbar');
1266
+ bar.setAttribute('aria-valuemin', '0');
1267
+ bar.setAttribute('aria-valuemax', '100');
1268
+ bar.setAttribute('aria-valuenow', String(state.progress));
1269
+ bar.setAttribute('aria-label', 'Upload progress for ' + file.name);
1270
+ var fill = el('span', 'zs-file-progress-bar');
1271
+ fill.style.width = state.progress + '%';
1272
+ bar.appendChild(fill);
1273
+ stateLine.appendChild(bar);
1274
+ } else if (state.status === 'done') {
1275
+ stateLine.textContent = opts.uploadedLabel || 'Uploaded';
1276
+ } else if (state.status === 'error') {
1277
+ stateLine.textContent = (opts.failedLabel || 'Upload failed') + (state.error ? ' — ' + state.error : '');
1278
+ } else if (state.status === 'canceled') {
1279
+ stateLine.textContent = opts.canceledLabel || 'Upload canceled';
1280
+ }
1281
+ if (stateLine.textContent) meta.appendChild(stateLine);
1282
+ }
1283
+
1284
+ var actions = el('span', 'zs-file-actions');
1285
+ if (state.status === 'uploading') {
1286
+ var cancel = el('button', 'zs-file-cancel', { type: 'button', 'aria-label': 'Cancel upload of ' + file.name });
1287
+ cancel.textContent = opts.cancelLabel || 'Cancel';
1288
+ self.on(cancel, 'click', function (event) {
1289
+ event.preventDefault();
1290
+ event.stopPropagation();
1291
+ self.cancelUpload(file);
1292
+ });
1293
+ actions.appendChild(cancel);
1294
+ } else if (state.status === 'error' || state.status === 'canceled') {
1295
+ var retry = el('button', 'zs-file-retry', { type: 'button', 'aria-label': 'Retry upload of ' + file.name });
1296
+ retry.textContent = opts.retryLabel || 'Retry';
1297
+ self.on(retry, 'click', function (event) {
1298
+ event.preventDefault();
1299
+ event.stopPropagation();
1300
+ self.retryUpload(file);
1301
+ });
1302
+ actions.appendChild(retry);
1303
+ }
1304
+
1305
+ var remove = el('button', 'zs-file-remove', { type: 'button', 'aria-label': 'Remove ' + file.name });
1306
+ remove.textContent = '\u00d7';
1307
+ self.on(remove, 'click', function (event) {
1308
+ event.preventDefault();
1309
+ event.stopPropagation();
1310
+ self.removeFile(file);
1311
+ });
1312
+ actions.appendChild(remove);
1313
+
1314
+ item.appendChild(thumb);
1315
+ item.appendChild(meta);
1316
+ item.appendChild(actions);
1317
+ self.list.appendChild(item);
1318
+
1319
+ if (typeof opts.renderFile === 'function') {
1320
+ try {
1321
+ opts.renderFile(item, {
1322
+ file: file,
1323
+ index: index,
1324
+ state: state,
1325
+ field: self
1326
+ });
1327
+ } catch (err) {
1328
+ self.emit('error', { error: err, callback: 'renderFile' });
1329
+ }
1330
+ }
1331
+ });
1332
+
1333
+ this._renderStatus();
1334
+ };
1335
+
1336
+ ZidanFileUpload.prototype.setVariant = function (name) {
1337
+ var next = pickList(name, FILE_VARIANTS, this.variant);
1338
+ if (next === this.variant) return this;
1339
+ this.variant = next;
1340
+ FILE_VARIANTS.forEach(function (variant) { this.drop.classList.remove('zs-file-drop--' + variant); }, this);
1341
+ this.drop.classList.add('zs-file-drop--' + next);
1342
+ this.root.setAttribute('data-zs-file-variant', next);
1343
+ this._render();
1344
+ return this;
1345
+ };
1346
+
1347
+ ZidanFileUpload.prototype.setUploader = function (source) {
1348
+ if (typeof source === 'function') {
1349
+ this.uploadHandler = source;
1350
+ this.uploadUrl = '';
1351
+ } else {
1352
+ this.uploadHandler = null;
1353
+ this.uploadUrl = source ? String(source) : '';
1354
+ }
1355
+ this.hasUploader = !!(this.uploadHandler || this.uploadUrl || this.simulateUpload);
1356
+ this.root.setAttribute('data-zs-upload', this.hasUploader ? 'true' : 'false');
1357
+ this._render();
1358
+ return this;
1359
+ };
1360
+
1361
+ ZidanFileUpload.prototype._formData = function (file) {
1362
+ var data = new FormData();
1363
+ data.append(this.uploadField, file, file.name);
1364
+ var extra = typeof this.opts.uploadData === 'function' ? this.opts.uploadData(file, this) : this.opts.uploadData;
1365
+ if (extra && typeof extra === 'object') {
1366
+ Object.keys(extra).forEach(function (key) {
1367
+ var value = extra[key];
1368
+ if (value !== undefined && value !== null) data.append(key, value);
1369
+ });
1370
+ }
1371
+ return data;
1372
+ };
1373
+
1374
+ ZidanFileUpload.prototype.uploadAll = function () {
1375
+ var self = this;
1376
+ if (!this.hasUploader) return this;
1377
+ if (!this._validate()) return this;
1378
+ this.getFiles().forEach(function (file) { self.uploadFile(file); });
1379
+ return this;
1380
+ };
1381
+
1382
+ ZidanFileUpload.prototype.uploadFile = function (file) {
1383
+ var self = this;
1384
+ var key = fileKey(file);
1385
+ var state = this._stateFor(file, true);
1386
+ if (state.status === 'uploading' || state.status === 'done') return this;
1387
+
1388
+ state.status = 'uploading';
1389
+ state.progress = 0;
1390
+ state.error = '';
1391
+ state.result = null;
1392
+ this._queueRender();
1393
+ this.emit('upload-start', { file: file, name: file.name, size: file.size });
1394
+ this.call('onUploadStart', { file: file, name: file.name, size: file.size, instance: this });
1395
+
1396
+ if (this.uploadHandler) {
1397
+ var controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
1398
+ this._active[key] = {
1399
+ type: 'handler',
1400
+ abort: function () { if (controller) controller.abort(); }
1401
+ };
1402
+ var context = {
1403
+ file: file,
1404
+ field: this,
1405
+ formData: this._formData(file),
1406
+ signal: controller ? controller.signal : null,
1407
+ onProgress: function (percent) { self._setProgress(file, percent); },
1408
+ complete: function (value) { self._finish(file, value); },
1409
+ fail: function (err) { self._fail(file, err); }
1410
+ };
1411
+ var result;
1412
+ try {
1413
+ result = this.uploadHandler(file, context);
1414
+ } catch (err) {
1415
+ this._fail(file, err);
1416
+ return this;
1417
+ }
1418
+ if (result && typeof result.then === 'function') {
1419
+ result.then(function (value) {
1420
+ self._finish(file, value);
1421
+ }, function (err) {
1422
+ if (err && (err.name === 'AbortError' || err.aborted)) self._canceledUpload(file);
1423
+ else self._fail(file, err);
1424
+ });
1425
+ } else if (result !== undefined) {
1426
+ this._finish(file, result);
1427
+ }
1428
+ // returning nothing means the handler will call context.complete/fail
1429
+ return this;
1430
+ }
1431
+
1432
+ if (this.uploadUrl) {
1433
+ var xhr = new global.XMLHttpRequest();
1434
+ this._active[key] = {
1435
+ type: 'xhr',
1436
+ abort: function () { try { xhr.abort(); } catch (err) { /* already done */ } }
1437
+ };
1438
+ xhr.open('POST', this.uploadUrl, true);
1439
+ if (this.withCredentials) xhr.withCredentials = true;
1440
+ var headers = typeof this.uploadHeaders === 'function' ? this.uploadHeaders(file, this) : this.uploadHeaders;
1441
+ if (headers && typeof headers === 'object') {
1442
+ Object.keys(headers).forEach(function (name) { xhr.setRequestHeader(name, headers[name]); });
1443
+ }
1444
+ xhr.upload.onprogress = function (event) {
1445
+ if (!event.lengthComputable) return;
1446
+ self._setProgress(file, Math.min(99, Math.round((event.loaded / event.total) * 100)));
1447
+ };
1448
+ xhr.onload = function () {
1449
+ if (xhr.status >= 200 && xhr.status < 300) {
1450
+ var body = xhr.responseText;
1451
+ try { body = JSON.parse(body); } catch (err) { /* plain text response */ }
1452
+ self._finish(file, body);
1453
+ } else {
1454
+ self._fail(file, { status: xhr.status, message: 'Upload failed (HTTP ' + xhr.status + ').' });
1455
+ }
1456
+ };
1457
+ xhr.onerror = function () { self._fail(file, { message: 'Network error while uploading.' }); };
1458
+ xhr.onabort = function () { self._canceledUpload(file); };
1459
+ xhr.send(this._formData(file));
1460
+ return this;
1461
+ }
1462
+
1463
+ if (this.simulateUpload) {
1464
+ var started = Date.now();
1465
+ var timer = null;
1466
+ var tick = function () {
1467
+ if (!self._uploads[key] || state.status !== 'uploading') return;
1468
+ var percent = Math.min(99, Math.round(((Date.now() - started) / self.simulateDuration) * 100));
1469
+ self._setProgress(file, percent);
1470
+ if (percent >= 99) {
1471
+ delete self._active[key];
1472
+ self._finish(file, { simulated: true });
1473
+ } else {
1474
+ timer = global.setTimeout(tick, 40);
1475
+ }
1476
+ };
1477
+ this._active[key] = { type: 'simulation', abort: function () { if (timer) global.clearTimeout(timer); } };
1478
+ timer = global.setTimeout(tick, 40);
1479
+ return this;
1480
+ }
1481
+
1482
+ state.status = 'idle';
1483
+ this._queueRender();
1484
+ return this;
1485
+ };
1486
+
1487
+ ZidanFileUpload.prototype._setProgress = function (file, percent) {
1488
+ var state = this._stateFor(file, false);
1489
+ if (!state || state.status !== 'uploading') return;
1490
+ var value = clamp(Math.round(Number(percent) || 0), 0, 99);
1491
+ if (value === state.progress) return;
1492
+ state.progress = value;
1493
+ this._queueRender();
1494
+ this.emit('upload-progress', { file: file, progress: value, name: file.name });
1495
+ this.call('onUploadProgress', { file: file, progress: value, name: file.name, instance: this });
1496
+ };
1497
+
1498
+ ZidanFileUpload.prototype._finish = function (file, result) {
1499
+ var state = this._stateFor(file, false);
1500
+ if (!state || state.status !== 'uploading') return;
1501
+ delete this._active[fileKey(file)];
1502
+ state.status = 'done';
1503
+ state.progress = 100;
1504
+ state.result = result === undefined ? null : result;
1505
+ this._queueRender();
1506
+ this.emit('upload-success', { file: file, name: file.name, result: state.result });
1507
+ this.call('onUploadSuccess', { file: file, name: file.name, result: state.result, instance: this });
1508
+ this.call('onUpload', { file: file, name: file.name, result: state.result, instance: this });
1509
+ };
1510
+
1511
+ ZidanFileUpload.prototype._fail = function (file, err) {
1512
+ var state = this._stateFor(file, false);
1513
+ if (!state || state.status !== 'uploading') return;
1514
+ delete this._active[fileKey(file)];
1515
+ state.status = 'error';
1516
+ state.error = uploadErrorText(err, this.opts.messages.upload || 'Upload failed.');
1517
+ this._queueRender();
1518
+ this.emit('upload-error', { file: file, name: file.name, error: err, message: state.error });
1519
+ this.call('onUploadError', { file: file, name: file.name, error: err, message: state.error, instance: this });
1520
+ };
1521
+
1522
+ ZidanFileUpload.prototype._canceledUpload = function (file) {
1523
+ var state = this._stateFor(file, false);
1524
+ if (!state || state.status !== 'uploading') return;
1525
+ delete this._active[fileKey(file)];
1526
+ state.status = 'canceled';
1527
+ state.progress = 0;
1528
+ state.error = '';
1529
+ this._queueRender();
1530
+ this.emit('upload-cancel', { file: file, name: file.name });
1531
+ this.call('onUploadCancel', { file: file, name: file.name, instance: this });
1532
+ };
1533
+
1534
+ ZidanFileUpload.prototype.cancelUpload = function (file) {
1535
+ var key = fileKey(file);
1536
+ var active = this._active[key];
1537
+ if (active) {
1538
+ try { active.abort(); } catch (err) { /* already stopped */ }
1539
+ delete this._active[key];
1540
+ }
1541
+ this._canceledUpload(file);
1542
+ return this;
1543
+ };
1544
+
1545
+ ZidanFileUpload.prototype.cancelAll = function () {
1546
+ var self = this;
1547
+ Object.keys(this._active).forEach(function (key) {
1548
+ try { self._active[key].abort(); } catch (err) { /* already stopped */ }
1549
+ delete self._active[key];
1550
+ });
1551
+ return this;
1552
+ };
1553
+
1554
+ ZidanFileUpload.prototype.retryUpload = function (file) {
1555
+ var state = this._stateFor(file, false);
1556
+ if (!state) return this;
1557
+ state.status = 'idle';
1558
+ state.progress = 0;
1559
+ state.error = '';
1560
+ return this.uploadFile(file);
1561
+ };
1562
+
1563
+ ZidanFileUpload.prototype._revokeLater = function (urls) {
1564
+ if (!urls || !urls.length) return;
1565
+ global.setTimeout(function () {
1566
+ urls.forEach(function (url) {
1567
+ try { URL.revokeObjectURL(url); } catch (err) { /* already gone */ }
1568
+ });
1569
+ }, 800);
1570
+ };
1571
+
1572
+ ZidanFileUpload.prototype._teardown = function () {
1573
+ this.cancelAll();
1574
+ this._uploads = Object.create(null);
1575
+ this._revokeLater(this._urls);
1576
+ this._urls = [];
1577
+ if (this._restoreInput) this._restoreInput();
1578
+ };
1579
+
1580
+ /* ---------------- factory, registry, auto-init ---------------- */
1581
+
1582
+ function fieldKindFor(node) {
1583
+ if (!isElement(node)) return null;
1584
+ var flag = String(node.getAttribute('data-zidan') || '').toLowerCase();
1585
+ if (FIELD_KINDS.indexOf(flag) !== -1) return flag;
1586
+ if (node.hasAttribute('data-zidan-radio-group')) return 'radio-group';
1587
+ if (node.hasAttribute('data-zidan-radio')) return 'radio';
1588
+ if (node.hasAttribute('data-zidan-checkbox') || node.hasAttribute('data-zidan-switch')) return 'checkbox';
1589
+ if (node.hasAttribute('data-zidan-file')) return 'file';
1590
+ if (node.hasAttribute('data-zidan-textarea')) return 'textarea';
1591
+ if (node.hasAttribute('data-zidan-input')) return 'input';
1592
+ var type = String(node.type || '').toLowerCase();
1593
+ if (type === 'checkbox') return 'checkbox';
1594
+ if (type === 'radio') return 'radio';
1595
+ if (type === 'file') return 'file';
1596
+ if (hasClass(node, 'zidan-field')) {
1597
+ if (node.tagName === 'FIELDSET') return node.querySelector('input[type="radio"]') ? 'radio-group' : null;
1598
+ if (node.tagName === 'TEXTAREA') return 'textarea';
1599
+ if (node.tagName !== 'INPUT') return null;
1600
+ // a lone radio needs its group container, so only the fieldset form is inferred
1601
+ if (type === 'radio') return null;
1602
+ if (typeof TEXT_TYPES !== 'undefined' && TEXT_TYPES.indexOf(type) !== -1) return 'input';
1603
+ }
1604
+ return null;
1605
+ }
1606
+
1607
+ function createField(node, kind, options) {
1608
+ var opts = mergeOptions(parseOptionsAttr(node), options);
1609
+ if (node.__zidanField && !opts.force) return node.__zidanField;
1610
+ switch (kind) {
1611
+ case 'checkbox':
1612
+ return typeof ZidanCheckbox !== 'undefined' ? new ZidanCheckbox(node, opts) : null;
1613
+ case 'radio':
1614
+ case 'radio-group':
1615
+ return typeof ZidanRadioGroup !== 'undefined' ? new ZidanRadioGroup(node, opts) : null;
1616
+ case 'file':
1617
+ return typeof ZidanFileUpload !== 'undefined' ? new ZidanFileUpload(node, opts) : null;
1618
+ case 'input':
1619
+ case 'textarea':
1620
+ return typeof ZidanTextField !== 'undefined' ? new ZidanTextField(node, opts) : null;
1621
+ default: return null;
1622
+ }
1623
+ }
1624
+
1625
+ function zidanField(target, options) {
1626
+ var nodes = [];
1627
+ if (typeof target === 'string') {
1628
+ nodes = Array.prototype.slice.call(doc.querySelectorAll(target));
1629
+ } else if (isElement(target)) {
1630
+ nodes = [target];
1631
+ } else if (target && typeof target.length === 'number') {
1632
+ nodes = Array.prototype.slice.call(target);
1633
+ }
1634
+ var created = [];
1635
+ nodes.forEach(function (node) {
1636
+ if (node.__zidanField) return;
1637
+ // zidanField() accepts a plain input/textarea too, so JS-only options
1638
+ // (output, counter, clearable, …) work without a data attribute
1639
+ var kind = fieldKindFor(node) || inferredTextKind(node);
1640
+ if (!kind) return;
1641
+ if (kind === 'radio' && !node.hasAttribute('data-zidan-radio')) {
1642
+ kind = 'radio-group';
1643
+ }
1644
+ var instance = createField(node, kind, options || {});
1645
+ if (instance) created.push(instance);
1646
+ });
1647
+ return created.length === 1 ? created[0] : created;
1648
+ }
1649
+
1650
+ function initFieldList(nodes, options) {
1651
+ var instances = [];
1652
+ nodes.forEach(function (node) {
1653
+ if (!isElement(node) || node.__zidanField) return;
1654
+ var kind = fieldKindFor(node);
1655
+ if (!kind) return;
1656
+ if (kind === 'radio') kind = 'radio-group';
1657
+ var instance = createField(node, kind, options || {});
1658
+ if (instance) instances.push(instance);
1659
+ });
1660
+ return instances;
1661
+ }
1662
+
1663
+ function initZidanForms(container, options) {
1664
+ var scope = container || doc;
1665
+ if (!scope || !scope.querySelectorAll) return [];
1666
+ var nodes = Array.prototype.slice.call(scope.querySelectorAll(FIELDS_SELECTOR));
1667
+ if (isElement(scope) && scope.matches && scope.matches(FIELDS_SELECTOR)) nodes.unshift(scope);
1668
+ return initFieldList(nodes, options);
1669
+ }
1670
+
1671
+ var ZidanForm = {
1672
+ version: VERSION,
1673
+ __zidanFormGuard: VERSION,
1674
+ // live registries: pushing a name here makes it a valid theme/layout
1675
+ themes: THEMES,
1676
+ frameworks: FRAMEWORKS.slice(),
1677
+ fieldLayouts: FIELD_LAYOUTS,
1678
+ fields: [],
1679
+ _register: function (field) {
1680
+ if (ZidanForm.fields.indexOf(field) === -1) ZidanForm.fields.push(field);
1681
+ },
1682
+ _unregister: function (field) {
1683
+ var index = ZidanForm.fields.indexOf(field);
1684
+ if (index !== -1) ZidanForm.fields.splice(index, 1);
1685
+ },
1686
+ get: function (target) {
1687
+ var node = typeof target === 'string' ? doc.querySelector(target) : target;
1688
+ return isElement(node) ? node.__zidanField || null : null;
1689
+ },
1690
+ init: function (scope, options) {
1691
+ return initZidanForms(scope || doc, options || {});
1692
+ },
1693
+ field: zidanField,
1694
+ refresh: function (scope) {
1695
+ initZidanForms(scope || doc, {});
1696
+ ZidanForm.fields.slice().forEach(function (field) { field.update(); });
1697
+ return ZidanForm.fields.slice();
1698
+ },
1699
+ destroyAll: function () {
1700
+ ZidanForm.fields.slice().forEach(function (field) { field.destroy(); });
1701
+ ZidanForm.fields = [];
1702
+ if (typeof ZidanSelect !== 'undefined' && ZidanSelect.destroyAll) ZidanSelect.destroyAll();
1703
+ return ZidanForm;
1704
+ },
1705
+ /* keep a subtree in sync when it is re-rendered by a framework */
1706
+ observe: function (scope, options) {
1707
+ var root = scope || doc.body;
1708
+ if (!root || !global.MutationObserver) return null;
1709
+ var observer = new global.MutationObserver(function (records) {
1710
+ records.forEach(function (record) {
1711
+ Array.prototype.slice.call(record.addedNodes).forEach(function (node) {
1712
+ if (!isElement(node)) return;
1713
+ if (fieldKindFor(node)) createField(node, fieldKindFor(node) === 'radio' ? 'radio-group' : fieldKindFor(node), options || {});
1714
+ if (node.querySelectorAll) initZidanForms(node, options || {});
1715
+ });
1716
+ });
1717
+ // drop instances whose control left the document
1718
+ ZidanForm.fields.slice().forEach(function (field) {
1719
+ if (!field.el.isConnected) field.destroy();
1720
+ });
1721
+ if (typeof ZidanSelect !== 'undefined') {
1722
+ ZidanSelect.instances.slice().forEach(function (instance) {
1723
+ if (!instance.el.isConnected) instance.destroy();
1724
+ });
1725
+ }
1726
+ });
1727
+ observer.observe(root, { childList: true, subtree: true });
1728
+ return observer;
1729
+ }
1730
+ };
1731
+
1732
+ ZidanForm.api = null;
1733
+
1734
+ /* registries, presets and helpers shared by every field type */
1735
+ ZidanForm.registerIcon = registerIcon;
1736
+ ZidanForm.icons = ICON_REGISTRY;
1737
+ if (typeof PHONE_COUNTRIES !== 'undefined') {
1738
+ ZidanForm.phoneCountries = PHONE_COUNTRIES;
1739
+ ZidanForm.phoneFormats = PHONE_FORMATS.slice();
1740
+ ZidanForm.formatPhone = formatPhone;
1741
+ ZidanForm.detectPhoneCountry = detectPhoneCountry;
1742
+ }
1743
+ ZidanForm.messages = FIELD_MESSAGES;
1744
+ ZidanForm.variants = {};
1745
+ if (typeof CHECKBOX_VARIANTS !== 'undefined') ZidanForm.variants.checkbox = CHECKBOX_VARIANTS.slice();
1746
+ if (typeof SWITCH_STYLES !== 'undefined') ZidanForm.variants.switch = SWITCH_STYLES.slice();
1747
+ if (typeof RADIO_VARIANTS !== 'undefined') ZidanForm.variants.radio = RADIO_VARIANTS.slice();
1748
+ if (typeof FILE_VARIANTS !== 'undefined') ZidanForm.variants.file = FILE_VARIANTS.slice();
1749
+ if (typeof RANGE_VARIANTS !== 'undefined') ZidanForm.variants.range = RANGE_VARIANTS.slice();
1750
+ if (typeof STEPPER_MODES !== 'undefined') ZidanForm.stepperModes = STEPPER_MODES.slice();
1751
+ ZidanForm.fieldLayouts = FIELD_LAYOUTS.slice();
1752
+
1753
+ /* static helpers */
1754
+ if (typeof ZidanSelect !== 'undefined') {
1755
+ ZidanSelect.version = VERSION;
1756
+ ZidanSelect.__zidanSelectGuard = VERSION;
1757
+ ZidanSelect.layouts = LAYOUTS.slice();
1758
+ ZidanSelect.frameworks = FRAMEWORKS.slice();
1759
+ ZidanSelect.scrollbars = SCROLLBARS.slice();
1760
+ ZidanSelect.defaults = DEFAULTS;
1761
+ ZidanSelect.get = function (target) {
1762
+ var element = typeof target === 'string' ? doc.querySelector(target) : target;
1763
+ if (!isElement(element)) return null;
1764
+ return element.__zidanSelect || null;
1765
+ };
1766
+ ZidanSelect.instances = [];
1767
+ ZidanSelect.destroyAll = function () {
1768
+ ZidanSelect.instances.slice().forEach(function (instance) { instance.destroy(); });
1769
+ ZidanSelect.instances = [];
1770
+ };
1771
+ }
1772
+
1773
+ /* ------------------------------------------------------------------ *
1774
+ * Factory + auto-init
1775
+ * ------------------------------------------------------------------ */
1776
+
1777
+ function zidanSelect(target, options) {
1778
+ var nodes = [];
1779
+ if (typeof target === 'string') {
1780
+ nodes = Array.prototype.slice.call(doc.querySelectorAll(target));
1781
+ } else if (target && typeof target.length === 'number' && !isElement(target) && target !== global) {
1782
+ nodes = Array.prototype.slice.call(target);
1783
+ } else if (isElement(target)) {
1784
+ nodes = [target];
1785
+ }
1786
+
1787
+ var instances = nodes.map(function (node) {
1788
+ var instance = new ZidanSelect(node, options || {});
1789
+ ZidanSelect.instances.push(instance);
1790
+ return instance;
1791
+ });
1792
+
1793
+ return instances.length === 1 ? instances[0] : instances;
1794
+ }
1795
+
1796
+ function initSelectList(nodes, options) {
1797
+ return nodes.filter(function (node) {
1798
+ return isElement(node) && !node.__zidanSelect;
1799
+ }).map(function (node) {
1800
+ ZidanSelect.instances.push(new ZidanSelect(node, options || {}));
1801
+ return node.__zidanSelect;
1802
+ });
1803
+ }
1804
+
1805
+ function initZidanSelects(container, options) {
1806
+ var scope = container || doc;
1807
+ if (!scope || !scope.querySelectorAll) return [];
1808
+ var nodes = Array.prototype.slice.call(scope.querySelectorAll(SELECT_SELECTOR));
1809
+ if (isElement(scope) && scope.matches && scope.matches(SELECT_SELECTOR)) nodes.unshift(scope);
1810
+ return initSelectList(nodes, options);
1811
+ }
1812
+
1813
+ /* a config target is a CSS selector string or { selector, options } */
1814
+ function eachTarget(list, run) {
1815
+ toArray(list).forEach(function (entry) {
1816
+ if (!entry) return;
1817
+ if (typeof entry === 'string') run(entry, null);
1818
+ else if (entry.selector) run(String(entry.selector), entry.options || null);
1819
+ });
1820
+ }
1821
+
1822
+ function initSelectTargets(list, shared) {
1823
+ eachTarget(list, function (selector, options) {
1824
+ initSelectList(Array.prototype.slice.call(doc.querySelectorAll(selector)),
1825
+ mergeOptions(shared, options));
1826
+ });
1827
+ }
1828
+
1829
+ function initFieldTargets(list, shared) {
1830
+ eachTarget(list, function (selector, options) {
1831
+ var opts = mergeOptions(shared, options);
1832
+ Array.prototype.slice.call(doc.querySelectorAll(selector)).forEach(function (node) {
1833
+ if (!isElement(node) || node.__zidanField) return;
1834
+ var kind = fieldKindFor(node) || inferredTextKind(node);
1835
+ if (!kind) return;
1836
+ if (kind === 'radio') kind = 'radio-group';
1837
+ createField(node, kind, opts);
1838
+ });
1839
+ });
1840
+ }
1841
+
1842
+ /* explicit targets may point at a plain text input or textarea */
1843
+ function inferredTextKind(node) {
1844
+ if (typeof TEXT_TYPES === 'undefined' || !isElement(node)) return null;
1845
+ if (node.tagName === 'TEXTAREA') return 'textarea';
1846
+ if (node.tagName !== 'INPUT') return null;
1847
+ return TEXT_TYPES.indexOf(String(node.type).toLowerCase()) !== -1 ? 'input' : null;
1848
+ }
1849
+
1850
+ /* a form scope enhances every native select inside, marked or not */
1851
+ function initScopeSelects(scope, options) {
1852
+ if (typeof ZidanSelect === 'undefined') return [];
1853
+ var selector = SELECT_SELECTOR + ', select';
1854
+ var nodes = Array.prototype.slice.call(scope.querySelectorAll(selector));
1855
+ if (isElement(scope) && scope.matches && scope.matches(selector)) nodes.unshift(scope);
1856
+ return initSelectList(nodes, options);
1857
+ }
1858
+
1859
+ function initScope(scope, selectOptions, fieldOptions) {
1860
+ if (!isElement(scope)) return;
1861
+ initScopeSelects(scope, selectOptions);
1862
+ if (typeof ZidanFileUpload !== 'undefined') {
1863
+ // a form scope also picks up plain file inputs, not just marked ones
1864
+ initFieldList(Array.prototype.slice.call(scope.querySelectorAll('input[type="file"]')), fieldOptions);
1865
+ }
1866
+ if (typeof ZidanCheckbox !== 'undefined' || typeof ZidanRadioGroup !== 'undefined' ||
1867
+ typeof ZidanFileUpload !== 'undefined' || typeof ZidanTextField !== 'undefined') {
1868
+ initZidanForms(scope, fieldOptions);
1869
+ }
1870
+ }
1871
+
1872
+ function initFormScopes(list, selectOptions, fieldOptions) {
1873
+ Array.prototype.slice.call(doc.querySelectorAll(FORM_SCOPE_SELECTOR))
1874
+ .forEach(function (scope) { initScope(scope, selectOptions, fieldOptions); });
1875
+ eachTarget(list, function (selector, options) {
1876
+ Array.prototype.slice.call(doc.querySelectorAll(selector)).forEach(function (scope) {
1877
+ initScope(scope, mergeOptions(selectOptions, options), mergeOptions(fieldOptions, options));
1878
+ });
1879
+ });
1880
+ }
1881
+
1882
+ function autoInit() {
1883
+ if (!doc) return;
1884
+ var config = global.ZIDAN_FORM_CONFIG || global.ZIDAN_SELECT_CONFIG || {};
1885
+ if (config.autoInit === false) return;
1886
+ if (global.ZidanSelect && global.ZidanSelect.autoInit === false) return;
1887
+ if (doc.documentElement.getAttribute('data-zidan-auto-init') === 'false') return;
1888
+
1889
+ var hasSelect = typeof ZidanSelect !== 'undefined';
1890
+ var hasFields = typeof ZidanCheckbox !== 'undefined' || typeof ZidanRadioGroup !== 'undefined' ||
1891
+ typeof ZidanFileUpload !== 'undefined' || typeof ZidanTextField !== 'undefined';
1892
+ var selectOptions = config.options || {};
1893
+ var fieldOptions = config.fieldOptions || config.fields || {};
1894
+
1895
+ // explicit targets run first so their per-target options win over the
1896
+ // generic attribute scan (the scan then skips what is already initialised)
1897
+ if (hasSelect) {
1898
+ if (config.selector) {
1899
+ // legacy: an explicit selector replaces the data-attribute scan
1900
+ initSelectTargets(config.selector, selectOptions);
1901
+ } else {
1902
+ initSelectTargets(config.targets || config.selectors, selectOptions);
1903
+ }
1904
+ }
1905
+ if (hasFields) initFieldTargets(config.fieldTargets, fieldOptions);
1906
+ initFormScopes(config.formTargets, selectOptions, fieldOptions);
1907
+
1908
+ if (hasSelect && !config.selector) initZidanSelects(doc, selectOptions);
1909
+ if (hasFields) initZidanForms(doc, fieldOptions);
1910
+ }
1911
+
1912
+ if (doc) {
1913
+ if (doc.readyState === 'loading') {
1914
+ doc.addEventListener('DOMContentLoaded', autoInit);
1915
+ } else {
1916
+ setTimeout(autoInit, 0);
1917
+ }
1918
+ }
1919
+
1920
+ var api = {
1921
+ ZidanForm: ZidanForm,
1922
+ registerIcon: registerIcon
1923
+ };
1924
+ if (typeof ZidanSelect !== 'undefined') {
1925
+ api.ZidanSelect = ZidanSelect;
1926
+ api.zidanSelect = zidanSelect;
1927
+ api.initZidanSelects = initZidanSelects;
1928
+ }
1929
+ if (typeof ZidanCheckbox !== 'undefined' || typeof ZidanRadioGroup !== 'undefined' ||
1930
+ typeof ZidanFileUpload !== 'undefined' || typeof ZidanTextField !== 'undefined') {
1931
+ api.zidanField = zidanField;
1932
+ api.initZidanForms = initZidanForms;
1933
+ }
1934
+ if (typeof ZidanCheckbox !== 'undefined') api.ZidanCheckbox = ZidanCheckbox;
1935
+ if (typeof ZidanRadioGroup !== 'undefined') api.ZidanRadioGroup = ZidanRadioGroup;
1936
+ if (typeof ZidanFileUpload !== 'undefined') api.ZidanFileUpload = ZidanFileUpload;
1937
+ if (typeof ZidanTextField !== 'undefined') api.ZidanTextField = ZidanTextField;
1938
+ if (typeof formatPhone === 'function') {
1939
+ api.formatPhone = formatPhone;
1940
+ api.detectPhoneCountry = detectPhoneCountry;
1941
+ }
1942
+
1943
+ ZidanForm.api = api;
1944
+
1945
+ return api;
1946
+ });