zidan-select 2.0.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
1
  /*!
2
- * ZidanForm v2.0.0
2
+ * ZidanForm v2.1.0
3
3
  * Zero-dependency form enhancement library: select / combobox / tags,
4
- * checkboxes, switches, radio groups, file upload with drag & drop, and
5
- * text inputs / textarea. Structure and theming are split into
6
- * plugin-core.css and plugin-theme.css.
4
+ * checkboxes, switches, radio groups, file upload with drag & drop and
5
+ * upload progress, text / number / phone / date / range inputs and textarea.
6
+ * Structure and theming are split into plugin-core.css and plugin-theme.css.
7
7
  *
8
8
  * https://github.com/akhtar1985/zidan-select
9
9
  * MIT License © akhtar1985
@@ -22,6 +22,7 @@
22
22
  window.initZidanSelects = api.initZidanSelects;
23
23
  window.zidanField = api.zidanField;
24
24
  window.initZidanForms = api.initZidanForms;
25
+ window.registerZidanIcon = api.registerIcon;
25
26
  }
26
27
  if (typeof module !== 'undefined' && module.exports) {
27
28
  module.exports = api;
@@ -29,7 +30,7 @@
29
30
  })(typeof window !== 'undefined' ? window : this, function (global) {
30
31
  'use strict';
31
32
 
32
- var VERSION = '2.0.0';
33
+ var VERSION = '2.1.0';
33
34
 
34
35
  // Loading the file twice (classic script + module wrapper, or two bundles)
35
36
  // must not replace the classes and orphan the live instances.
@@ -105,6 +106,394 @@
105
106
  return Math.min(max, Math.max(min, value));
106
107
  }
107
108
 
109
+ function fillTemplate(template, vars) {
110
+ return String(template).replace(/\{(\w+)\}/g, function (match, key) {
111
+ return vars && vars[key] !== undefined && vars[key] !== null ? String(vars[key]) : match;
112
+ });
113
+ }
114
+
115
+ /* ---------------- opt-in icon presets ---------------- */
116
+
117
+ var ICON_PATHS = {
118
+ text: '<path d="M4 7h16M4 12h10M4 17h13"/>',
119
+ mail: '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/>',
120
+ 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"/>',
121
+ user: '<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>',
122
+ lock: '<rect x="4" y="10" width="16" height="11" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/>',
123
+ search: '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',
124
+ calendar: '<rect x="3" y="5" width="18" height="16" rx="2"/><path d="M16 3v4M8 3v4M3 11h18"/>',
125
+ clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
126
+ 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"/>',
127
+ hash: '<path d="M4 9h16M4 15h16M10 3 8 21M16 3l-2 18"/>',
128
+ 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"/>',
129
+ sliders: '<path d="M4 7h16M4 17h16"/><circle cx="9" cy="7" r="2.5"/><circle cx="15" cy="17" r="2.5"/>',
130
+ 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"/>',
131
+ 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"/>',
132
+ 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"/>',
133
+ '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"/>',
134
+ check: '<path d="m4 12.5 5 5L20 6.5"/>',
135
+ x: '<path d="M6 6l12 12M18 6 6 18"/>',
136
+ plus: '<path d="M12 5v14M5 12h14"/>',
137
+ minus: '<path d="M5 12h14"/>',
138
+ 'chevron-down': '<path d="m6 9 6 6 6-6"/>',
139
+ 'chevron-up': '<path d="m6 15 6-6 6 6"/>',
140
+ 'chevron-left': '<path d="m15 6-6 6 6 6"/>',
141
+ 'chevron-right': '<path d="m9 6 6 6-6 6"/>',
142
+ 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"/>',
143
+ info: '<circle cx="12" cy="12" r="9"/><path d="M12 11v5"/><path d="M12 8h.01"/>',
144
+ 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"/>',
145
+ '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"/>',
146
+ 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"/>',
147
+ 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"/>',
148
+ trash: '<path d="M4 7h16"/><path d="M9 7V4h6v3"/><path d="M6 7l1 13h10l1-13"/><path d="M10 11v5M14 11v5"/>'
149
+ };
150
+
151
+ var ICON_REGISTRY = {};
152
+ Object.keys(ICON_PATHS).forEach(function (key) { ICON_REGISTRY[key] = ICON_PATHS[key]; });
153
+ var ICON_NAMESPACE = 'http://www.w3.org/2000/svg';
154
+
155
+ var ICON_ALLOWED = {
156
+ svg: 1, g: 1, path: 1, circle: 1, rect: 1, line: 1, polyline: 1,
157
+ polygon: 1, ellipse: 1, title: 1, defs: 1, clipPath: 1, clippath: 1, mask: 1
158
+ };
159
+
160
+ function sanitizeIcon(markup) {
161
+ if (typeof markup !== 'string' || !markup.trim()) return '';
162
+ var parsed;
163
+ try {
164
+ if (typeof global.DOMParser === 'undefined') return '';
165
+ parsed = new global.DOMParser().parseFromString(markup, 'image/svg+xml');
166
+ } catch (err) {
167
+ return '';
168
+ }
169
+ if (!parsed || !parsed.documentElement) return '';
170
+ var svg = parsed.documentElement;
171
+ if (String(svg.nodeName).toLowerCase() !== 'svg') return '';
172
+ if (parsed.getElementsByTagName('parsererror').length) return '';
173
+ var walk = function (node) {
174
+ Array.prototype.slice.call(node.children || []).forEach(function (child) {
175
+ var tag = String(child.nodeName);
176
+ if (tag !== tag.toLowerCase()) tag = tag.toLowerCase();
177
+ if (!ICON_ALLOWED[tag]) {
178
+ child.parentNode.removeChild(child);
179
+ return;
180
+ }
181
+ Array.prototype.slice.call(child.attributes || []).forEach(function (attr) {
182
+ var name = String(attr.name).toLowerCase();
183
+ if (name.indexOf('on') === 0) child.removeAttribute(attr.name);
184
+ if ((name === 'href' || name === 'xlink:href') && !/^#/.test(attr.value)) child.removeAttribute(attr.name);
185
+ if (/url\s*\(\s*['"]?\s*(?:https?:|\/\/)/i.test(attr.value)) child.removeAttribute(attr.name);
186
+ });
187
+ walk(child);
188
+ });
189
+ };
190
+ walk(svg);
191
+ return svg.outerHTML;
192
+ }
193
+
194
+ function iconSvgFromMarkup(markup) {
195
+ var paths = markup;
196
+ if (/^\s*</.test(paths) && !/^\s*<svg/i.test(paths)) {
197
+ paths = '<svg xmlns="' + ICON_NAMESPACE + '" viewBox="0 0 24 24" fill="none" stroke="currentColor" ' +
198
+ 'stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' + paths + '</svg>';
199
+ } else if (!/^\s*<svg/i.test(paths)) {
200
+ paths = '';
201
+ }
202
+ return sanitizeIcon(paths);
203
+ }
204
+
205
+ function iconNode(spec, className) {
206
+ var markup = '';
207
+ var name = '';
208
+ if (typeof spec === 'string' && spec) {
209
+ name = spec;
210
+ if (/^\s*</.test(spec)) {
211
+ markup = iconSvgFromMarkup(spec) || iconSvgFromMarkup('<path d="M4 12h16"/>');
212
+ } else if (ICON_REGISTRY[spec]) {
213
+ markup = iconSvgFromMarkup(ICON_REGISTRY[spec]) || '';
214
+ }
215
+ } else if (spec && typeof spec === 'object' && spec.name) {
216
+ name = spec.name;
217
+ markup = iconSvgFromMarkup(ICON_REGISTRY[spec.name] || '');
218
+ }
219
+ if (!markup) return null;
220
+ var node = doc.createElement('span');
221
+ if (className) node.className = className;
222
+ node.setAttribute('data-zs-icon', name || 'custom');
223
+ try {
224
+ node.innerHTML = markup;
225
+ } catch (err) {
226
+ return null;
227
+ }
228
+ var svg = node.firstChild;
229
+ if (svg) {
230
+ svg.setAttribute('focusable', 'false');
231
+ svg.setAttribute('aria-hidden', 'true');
232
+ svg.setAttribute('width', '18');
233
+ svg.setAttribute('height', '18');
234
+ }
235
+ return node;
236
+ }
237
+
238
+ var TYPE_ICONS = {
239
+ text: 'text',
240
+ email: 'mail',
241
+ password: 'lock',
242
+ number: 'hash',
243
+ tel: 'phone',
244
+ url: 'link',
245
+ search: 'search',
246
+ date: 'calendar',
247
+ time: 'clock',
248
+ 'datetime-local': 'calendar',
249
+ month: 'calendar',
250
+ week: 'calendar',
251
+ range: 'sliders',
252
+ color: 'palette'
253
+ };
254
+
255
+ function iconForType(type) {
256
+ return TYPE_ICONS[type] || '';
257
+ }
258
+
259
+ function registerIcon(name, markup) {
260
+ if (!name || typeof markup !== 'string') return ZidanSelect;
261
+ ICON_REGISTRY[String(name)] = markup;
262
+ return ZidanSelect;
263
+ }
264
+
265
+ /* ---------------- field options (JS options + data-* attributes) ---------------- */
266
+
267
+ function fieldOption(node, options, key, attr, fallback) {
268
+ if (options && options[key] !== undefined && options[key] !== null) return options[key];
269
+ if (node && attr && node.getAttribute) {
270
+ var value = node.getAttribute('data-zidan-' + attr);
271
+ if (value !== null && value !== '') return value;
272
+ }
273
+ return fallback;
274
+ }
275
+
276
+ function fieldBool(node, options, key, attr, fallback) {
277
+ if (options && options[key] !== undefined && options[key] !== null) return !!options[key];
278
+ if (node && attr && node.getAttribute) {
279
+ var value = node.getAttribute('data-zidan-' + attr);
280
+ if (value !== null) return readBoolAttr(value, fallback);
281
+ }
282
+ return fallback;
283
+ }
284
+
285
+ function fieldNumber(node, options, key, attr, fallback) {
286
+ var value = fieldOption(node, options, key, attr, fallback);
287
+ if (value === null || value === undefined || value === '') return fallback;
288
+ var number = parseFloat(value);
289
+ return isFinite(number) ? number : fallback;
290
+ }
291
+
292
+ function fieldList(node, options, key, attr, fallback) {
293
+ var value = fieldOption(node, options, key, attr, null);
294
+ if (value === null || value === undefined || value === '') return fallback;
295
+ if (Array.isArray(value)) return value.slice();
296
+ return String(value).split(',').map(function (item) { return item.trim(); }).filter(Boolean);
297
+ }
298
+
299
+ /* ---------------- validation messages ---------------- */
300
+
301
+ var FIELD_MESSAGES = {
302
+ required: 'This field is required.',
303
+ email: 'Enter a valid email address.',
304
+ url: 'Enter a valid URL.',
305
+ pattern: 'The value does not match the expected format.',
306
+ min: 'Value must be at least {min}.',
307
+ max: 'Value must be at most {max}.',
308
+ step: 'Value must be a multiple of {step}.',
309
+ minlength: 'Use at least {minlength} characters.',
310
+ maxlength: 'Use at most {maxlength} characters.',
311
+ badInput: 'Enter a valid value.',
312
+ phone: 'Enter a valid phone number for {country}.',
313
+ integer: 'Enter a whole number.',
314
+ date: 'Enter a valid date.',
315
+ weekend: 'Weekends are not available — pick a weekday.',
316
+ dateDisabled: 'This date is not available.',
317
+ fileType: 'This file type is not allowed.',
318
+ fileSize: 'This file is too large.',
319
+ fileCount: 'Too many files.',
320
+ generic: 'Please check this field.'
321
+ };
322
+
323
+ function validityMessage(input, messages) {
324
+ if (!input || !input.validity || input.validity.valid) return '';
325
+ var v = input.validity;
326
+ var map = messages || FIELD_MESSAGES;
327
+ var type = String(input.type || '').toLowerCase();
328
+ var key = '';
329
+ var vars = { min: input.getAttribute('min'), max: input.getAttribute('max'), step: input.getAttribute('step') };
330
+ if (v.valueMissing) key = 'required';
331
+ else if (v.typeMismatch) key = type === 'email' ? 'email' : (type === 'url' ? 'url' : 'generic');
332
+ else if (v.patternMismatch) key = 'pattern';
333
+ else if (v.rangeUnderflow) key = 'min';
334
+ else if (v.rangeOverflow) key = 'max';
335
+ else if (v.stepMismatch) key = 'step';
336
+ else if (v.tooShort) {
337
+ key = 'minlength';
338
+ vars.minlength = input.getAttribute('minlength');
339
+ } else if (v.tooLong) {
340
+ key = 'maxlength';
341
+ vars.maxlength = input.getAttribute('maxlength');
342
+ } else if (v.badInput || v.customError) key = 'badInput';
343
+ if (!key) return input.validationMessage || map.generic;
344
+ return fillTemplate(map[key] || FIELD_MESSAGES[key] || map.generic, vars);
345
+ }
346
+
347
+ /* ---------------- phone formatting ---------------- */
348
+
349
+ var PHONE_COUNTRIES = {
350
+ US: { flag: '🇺🇸', name: 'United States', dial: '1', mask: '(###) ###-####', groups: [3, 3, 4], min: 10, max: 10 },
351
+ CA: { flag: '🇨🇦', name: 'Canada', dial: '1', mask: '(###) ###-####', groups: [3, 3, 4], min: 10, max: 10 },
352
+ GB: { flag: '🇬🇧', name: 'United Kingdom', dial: '44', mask: '##### ######', groups: [5, 6], intlGroups: [4, 6], min: 10, max: 11 },
353
+ DE: { flag: '🇩🇪', name: 'Germany', dial: '49', mask: '#### #######', groups: [4, 7], min: 10, max: 11 },
354
+ FR: { flag: '🇫🇷', name: 'France', dial: '33', mask: '# ## ## ## ##', groups: [1, 2, 2, 2, 2], min: 9, max: 10 },
355
+ IN: { flag: '🇮🇳', name: 'India', dial: '91', mask: '##### #####', groups: [5, 5], min: 10, max: 10 },
356
+ PK: { flag: '🇵🇰', name: 'Pakistan', dial: '92', mask: '### #######', groups: [3, 7], min: 10, max: 10 },
357
+ AE: { flag: '🇦🇪', name: 'United Arab Emirates', dial: '971', mask: '## ### ####', groups: [2, 3, 4], min: 9, max: 9 },
358
+ SA: { flag: '🇸🇦', name: 'Saudi Arabia', dial: '966', mask: '## ### ####', groups: [2, 3, 4], min: 9, max: 9 },
359
+ AU: { flag: '🇦🇺', name: 'Australia', dial: '61', mask: '### ### ###', groups: [3, 3, 3], min: 9, max: 9 },
360
+ BR: { flag: '🇧🇷', name: 'Brazil', dial: '55', mask: '(##) #####-####', groups: [2, 5, 4], min: 10, max: 11 },
361
+ CN: { flag: '🇨🇳', name: 'China', dial: '86', mask: '### #### ####', groups: [3, 4, 4], min: 11, max: 11 },
362
+ JP: { flag: '🇯🇵', name: 'Japan', dial: '81', mask: '## #### ####', groups: [2, 4, 4], min: 10, max: 11 },
363
+ RU: { flag: '🇷🇺', name: 'Russia', dial: '7', mask: '### ###-##-##', groups: [3, 3, 2, 2], min: 10, max: 10 },
364
+ ZA: { flag: '🇿🇦', name: 'South Africa', dial: '27', mask: '## ### ####', groups: [2, 3, 4], min: 9, max: 9 },
365
+ NG: { flag: '🇳🇬', name: 'Nigeria', dial: '234', mask: '### ### ####', groups: [3, 3, 4], min: 10, max: 10 },
366
+ EG: { flag: '🇪🇬', name: 'Egypt', dial: '20', mask: '## #### ####', groups: [2, 4, 4], min: 10, max: 10 },
367
+ TR: { flag: '🇹🇷', name: 'Türkiye', dial: '90', mask: '### ### ## ##', groups: [3, 3, 2, 2], min: 10, max: 10 },
368
+ ID: { flag: '🇮🇩', name: 'Indonesia', dial: '62', mask: '### ### ####', groups: [3, 3, 4], min: 9, max: 12 },
369
+ MY: { flag: '🇲🇾', name: 'Malaysia', dial: '60', mask: '## ### ####', groups: [2, 3, 4], min: 9, max: 10 },
370
+ PH: { flag: '🇵🇭', name: 'Philippines', dial: '63', mask: '### ### ####', groups: [3, 3, 4], min: 10, max: 10 },
371
+ BD: { flag: '🇧🇩', name: 'Bangladesh', dial: '880', mask: '#### ######', groups: [4, 6], min: 10, max: 10 },
372
+ IT: { flag: '🇮🇹', name: 'Italy', dial: '39', mask: '### ### ####', groups: [3, 3, 4], min: 9, max: 10 },
373
+ ES: { flag: '🇪🇸', name: 'Spain', dial: '34', mask: '### ## ## ##', groups: [3, 2, 2, 2], min: 9, max: 9 },
374
+ MX: { flag: '🇲🇽', name: 'Mexico', dial: '52', mask: '## #### ####', groups: [2, 4, 4], min: 10, max: 10 },
375
+ AR: { flag: '🇦🇷', name: 'Argentina', dial: '54', mask: '## #### ####', groups: [2, 4, 4], min: 10, max: 10 },
376
+ NZ: { flag: '🇳🇿', name: 'New Zealand', dial: '64', mask: '## ### ####', groups: [2, 3, 4], min: 8, max: 10 },
377
+ SG: { flag: '🇸🇬', name: 'Singapore', dial: '65', mask: '#### ####', groups: [4, 4], min: 8, max: 8 },
378
+ HK: { flag: '🇭🇰', name: 'Hong Kong', dial: '852', mask: '#### ####', groups: [4, 4], min: 8, max: 8 },
379
+ KR: { flag: '🇰🇷', name: 'South Korea', dial: '82', mask: '## #### ####', groups: [2, 4, 4], min: 9, max: 10 },
380
+ TH: { flag: '🇹🇭', name: 'Thailand', dial: '66', mask: '## ### ####', groups: [2, 3, 4], min: 9, max: 9 },
381
+ VN: { flag: '🇻🇳', name: 'Vietnam', dial: '84', mask: '### ### ####', groups: [3, 3, 4], min: 9, max: 10 },
382
+ NL: { flag: '🇳🇱', name: 'Netherlands', dial: '31', mask: '# ## ## ## ##', groups: [1, 2, 2, 2, 2], min: 9, max: 9 },
383
+ BE: { flag: '🇧🇪', name: 'Belgium', dial: '32', mask: '### ## ## ##', groups: [3, 2, 2, 2], min: 9, max: 9 },
384
+ CH: { flag: '🇨🇭', name: 'Switzerland', dial: '41', mask: '## ### ## ##', groups: [2, 3, 2, 2], min: 9, max: 9 },
385
+ SE: { flag: '🇸🇪', name: 'Sweden', dial: '46', mask: '## ### ## ##', groups: [2, 3, 2, 2], min: 9, max: 9 },
386
+ NO: { flag: '🇳🇴', name: 'Norway', dial: '47', mask: '### ## ###', groups: [3, 2, 3], min: 8, max: 8 },
387
+ DK: { flag: '🇩🇰', name: 'Denmark', dial: '45', mask: '## ## ## ##', groups: [2, 2, 2, 2], min: 8, max: 8 },
388
+ FI: { flag: '🇫🇮', name: 'Finland', dial: '358', mask: '## ### ####', groups: [2, 3, 4], min: 9, max: 10 },
389
+ PL: { flag: '🇵🇱', name: 'Poland', dial: '48', mask: '### ### ###', groups: [3, 3, 3], min: 9, max: 9 },
390
+ PT: { flag: '🇵🇹', name: 'Portugal', dial: '351', mask: '### ### ###', groups: [3, 3, 3], min: 9, max: 9 },
391
+ IE: { flag: '🇮🇪', name: 'Ireland', dial: '353', mask: '## ### ####', groups: [2, 3, 4], min: 9, max: 9 },
392
+ GR: { flag: '🇬🇷', name: 'Greece', dial: '30', mask: '### ### ####', groups: [3, 3, 4], min: 10, max: 10 },
393
+ UA: { flag: '🇺🇦', name: 'Ukraine', dial: '380', mask: '## ### ####', groups: [2, 3, 4], min: 9, max: 9 },
394
+ IL: { flag: '🇮🇱', name: 'Israel', dial: '972', mask: '##-###-####', groups: [2, 3, 4], min: 9, max: 9 },
395
+ QA: { flag: '🇶🇦', name: 'Qatar', dial: '974', mask: '#### ####', groups: [4, 4], min: 8, max: 8 },
396
+ KW: { flag: '🇰🇼', name: 'Kuwait', dial: '965', mask: '#### ####', groups: [4, 4], min: 8, max: 8 },
397
+ BH: { flag: '🇧🇭', name: 'Bahrain', dial: '973', mask: '#### ####', groups: [4, 4], min: 8, max: 8 },
398
+ OM: { flag: '🇴🇲', name: 'Oman', dial: '968', mask: '#### ####', groups: [4, 4], min: 8, max: 8 }
399
+ };
400
+
401
+ var PHONE_DEFAULT_COUNTRIES = ['US', 'CA', 'GB', 'AU', 'DE', 'FR', 'IN', 'PK', 'AE', 'SA', 'BR', 'CN', 'JP', 'RU', 'ZA', 'NG', 'TR', 'ID', 'MY', 'PH', 'BD', 'ES', 'IT', 'MX', 'NL', 'PL', 'PT', 'SE', 'CH', 'IE'];
402
+ var PHONE_FORMATS = ['national', 'international', 'e164'];
403
+
404
+ function digitsOnly(value) {
405
+ return String(value === null || value === undefined ? '' : value).replace(/\D+/g, '');
406
+ }
407
+
408
+ function formatWithMask(digits, mask) {
409
+ var out = '';
410
+ var index = 0;
411
+ for (var i = 0; i < mask.length; i += 1) {
412
+ if (mask.charAt(i) === '#') {
413
+ if (index >= digits.length) break;
414
+ out += digits.charAt(index);
415
+ index += 1;
416
+ } else {
417
+ out += mask.charAt(i);
418
+ }
419
+ }
420
+ if (index < digits.length) out += digits.slice(index);
421
+ return out;
422
+ }
423
+
424
+ function groupDigits(digits, groups) {
425
+ var out = [];
426
+ var index = 0;
427
+ (groups || []).forEach(function (size) {
428
+ if (index < digits.length) {
429
+ out.push(digits.slice(index, index + size));
430
+ index += size;
431
+ }
432
+ });
433
+ if (index < digits.length) out.push(digits.slice(index));
434
+ return out;
435
+ }
436
+
437
+ function formatPhone(value, countryIso, format) {
438
+ var country = PHONE_COUNTRIES[countryIso] || PHONE_COUNTRIES.US;
439
+ var mode = PHONE_FORMATS.indexOf(String(format)) === -1 ? 'national' : String(format);
440
+ var digits = digitsOnly(value);
441
+ if (mode !== 'national' && /^\s*\+/.test(String(value || ''))) {
442
+ // a pasted +<dial> value is normalized to the selected country
443
+ var detected = detectPhoneCountry(value);
444
+ if (detected) digits = digits.slice(PHONE_COUNTRIES[detected].dial.length);
445
+ }
446
+ if (mode !== 'national' && digits.indexOf(country.dial) === 0 && digits.length > country.max) {
447
+ digits = digits.slice(country.dial.length);
448
+ }
449
+ if (mode !== 'national' && digits.charAt(0) === '0') digits = digits.slice(1);
450
+ digits = digits.slice(0, country.max);
451
+ if (!digits) return '';
452
+ if (mode === 'e164') return '+' + country.dial + digits;
453
+ if (mode === 'international') return '+' + country.dial + ' ' + groupDigits(digits, country.intlGroups || country.groups).join(' ');
454
+ return formatWithMask(digits, country.mask);
455
+ }
456
+
457
+ function phoneDigitsForCountry(value, countryIso, format) {
458
+ var country = PHONE_COUNTRIES[countryIso] || PHONE_COUNTRIES.US;
459
+ var digits = digitsOnly(value);
460
+ if (format !== 'national' && /^\s*\+/.test(String(value || ''))) {
461
+ var detected = detectPhoneCountry(value);
462
+ if (detected) digits = digits.slice(PHONE_COUNTRIES[detected].dial.length);
463
+ } else if (format !== 'national' && digits.indexOf(country.dial) === 0 && digits.length > country.max) {
464
+ digits = digits.slice(country.dial.length);
465
+ }
466
+ if (format !== 'national' && digits.charAt(0) === '0') digits = digits.slice(1);
467
+ return digits;
468
+ }
469
+
470
+ function detectPhoneCountry(value) {
471
+ var digits = digitsOnly(value);
472
+ if (!/^\s*\+/.test(String(value || ''))) return '';
473
+ var best = '';
474
+ Object.keys(PHONE_COUNTRIES).forEach(function (iso) {
475
+ var dial = PHONE_COUNTRIES[iso].dial;
476
+ if (digits.indexOf(dial) === 0 && dial.length > (PHONE_COUNTRIES[best] ? PHONE_COUNTRIES[best].dial.length : 0)) best = iso;
477
+ });
478
+ return best;
479
+ }
480
+
481
+ function digitsBefore(text, position) {
482
+ return (String(text).slice(0, position).match(/\d/g) || []).length;
483
+ }
484
+
485
+ function caretAfterDigits(text, count) {
486
+ if (count <= 0) return 0;
487
+ var seen = 0;
488
+ for (var i = 0; i < text.length; i += 1) {
489
+ if (/\d/.test(text.charAt(i))) {
490
+ seen += 1;
491
+ if (seen === count) return i + 1;
492
+ }
493
+ }
494
+ return text.length;
495
+ }
496
+
108
497
  /* first non-empty value of any of `names`, walking up the tree */
109
498
  function inheritedAttr(node, names) {
110
499
  var current = node;
@@ -1854,8 +2243,11 @@
1854
2243
  * ================================================================== */
1855
2244
 
1856
2245
  var VALIDATION_STATES = ['valid', 'invalid'];
1857
- var CHECKBOX_VARIANTS = ['default', 'switch', 'card'];
1858
- var RADIO_VARIANTS = ['stacked', 'inline', 'card'];
2246
+ var CHECKBOX_VARIANTS = ['default', 'switch', 'card', 'button', 'minimal'];
2247
+ var SWITCH_STYLES = ['ios', 'material', 'square', 'labeled', 'icon'];
2248
+ var RADIO_VARIANTS = ['stacked', 'inline', 'card', 'button', 'tile'];
2249
+ var FILE_VARIANTS = ['dropzone', 'button', 'avatar', 'gallery', 'compact'];
2250
+ var RANGE_VARIANTS = ['default', 'gradient', 'stepped', 'minimal'];
1859
2251
 
1860
2252
  function textWithout(rootNode, skip) {
1861
2253
  var out = '';
@@ -1881,10 +2273,13 @@
1881
2273
  this.el = target;
1882
2274
  this.kind = kind;
1883
2275
  this.opts = options || {};
2276
+ this.opts.messages = Object.assign({}, FIELD_MESSAGES, this.opts.messages || {});
1884
2277
  this.id = target.id || (target.id = uid('zf'));
1885
2278
  this.root = null;
1886
2279
  this.touched = false;
1887
2280
  this.validation = null;
2281
+ this.errorMessage = null;
2282
+ this.errorEl = null;
1888
2283
  this.destroyed = false;
1889
2284
  this._listeners = [];
1890
2285
  this._cleanups = [];
@@ -1959,13 +2354,101 @@
1959
2354
  return [this.el];
1960
2355
  };
1961
2356
 
1962
- /* mirror native constraint validity into classes and aria-invalid */
2357
+ /* field-specific cross-field / format checks; subclasses override */
2358
+ ZidanFieldBase.prototype._customError = function () {
2359
+ return '';
2360
+ };
2361
+
2362
+ ZidanFieldBase.prototype._messageFor = function (input) {
2363
+ var message = validityMessage(input, this.opts.messages);
2364
+ if (message) return message;
2365
+ if (input && input.validationMessage) return input.validationMessage;
2366
+ return this.opts.messages.generic || FIELD_MESSAGES.generic;
2367
+ };
2368
+
2369
+ ZidanFieldBase.prototype._nativeError = function () {
2370
+ var targets = this.validationTargets();
2371
+ for (var i = 0; i < targets.length; i += 1) {
2372
+ var input = targets[i];
2373
+ if (input && input.validity && !input.validity.valid) return this._messageFor(input);
2374
+ }
2375
+ return '';
2376
+ };
2377
+
2378
+ ZidanFieldBase.prototype._evaluateError = function () {
2379
+ var custom = this._customError ? this._customError() : '';
2380
+ if (custom) return typeof custom === 'string' ? custom : this.opts.messages.generic;
2381
+ return this._nativeError();
2382
+ };
2383
+
2384
+ ZidanFieldBase.prototype._syncDescribedBy = function () {
2385
+ if (!this.el || !this.el.getAttribute) return;
2386
+ var errorId = this.id + '-error';
2387
+ var hint = this.root && this.root.querySelector ? this.root.querySelector('.zs-field__hint[id]') : null;
2388
+ var hintId = hint ? hint.id : '';
2389
+ var targets = this.validationTargets();
2390
+ targets.forEach(function (input) {
2391
+ if (!input || !input.getAttribute) return;
2392
+ var current = (input.getAttribute('aria-describedby') || '').split(/\s+/).filter(Boolean);
2393
+ var next = current.filter(function (id) { return id !== errorId && id !== hintId; });
2394
+ if (hintId) next.push(hintId);
2395
+ if (this.errorMessage) next.push(errorId);
2396
+ if (next.length) input.setAttribute('aria-describedby', next.join(' '));
2397
+ else input.removeAttribute('aria-describedby');
2398
+ }, this);
2399
+ };
2400
+
2401
+ ZidanFieldBase.prototype._renderError = function () {
2402
+ if (!this.root) return;
2403
+ if (!this.errorEl) {
2404
+ this.errorEl = el('p', 'zs-field__error', {
2405
+ id: this.id + '-error',
2406
+ role: 'status',
2407
+ 'aria-live': 'polite'
2408
+ });
2409
+ this.root.appendChild(this.errorEl);
2410
+ }
2411
+ this.errorEl.textContent = this.errorMessage || '';
2412
+ this.errorEl.hidden = !this.errorMessage;
2413
+ this._syncDescribedBy();
2414
+ };
2415
+
2416
+ ZidanFieldBase.prototype.setError = function (message) {
2417
+ this.errorMessage = message || null;
2418
+ if (this.errorMessage) this.validation = 'invalid';
2419
+ else if (this.validation === 'invalid') this.validation = null;
2420
+ var invalid = !!this.errorMessage || this.validation === 'invalid';
2421
+ if (this.root) {
2422
+ this.root.classList.toggle('zs-field--invalid', invalid);
2423
+ this.root.classList.toggle('zs-field--valid', this.validation === 'valid' && !this.errorMessage);
2424
+ if (invalid || this.validation) this.root.setAttribute('data-zs-validation', invalid ? 'invalid' : this.validation);
2425
+ else this.root.removeAttribute('data-zs-validation');
2426
+ }
2427
+ this._renderError();
2428
+ this.validationTargets().forEach(function (input) {
2429
+ if (!input || !input.setAttribute) return;
2430
+ if (invalid) input.setAttribute('aria-invalid', 'true');
2431
+ else if (this.validation === 'valid') input.setAttribute('aria-invalid', 'false');
2432
+ else input.removeAttribute('aria-invalid');
2433
+ }, this);
2434
+ this.emit('validation', { state: invalid ? 'invalid' : this.validation, message: this.errorMessage });
2435
+ this.call('onValidation', { state: invalid ? 'invalid' : this.validation, message: this.errorMessage, instance: this });
2436
+ return this;
2437
+ };
2438
+
2439
+ ZidanFieldBase.prototype.clearError = function () {
2440
+ return this.setError(null);
2441
+ };
2442
+
2443
+ /* mirror native constraint validity + custom rules into classes and aria */
1963
2444
  ZidanFieldBase.prototype._bindValidity = function () {
1964
2445
  var self = this;
1965
2446
  this.validationTargets().forEach(function (input) {
1966
2447
  self.on(input, 'invalid', function () {
1967
2448
  self.touched = true;
1968
- self.setValidation('invalid');
2449
+ var message = self._evaluateError();
2450
+ if (message) self.setError(message);
2451
+ else self.setValidation('invalid');
1969
2452
  });
1970
2453
  self.on(input, 'blur', function () {
1971
2454
  self.touched = true;
@@ -1978,6 +2461,11 @@
1978
2461
  global.setTimeout(function () {
1979
2462
  if (self.destroyed) return;
1980
2463
  self.touched = false;
2464
+ self.errorMessage = null;
2465
+ if (self.errorEl) {
2466
+ self.errorEl.textContent = '';
2467
+ self.errorEl.hidden = true;
2468
+ }
1981
2469
  self.setValidation(null);
1982
2470
  self.update();
1983
2471
  }, 0);
@@ -1985,34 +2473,51 @@
1985
2473
  var preset = this.opts.validation || this.el.getAttribute('data-zidan-validation') ||
1986
2474
  this.el.getAttribute('data-zs-validation');
1987
2475
  if (preset === 'valid' || preset === 'invalid') this.setValidation(preset);
2476
+ this._syncDescribedBy();
1988
2477
  };
1989
2478
 
1990
2479
  ZidanFieldBase.prototype._mirrorValidity = function () {
1991
- var target = this.el;
1992
- if (!target || !target.validity) return this;
1993
- if (target.validity.valid) {
1994
- if (this.validation === 'invalid') this.setValidation(null);
2480
+ var error = this._evaluateError();
2481
+ if (error) {
2482
+ if (this.touched || this.opts.alwaysValidate) this.setError(error);
2483
+ else this.setValidation('invalid');
1995
2484
  return this;
1996
2485
  }
1997
- if (this.touched || this.opts.alwaysValidate) this.setValidation('invalid');
2486
+ if (this.errorMessage) this.setError(null);
2487
+ if (this.validation === 'invalid') this.setValidation(null);
1998
2488
  return this;
1999
2489
  };
2000
2490
 
2491
+ ZidanFieldBase.prototype.validate = function () {
2492
+ this.touched = true;
2493
+ var error = this._evaluateError();
2494
+ if (error) {
2495
+ this.setError(error);
2496
+ return false;
2497
+ }
2498
+ this.setError(null);
2499
+ if (this.opts.showValidState) this.setValidation('valid');
2500
+ return true;
2501
+ };
2502
+
2001
2503
  ZidanFieldBase.prototype.setValidation = function (state) {
2002
2504
  this.validation = VALIDATION_STATES.indexOf(state) === -1 ? null : state;
2505
+ var invalid = this.validation === 'invalid' || !!this.errorMessage;
2003
2506
  if (this.root) {
2004
- this.root.classList.toggle('zs-field--invalid', this.validation === 'invalid');
2005
- this.root.classList.toggle('zs-field--valid', this.validation === 'valid');
2006
- if (this.validation) this.root.setAttribute('data-zs-validation', this.validation);
2507
+ this.root.classList.toggle('zs-field--invalid', invalid);
2508
+ this.root.classList.toggle('zs-field--valid', this.validation === 'valid' && !this.errorMessage);
2509
+ if (invalid) this.root.setAttribute('data-zs-validation', 'invalid');
2510
+ else if (this.validation) this.root.setAttribute('data-zs-validation', this.validation);
2007
2511
  else this.root.removeAttribute('data-zs-validation');
2008
2512
  }
2009
2513
  this.validationTargets().forEach(function (input) {
2010
- if (state === 'invalid') input.setAttribute('aria-invalid', 'true');
2011
- else if (state === 'valid') input.setAttribute('aria-invalid', 'false');
2514
+ if (!input || !input.setAttribute) return;
2515
+ if (invalid) input.setAttribute('aria-invalid', 'true');
2516
+ else if (this.validation === 'valid') input.setAttribute('aria-invalid', 'false');
2012
2517
  else input.removeAttribute('aria-invalid');
2013
- });
2014
- this.emit('validation', { state: this.validation });
2015
- this.call('onValidation', { state: this.validation, instance: this });
2518
+ }, this);
2519
+ this.emit('validation', { state: invalid ? 'invalid' : this.validation, message: this.errorMessage });
2520
+ this.call('onValidation', { state: invalid ? 'invalid' : this.validation, message: this.errorMessage, instance: this });
2016
2521
  return this;
2017
2522
  };
2018
2523
 
@@ -2064,6 +2569,12 @@
2064
2569
  'default'
2065
2570
  );
2066
2571
  this.variant = variant;
2572
+ var switchStyle = pickList(
2573
+ this.opts.switchStyle || input.getAttribute('data-zidan-switch-style'),
2574
+ SWITCH_STYLES,
2575
+ 'ios'
2576
+ );
2577
+ this.switchStyle = switchStyle;
2067
2578
 
2068
2579
  var originalParent = input.parentNode;
2069
2580
  var originalNext = input.nextSibling;
@@ -2082,6 +2593,7 @@
2082
2593
 
2083
2594
  var root = this._scope('checkbox');
2084
2595
  root.setAttribute('data-zs-variant', variant);
2596
+ root.setAttribute('data-zs-switch-style', switchStyle);
2085
2597
  // mount outside the original <label>: it is removed once its text is moved
2086
2598
  var mountParent = wrappingLabel && wrappingLabel.parentNode ? wrappingLabel.parentNode : originalParent;
2087
2599
  var mountBefore = wrappingLabel && wrappingLabel.parentNode ? wrappingLabel : input;
@@ -2094,8 +2606,21 @@
2094
2606
  if (!wrappingLabel) check.setAttribute('for', this.id);
2095
2607
 
2096
2608
  var indicator = el('span', variant === 'switch' ? 'zs-switch-track' : 'zs-check-box', { 'aria-hidden': 'true' });
2609
+ if (variant === 'switch') {
2610
+ indicator.appendChild(el('span', 'zs-switch-on', { 'aria-hidden': 'true' },
2611
+ this.opts.onLabel || input.getAttribute('data-zidan-on-label') || 'ON'));
2612
+ indicator.appendChild(el('span', 'zs-switch-off', { 'aria-hidden': 'true' },
2613
+ this.opts.offLabel || input.getAttribute('data-zidan-off-label') || 'OFF'));
2614
+ }
2097
2615
  var text = el('span', 'zs-check-label');
2098
2616
  text.textContent = labelText || '';
2617
+ var description = this.opts.description || input.getAttribute('data-zidan-description');
2618
+ if (description) {
2619
+ var desc = el('span', 'zs-check-desc');
2620
+ desc.textContent = description;
2621
+ text.appendChild(desc);
2622
+ root.classList.add('zs-field--has-description');
2623
+ }
2099
2624
 
2100
2625
  if (wrappingLabel) {
2101
2626
  Array.prototype.slice.call(check.childNodes).forEach(function (node) {
@@ -2184,10 +2709,26 @@
2184
2709
  return this.update();
2185
2710
  };
2186
2711
 
2712
+ ZidanCheckbox.prototype.setChecked = function (on) {
2713
+ this.el.checked = !!on;
2714
+ this.el.indeterminate = false;
2715
+ this.el.dispatchEvent(new Event('change', { bubbles: true }));
2716
+ return this.update();
2717
+ };
2718
+
2187
2719
  ZidanCheckbox.prototype.isChecked = function () {
2188
2720
  return !!this.el.checked;
2189
2721
  };
2190
2722
 
2723
+ ZidanCheckbox.prototype._customError = function () {
2724
+ if (typeof this.opts.validate === 'function') {
2725
+ var result = this.opts.validate(this.el.checked, this);
2726
+ if (result === false) return this.opts.messages.generic;
2727
+ if (typeof result === 'string' && result) return result;
2728
+ }
2729
+ return '';
2730
+ };
2731
+
2191
2732
  ZidanCheckbox.prototype._teardown = function () {
2192
2733
  if (this._restoreInput) this._restoreInput();
2193
2734
  };
@@ -2199,6 +2740,7 @@
2199
2740
  ZidanFieldBase.call(this, target, options, 'radio-group');
2200
2741
  var variant = pickList(this.opts.variant || target.getAttribute('data-zidan-variant'), RADIO_VARIANTS, 'stacked');
2201
2742
  this.variant = variant;
2743
+ this.deselectable = fieldBool(target, this.opts, 'deselectable', 'deselectable', false);
2202
2744
  this.root = target;
2203
2745
  addClass(target, 'zs-radio-group');
2204
2746
  target.setAttribute('data-zs-kind', 'radio-group');
@@ -2215,6 +2757,26 @@
2215
2757
  self.emit('change', { value: value });
2216
2758
  self.call('onChange', { value: value, instance: self });
2217
2759
  });
2760
+ if (this.deselectable) {
2761
+ this.on(target, 'mousedown', function (event) {
2762
+ var node = event.target;
2763
+ var input = node && node.closest ? node.closest('input[type="radio"]') : null;
2764
+ if (!input && node && node.closest) {
2765
+ var label = node.closest('label');
2766
+ input = label && label.control && /^radio$/i.test(label.control.type) ? label.control : null;
2767
+ }
2768
+ self._deselectCandidate = input && input.checked ? input : null;
2769
+ });
2770
+ this.on(target, 'click', function () {
2771
+ var candidate = self._deselectCandidate;
2772
+ self._deselectCandidate = null;
2773
+ if (!candidate || !candidate.checked) return;
2774
+ candidate.checked = false;
2775
+ self.update();
2776
+ self.emit('change', { value: '' });
2777
+ self.call('onChange', { value: '', instance: self });
2778
+ });
2779
+ }
2218
2780
  this.update();
2219
2781
  target.__zidanField = this;
2220
2782
  this.emit('init', { variant: variant });
@@ -2266,6 +2828,15 @@
2266
2828
  holder.appendChild(textWrapper);
2267
2829
  }
2268
2830
 
2831
+ var descText = (self.opts.descriptions && self.opts.descriptions[input.value]) ||
2832
+ input.getAttribute('data-zidan-description');
2833
+ if (descText && !textWrapper.querySelector('.zs-radio-desc')) {
2834
+ var desc = el('span', 'zs-radio-desc');
2835
+ desc.textContent = descText;
2836
+ textWrapper.appendChild(desc);
2837
+ holder.classList.add('zs-radio--has-description');
2838
+ }
2839
+
2269
2840
  var dot = holder.querySelector('.zs-radio-dot');
2270
2841
  if (!dot) {
2271
2842
  dot = el('span', 'zs-radio-dot', { 'aria-hidden': 'true' });
@@ -2325,6 +2896,15 @@
2325
2896
  return this.update();
2326
2897
  };
2327
2898
 
2899
+ ZidanRadioGroup.prototype._customError = function () {
2900
+ if (typeof this.opts.validate === 'function') {
2901
+ var result = this.opts.validate(this.getValue(), this);
2902
+ if (result === false) return this.opts.messages.generic;
2903
+ if (typeof result === 'string' && result) return result;
2904
+ }
2905
+ return '';
2906
+ };
2907
+
2328
2908
  /* ---------------- file upload ---------------- */
2329
2909
 
2330
2910
  function formatBytes(bytes) {
@@ -2350,6 +2930,17 @@
2350
2930
  });
2351
2931
  }
2352
2932
 
2933
+ function fileKey(file) {
2934
+ return [file.name, file.size, file.lastModified || 0, file.type || ''].join('|');
2935
+ }
2936
+
2937
+ function uploadErrorText(err, fallback) {
2938
+ if (err && typeof err === 'string') return err;
2939
+ if (err && err.message) return err.message;
2940
+ if (err && err.status) return 'Upload failed (HTTP ' + err.status + ').';
2941
+ return fallback || 'Upload failed.';
2942
+ }
2943
+
2353
2944
  function ZidanFileUpload(target, options) {
2354
2945
  if (!(this instanceof ZidanFileUpload)) return new ZidanFileUpload(target, options);
2355
2946
  if (!/^file$/i.test(target.type)) {
@@ -2360,21 +2951,37 @@
2360
2951
  var input = target;
2361
2952
  var opts = this.opts;
2362
2953
 
2954
+ var variant = pickList(
2955
+ fieldOption(input, opts, 'fileVariant', 'file-variant',
2956
+ fieldOption(input, opts, 'variant', 'variant', 'dropzone')),
2957
+ FILE_VARIANTS, 'dropzone');
2958
+
2363
2959
  var originalParent = input.parentNode;
2364
- var originalNext = input.nextSibling;
2365
2960
  var root = this._scope('file');
2961
+ root.setAttribute('data-zs-file-variant', variant);
2366
2962
  originalParent.insertBefore(root, input);
2367
2963
 
2368
- var drop = doc.createElement('label');
2369
- drop.className = 'zs-file-drop';
2964
+ var drop = el('label', 'zs-file-drop zs-file-drop--' + variant);
2370
2965
  drop.setAttribute('for', this.id);
2371
2966
 
2967
+ var avatar = el('span', 'zs-file-avatar', { hidden: true });
2968
+ var avatarImg = doc.createElement('img');
2969
+ avatarImg.alt = '';
2970
+ avatar.appendChild(avatarImg);
2971
+
2372
2972
  var icon = el('span', 'zs-file-icon', { 'aria-hidden': 'true' });
2373
- var title = el('span', 'zs-file-drop-title', null,
2374
- opts.title || input.getAttribute('data-zidan-title') || 'Choose a file');
2973
+ var iconSpec = fieldOption(input, opts, 'uploadIcon', 'upload-icon',
2974
+ fieldOption(input, opts, 'icon', 'icon', 'upload'));
2975
+ var glyph = iconNode(iconSpec, 'zs-file-icon-svg');
2976
+ if (glyph) icon.appendChild(glyph);
2977
+
2978
+ var fallbackTitle = opts.title || input.getAttribute('data-zidan-title') ||
2979
+ (variant === 'avatar' ? 'Upload an image' : (variant === 'gallery' ? 'Add images' : 'Choose a file'));
2980
+ var title = el('span', 'zs-file-drop-title', null, fallbackTitle);
2375
2981
  var hint = el('span', 'zs-file-drop-hint', null,
2376
2982
  opts.dropHint || input.getAttribute('data-zidan-drop-hint') ||
2377
- (input.multiple ? 'or drag files here — multiple allowed' : 'or drag it here'));
2983
+ (input.multiple ? 'or drop files here — multiple allowed' : 'or drop it here'));
2984
+ drop.appendChild(avatar);
2378
2985
  drop.appendChild(icon);
2379
2986
  drop.appendChild(title);
2380
2987
  drop.appendChild(hint);
@@ -2394,15 +3001,38 @@
2394
3001
  root.appendChild(footer);
2395
3002
 
2396
3003
  var acceptHint = opts.accept || input.accept;
2397
- if (acceptHint) {
2398
- hint.textContent = hint.textContent + ' · ' + acceptHint;
2399
- }
3004
+ if (acceptHint) hint.textContent = hint.textContent + ' · ' + acceptHint;
2400
3005
 
3006
+ this.variant = variant;
2401
3007
  this.drop = drop;
2402
3008
  this.list = list;
2403
3009
  this.status = status;
2404
3010
  this.clearBtn = clearBtn;
3011
+ this.titleEl = title;
3012
+ this.hintEl = hint;
3013
+ this._fallbackTitle = fallbackTitle;
3014
+ this.avatarEl = avatar;
3015
+ this.avatarImg = avatarImg;
3016
+
3017
+ this.uploadHandler = typeof opts.upload === 'function' ? opts.upload :
3018
+ (typeof opts.uploadHandler === 'function' ? opts.uploadHandler : null);
3019
+ this.uploadUrl = fieldOption(input, opts, 'uploadUrl', 'upload-url', '');
3020
+ this.uploadField = fieldOption(input, opts, 'uploadField', 'upload-field', 'file');
3021
+ this.withCredentials = fieldBool(input, opts, 'withCredentials', 'with-credentials', false);
3022
+ this.uploadHeaders = opts.uploadHeaders || opts.headers || null;
3023
+ this.simulateUpload = fieldBool(input, opts, 'simulateUpload', 'simulate-upload', false);
3024
+ this.simulateDuration = Math.max(120, fieldNumber(input, opts, 'simulateDuration', 'simulate-duration', 900));
3025
+ this.autoUpload = fieldBool(input, opts, 'autoUpload', 'auto-upload', true);
3026
+ this.showFileMeta = fieldBool(input, opts, 'showFileMeta', 'show-file-meta', true);
3027
+ this.showPreview = fieldBool(input, opts, 'showPreview', 'preview', true);
3028
+ this.hasUploader = !!(this.uploadHandler || this.uploadUrl || this.simulateUpload);
3029
+ root.setAttribute('data-zs-upload', this.hasUploader ? 'true' : 'false');
3030
+
3031
+ this._uploads = Object.create(null);
3032
+ this._active = Object.create(null);
2405
3033
  this._urls = [];
3034
+ this._renderQueued = false;
3035
+ this.fileError = '';
2406
3036
  this._restoreInput = function () {
2407
3037
  var parent = root.parentNode || originalParent;
2408
3038
  parent.insertBefore(input, root.parentNode ? root : null);
@@ -2413,10 +3043,11 @@
2413
3043
  addClass(input, 'zs-file-input');
2414
3044
 
2415
3045
  this.on(input, 'change', function () {
2416
- self._validate();
3046
+ var ok = self._validate();
2417
3047
  self._render();
2418
3048
  self.emit('change', { files: self.getFiles() });
2419
3049
  self.call('onChange', { files: self.getFiles(), instance: self });
3050
+ if (ok && self.autoUpload && self.hasUploader) self.uploadAll();
2420
3051
  });
2421
3052
 
2422
3053
  var dragDepth = 0;
@@ -2438,17 +3069,23 @@
2438
3069
  if (!event.dataTransfer || !event.dataTransfer.files || !event.dataTransfer.files.length) return;
2439
3070
  var incoming = Array.prototype.slice.call(event.dataTransfer.files);
2440
3071
  if (!input.multiple) incoming = incoming.slice(0, 1);
2441
- self._applyFiles(incoming, true);
3072
+ self.addFiles(incoming);
2442
3073
  });
2443
3074
 
2444
- self.on(clearBtn, 'click', function () {
2445
- input.value = '';
2446
- self._validate();
2447
- self._render();
2448
- self.emit('change', { files: [] });
2449
- });
3075
+ self.on(clearBtn, 'click', function () { self.clear(); });
2450
3076
 
2451
3077
  this._bindValidity();
3078
+ this.on(this.formEl, 'reset', function () {
3079
+ global.setTimeout(function () {
3080
+ if (self.destroyed) return;
3081
+ self.cancelAll();
3082
+ self._uploads = Object.create(null);
3083
+ self.fileError = '';
3084
+ if (input.setCustomValidity) input.setCustomValidity('');
3085
+ self._render();
3086
+ }, 0);
3087
+ });
3088
+
2452
3089
  input.__zidanField = this;
2453
3090
  this._render();
2454
3091
  this.emit('init', {});
@@ -2462,76 +3099,234 @@
2462
3099
  return this.el.files ? Array.prototype.slice.call(this.el.files) : [];
2463
3100
  };
2464
3101
 
3102
+ ZidanFileUpload.prototype.getUploadState = function () {
3103
+ var self = this;
3104
+ return this.getFiles().map(function (file) {
3105
+ var state = self._stateFor(file, false) || { status: 'idle', progress: 0, error: '', result: null };
3106
+ return {
3107
+ file: file,
3108
+ name: file.name,
3109
+ size: file.size,
3110
+ status: state.status,
3111
+ progress: state.progress,
3112
+ error: state.error,
3113
+ result: state.result
3114
+ };
3115
+ });
3116
+ };
3117
+
3118
+ ZidanFileUpload.prototype._stateFor = function (file, create) {
3119
+ var key = fileKey(file);
3120
+ var state = this._uploads[key];
3121
+ if (!state && create) {
3122
+ state = this._uploads[key] = {
3123
+ status: 'idle', progress: 0, error: '', result: null
3124
+ };
3125
+ }
3126
+ return state;
3127
+ };
3128
+
3129
+ ZidanFileUpload.prototype._setFiles = function (files) {
3130
+ try {
3131
+ var Ctor = typeof DataTransfer !== 'undefined' ? DataTransfer : global.DataTransfer;
3132
+ if (!Ctor) return false;
3133
+ var dt = new Ctor();
3134
+ files.forEach(function (file) { dt.items.add(file); });
3135
+ this.el.files = dt.files;
3136
+ return true;
3137
+ } catch (err) {
3138
+ return false;
3139
+ }
3140
+ };
3141
+
3142
+ /* keeps native input.files authoritative; `source: 'user'` mirrors a pick/drop */
2465
3143
  ZidanFileUpload.prototype._applyFiles = function (files, fromDrop) {
2466
- var dt = new DataTransfer();
2467
- files.forEach(function (file) { dt.items.add(file); });
2468
- this.el.files = dt.files;
3144
+ if (!this._setFiles(files)) {
3145
+ this.emit('error', { error: new Error('This browser cannot assign files programmatically.'), action: 'setFiles' });
3146
+ return this;
3147
+ }
2469
3148
  if (fromDrop) {
2470
- this.el.dispatchEvent(new Event('change', { bubbles: true }));
3149
+ try { this.el.dispatchEvent(new Event('change', { bubbles: true })); } catch (err) { /* old browsers */ }
2471
3150
  } else {
2472
3151
  this._validate();
2473
3152
  this._render();
2474
3153
  }
3154
+ return this;
3155
+ };
3156
+
3157
+ ZidanFileUpload.prototype.addFiles = function (files) {
3158
+ var incoming = files && files.length !== undefined ? Array.prototype.slice.call(files) : toArray(files);
3159
+ if (!incoming.length) return this;
3160
+ var current = this.el.multiple ? this.getFiles() : [];
3161
+ var seen = Object.create(null);
3162
+ var next = current.concat(incoming).filter(function (file) {
3163
+ var key = fileKey(file);
3164
+ if (seen[key]) return false;
3165
+ seen[key] = true;
3166
+ return true;
3167
+ });
3168
+ if (!this.el.multiple) next = next.slice(0, 1);
3169
+ if (!this._setFiles(next)) {
3170
+ this.emit('error', { error: new Error('This browser cannot assign files programmatically.'), action: 'addFiles' });
3171
+ return this;
3172
+ }
3173
+ try { this.el.dispatchEvent(new Event('change', { bubbles: true })); } catch (err) { /* old browsers */ }
3174
+ return this;
2475
3175
  };
2476
3176
 
2477
- ZidanFileUpload.prototype._validate = function () {
3177
+ ZidanFileUpload.prototype.replaceFiles = function (files) {
3178
+ return this._applyFiles(files && files.length !== undefined ? Array.prototype.slice.call(files) : toArray(files), true);
3179
+ };
3180
+
3181
+ ZidanFileUpload.prototype.removeFile = function (target) {
3182
+ var files = this.getFiles();
3183
+ var index = typeof target === 'number' ? target : files.indexOf(target);
3184
+ if (index === -1 || !files[index]) return this;
3185
+ var file = files[index];
3186
+ this.cancelUpload(file);
3187
+ delete this._uploads[fileKey(file)];
3188
+ var next = files.slice();
3189
+ next.splice(index, 1);
3190
+ this._setFiles(next);
3191
+ this._validate();
3192
+ this._render();
3193
+ this.emit('change', { files: next });
3194
+ this.emit('remove', { file: file, index: index });
3195
+ this.call('onChange', { files: next, instance: this });
3196
+ this.call('onRemove', { file: file, index: index, instance: this });
3197
+ return this;
3198
+ };
3199
+
3200
+ ZidanFileUpload.prototype.clear = function () {
3201
+ this.cancelAll();
3202
+ this._uploads = Object.create(null);
3203
+ this.fileError = '';
3204
+ this.el.value = '';
3205
+ if (this.el.setCustomValidity) this.el.setCustomValidity('');
3206
+ this._validate();
3207
+ this._render();
3208
+ this.emit('change', { files: [] });
3209
+ this.emit('clear', {});
3210
+ this.call('onChange', { files: [], instance: this });
3211
+ return this;
3212
+ };
3213
+
3214
+ ZidanFileUpload.prototype._limits = function () {
2478
3215
  var input = this.el;
2479
3216
  var opts = this.opts;
2480
- var files = this.getFiles();
2481
3217
  var maxFiles = parseInt(opts.maxFiles || input.getAttribute('data-zidan-max-files'), 10);
2482
3218
  var maxSize = parseInt(opts.maxSize || input.getAttribute('data-zidan-max-size'), 10);
2483
3219
  if (!(maxSize > 0)) {
2484
3220
  var sizeMb = opts.maxSizeMB;
2485
- if (sizeMb === undefined || sizeMb === null || sizeMb === '') {
2486
- sizeMb = input.getAttribute('data-zidan-max-size-mb');
2487
- }
3221
+ if (sizeMb === undefined || sizeMb === null || sizeMb === '') sizeMb = input.getAttribute('data-zidan-max-size-mb');
2488
3222
  if (sizeMb !== null && sizeMb !== undefined && sizeMb !== '') {
2489
3223
  var sizeMbValue = parseFloat(sizeMb);
2490
3224
  if (sizeMbValue > 0) maxSize = Math.round(sizeMbValue * 1024 * 1024);
2491
3225
  }
2492
3226
  }
2493
- var accept = opts.accept || input.accept;
3227
+ return {
3228
+ maxFiles: maxFiles > 0 ? maxFiles : 0,
3229
+ maxSize: maxSize > 0 ? maxSize : 0,
3230
+ accept: opts.accept || input.accept || ''
3231
+ };
3232
+ };
3233
+
3234
+ ZidanFileUpload.prototype._customError = function () {
3235
+ return this.fileError || '';
3236
+ };
3237
+
3238
+ ZidanFileUpload.prototype._validate = function () {
3239
+ var input = this.el;
3240
+ var messages = this.opts.messages;
3241
+ var limits = this._limits();
3242
+ var files = this.getFiles();
2494
3243
  var error = '';
2495
3244
 
2496
- if (maxFiles && files.length > maxFiles) {
2497
- error = 'Too many files — ' + maxFiles + ' maximum.';
2498
- files = files.slice(0, maxFiles);
2499
- this._applyFiles(files, false);
3245
+ if (limits.maxFiles && files.length > limits.maxFiles) {
3246
+ error = fillTemplate(messages.fileCount, { max: limits.maxFiles });
3247
+ files = files.slice(0, limits.maxFiles);
3248
+ this._setFiles(files);
2500
3249
  }
2501
- if (!error && maxSize) {
3250
+ if (!error && limits.maxSize) {
2502
3251
  for (var i = 0; i < files.length; i += 1) {
2503
- if (files[i].size > maxSize) {
2504
- error = '"' + files[i].name + '" is ' + formatBytes(files[i].size) + ' — limit ' + formatBytes(maxSize) + '.';
3252
+ if (files[i].size > limits.maxSize) {
3253
+ error = fillTemplate(messages.fileSize, {
3254
+ name: files[i].name,
3255
+ size: formatBytes(files[i].size),
3256
+ limit: formatBytes(limits.maxSize)
3257
+ });
2505
3258
  break;
2506
3259
  }
2507
3260
  }
2508
3261
  }
2509
- if (!error && accept) {
3262
+ if (!error && limits.accept) {
2510
3263
  for (var j = 0; j < files.length; j += 1) {
2511
- if (!matchesAccept(files[j], accept)) {
2512
- error = '"' + files[j].name + '" is not an allowed type (' + accept + ').';
3264
+ if (!matchesAccept(files[j], limits.accept)) {
3265
+ error = fillTemplate(messages.fileType, { name: files[j].name, accept: limits.accept });
2513
3266
  break;
2514
3267
  }
2515
3268
  }
2516
3269
  }
2517
3270
 
2518
- this.root.classList.toggle('zs-field--invalid', !!error);
2519
- if (error) this.el.setAttribute('aria-invalid', 'true');
2520
- else if (this.validation !== 'invalid') this.el.removeAttribute('aria-invalid');
2521
- this.drop.classList.toggle('zs-file-drop--invalid', !!error);
2522
- this.status.textContent = error || '';
2523
- this.status.classList.toggle('zs-file-status--error', !!error);
2524
- this.emit('validation', { state: error ? 'invalid' : this.validation, message: error });
2525
- return !error;
3271
+ this.fileError = error;
3272
+ if (input.setCustomValidity) input.setCustomValidity(error || '');
3273
+ var shown = error || this._nativeError();
3274
+ if (shown) this.setError(shown);
3275
+ else if (this.errorMessage) this.setError(null);
3276
+ this.root.classList.toggle('zs-field--filled', files.length > 0);
3277
+ this.drop.classList.toggle('zs-file-drop--invalid', !!shown);
3278
+ this._renderStatus();
3279
+ return !shown;
2526
3280
  };
2527
3281
 
2528
3282
  ZidanFileUpload.prototype._sync = function () {
2529
3283
  this._render();
2530
3284
  };
2531
3285
 
3286
+ ZidanFileUpload.prototype._queueRender = function () {
3287
+ var self = this;
3288
+ if (this._renderQueued || this.destroyed) return;
3289
+ this._renderQueued = true;
3290
+ var run = function () {
3291
+ self._renderQueued = false;
3292
+ if (!self.destroyed) self._render();
3293
+ };
3294
+ if (global.requestAnimationFrame) global.requestAnimationFrame(run);
3295
+ else global.setTimeout(run, 32);
3296
+ };
3297
+
3298
+ ZidanFileUpload.prototype._renderStatus = function () {
3299
+ var files = this.getFiles();
3300
+ var states = this.getUploadState();
3301
+ var total = files.reduce(function (sum, file) { return sum + file.size; }, 0);
3302
+ var uploading = states.filter(function (state) { return state.status === 'uploading'; });
3303
+ var failed = states.filter(function (state) { return state.status === 'error'; });
3304
+ var done = states.filter(function (state) { return state.status === 'done'; });
3305
+ var text = '';
3306
+
3307
+ if (this.fileError) {
3308
+ text = this.fileError;
3309
+ } else if (files.length) {
3310
+ text = files.length + (files.length === 1 ? ' file selected' : ' files selected') + ' · ' + formatBytes(total);
3311
+ if (uploading.length) {
3312
+ var percent = Math.round(uploading.reduce(function (sum, state) { return sum + state.progress; }, 0) / uploading.length);
3313
+ text += ' · Uploading ' + percent + '%';
3314
+ } else if (failed.length) {
3315
+ text += ' · ' + failed.length + ' failed';
3316
+ } else if (done.length === files.length && this.hasUploader) {
3317
+ text += ' · Uploaded';
3318
+ }
3319
+ }
3320
+
3321
+ this.status.textContent = text;
3322
+ this.status.classList.toggle('zs-file-status--error', !!this.fileError);
3323
+ this.status.classList.toggle('zs-file-status--success', !this.fileError && files.length > 0 && done.length === files.length && this.hasUploader);
3324
+ };
3325
+
2532
3326
  ZidanFileUpload.prototype._render = function () {
2533
3327
  var self = this;
2534
3328
  var files = this.getFiles();
3329
+ var opts = this.opts;
2535
3330
  // detach first, then revoke a tick later: revoking a blob that a live
2536
3331
  // <img> still points at (or that is mid-decode) makes the browser raise a
2537
3332
  // failed-resource error
@@ -2541,14 +3336,28 @@
2541
3336
  this.list.hidden = files.length === 0;
2542
3337
  this.clearBtn.hidden = files.length === 0;
2543
3338
  this.root.classList.toggle('zs-field--filled', files.length > 0);
2544
- if (!this.status.textContent) {
2545
- this.status.textContent = files.length
2546
- ? files.length + (files.length === 1 ? ' file selected' : ' files selected') + ' · ' + formatBytes(files.reduce(function (total, file) { return total + file.size; }, 0))
2547
- : '';
3339
+ this.drop.classList.toggle('zs-file-drop--has-files', files.length > 0);
3340
+
3341
+ var previewFile = this.showPreview ? files.filter(function (file) { return /^image\//.test(file.type); })[0] : null;
3342
+ if (previewFile) {
3343
+ var previewUrl = URL.createObjectURL(previewFile);
3344
+ this._urls.push(previewUrl);
3345
+ this.avatarImg.src = previewUrl;
3346
+ this.avatarEl.hidden = false;
3347
+ this.drop.classList.add('zs-file-drop--has-preview');
3348
+ this.titleEl.textContent = opts.replaceTitle || 'Change image';
3349
+ } else {
3350
+ this.avatarImg.removeAttribute('src');
3351
+ this.avatarEl.hidden = true;
3352
+ this.drop.classList.remove('zs-file-drop--has-preview');
3353
+ this.titleEl.textContent = this._fallbackTitle;
2548
3354
  }
2549
3355
 
2550
3356
  files.forEach(function (file, index) {
3357
+ var state = self._stateFor(file, false) || { status: 'idle', progress: 0, error: '', result: null };
2551
3358
  var item = el('li', 'zs-file-item');
3359
+ item.setAttribute('data-zs-upload-state', state.status);
3360
+
2552
3361
  var thumb = el('span', 'zs-file-thumb');
2553
3362
  if (/^image\//.test(file.type)) {
2554
3363
  var url = URL.createObjectURL(file);
@@ -2560,38 +3369,318 @@
2560
3369
  } else {
2561
3370
  thumb.textContent = (fileExtension(file.name) || 'file').replace('.', '').slice(0, 4).toUpperCase();
2562
3371
  }
3372
+
2563
3373
  var meta = el('span', 'zs-file-info');
2564
3374
  var name = el('span', 'zs-file-name', null, file.name);
2565
- var size = el('span', 'zs-file-size', null, formatBytes(file.size) + (file.type ? ' · ' + file.type : ''));
2566
3375
  meta.appendChild(name);
2567
- meta.appendChild(size);
3376
+ if (self.showFileMeta) {
3377
+ var sizeText = formatBytes(file.size) + (file.type ? ' · ' + file.type : '');
3378
+ meta.appendChild(el('span', 'zs-file-size', null, sizeText));
3379
+ }
2568
3380
 
2569
- var remove = el('button', 'zs-file-remove', {
2570
- type: 'button',
2571
- 'aria-label': 'Remove ' + file.name
2572
- });
3381
+ if (self.hasUploader) {
3382
+ var stateLine = el('span', 'zs-file-upload-state');
3383
+ if (state.status === 'uploading') {
3384
+ stateLine.textContent = fillTemplate(opts.progressTemplate || 'Uploading {percent}%', { percent: state.progress });
3385
+ var bar = el('span', 'zs-file-progress');
3386
+ bar.setAttribute('role', 'progressbar');
3387
+ bar.setAttribute('aria-valuemin', '0');
3388
+ bar.setAttribute('aria-valuemax', '100');
3389
+ bar.setAttribute('aria-valuenow', String(state.progress));
3390
+ bar.setAttribute('aria-label', 'Upload progress for ' + file.name);
3391
+ var fill = el('span', 'zs-file-progress-bar');
3392
+ fill.style.width = state.progress + '%';
3393
+ bar.appendChild(fill);
3394
+ stateLine.appendChild(bar);
3395
+ } else if (state.status === 'done') {
3396
+ stateLine.textContent = opts.uploadedLabel || 'Uploaded';
3397
+ } else if (state.status === 'error') {
3398
+ stateLine.textContent = (opts.failedLabel || 'Upload failed') + (state.error ? ' — ' + state.error : '');
3399
+ } else if (state.status === 'canceled') {
3400
+ stateLine.textContent = opts.canceledLabel || 'Upload canceled';
3401
+ }
3402
+ if (stateLine.textContent) meta.appendChild(stateLine);
3403
+ }
3404
+
3405
+ var actions = el('span', 'zs-file-actions');
3406
+ if (state.status === 'uploading') {
3407
+ var cancel = el('button', 'zs-file-cancel', { type: 'button', 'aria-label': 'Cancel upload of ' + file.name });
3408
+ cancel.textContent = opts.cancelLabel || 'Cancel';
3409
+ self.on(cancel, 'click', function (event) {
3410
+ event.preventDefault();
3411
+ event.stopPropagation();
3412
+ self.cancelUpload(file);
3413
+ });
3414
+ actions.appendChild(cancel);
3415
+ } else if (state.status === 'error' || state.status === 'canceled') {
3416
+ var retry = el('button', 'zs-file-retry', { type: 'button', 'aria-label': 'Retry upload of ' + file.name });
3417
+ retry.textContent = opts.retryLabel || 'Retry';
3418
+ self.on(retry, 'click', function (event) {
3419
+ event.preventDefault();
3420
+ event.stopPropagation();
3421
+ self.retryUpload(file);
3422
+ });
3423
+ actions.appendChild(retry);
3424
+ }
3425
+
3426
+ var remove = el('button', 'zs-file-remove', { type: 'button', 'aria-label': 'Remove ' + file.name });
2573
3427
  remove.textContent = '\u00d7';
2574
- self.on(remove, 'click', function () {
2575
- var next = self.getFiles().filter(function (candidate, position) { return position !== index; });
2576
- self._applyFiles(next, false);
2577
- self.emit('remove', { file: file });
2578
- self.call('onRemove', { file: file, instance: self });
3428
+ self.on(remove, 'click', function (event) {
3429
+ event.preventDefault();
3430
+ event.stopPropagation();
3431
+ self.removeFile(file);
2579
3432
  });
3433
+ actions.appendChild(remove);
2580
3434
 
2581
3435
  item.appendChild(thumb);
2582
3436
  item.appendChild(meta);
2583
- item.appendChild(remove);
3437
+ item.appendChild(actions);
2584
3438
  self.list.appendChild(item);
3439
+
3440
+ if (typeof opts.renderFile === 'function') {
3441
+ try {
3442
+ opts.renderFile(item, {
3443
+ file: file,
3444
+ index: index,
3445
+ state: state,
3446
+ field: self
3447
+ });
3448
+ } catch (err) {
3449
+ self.emit('error', { error: err, callback: 'renderFile' });
3450
+ }
3451
+ }
2585
3452
  });
3453
+
3454
+ this._renderStatus();
2586
3455
  };
2587
3456
 
2588
- ZidanFileUpload.prototype.clear = function () {
2589
- this.el.value = '';
2590
- this._validate();
3457
+ ZidanFileUpload.prototype.setVariant = function (name) {
3458
+ var next = pickList(name, FILE_VARIANTS, this.variant);
3459
+ if (next === this.variant) return this;
3460
+ this.variant = next;
3461
+ FILE_VARIANTS.forEach(function (variant) { this.drop.classList.remove('zs-file-drop--' + variant); }, this);
3462
+ this.drop.classList.add('zs-file-drop--' + next);
3463
+ this.root.setAttribute('data-zs-file-variant', next);
3464
+ this._render();
3465
+ return this;
3466
+ };
3467
+
3468
+ ZidanFileUpload.prototype.setUploader = function (source) {
3469
+ if (typeof source === 'function') {
3470
+ this.uploadHandler = source;
3471
+ this.uploadUrl = '';
3472
+ } else {
3473
+ this.uploadHandler = null;
3474
+ this.uploadUrl = source ? String(source) : '';
3475
+ }
3476
+ this.hasUploader = !!(this.uploadHandler || this.uploadUrl || this.simulateUpload);
3477
+ this.root.setAttribute('data-zs-upload', this.hasUploader ? 'true' : 'false');
2591
3478
  this._render();
2592
3479
  return this;
2593
3480
  };
2594
3481
 
3482
+ ZidanFileUpload.prototype._formData = function (file) {
3483
+ var data = new FormData();
3484
+ data.append(this.uploadField, file, file.name);
3485
+ var extra = typeof this.opts.uploadData === 'function' ? this.opts.uploadData(file, this) : this.opts.uploadData;
3486
+ if (extra && typeof extra === 'object') {
3487
+ Object.keys(extra).forEach(function (key) {
3488
+ var value = extra[key];
3489
+ if (value !== undefined && value !== null) data.append(key, value);
3490
+ });
3491
+ }
3492
+ return data;
3493
+ };
3494
+
3495
+ ZidanFileUpload.prototype.uploadAll = function () {
3496
+ var self = this;
3497
+ if (!this.hasUploader) return this;
3498
+ if (!this._validate()) return this;
3499
+ this.getFiles().forEach(function (file) { self.uploadFile(file); });
3500
+ return this;
3501
+ };
3502
+
3503
+ ZidanFileUpload.prototype.uploadFile = function (file) {
3504
+ var self = this;
3505
+ var key = fileKey(file);
3506
+ var state = this._stateFor(file, true);
3507
+ if (state.status === 'uploading' || state.status === 'done') return this;
3508
+
3509
+ state.status = 'uploading';
3510
+ state.progress = 0;
3511
+ state.error = '';
3512
+ state.result = null;
3513
+ this._queueRender();
3514
+ this.emit('upload-start', { file: file, name: file.name, size: file.size });
3515
+ this.call('onUploadStart', { file: file, name: file.name, size: file.size, instance: this });
3516
+
3517
+ if (this.uploadHandler) {
3518
+ var controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
3519
+ this._active[key] = {
3520
+ type: 'handler',
3521
+ abort: function () { if (controller) controller.abort(); }
3522
+ };
3523
+ var context = {
3524
+ file: file,
3525
+ field: this,
3526
+ formData: this._formData(file),
3527
+ signal: controller ? controller.signal : null,
3528
+ onProgress: function (percent) { self._setProgress(file, percent); },
3529
+ complete: function (value) { self._finish(file, value); },
3530
+ fail: function (err) { self._fail(file, err); }
3531
+ };
3532
+ var result;
3533
+ try {
3534
+ result = this.uploadHandler(file, context);
3535
+ } catch (err) {
3536
+ this._fail(file, err);
3537
+ return this;
3538
+ }
3539
+ if (result && typeof result.then === 'function') {
3540
+ result.then(function (value) {
3541
+ self._finish(file, value);
3542
+ }, function (err) {
3543
+ if (err && (err.name === 'AbortError' || err.aborted)) self._canceledUpload(file);
3544
+ else self._fail(file, err);
3545
+ });
3546
+ } else if (result !== undefined) {
3547
+ this._finish(file, result);
3548
+ }
3549
+ // returning nothing means the handler will call context.complete/fail
3550
+ return this;
3551
+ }
3552
+
3553
+ if (this.uploadUrl) {
3554
+ var xhr = new global.XMLHttpRequest();
3555
+ this._active[key] = {
3556
+ type: 'xhr',
3557
+ abort: function () { try { xhr.abort(); } catch (err) { /* already done */ } }
3558
+ };
3559
+ xhr.open('POST', this.uploadUrl, true);
3560
+ if (this.withCredentials) xhr.withCredentials = true;
3561
+ var headers = typeof this.uploadHeaders === 'function' ? this.uploadHeaders(file, this) : this.uploadHeaders;
3562
+ if (headers && typeof headers === 'object') {
3563
+ Object.keys(headers).forEach(function (name) { xhr.setRequestHeader(name, headers[name]); });
3564
+ }
3565
+ xhr.upload.onprogress = function (event) {
3566
+ if (!event.lengthComputable) return;
3567
+ self._setProgress(file, Math.min(99, Math.round((event.loaded / event.total) * 100)));
3568
+ };
3569
+ xhr.onload = function () {
3570
+ if (xhr.status >= 200 && xhr.status < 300) {
3571
+ var body = xhr.responseText;
3572
+ try { body = JSON.parse(body); } catch (err) { /* plain text response */ }
3573
+ self._finish(file, body);
3574
+ } else {
3575
+ self._fail(file, { status: xhr.status, message: 'Upload failed (HTTP ' + xhr.status + ').' });
3576
+ }
3577
+ };
3578
+ xhr.onerror = function () { self._fail(file, { message: 'Network error while uploading.' }); };
3579
+ xhr.onabort = function () { self._canceledUpload(file); };
3580
+ xhr.send(this._formData(file));
3581
+ return this;
3582
+ }
3583
+
3584
+ if (this.simulateUpload) {
3585
+ var started = Date.now();
3586
+ var timer = null;
3587
+ var tick = function () {
3588
+ if (!self._uploads[key] || state.status !== 'uploading') return;
3589
+ var percent = Math.min(99, Math.round(((Date.now() - started) / self.simulateDuration) * 100));
3590
+ self._setProgress(file, percent);
3591
+ if (percent >= 99) {
3592
+ delete self._active[key];
3593
+ self._finish(file, { simulated: true });
3594
+ } else {
3595
+ timer = global.setTimeout(tick, 40);
3596
+ }
3597
+ };
3598
+ this._active[key] = { type: 'simulation', abort: function () { if (timer) global.clearTimeout(timer); } };
3599
+ timer = global.setTimeout(tick, 40);
3600
+ return this;
3601
+ }
3602
+
3603
+ state.status = 'idle';
3604
+ this._queueRender();
3605
+ return this;
3606
+ };
3607
+
3608
+ ZidanFileUpload.prototype._setProgress = function (file, percent) {
3609
+ var state = this._stateFor(file, false);
3610
+ if (!state || state.status !== 'uploading') return;
3611
+ var value = clamp(Math.round(Number(percent) || 0), 0, 99);
3612
+ if (value === state.progress) return;
3613
+ state.progress = value;
3614
+ this._queueRender();
3615
+ this.emit('upload-progress', { file: file, progress: value, name: file.name });
3616
+ this.call('onUploadProgress', { file: file, progress: value, name: file.name, instance: this });
3617
+ };
3618
+
3619
+ ZidanFileUpload.prototype._finish = function (file, result) {
3620
+ var state = this._stateFor(file, false);
3621
+ if (!state || state.status !== 'uploading') return;
3622
+ delete this._active[fileKey(file)];
3623
+ state.status = 'done';
3624
+ state.progress = 100;
3625
+ state.result = result === undefined ? null : result;
3626
+ this._queueRender();
3627
+ this.emit('upload-success', { file: file, name: file.name, result: state.result });
3628
+ this.call('onUploadSuccess', { file: file, name: file.name, result: state.result, instance: this });
3629
+ this.call('onUpload', { file: file, name: file.name, result: state.result, instance: this });
3630
+ };
3631
+
3632
+ ZidanFileUpload.prototype._fail = function (file, err) {
3633
+ var state = this._stateFor(file, false);
3634
+ if (!state || state.status !== 'uploading') return;
3635
+ delete this._active[fileKey(file)];
3636
+ state.status = 'error';
3637
+ state.error = uploadErrorText(err, this.opts.messages.upload || 'Upload failed.');
3638
+ this._queueRender();
3639
+ this.emit('upload-error', { file: file, name: file.name, error: err, message: state.error });
3640
+ this.call('onUploadError', { file: file, name: file.name, error: err, message: state.error, instance: this });
3641
+ };
3642
+
3643
+ ZidanFileUpload.prototype._canceledUpload = function (file) {
3644
+ var state = this._stateFor(file, false);
3645
+ if (!state || state.status !== 'uploading') return;
3646
+ delete this._active[fileKey(file)];
3647
+ state.status = 'canceled';
3648
+ state.progress = 0;
3649
+ state.error = '';
3650
+ this._queueRender();
3651
+ this.emit('upload-cancel', { file: file, name: file.name });
3652
+ this.call('onUploadCancel', { file: file, name: file.name, instance: this });
3653
+ };
3654
+
3655
+ ZidanFileUpload.prototype.cancelUpload = function (file) {
3656
+ var key = fileKey(file);
3657
+ var active = this._active[key];
3658
+ if (active) {
3659
+ try { active.abort(); } catch (err) { /* already stopped */ }
3660
+ delete this._active[key];
3661
+ }
3662
+ this._canceledUpload(file);
3663
+ return this;
3664
+ };
3665
+
3666
+ ZidanFileUpload.prototype.cancelAll = function () {
3667
+ var self = this;
3668
+ Object.keys(this._active).forEach(function (key) {
3669
+ try { self._active[key].abort(); } catch (err) { /* already stopped */ }
3670
+ delete self._active[key];
3671
+ });
3672
+ return this;
3673
+ };
3674
+
3675
+ ZidanFileUpload.prototype.retryUpload = function (file) {
3676
+ var state = this._stateFor(file, false);
3677
+ if (!state) return this;
3678
+ state.status = 'idle';
3679
+ state.progress = 0;
3680
+ state.error = '';
3681
+ return this.uploadFile(file);
3682
+ };
3683
+
2595
3684
  ZidanFileUpload.prototype._revokeLater = function (urls) {
2596
3685
  if (!urls || !urls.length) return;
2597
3686
  global.setTimeout(function () {
@@ -2602,6 +3691,8 @@
2602
3691
  };
2603
3692
 
2604
3693
  ZidanFileUpload.prototype._teardown = function () {
3694
+ this.cancelAll();
3695
+ this._uploads = Object.create(null);
2605
3696
  this._revokeLater(this._urls);
2606
3697
  this._urls = [];
2607
3698
  if (this._restoreInput) this._restoreInput();
@@ -2610,6 +3701,15 @@
2610
3701
  /* ---------------- text inputs & textarea ---------------- */
2611
3702
 
2612
3703
  var TEXT_TYPES = ['text', 'email', 'password', 'number', 'tel', 'url', 'search', 'date', 'time', 'datetime-local', 'month', 'week', 'range', 'color'];
3704
+ var PICKER_TYPES = ['date', 'time', 'datetime-local', 'month', 'week', 'color'];
3705
+ var STEPPER_MODES = ['stacked', 'split', 'inline'];
3706
+
3707
+ function decimalsOf(number) {
3708
+ var text = String(number);
3709
+ if (/e-/i.test(text)) return 10;
3710
+ var dot = text.indexOf('.');
3711
+ return dot === -1 ? 0 : Math.min(10, text.length - dot - 1);
3712
+ }
2613
3713
 
2614
3714
  function ZidanTextField(target, options) {
2615
3715
  if (!(this instanceof ZidanTextField)) return new ZidanTextField(target, options);
@@ -2625,9 +3725,10 @@
2625
3725
  var input = target;
2626
3726
  var opts = this.opts;
2627
3727
  var type = isTextarea ? 'textarea' : String(input.type).toLowerCase();
3728
+ var isRange = type === 'range';
3729
+ var isPicker = PICKER_TYPES.indexOf(type) !== -1;
2628
3730
 
2629
3731
  var originalParent = input.parentNode;
2630
- var originalNext = input.nextSibling;
2631
3732
  var externalLabel = input.labels && input.labels[0] ? input.labels[0] : null;
2632
3733
  if (externalLabel && externalLabel.closest && externalLabel.closest('.zs-field')) externalLabel = null;
2633
3734
  var labelText = opts.label || input.getAttribute('data-zidan-label') ||
@@ -2658,12 +3759,140 @@
2658
3759
  root.appendChild(shell);
2659
3760
  if (floating && label) shell.appendChild(label);
2660
3761
 
3762
+ /* ---------- phone country selector & formatting ---------- */
3763
+ var phoneEnabled = type === 'tel' && (opts.phone || input.hasAttribute('data-zidan-phone'));
3764
+ this.phone = null;
3765
+ if (phoneEnabled) {
3766
+ var phoneCfg = opts.phone && typeof opts.phone === 'object' ? opts.phone : {};
3767
+ var phoneCountry = String(phoneCfg.country || fieldOption(input, opts, 'phoneCountry', 'phone-country', 'US')).toUpperCase();
3768
+ if (!PHONE_COUNTRIES[phoneCountry]) phoneCountry = 'US';
3769
+ var phoneFormat = String(phoneCfg.format || fieldOption(input, opts, 'phoneFormat', 'phone-format', 'national')).toLowerCase();
3770
+ if (PHONE_FORMATS.indexOf(phoneFormat) === -1) phoneFormat = 'national';
3771
+ var showCountry = phoneCfg.showCountry !== undefined ? !!phoneCfg.showCountry : fieldBool(input, opts, 'phoneCountrySelect', 'phone-country-select', true);
3772
+ var countryList = phoneCfg.countries || fieldList(input, opts, 'phoneCountries', 'phone-countries', PHONE_DEFAULT_COUNTRIES);
3773
+ var countrySelect = null;
3774
+ if (showCountry) {
3775
+ countrySelect = el('select', 'zs-phone-country', { 'aria-label': opts.phoneCountryLabel || 'Country code' });
3776
+ countryList.forEach(function (iso) {
3777
+ iso = String(iso).toUpperCase();
3778
+ var country = PHONE_COUNTRIES[iso];
3779
+ if (!country) return;
3780
+ var optionNode = el('option', null, { value: iso },
3781
+ (country.flag ? country.flag + ' ' : '') + iso + ' +' + country.dial);
3782
+ countrySelect.appendChild(optionNode);
3783
+ });
3784
+ countrySelect.value = phoneCountry;
3785
+ shell.appendChild(countrySelect);
3786
+ this.on(countrySelect, 'change', function () { self.setPhoneCountry(countrySelect.value); });
3787
+ }
3788
+ this.phone = {
3789
+ country: phoneCountry,
3790
+ format: phoneFormat,
3791
+ select: countrySelect,
3792
+ validate: phoneCfg.validate !== false,
3793
+ countries: countryList.slice()
3794
+ };
3795
+ root.classList.add('zs-field--phone');
3796
+
3797
+ if (input.value) {
3798
+ var detected = detectPhoneCountry(input.value);
3799
+ if (detected && !phoneCfg.country && !input.getAttribute('data-zidan-phone-country')) {
3800
+ this.phone.country = detected;
3801
+ if (countrySelect) countrySelect.value = detected;
3802
+ }
3803
+ this._applyPhoneFormat(false);
3804
+ }
3805
+ this.on(input, 'input', function () { self._applyPhoneFormat(true); });
3806
+ this.on(input, 'focus', function () { self._applyPhoneFormat(true); });
3807
+ this.on(input, 'blur', function () { self._applyPhoneFormat(false); });
3808
+ }
3809
+
3810
+ /* ---------- icons ---------- */
3811
+ var iconSpec = opts.icon || input.getAttribute('data-zidan-icon') || null;
3812
+ var autoIcon = fieldBool(input, opts, 'autoIcon', 'auto-icon', false);
3813
+ if (iconSpec === 'auto') {
3814
+ iconSpec = null;
3815
+ autoIcon = true;
3816
+ }
3817
+ if (!iconSpec && autoIcon) iconSpec = iconForType(type);
3818
+ var iconPosition = String(fieldOption(input, opts, 'iconPosition', 'icon-position', 'left')).toLowerCase() === 'right' ? 'right' : 'left';
3819
+ var iconClickable = fieldBool(input, opts, 'iconClickable', 'icon-clickable', false);
3820
+ var iconLabel = opts.iconLabel || input.getAttribute('data-zidan-icon-label') || '';
3821
+ var iconControl = null;
3822
+ if (iconSpec) {
3823
+ var iconContent = iconNode(iconSpec, 'zs-input-icon-glyph') || iconNode('info', 'zs-input-icon-glyph');
3824
+ var clickable = iconClickable || isPicker;
3825
+ if (clickable) {
3826
+ iconControl = el('button', 'zs-input-icon zs-input-icon--action', {
3827
+ type: 'button',
3828
+ 'aria-label': iconLabel || (isPicker ? 'Open ' + type.replace('-', ' ') + ' picker' : 'Field action')
3829
+ });
3830
+ if (iconContent) iconControl.appendChild(iconContent);
3831
+ this.on(iconControl, 'click', function (event) {
3832
+ event.preventDefault();
3833
+ if (isPicker) self.openPicker();
3834
+ self.emit('icon-click', { icon: iconSpec, position: iconPosition });
3835
+ self.call('onIconClick', { icon: iconSpec, position: iconPosition, instance: self });
3836
+ });
3837
+ } else {
3838
+ iconControl = el('span', 'zs-input-icon', iconLabel ? null : { 'aria-hidden': 'true' });
3839
+ if (iconLabel) {
3840
+ iconControl.setAttribute('role', 'img');
3841
+ iconControl.setAttribute('aria-label', iconLabel);
3842
+ }
3843
+ if (iconContent) iconControl.appendChild(iconContent);
3844
+ }
3845
+ root.classList.add('zs-field--icon-' + iconPosition);
3846
+ this.icon = iconControl;
3847
+ if (iconPosition === 'left') {
3848
+ if (this.phone && this.phone.select) shell.insertBefore(iconControl, this.phone.select);
3849
+ else shell.appendChild(iconControl);
3850
+ }
3851
+ }
3852
+
2661
3853
  var prefixText = opts.prefix || input.getAttribute('data-zidan-prefix');
2662
3854
  if (prefixText) {
2663
3855
  shell.appendChild(el('span', 'zs-input-prefix', { 'aria-hidden': 'true' }, prefixText));
2664
3856
  }
2665
3857
 
2666
- shell.appendChild(input);
3858
+ /* ---------- native control (optionally wrapped by range chrome) ---------- */
3859
+ var rangeWrap = null;
3860
+ var rangeBubble = null;
3861
+ var rangeTicksEl = null;
3862
+ var rangeScale = null;
3863
+ if (isRange) {
3864
+ var rangeVariant = pickList(fieldOption(input, opts, 'rangeVariant', 'range-variant', 'default'), RANGE_VARIANTS, 'default');
3865
+ var rangeBubbleOn = fieldBool(input, opts, 'rangeBubble', 'range-bubble', true);
3866
+ var rangeScaleOn = fieldBool(input, opts, 'rangeMinMax', 'range-minmax', true);
3867
+ rangeWrap = el('div', 'zs-range');
3868
+ rangeWrap.setAttribute('data-zs-range', rangeVariant);
3869
+ if (rangeBubbleOn) {
3870
+ rangeBubble = el('output', 'zs-range-bubble', { for: this.id, 'aria-hidden': 'true' });
3871
+ rangeWrap.appendChild(rangeBubble);
3872
+ }
3873
+ rangeWrap.appendChild(input);
3874
+ rangeTicksEl = el('div', 'zs-range-ticks', { 'aria-hidden': 'true' });
3875
+ rangeWrap.appendChild(rangeTicksEl);
3876
+ if (rangeScaleOn) {
3877
+ rangeScale = el('div', 'zs-range-scale');
3878
+ rangeScale.appendChild(el('span', 'zs-range-min'));
3879
+ rangeScale.appendChild(el('span', 'zs-range-max'));
3880
+ rangeWrap.appendChild(rangeScale);
3881
+ }
3882
+ shell.appendChild(rangeWrap);
3883
+ shell.classList.add('zs-input-shell--range');
3884
+ this.range = rangeWrap;
3885
+ this.rangeBubble = rangeBubble;
3886
+ this.rangeTicksEl = rangeTicksEl;
3887
+ this.rangeScale = rangeScale;
3888
+ this.rangeFormat = opts.rangeFormat || input.getAttribute('data-zidan-range-format') || null;
3889
+ this.rangeTicksOption = fieldOption(input, opts, 'rangeTicks', 'range-ticks', 0);
3890
+ this.rangeTickLabels = fieldBool(input, opts, 'rangeTickLabels', 'range-tick-labels', false);
3891
+ this.rangeLabelMap = opts.rangeLabels || null;
3892
+ this.rangeSignature = '';
3893
+ } else {
3894
+ shell.appendChild(input);
3895
+ }
2667
3896
 
2668
3897
  var suffixText = opts.suffix || input.getAttribute('data-zidan-suffix');
2669
3898
  if (suffixText) {
@@ -2712,6 +3941,138 @@
2712
3941
  });
2713
3942
  }
2714
3943
 
3944
+ /* ---------- number stepper ---------- */
3945
+ var stepperEnabled = false;
3946
+ var stepperRaw = opts.stepper !== undefined && opts.stepper !== null
3947
+ ? opts.stepper
3948
+ : input.getAttribute('data-zidan-stepper');
3949
+ if (type === 'number' && stepperRaw !== null && stepperRaw !== undefined && stepperRaw !== '' &&
3950
+ stepperRaw !== false && stepperRaw !== 'false') {
3951
+ stepperEnabled = true;
3952
+ }
3953
+ this.stepper = null;
3954
+ var stepperContainer = null;
3955
+ if (stepperEnabled) {
3956
+ var stepperMode = typeof stepperRaw === 'string' && stepperRaw !== 'true'
3957
+ ? pickList(stepperRaw, STEPPER_MODES, 'stacked')
3958
+ : 'stacked';
3959
+ var stepperPosition = String(fieldOption(input, opts, 'stepperPosition', 'stepper-position', 'right')).toLowerCase() === 'left' ? 'left' : 'right';
3960
+ var stepperWrap = fieldBool(input, opts, 'stepperWrap', 'stepper-wrap', false);
3961
+ var stepperLongPress = fieldBool(input, opts, 'stepperLongPress', 'stepper-long-press', true);
3962
+ var stepperDelay = fieldNumber(input, opts, 'stepperDelay', 'stepper-delay', 420);
3963
+ var stepperInterval = fieldNumber(input, opts, 'stepperInterval', 'stepper-interval', 90);
3964
+ var minusLabel = opts.stepperDownLabel || fieldOption(input, opts, 'stepperDownLabel', 'stepper-down-label', 'Decrease value');
3965
+ var plusLabel = opts.stepperUpLabel || fieldOption(input, opts, 'stepperUpLabel', 'stepper-up-label', 'Increase value');
3966
+
3967
+ var makeStepButton = function (direction) {
3968
+ var isUp = direction > 0;
3969
+ var button = el('button', 'zs-stepper-btn zs-stepper-btn--' + (isUp ? 'up' : 'down'), {
3970
+ type: 'button',
3971
+ 'aria-label': isUp ? plusLabel : minusLabel,
3972
+ 'data-zs-step': direction
3973
+ });
3974
+ var glyph = iconNode(isUp ? 'plus' : 'minus', 'zs-stepper-glyph');
3975
+ if (glyph) button.appendChild(glyph);
3976
+ else button.textContent = isUp ? '+' : '\u2212';
3977
+
3978
+ var holdTimer = null;
3979
+ var holdInterval = null;
3980
+ var stopHold = function () {
3981
+ if (holdTimer) global.clearTimeout(holdTimer);
3982
+ if (holdInterval) global.clearInterval(holdInterval);
3983
+ holdTimer = null;
3984
+ holdInterval = null;
3985
+ };
3986
+ var startHold = function (event) {
3987
+ if (event.button !== undefined && event.button !== 0) return;
3988
+ event.preventDefault();
3989
+ self._stepBy(direction);
3990
+ if (!stepperLongPress) return;
3991
+ holdTimer = global.setTimeout(function () {
3992
+ holdInterval = global.setInterval(function () { self._stepBy(direction); }, stepperInterval);
3993
+ }, stepperDelay);
3994
+ };
3995
+ self.on(button, 'pointerdown', startHold);
3996
+ self.on(button, 'mousedown', function (event) {
3997
+ // pointerdown is the primary path; mousedown keeps very old engines working
3998
+ if (typeof global.PointerEvent === 'undefined') startHold(event);
3999
+ });
4000
+ ['pointerup', 'pointercancel', 'pointerleave', 'mouseup', 'mouseleave', 'blur'].forEach(function (typeName) {
4001
+ self.on(button, typeName, stopHold);
4002
+ });
4003
+ self.on(button, 'keydown', function (event) {
4004
+ if (event.key !== 'Enter' && event.key !== ' ' && event.key !== 'Spacebar') return;
4005
+ event.preventDefault();
4006
+ self._stepBy(direction);
4007
+ });
4008
+ return button;
4009
+ };
4010
+
4011
+ var minusButton = makeStepButton(-1);
4012
+ var plusButton = makeStepButton(1);
4013
+ this.stepper = {
4014
+ mode: stepperMode,
4015
+ position: stepperPosition,
4016
+ wrap: stepperWrap,
4017
+ minus: minusButton,
4018
+ plus: plusButton
4019
+ };
4020
+ root.classList.add('zs-field--stepper', 'zs-field--stepper-' + stepperMode);
4021
+ if (stepperMode === 'split') {
4022
+ // minus sits before the field, plus after it
4023
+ shell.insertBefore(minusButton, iconPosition === 'left' && iconControl ? iconControl.nextSibling : input);
4024
+ shell.appendChild(plusButton);
4025
+ } else {
4026
+ stepperContainer = el('span', 'zs-stepper zs-stepper--' + stepperMode, { role: 'group', 'aria-label': 'Number stepper' });
4027
+ if (stepperMode === 'stacked') {
4028
+ stepperContainer.appendChild(plusButton);
4029
+ stepperContainer.appendChild(minusButton);
4030
+ } else {
4031
+ stepperContainer.appendChild(minusButton);
4032
+ stepperContainer.appendChild(plusButton);
4033
+ }
4034
+ if (stepperPosition === 'left') shell.insertBefore(stepperContainer, iconPosition === 'left' && iconControl ? iconControl.nextSibling : shell.firstChild);
4035
+ else shell.appendChild(stepperContainer);
4036
+ }
4037
+ addClass(input, 'zs-input-native--stepper');
4038
+ }
4039
+
4040
+ /* ---------- explicit picker button ---------- */
4041
+ var pickerButton = fieldBool(input, opts, 'pickerButton', 'picker-button', false);
4042
+ if (isPicker && pickerButton && !iconControl) {
4043
+ var pickerIcon = opts.pickerIcon || fieldOption(input, opts, 'pickerIcon', 'picker-icon', iconForType(type) || 'calendar');
4044
+ var pickerControl = el('button', 'zs-input-icon zs-input-icon--action zs-input-picker', {
4045
+ type: 'button',
4046
+ 'aria-label': opts.pickerLabel || ('Open ' + type.replace('-', ' ') + ' picker')
4047
+ });
4048
+ var pickerGlyph = iconNode(pickerIcon, 'zs-input-icon-glyph');
4049
+ if (pickerGlyph) pickerControl.appendChild(pickerGlyph);
4050
+ shell.appendChild(pickerControl);
4051
+ this.on(pickerControl, 'click', function (event) {
4052
+ event.preventDefault();
4053
+ self.openPicker();
4054
+ });
4055
+ this.pickerButton = pickerControl;
4056
+ root.classList.add('zs-field--custom-picker');
4057
+ } else if (isPicker && iconControl) {
4058
+ root.classList.add('zs-field--custom-picker');
4059
+ }
4060
+
4061
+ /* right-positioned icon is appended after all actions */
4062
+ if (iconControl && iconPosition === 'right') {
4063
+ if (isRange) shell.insertBefore(iconControl, rangeWrap.nextSibling);
4064
+ else shell.appendChild(iconControl);
4065
+ }
4066
+
4067
+ var showValidationIcon = fieldBool(input, opts, 'validationIcon', 'validation-icon', false);
4068
+ if (showValidationIcon) {
4069
+ var validIcon = iconNode('check', 'zs-input-validation zs-input-validation--valid');
4070
+ var invalidIcon = iconNode('alert', 'zs-input-validation zs-input-validation--invalid');
4071
+ if (validIcon) shell.appendChild(validIcon);
4072
+ if (invalidIcon) shell.appendChild(invalidIcon);
4073
+ root.classList.add('zs-field--validation-icon');
4074
+ }
4075
+
2715
4076
  var hintText = opts.hint || input.getAttribute('data-zidan-hint');
2716
4077
  var counterMax = parseInt(opts.counter, 10) ||
2717
4078
  parseInt(input.getAttribute('data-zidan-counter'), 10) ||
@@ -2727,10 +4088,6 @@
2727
4088
  meta.appendChild(counter);
2728
4089
  }
2729
4090
  root.appendChild(meta);
2730
- if (hintText) {
2731
- input.setAttribute('aria-describedby', this.id + '-hint');
2732
- this._cleanups.push(function () { input.removeAttribute('aria-describedby'); });
2733
- }
2734
4091
  }
2735
4092
 
2736
4093
  this.label = label;
@@ -2741,26 +4098,31 @@
2741
4098
  this._restoreInput = function () {
2742
4099
  var parent = root.parentNode || originalParent;
2743
4100
  parent.insertBefore(input, root.parentNode ? root : null);
2744
- input.classList.remove('zs-input-native');
4101
+ input.classList.remove('zs-input-native', 'zs-input-native--stepper');
2745
4102
  };
2746
4103
 
2747
4104
  addClass(input, 'zs-input-native');
2748
4105
  addClass(root, 'zs-field--' + layout);
2749
4106
 
2750
4107
  var outputSelector = opts.output || input.getAttribute('data-zidan-output');
2751
- if (type === 'range' && outputSelector) {
4108
+ if (isRange && outputSelector) {
2752
4109
  var out = doc.querySelector(outputSelector);
2753
4110
  if (out) {
2754
- var syncOut = function () {
2755
- out.textContent = input.value;
2756
- out.value = input.value;
2757
- };
2758
- syncOut();
2759
- this.on(input, 'input', syncOut);
4111
+ this.rangeOutput = out;
2760
4112
  }
2761
4113
  }
2762
4114
 
2763
- this.on(input, 'input', function () { self.update(); });
4115
+ var previousValue = input.value;
4116
+ this.on(input, 'input', function () {
4117
+ var current = input.value;
4118
+ self._syncRangeOutput(current);
4119
+ self.update();
4120
+ if (current !== previousValue) {
4121
+ previousValue = current;
4122
+ self.emit('input', { value: current });
4123
+ self.call('onInput', { value: current, instance: self });
4124
+ }
4125
+ });
2764
4126
  this.on(input, 'change', function () {
2765
4127
  self.update();
2766
4128
  self.emit('change', { value: input.value });
@@ -2772,7 +4134,8 @@
2772
4134
  this._bindValidity();
2773
4135
  input.__zidanField = this;
2774
4136
  this.update();
2775
- this.emit('init', { type: type });
4137
+ this._syncRangeOutput(input.value);
4138
+ this.emit('init', { type: type, stepper: !!this.stepper, phone: !!this.phone, range: !!this.range });
2776
4139
  this.call('onInit', { instance: this, type: type });
2777
4140
  ZidanForm._register(this);
2778
4141
  }
@@ -2780,6 +4143,275 @@
2780
4143
  ZidanTextField.prototype = Object.create(ZidanFieldBase.prototype);
2781
4144
  ZidanTextField.prototype.constructor = ZidanTextField;
2782
4145
 
4146
+ // phone/date/custom rules must also block native form submission
4147
+ ZidanTextField.prototype._mirrorValidity = function () {
4148
+ var input = this.el;
4149
+ if (input.setCustomValidity) {
4150
+ var custom = this._customError();
4151
+ var message = typeof custom === 'string' ? custom : (custom ? this.opts.messages.generic : '');
4152
+ if (input.__zidanCustomError !== message) {
4153
+ input.setCustomValidity(message);
4154
+ input.__zidanCustomError = message;
4155
+ }
4156
+ }
4157
+ return ZidanFieldBase.prototype._mirrorValidity.call(this);
4158
+ };
4159
+
4160
+ ZidanTextField.prototype._formatRangeValue = function (value) {
4161
+ var formatter = this.rangeFormat;
4162
+ if (typeof formatter === 'function') {
4163
+ try { return String(formatter(value, this)); } catch (err) { return String(value); }
4164
+ }
4165
+ if (typeof formatter === 'string' && formatter) {
4166
+ if (formatter.indexOf('%s') !== -1) return formatter.replace('%s', String(value));
4167
+ return fillTemplate(formatter, {
4168
+ value: value,
4169
+ min: this.el.min,
4170
+ max: this.el.max
4171
+ });
4172
+ }
4173
+ return String(value);
4174
+ };
4175
+
4176
+ ZidanTextField.prototype._rangeBounds = function () {
4177
+ var input = this.el;
4178
+ var min = parseFloat(input.min);
4179
+ var max = parseFloat(input.max);
4180
+ if (!isFinite(min)) min = 0;
4181
+ if (!isFinite(max)) max = 100;
4182
+ return { min: min, max: max };
4183
+ };
4184
+
4185
+ ZidanTextField.prototype._renderRangeTicks = function () {
4186
+ if (!this.rangeTicksEl) return;
4187
+ var bounds = this._rangeBounds();
4188
+ var option = this.rangeTicksOption;
4189
+ var values = [];
4190
+ if (Array.isArray(option)) values = option.map(Number).filter(function (n) { return isFinite(n); });
4191
+ else {
4192
+ var count = parseInt(option, 10);
4193
+ if (!(count > 1)) return;
4194
+ for (var i = 0; i < count; i += 1) values.push(bounds.min + ((bounds.max - bounds.min) * i) / (count - 1));
4195
+ }
4196
+ this.rangeTicksEl.textContent = '';
4197
+ values.forEach(function (value) {
4198
+ var pct = bounds.max > bounds.min ? (value - bounds.min) / (bounds.max - bounds.min) : 0;
4199
+ var tick = el('span', 'zs-range-tick');
4200
+ tick.style.left = (clamp(pct, 0, 1) * 100).toFixed(2) + '%';
4201
+ if (this.rangeTickLabels) {
4202
+ var label = this.rangeLabelMap && this.rangeLabelMap[value] !== undefined
4203
+ ? this.rangeLabelMap[value]
4204
+ : this._formatRangeValue(value);
4205
+ tick.textContent = label;
4206
+ tick.classList.add('zs-range-tick--labeled');
4207
+ }
4208
+ this.rangeTicksEl.appendChild(tick);
4209
+ }, this);
4210
+ };
4211
+
4212
+ ZidanTextField.prototype._syncRange = function (value) {
4213
+ if (!this.range) return;
4214
+ var bounds = this._rangeBounds();
4215
+ var numeric = parseFloat(value);
4216
+ if (!isFinite(numeric)) numeric = bounds.min;
4217
+ var pct = bounds.max > bounds.min ? (numeric - bounds.min) / (bounds.max - bounds.min) : 0;
4218
+ pct = clamp(pct, 0, 1);
4219
+ this.range.style.setProperty('--zs-range-pct', pct.toFixed(4));
4220
+ this.range.style.setProperty('--zs-range-fill', (pct * 100).toFixed(2) + '%');
4221
+ if (this.rangeBubble) this.rangeBubble.textContent = this._formatRangeValue(numeric);
4222
+ if (this.rangeScale) {
4223
+ this.rangeScale.firstChild.textContent = this._formatRangeValue(bounds.min);
4224
+ this.rangeScale.lastChild.textContent = this._formatRangeValue(bounds.max);
4225
+ }
4226
+ var signature = [bounds.min, bounds.max, this.el.step, JSON.stringify(this.rangeTicksOption), this.rangeTickLabels].join('|');
4227
+ if (signature !== this.rangeSignature) {
4228
+ this.rangeSignature = signature;
4229
+ this._renderRangeTicks();
4230
+ }
4231
+ };
4232
+
4233
+ ZidanTextField.prototype._syncRangeOutput = function (value) {
4234
+ if (this.range) this._syncRange(value);
4235
+ if (this.rangeOutput) {
4236
+ this.rangeOutput.textContent = value;
4237
+ this.rangeOutput.value = value;
4238
+ }
4239
+ };
4240
+
4241
+ ZidanTextField.prototype._applyPhoneFormat = function (preserveCaret) {
4242
+ if (!this.phone) return this;
4243
+ var input = this.el;
4244
+ var raw = input.value;
4245
+ if (!digitsOnly(raw)) {
4246
+ if (raw && /\+/.test(raw)) input.value = '+';
4247
+ return this;
4248
+ }
4249
+ var caret = null;
4250
+ var digitCount = 0;
4251
+ var dialLength = this.phone.format === 'national'
4252
+ ? 0
4253
+ : String((PHONE_COUNTRIES[this.phone.country] || PHONE_COUNTRIES.US).dial).length;
4254
+ if (preserveCaret && typeof input.selectionStart === 'number') {
4255
+ caret = input.selectionStart;
4256
+ digitCount = digitsBefore(raw, caret);
4257
+ if (/^\s*\+/.test(raw)) digitCount = Math.max(0, digitCount - dialLength);
4258
+ }
4259
+ var formatted = formatPhone(raw, this.phone.country, this.phone.format);
4260
+ if (formatted === input.value) return this;
4261
+ input.value = formatted;
4262
+ if (preserveCaret && caret !== null) {
4263
+ var targetDigits = digitCount + (formatted.charAt(0) === '+' ? dialLength : 0);
4264
+ var position = caretAfterDigits(formatted, targetDigits);
4265
+ try { input.setSelectionRange(position, position); } catch (err) { /* unsupported */ }
4266
+ }
4267
+ return this;
4268
+ };
4269
+
4270
+ ZidanTextField.prototype._stepBy = function (direction, times) {
4271
+ var input = this.el;
4272
+ if (!this.stepper || !direction || input.disabled || input.readOnly) return this;
4273
+ var count = Math.max(1, parseInt(times, 10) || 1);
4274
+ var step = parseFloat(this.opts.stepperStep || input.step);
4275
+ if (!isFinite(step) || step <= 0) step = 1;
4276
+ var bounds = this._rangeBounds();
4277
+ var min = parseFloat(input.min);
4278
+ var max = parseFloat(input.max);
4279
+ var hasValue = input.value !== '' && isFinite(parseFloat(input.value));
4280
+ var current = hasValue ? parseFloat(input.value) : (isFinite(min) ? min : 0);
4281
+ var next;
4282
+ if (!hasValue && direction > 0 && isFinite(min)) next = min;
4283
+ else next = current + direction * step * count;
4284
+ if (this.stepper.wrap && isFinite(min) && isFinite(max)) {
4285
+ var span = max - min;
4286
+ while (next > max) next -= span || step;
4287
+ while (next < min) next += span || step;
4288
+ } else {
4289
+ if (isFinite(min)) next = Math.max(min, next);
4290
+ if (isFinite(max)) next = Math.min(max, next);
4291
+ }
4292
+ var decimals = Math.max(decimalsOf(step), decimalsOf(next));
4293
+ var value = String(parseFloat(next.toFixed(Math.min(10, decimals))));
4294
+ if (value === input.value) {
4295
+ this._sync();
4296
+ return this;
4297
+ }
4298
+ input.value = value;
4299
+ input.dispatchEvent(new Event('input', { bubbles: true }));
4300
+ input.dispatchEvent(new Event('change', { bubbles: true }));
4301
+ this.emit('step', { value: value, direction: direction, step: step });
4302
+ this.call('onStep', { value: value, direction: direction, instance: this });
4303
+ return this;
4304
+ };
4305
+
4306
+ ZidanTextField.prototype.stepUp = function (times) {
4307
+ return this._stepBy(1, times);
4308
+ };
4309
+
4310
+ ZidanTextField.prototype.stepDown = function (times) {
4311
+ return this._stepBy(-1, times);
4312
+ };
4313
+
4314
+ ZidanTextField.prototype.setStepper = function (enabled) {
4315
+ var input = this.el;
4316
+ if (enabled) input.setAttribute('data-zidan-stepper', 'true');
4317
+ else input.removeAttribute('data-zidan-stepper');
4318
+ return this;
4319
+ };
4320
+
4321
+ ZidanTextField.prototype.openPicker = function () {
4322
+ var input = this.el;
4323
+ try {
4324
+ if (typeof input.showPicker === 'function') input.showPicker();
4325
+ else if (input.focus) input.focus();
4326
+ } catch (err) {
4327
+ if (input.focus) input.focus();
4328
+ }
4329
+ this.emit('picker', { type: this.el.type });
4330
+ this.call('onPicker', { type: this.el.type, instance: this });
4331
+ return this;
4332
+ };
4333
+
4334
+ ZidanTextField.prototype.showPicker = function () {
4335
+ return this.openPicker();
4336
+ };
4337
+
4338
+ ZidanTextField.prototype.getPhoneCountry = function () {
4339
+ return this.phone ? this.phone.country : '';
4340
+ };
4341
+
4342
+ ZidanTextField.prototype.setPhoneCountry = function (iso) {
4343
+ if (!this.phone) return this;
4344
+ iso = String(iso || '').toUpperCase();
4345
+ if (!PHONE_COUNTRIES[iso]) return this;
4346
+ this.phone.country = iso;
4347
+ if (this.phone.select) this.phone.select.value = iso;
4348
+ this._applyPhoneFormat(false);
4349
+ this.update();
4350
+ this.emit('phone-country', { country: iso });
4351
+ this.call('onPhoneCountry', { country: iso, instance: this });
4352
+ return this;
4353
+ };
4354
+
4355
+ ZidanTextField.prototype.setPhoneFormat = function (format) {
4356
+ if (!this.phone) return this;
4357
+ var mode = String(format || '').toLowerCase();
4358
+ if (PHONE_FORMATS.indexOf(mode) === -1) return this;
4359
+ this.phone.format = mode;
4360
+ this._applyPhoneFormat(false);
4361
+ this.update();
4362
+ this.emit('phone-format', { format: mode });
4363
+ this.call('onPhoneFormat', { format: mode, instance: this });
4364
+ return this;
4365
+ };
4366
+
4367
+ ZidanTextField.prototype.formatPhone = function (value) {
4368
+ if (!this.phone) return String(value === undefined ? this.el.value : value);
4369
+ return formatPhone(value === undefined ? this.el.value : value, this.phone.country, this.phone.format);
4370
+ };
4371
+
4372
+ ZidanTextField.prototype._customError = function () {
4373
+ var input = this.el;
4374
+ var opts = this.opts;
4375
+ var messages = opts.messages;
4376
+
4377
+ if (this.phone && this.phone.validate && input.value) {
4378
+ var country = PHONE_COUNTRIES[this.phone.country];
4379
+ var digits = phoneDigitsForCountry(input.value, this.phone.country, this.phone.format);
4380
+ if (digits && (digits.length < country.min || digits.length > country.max)) {
4381
+ return fillTemplate(messages.phone, { country: country.name, min: country.min, max: country.max });
4382
+ }
4383
+ }
4384
+
4385
+ if (input.type === 'date' && input.value) {
4386
+ var weekend = fieldBool(input, opts, 'disableWeekends', 'disable-weekends', false);
4387
+ var disabledDates = opts.disabledDates || input.getAttribute('data-zidan-disabled-dates');
4388
+ var date = new Date(input.value + 'T00:00:00');
4389
+ if (!isNaN(date.getTime())) {
4390
+ if (weekend && (date.getDay() === 0 || date.getDay() === 6)) return messages.weekend;
4391
+ var blocked = false;
4392
+ if (typeof disabledDates === 'function') {
4393
+ try { blocked = disabledDates(input.value, date, this) === true; } catch (err) { blocked = false; }
4394
+ } else if (disabledDates) {
4395
+ var list = Array.isArray(disabledDates) ? disabledDates : String(disabledDates).split(',').map(function (item) { return item.trim(); });
4396
+ blocked = list.indexOf(input.value) !== -1;
4397
+ }
4398
+ if (blocked) return messages.dateDisabled;
4399
+ }
4400
+ if (typeof opts.validateDate === 'function') {
4401
+ var dateResult = opts.validateDate(input.value, date, this);
4402
+ if (dateResult === false) return messages.date;
4403
+ if (typeof dateResult === 'string' && dateResult) return dateResult;
4404
+ }
4405
+ }
4406
+
4407
+ if (typeof opts.validate === 'function') {
4408
+ var result = opts.validate(input.value, this);
4409
+ if (result === false) return messages.generic;
4410
+ if (typeof result === 'string' && result) return result;
4411
+ }
4412
+ return '';
4413
+ };
4414
+
2783
4415
  ZidanTextField.prototype._sync = function () {
2784
4416
  var input = this.el;
2785
4417
  var value = input.value === undefined ? '' : String(input.value);
@@ -2793,6 +4425,16 @@
2793
4425
  this.counter.textContent = length + ' / ' + this.counterMax;
2794
4426
  this.counter.classList.toggle('zs-counter--limit', length >= this.counterMax);
2795
4427
  }
4428
+ if (this.range) this._syncRange(value);
4429
+ if (this.stepper) {
4430
+ var min = parseFloat(input.min);
4431
+ var max = parseFloat(input.max);
4432
+ var current = parseFloat(value);
4433
+ if (!isFinite(current)) current = isFinite(min) ? min : 0;
4434
+ var blocked = !!input.disabled || !!input.readOnly;
4435
+ this.stepper.minus.disabled = blocked || (!this.stepper.wrap && isFinite(min) && current <= min);
4436
+ this.stepper.plus.disabled = blocked || (!this.stepper.wrap && isFinite(max) && current >= max);
4437
+ }
2796
4438
  };
2797
4439
 
2798
4440
  ZidanTextField.prototype.getValue = function () {
@@ -2801,6 +4443,7 @@
2801
4443
 
2802
4444
  ZidanTextField.prototype.setValue = function (value) {
2803
4445
  this.el.value = value === null || value === undefined ? '' : String(value);
4446
+ if (this.phone) this._applyPhoneFormat(false);
2804
4447
  return this.update();
2805
4448
  };
2806
4449
 
@@ -2949,6 +4592,24 @@
2949
4592
 
2950
4593
  ZidanForm.api = null;
2951
4594
 
4595
+ /* registries, presets and helpers shared by every field type */
4596
+ ZidanForm.registerIcon = registerIcon;
4597
+ ZidanForm.icons = ICON_REGISTRY;
4598
+ ZidanForm.phoneCountries = PHONE_COUNTRIES;
4599
+ ZidanForm.phoneFormats = PHONE_FORMATS.slice();
4600
+ ZidanForm.formatPhone = formatPhone;
4601
+ ZidanForm.detectPhoneCountry = detectPhoneCountry;
4602
+ ZidanForm.messages = FIELD_MESSAGES;
4603
+ ZidanForm.variants = {
4604
+ checkbox: CHECKBOX_VARIANTS.slice(),
4605
+ switch: SWITCH_STYLES.slice(),
4606
+ radio: RADIO_VARIANTS.slice(),
4607
+ file: FILE_VARIANTS.slice(),
4608
+ range: RANGE_VARIANTS.slice()
4609
+ };
4610
+ ZidanForm.stepperModes = STEPPER_MODES.slice();
4611
+ ZidanForm.fieldLayouts = FIELD_LAYOUTS.slice();
4612
+
2952
4613
  /* static helpers */
2953
4614
  ZidanSelect.version = VERSION;
2954
4615
  ZidanSelect.__zidanSelectGuard = VERSION;
@@ -3038,7 +4699,10 @@
3038
4699
  zidanSelect: zidanSelect,
3039
4700
  zidanField: zidanField,
3040
4701
  initZidanSelects: initZidanSelects,
3041
- initZidanForms: initZidanForms
4702
+ initZidanForms: initZidanForms,
4703
+ registerIcon: registerIcon,
4704
+ formatPhone: formatPhone,
4705
+ detectPhoneCountry: detectPhoneCountry
3042
4706
  };
3043
4707
 
3044
4708
  ZidanForm.api = api;