@t007/input 0.0.12 → 0.0.16

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,18 +1,6 @@
1
1
  "use strict";
2
2
  (() => {
3
3
  // ../utils/dist/index.js
4
- function isDef(val) {
5
- return "undefined" !== typeof val;
6
- }
7
- function isSym(val) {
8
- return "symbol" === typeof val;
9
- }
10
- function isStr(val) {
11
- return "string" === typeof val;
12
- }
13
- function isArr(obj) {
14
- return Array.isArray(obj);
15
- }
16
4
  function createEl(tag, props, dataset, styles, el = tag ? document?.createElement(tag) : null) {
17
5
  return assignEl(el, props, dataset, styles), el;
18
6
  }
@@ -56,6 +44,15 @@
56
44
  });
57
45
  return w.t007._resourceCache[src];
58
46
  }
47
+ function isSym(val) {
48
+ return "symbol" === typeof val;
49
+ }
50
+ function isStr(val) {
51
+ return "string" === typeof val;
52
+ }
53
+ function isArr(obj) {
54
+ return Array.isArray(obj);
55
+ }
59
56
  function isSameURL(src1, src2) {
60
57
  if (!isStr(src1) || !isStr(src2) || !src1 || !src2) return false;
61
58
  try {
@@ -136,7 +133,7 @@
136
133
  });
137
134
  return update(), t007._scrollers.get(el);
138
135
  }
139
- if (isDef(window)) {
136
+ if ("undefined" !== typeof window) {
140
137
  window.t007 ??= {};
141
138
  t007.VIRTUAL_RESOURCE = VIRTUAL_RESOURCE;
142
139
  window.T007_TOAST_JS_SRC ??= `https://cdn.jsdelivr.net/npm/@t007/toast@latest`;
@@ -442,7 +439,7 @@
442
439
  }
443
440
  };
444
441
  var { field, handleFormValidation } = formManager;
445
- if (isDef(window)) {
442
+ if ("undefined" !== typeof window) {
446
443
  t007.FM = t007.formManager = formManager;
447
444
  t007.field = field;
448
445
  t007.handleFormValidation = handleFormValidation;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/index.js
2
- import { isArr, isDef, isStr, createEl, loadResource, initScrollAssist } from "@t007/utils";
2
+ import { isArr, isStr, createEl, loadResource, initScrollAssist } from "@t007/utils";
3
3
  var formManager = {
4
4
  forms: document.getElementsByClassName("t007-input-form"),
5
5
  violationKeys: ["valueMissing", "typeMismatch", "patternMismatch", "stepMismatch", "tooShort", "tooLong", "rangeUnderflow", "rangeOverflow", "badInput", "customError"],
@@ -294,7 +294,7 @@ var formManager = {
294
294
  }
295
295
  };
296
296
  var { field, handleFormValidation } = formManager;
297
- if (isDef(window)) {
297
+ if ("undefined" !== typeof window) {
298
298
  t007.FM = t007.formManager = formManager;
299
299
  t007.field = field;
300
300
  t007.handleFormValidation = handleFormValidation;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@t007/input",
3
- "version": "0.0.12",
3
+ "version": "0.0.16",
4
4
  "description": "A lightweight, pure JS input system.",
5
5
  "author": "Oketade Oluwatobiloba <tobioketade007@gmail.com>",
6
6
  "license": "MIT",
@@ -29,8 +29,6 @@
29
29
  "import": "./dist/index.js",
30
30
  "default": "./dist/index.js"
31
31
  },
32
- "./standalone": "./dist/standalone.js",
33
- "./global": "./dist/index.global.js",
34
32
  "./style.css": "./dist/index.css"
35
33
  },
36
34
  "publishConfig": {
@@ -57,6 +55,6 @@
57
55
  "monkey-patch"
58
56
  ],
59
57
  "dependencies": {
60
- "@t007/utils": "^0.0.15"
58
+ "@t007/utils": "^0.0.18"
61
59
  }
62
60
  }
@@ -1,457 +0,0 @@
1
- // ../utils/dist/index.js
2
- function isDef(val) {
3
- return "undefined" !== typeof val;
4
- }
5
- function isSym(val) {
6
- return "symbol" === typeof val;
7
- }
8
- function isStr(val) {
9
- return "string" === typeof val;
10
- }
11
- function isArr(obj) {
12
- return Array.isArray(obj);
13
- }
14
- function createEl(tag, props, dataset, styles, el = tag ? document?.createElement(tag) : null) {
15
- return assignEl(el, props, dataset, styles), el;
16
- }
17
- function assignEl(el, props, dataset, styles) {
18
- if (!el) return;
19
- if (props) {
20
- for (const k of Object.keys(props)) if (props[k] !== void 0) el[k] = props[k];
21
- }
22
- if (dataset) {
23
- for (const k of Object.keys(dataset)) if (dataset[k] !== void 0) el.dataset[k] = String(dataset[k]);
24
- }
25
- if (styles) {
26
- for (const k of Object.keys(styles)) if (styles[k] !== void 0) el.style[k] = styles[k];
27
- }
28
- }
29
- var VIRTUAL_RESOURCE = /* @__PURE__ */ Symbol.for("T007_VIRTUAL_RESOURCE");
30
- function loadResource(req, type = "style", { module, media, crossOrigin, integrity, referrerPolicy, nonce, fetchPriority, attempts = 3, retryKey = false } = {}, w = window) {
31
- w.t007 ??= {}, w.t007._resourceCache ??= {};
32
- if (req === VIRTUAL_RESOURCE || isSym(req)) return Promise.resolve();
33
- const src = req;
34
- if (w.t007._resourceCache[src]) return w.t007._resourceCache[src];
35
- const existing = type === "script" ? Array.prototype.find.call(w.document.scripts, (s) => isSameURL(s.src, src)) : type === "style" ? Array.prototype.find.call(w.document.styleSheets, (s) => isSameURL(s.href, src)) : null;
36
- if (existing) return w.t007._resourceCache[src] = Promise.resolve(existing);
37
- w.t007._resourceCache[src] = new Promise((resolve, reject) => {
38
- (function tryLoad(remaining, el) {
39
- const onerror = () => {
40
- el?.remove?.();
41
- if (remaining > 1) {
42
- setTimeout(tryLoad, 1e3, remaining - 1);
43
- console.warn(`Retrying ${type} load (${attempts - remaining + 1}): ${src}...`);
44
- } else {
45
- delete w.t007._resourceCache[src];
46
- reject(new Error(`${type} load failed after ${attempts} attempts: ${src}`));
47
- }
48
- };
49
- const url = retryKey && remaining < attempts ? `${src}${src.includes("?") ? "&" : "?"}_${retryKey}=${Date.now()}` : src;
50
- if (type === "script") w.document.body.append(el = createEl("script", { src: url, type: module ? "module" : "text/javascript", crossOrigin, integrity, referrerPolicy, nonce, fetchPriority, onload: () => resolve(el), onerror }) || "");
51
- else if (type === "style") w.document.head.append(el = createEl("link", { rel: "stylesheet", href: url, media, crossOrigin, integrity, referrerPolicy, nonce, fetchPriority, onload: () => resolve(el), onerror }) || "");
52
- else reject(new Error(`Unsupported resource type: ${type}`));
53
- })(attempts);
54
- });
55
- return w.t007._resourceCache[src];
56
- }
57
- function isSameURL(src1, src2) {
58
- if (!isStr(src1) || !isStr(src2) || !src1 || !src2) return false;
59
- try {
60
- const u1 = new URL(src1, window.location.href), u2 = new URL(src2, window.location.href);
61
- return decodeURIComponent(u1.origin + u1.pathname) === decodeURIComponent(u2.origin + u2.pathname);
62
- } catch {
63
- return src1.replace(/\\/g, "/").split("?")[0].trim() === src2.replace(/\\/g, "/").split("?")[0].trim();
64
- }
65
- }
66
- function initScrollAssist(el, { pxPerSecond = 80, assistClassName = "tmg-video-controls-scroll-assist", vertical = true, horizontal = true } = {}) {
67
- t007._scrollers ??= /* @__PURE__ */ new WeakMap();
68
- t007._scroller_r_observer ??= new ResizeObserver((entries) => entries.forEach(({ target }) => t007._scrollers.get(target)?.update()));
69
- t007._scroller_m_observer ??= new MutationObserver((entries) => {
70
- const els = /* @__PURE__ */ new Set();
71
- for (const entry of entries) {
72
- let node = entry.target instanceof Element ? entry.target : null;
73
- while (node && !t007._scrollers.has(node)) node = node.parentElement;
74
- if (node) els.add(node);
75
- }
76
- for (const el2 of els) t007._scrollers.get(el2)?.update();
77
- });
78
- const parent = el?.parentElement;
79
- if (!parent || t007._scrollers.has(el)) return;
80
- const assist = {};
81
- let scrollId = null, last = performance.now(), assistWidth = 20, assistHeight = 20;
82
- const update = () => {
83
- const hasInteractive = !!parent.querySelector('button, a[href], input, select, textarea, [contenteditable="true"], [tabindex]:not([tabindex="-1"])');
84
- if (horizontal) {
85
- const w = assist.left?.offsetWidth || assistWidth, check = hasInteractive ? el.clientWidth < w * 2 : false;
86
- assist.left.style.display = check ? "none" : el.scrollLeft > 0 ? "block" : "none";
87
- assist.right.style.display = check ? "none" : el.scrollLeft + el.clientWidth < el.scrollWidth - 1 ? "block" : "none";
88
- assistWidth = w;
89
- }
90
- if (vertical) {
91
- const h = assist.up?.offsetHeight || assistHeight, check = hasInteractive ? el.clientHeight < h * 2 : false;
92
- assist.up.style.display = check ? "none" : el.scrollTop > 0 ? "block" : "none";
93
- assist.down.style.display = check ? "none" : el.scrollTop + el.clientHeight < el.scrollHeight - 1 ? "block" : "none";
94
- assistHeight = h;
95
- }
96
- };
97
- const scroll = (dir) => {
98
- const frame = () => {
99
- const now = performance.now(), dt = now - last;
100
- last = now;
101
- const d = pxPerSecond * dt / 1e3;
102
- if (dir === "left") el.scrollLeft = Math.max(0, el.scrollLeft - d);
103
- if (dir === "right") el.scrollLeft = Math.min(el.scrollWidth - el.clientWidth, el.scrollLeft + d);
104
- if (dir === "up") el.scrollTop = Math.max(0, el.scrollTop - d);
105
- if (dir === "down") el.scrollTop = Math.min(el.scrollHeight - el.clientHeight, el.scrollTop + d);
106
- scrollId = requestAnimationFrame(frame);
107
- };
108
- last = performance.now();
109
- frame();
110
- };
111
- const stop = () => (cancelAnimationFrame(scrollId ?? 0), scrollId = null);
112
- const addAssist = (dir) => {
113
- const div = createEl("div", { className: assistClassName }, { scrollDirection: dir }, { display: "none" });
114
- if (!div) return;
115
- ["pointerenter", "dragenter"].forEach((evt) => div.addEventListener(evt, () => scroll(dir)));
116
- ["pointerleave", "pointerup", "pointercancel", "dragleave", "dragend"].forEach((evt) => div.addEventListener(evt, stop));
117
- dir === "left" || dir === "up" ? parent.insertBefore(div, el) : parent.append(div);
118
- assist[dir] = div;
119
- };
120
- if (horizontal) ["left", "right"].forEach(addAssist);
121
- if (vertical) ["up", "down"].forEach(addAssist);
122
- el.addEventListener("scroll", update);
123
- t007._scroller_r_observer.observe(el);
124
- t007._scroller_m_observer.observe(el, { childList: true, subtree: true, characterData: true });
125
- t007._scrollers.set(el, {
126
- update,
127
- destroy() {
128
- stop();
129
- el.removeEventListener("scroll", update);
130
- t007._scroller_r_observer.unobserve(el);
131
- t007._scrollers.delete(el);
132
- Object.values(assist).forEach((a) => a.remove());
133
- }
134
- });
135
- return update(), t007._scrollers.get(el);
136
- }
137
- if (isDef(window)) {
138
- window.t007 ??= {};
139
- t007.VIRTUAL_RESOURCE = VIRTUAL_RESOURCE;
140
- window.T007_TOAST_JS_SRC ??= `https://cdn.jsdelivr.net/npm/@t007/toast@latest`;
141
- window.T007_INPUT_JS_SRC ??= `https://cdn.jsdelivr.net/npm/@t007/input@latest`;
142
- window.T007_DIALOG_JS_SRC ??= `https://cdn.jsdelivr.net/npm/@t007/dialog@latest`;
143
- window.T007_TOAST_CSS_SRC ??= `https://cdn.jsdelivr.net/npm/@t007/toast@latest/dist/index.min.css`;
144
- window.T007_INPUT_CSS_SRC ??= `https://cdn.jsdelivr.net/npm/@t007/input@latest/dist/index.min.css`;
145
- window.T007_DIALOG_CSS_SRC ??= `https://cdn.jsdelivr.net/npm/@t007/dialog@latest/dist/index.min.css`;
146
- }
147
-
148
- // src/index.js
149
- var formManager = {
150
- forms: document.getElementsByClassName("t007-input-form"),
151
- violationKeys: ["valueMissing", "typeMismatch", "patternMismatch", "stepMismatch", "tooShort", "tooLong", "rangeUnderflow", "rangeOverflow", "badInput", "customError"],
152
- init() {
153
- t007.FM.observeDOMForFields();
154
- Array.from(t007.FM.forms).forEach(t007.FM.handleFormValidation);
155
- },
156
- observeDOMForFields() {
157
- new MutationObserver((mutations) => {
158
- for (const mutation of mutations) {
159
- for (const node of mutation.addedNodes) {
160
- if (!node.tagName || !(node?.classList?.contains("t007-input-field") || node?.querySelector?.(".t007-input-field"))) continue;
161
- for (const field2 of [...node.querySelector(".t007-input-field") ? node.querySelectorAll(".t007-input-field") : [node]]) t007.FM.setUpField(field2);
162
- }
163
- }
164
- }).observe(document.body, { childList: true, subtree: true });
165
- },
166
- getFilesHelper(files, opts) {
167
- if (!files || !files.length) return { violation: null, message: "" };
168
- const totalFiles = files.length;
169
- let totalSize = 0;
170
- let currFiles = 0;
171
- const setMaxError = (size, max, n = 0) => ({ violation: "rangeOverflow", message: n ? `File ${files.length > 1 ? n : ""} size of ${t007.FM.formatSize(size)} exceeds the per file maximum of ${t007.FM.formatSize(max)}` : `Total files size of ${t007.FM.formatSize(size)} exceeds the total maximum of ${t007.FM.formatSize(max)}` });
172
- const setMinError = (size, min, n = 0) => ({ violation: "rangeUnderflow", message: n ? `File ${files.length > 1 ? n : ""} size of ${t007.FM.formatSize(size)} is less than the per file minimum of ${t007.FM.formatSize(min)}` : `Total files size of ${t007.FM.formatSize(size)} is less than the total minimum of ${t007.FM.formatSize(min)}` });
173
- for (const file of files) {
174
- currFiles++;
175
- totalSize += file.size;
176
- if (opts.accept) {
177
- const acceptedTypes = opts.accept.split(",").map((type) => type.trim().replace(/^[*\.]+|[*\.]+$/g, "")).filter(Boolean) || [];
178
- if (!acceptedTypes.some((type) => file.type.includes(type))) return { violation: "typeMismatch", message: `File${currFiles > 1 ? currFiles : ""} type of '${file.type}' is not accepted.` };
179
- }
180
- if (opts.maxSize && file.size > opts.maxSize) return setMaxError(file.size, opts.maxSize, currFiles);
181
- if (opts.minSize && file.size < opts.minSize) return setMinError(file.size, opts.minSize, currFiles);
182
- if (opts.multiple) {
183
- if (opts.maxTotalSize && totalSize > opts.maxTotalSize) return setMaxError(totalSize, opts.maxTotalSize);
184
- if (opts.minTotalSize && totalSize < opts.minTotalSize) return setMinError(totalSize, opts.minTotalSize);
185
- if (opts.maxLength && totalFiles > opts.maxLength) return { violation: "tooLong", message: `Selected ${totalFiles} files exceeds the maximum of ${opts.maxLength} allowed file${opts.maxLength == 1 ? "" : "s"}` };
186
- if (opts.minLength && totalFiles < opts.minLength) return { violation: "tooShort", message: `Selected ${totalFiles} files is less than the minimum of ${opts.minLength} allowed file${opts.minLength == 1 ? "" : "s"}` };
187
- }
188
- }
189
- return { violation: null, message: "" };
190
- },
191
- formatSize(size, decimals = 3, base = 1e3) {
192
- if (size < base) return `${size} byte${size == 1 ? "" : "s"}`;
193
- const units = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"], exponent = Math.min(Math.floor(Math.log(size) / Math.log(base)), units.length - 1);
194
- return `${(size / Math.pow(base, exponent)).toFixed(decimals).replace(/\.0+$/, "")} ${units[exponent]}`;
195
- },
196
- togglePasswordType: (input) => input.type = input.type === "password" ? "text" : "password",
197
- toggleFilled: (input) => input?.toggleAttribute("data-filled", input.type === "checkbox" || input.type === "radio" ? input.checked : input.value !== "" || input.files?.length > 0),
198
- setFallbackHelper(field2) {
199
- const helperTextWrapper = field2?.querySelector(".t007-input-helper-text-wrapper");
200
- if (!helperTextWrapper || helperTextWrapper.querySelector(".t007-input-helper-text[data-violation='auto']")) return;
201
- helperTextWrapper.append(createEl("p", { className: "t007-input-helper-text" }, { violation: "auto" }));
202
- },
203
- setFieldListeners(field2) {
204
- if (!field2) return;
205
- const input = field2.querySelector(".t007-input"), floatingLabel = field2.querySelector(".t007-input-floating-label"), eyeOpen = field2.querySelector(".t007-input-password-visible-icon"), eyeClosed = field2.querySelector(".t007-input-password-hidden-icon");
206
- if (input.type === "file")
207
- input.addEventListener("input", async () => {
208
- const file = input.files?.[0], img = new Image();
209
- img.onload = () => {
210
- input.style.setProperty("--t007-input-image-src", `url(${src})`);
211
- input.classList.add("t007-input-image-selected");
212
- setTimeout(() => URL.revokeObjectURL(src), 1e3);
213
- };
214
- img.onerror = () => {
215
- input.style.removeProperty("--t007-input-image-src");
216
- input.classList.remove("t007-input-image-selected");
217
- URL.revokeObjectURL(src);
218
- };
219
- let src;
220
- if (file?.type?.startsWith("image")) src = URL.createObjectURL(file);
221
- else if (file?.type?.startsWith("video")) {
222
- src = await new Promise((resolve) => {
223
- let video = createEl("video"), canvas = createEl("canvas"), context = canvas.getContext("2d");
224
- video.ontimeupdate = () => {
225
- context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
226
- canvas.toBlob((blob) => resolve(URL.createObjectURL(blob)));
227
- URL.revokeObjectURL(video.src);
228
- video = video.src = video.onloadedmetadata = video.ontimeupdate = null;
229
- };
230
- video.onloadeddata = () => video.currentTime = 3;
231
- video.src = URL.createObjectURL(file);
232
- });
233
- }
234
- if (!src) {
235
- input.style.removeProperty("--t007-input-image-src");
236
- input.classList.remove("t007-input-image-selected");
237
- return;
238
- }
239
- img.src = src;
240
- });
241
- if (floatingLabel) floatingLabel.ontransitionend = () => floatingLabel.classList.remove("t007-input-shake");
242
- if (eyeOpen && eyeClosed) eyeOpen.onclick = eyeClosed.onclick = () => t007.FM.togglePasswordType(input);
243
- initScrollAssist(field2.querySelector(".t007-input-helper-text-wrapper"), { vertical: false });
244
- },
245
- setUpField(field2) {
246
- if (field2.dataset.setUp) return;
247
- t007.FM.toggleFilled(field2.querySelector(".t007-input"));
248
- t007.FM.setFallbackHelper(field2);
249
- t007.FM.setFieldListeners(field2);
250
- field2.dataset.setUp = "true";
251
- },
252
- field({ isWrapper = false, label = "", type = "text", placeholder = "", custom = "", minSize, maxSize, minTotalSize, maxTotalSize, options = [], indeterminate = false, eyeToggler = true, passwordMeter = true, helperText = {}, className = "", fieldClassName = "", children, startIcon = "", endIcon = "", nativeIcon = "", passwordVisibleIcon = "", passwordHiddenIcon = "", ...otherProps }) {
253
- const isSelect = type === "select", isTextArea = type === "textarea", isCheckboxOrRadio = type === "checkbox" || type === "radio", field2 = createEl("div", { className: `t007-input-field${isWrapper ? " t007-input-is-wrapper" : ""}${indeterminate ? " t007-input-indeterminate" : ""}${!!nativeIcon ? " t007-input-icon-override" : ""}${helperText === false ? " t007-input-no-helper" : ""}${fieldClassName ? ` ${fieldClassName}` : ""}` }), labelEl = createEl("label", { className: isCheckboxOrRadio ? `t007-input-${type}-wrapper` : "t007-input-wrapper" });
254
- field2.append(labelEl);
255
- if (isCheckboxOrRadio) {
256
- labelEl.innerHTML = `
257
- <span class="t007-input-${type}-box">
258
- <span class="t007-input-${type}-tag"></span>
259
- </span>
260
- <span class="t007-input-${type}-label">${label}</span>
261
- `;
262
- } else {
263
- const outline = createEl("span", { className: "t007-input-outline" });
264
- outline.innerHTML = `
265
- <span class="t007-input-outline-leading"></span>
266
- <span class="t007-input-outline-notch">
267
- <span class="t007-input-floating-label">${label}</span>
268
- </span>
269
- <span class="t007-input-outline-trailing"></span>
270
- `;
271
- labelEl.append(outline);
272
- }
273
- const inputEl = field2.inputEl = createEl(isTextArea ? "textarea" : isSelect ? "select" : "input", { className: `t007-input${className ? ` ${className}` : ""}`, placeholder });
274
- if (isSelect && isArr(options)) inputEl.innerHTML = options.map((opt) => isStr(opt) ? `<option value="${opt}">${opt}</option>` : `<option value="${opt.value}">${opt.option}</option>`).join("");
275
- if (!isSelect && !isTextArea) inputEl.type = type;
276
- if (custom) inputEl.setAttribute("custom", custom);
277
- if (minSize) inputEl.setAttribute("minsize", minSize);
278
- if (maxSize) inputEl.setAttribute("maxsize", maxSize);
279
- if (minTotalSize) inputEl.setAttribute("mintotalsize", minTotalSize);
280
- if (maxTotalSize) inputEl.setAttribute("maxtotalsize", maxTotalSize);
281
- Object.keys(otherProps).forEach((key) => inputEl[key] = otherProps[key]);
282
- labelEl.append(!isWrapper ? inputEl : children);
283
- const nativeTypes = ["date", "time", "month", "datetime-local"];
284
- if (nativeTypes.includes(type) && nativeIcon) labelEl.append(createEl("i", { className: "t007-input-icon t007-input-native-icon", innerHTML: nativeIcon }));
285
- else if (endIcon) labelEl.append(createEl("i", { className: "t007-input-icon", innerHTML: endIcon }));
286
- if (type === "password" && eyeToggler) {
287
- labelEl.append(createEl("i", { role: "button", ariaLabel: "Show password", className: "t007-input-icon t007-input-password-visible-icon", innerHTML: passwordVisibleIcon || `<svg width="24" height="24"><path fill="rgba(0,0,0,.54)" d="M12 16q1.875 0 3.188-1.312Q16.5 13.375 16.5 11.5q0-1.875-1.312-3.188Q13.875 7 12 7q-1.875 0-3.188 1.312Q7.5 9.625 7.5 11.5q0 1.875 1.312 3.188Q10.125 16 12 16Zm0-1.8q-1.125 0-1.912-.788Q9.3 12.625 9.3 11.5t.788-1.913Q10.875 8.8 12 8.8t1.913.787q.787.788.787 1.913t-.787 1.912q-.788.788-1.913.788Zm0 4.8q-3.65 0-6.65-2.038-3-2.037-4.35-5.462 1.35-3.425 4.35-5.463Q8.35 4 12 4q3.65 0 6.65 2.037 3 2.038 4.35 5.463-1.35 3.425-4.35 5.462Q15.65 19 12 19Z"/></svg>` }));
288
- labelEl.append(createEl("i", { role: "button", ariaLabel: "Hide password", className: "t007-input-icon t007-input-password-hidden-icon", innerHTML: passwordHiddenIcon || `<svg width="24" height="24"><path fill="rgba(0,0,0,.54)" d="m19.8 22.6-4.2-4.15q-.875.275-1.762.413Q12.95 19 12 19q-3.775 0-6.725-2.087Q2.325 14.825 1 11.5q.525-1.325 1.325-2.463Q3.125 7.9 4.15 7L1.4 4.2l1.4-1.4 18.4 18.4ZM12 16q.275 0 .512-.025.238-.025.513-.1l-5.4-5.4q-.075.275-.1.513-.025.237-.025.512 0 1.875 1.312 3.188Q10.125 16 12 16Zm7.3.45-3.175-3.15q.175-.425.275-.862.1-.438.1-.938 0-1.875-1.312-3.188Q13.875 7 12 7q-.5 0-.938.1-.437.1-.862.3L7.65 4.85q1.025-.425 2.1-.638Q10.825 4 12 4q3.775 0 6.725 2.087Q21.675 8.175 23 11.5q-.575 1.475-1.512 2.738Q20.55 15.5 19.3 16.45Zm-4.625-4.6-3-3q.7-.125 1.288.112.587.238 1.012.688.425.45.613 1.038.187.587.087 1.162Z"/></svg>` }));
289
- }
290
- if (helperText !== false) {
291
- const helperLine = createEl("div", { className: "t007-input-helper-line" }), helperWrapper = createEl("div", { className: "t007-input-helper-text-wrapper", tabIndex: "-1" });
292
- if (helperText.info) helperWrapper.append(createEl("p", { className: "t007-input-helper-text", textContent: helperText.info }, { violation: "none" }));
293
- t007.FM?.violationKeys?.forEach((key) => helperText[key] && helperWrapper.append(createEl("p", { className: "t007-input-helper-text", textContent: helperText[key] }, { violation: key })));
294
- helperLine.append(helperWrapper);
295
- field2.append(helperLine);
296
- }
297
- if (passwordMeter && type === "password") {
298
- const meter = createEl("div", { className: "t007-input-password-meter" }, { strengthLevel: "1" });
299
- meter.innerHTML = `
300
- <div class="t007-input-password-strength-meter">
301
- <div class="t007-input-p-weak"></div>
302
- <div class="t007-input-p-fair"></div>
303
- <div class="t007-input-p-strong"></div>
304
- <div class="t007-input-p-very-strong"></div>
305
- </div>
306
- `;
307
- field2.append(meter);
308
- }
309
- return field2;
310
- },
311
- handleFormValidation(form) {
312
- if (!form?.classList.contains("t007-input-form") || form.dataset?.isValidating) return;
313
- form.dataset.isValidating = "true";
314
- form.validateOnClient = validateFormOnClient;
315
- form.toggleGlobalError = toggleFormGlobalError;
316
- const fields = form.getElementsByClassName("t007-input-field"), inputs = form.getElementsByClassName("t007-input");
317
- Array.from(fields).forEach(t007.FM.setUpField);
318
- form.addEventListener("input", ({ target }) => {
319
- t007.FM.toggleFilled(target);
320
- validateInput(target);
321
- });
322
- form.addEventListener("focusout", ({ target }) => validateInput(target, true));
323
- form.addEventListener("submit", async (e) => {
324
- toggleSubmitLoader(true);
325
- try {
326
- e.preventDefault();
327
- if (!validateFormOnClient()) return;
328
- if (form.validateOnServer && !await form.validateOnServer()) {
329
- toggleFormGlobalError(true);
330
- form.addEventListener("input", () => toggleFormGlobalError(false), { once: true, useCapture: true });
331
- return;
332
- }
333
- form.onSubmit ? form.onSubmit() : form.submit();
334
- } catch (error) {
335
- console.error(error);
336
- }
337
- toggleSubmitLoader(false);
338
- });
339
- function toggleSubmitLoader(bool) {
340
- form.classList.toggle("t007-input-submit-loading", bool);
341
- }
342
- function toggleError(input, bool, flag = false) {
343
- const field2 = input.closest(".t007-input-field"), floatingLabel = field2.querySelector(".t007-input-floating-label");
344
- if (bool && flag) {
345
- input.setAttribute("data-error", "");
346
- floatingLabel?.classList.add("t007-input-shake");
347
- } else if (!bool) input.removeAttribute("data-error");
348
- toggleHelper(input, input.hasAttribute("data-error"));
349
- }
350
- function toggleHelper(input, bool) {
351
- const field2 = input.closest(".t007-input-field"), violation = t007.FM.violationKeys.find((violation2) => input.Validity?.[violation2] || input.validity[violation2]) ?? "", helper = field2.querySelector(`.t007-input-helper-text[data-violation="${violation}"]`), fallbackHelper = field2.querySelector(`.t007-input-helper-text[data-violation="auto"]`);
352
- input.closest(".t007-input-field").querySelectorAll(`.t007-input-helper-text:not([data-violation="${violation}"])`).forEach((helper2) => helper2?.classList.remove("t007-input-show"));
353
- if (helper) helper.classList.toggle("t007-input-show", bool);
354
- else if (fallbackHelper) {
355
- fallbackHelper.textContent = input.validationMessage;
356
- fallbackHelper.classList.toggle("t007-input-show", bool);
357
- }
358
- }
359
- function forceRevalidate(input) {
360
- input.checkValidity();
361
- input.dispatchEvent(new Event("input"));
362
- }
363
- function updatePasswordMeter(input) {
364
- const passwordMeter = input.closest(".t007-input-field").querySelector(".t007-input-password-meter");
365
- if (!passwordMeter) return;
366
- const value = input.value?.trim();
367
- let strengthLevel = 0;
368
- if (value.length < Number(input.minLength ?? 0)) strengthLevel = 1;
369
- else {
370
- if (/[a-z]/.test(value)) strengthLevel++;
371
- if (/[A-Z]/.test(value)) strengthLevel++;
372
- if (/[0-9]/.test(value)) strengthLevel++;
373
- if (/[\W_]/.test(value)) strengthLevel++;
374
- }
375
- passwordMeter.dataset.strengthLevel = strengthLevel;
376
- }
377
- function validateInput(input, flag = false) {
378
- if (form.dataset.globalError || !input?.classList.contains("t007-input")) return;
379
- updatePasswordMeter(input);
380
- let value, errorBool;
381
- switch (input.custom ?? input.getAttribute("custom")) {
382
- case "password":
383
- value = input.value?.trim();
384
- if (value === "") break;
385
- const confirmPasswordInput = Array.from(inputs).find((input2) => (input2.custom ?? input2.getAttribute("custom")) === "confirm-password");
386
- if (!confirmPasswordInput) break;
387
- const confirmPasswordValue = confirmPasswordInput.value?.trim();
388
- confirmPasswordInput.setCustomValidity(value !== confirmPasswordValue ? "Both passwords do not match" : "");
389
- toggleError(confirmPasswordInput, value !== confirmPasswordValue, flag);
390
- break;
391
- case "confirm_password":
392
- value = input.value?.trim();
393
- if (value === "") break;
394
- const passwordInput = Array.from(inputs).find((input2) => (input2.custom ?? input2.getAttribute("custom")) === "password");
395
- if (!passwordInput) break;
396
- const passwordValue = passwordInput.value?.trim();
397
- errorBool = value !== passwordValue;
398
- input.setCustomValidity(errorBool ? "Both passwords do not match" : "");
399
- break;
400
- case "onward_date":
401
- if (input.min) break;
402
- input.min = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
403
- forceRevalidate(input);
404
- break;
405
- }
406
- if (input.type === "file") {
407
- input.Validity = {};
408
- const { violation, message } = t007.FM.getFilesHelper(input.files ?? [], {
409
- accept: input.accept,
410
- multiple: input.multiple,
411
- maxSize: input.maxSize ?? Number(input.getAttribute("maxsize")),
412
- minSize: input.minSize ?? Number(input.getAttribute("minsize")),
413
- maxTotalSize: input.maxTotalSize ?? Number(input.getAttribute("maxtotalsize")),
414
- minTotalSize: input.minTotalSize ?? Number(input.getAttribute("mintotalsize")),
415
- maxLength: input.maxLength ?? Number(input.getAttribute("maxlength")),
416
- minLength: input.minLength ?? Number(input.getAttribute("minLength"))
417
- });
418
- errorBool = !!message;
419
- input.setCustomValidity(message);
420
- if (violation) input.Validity[violation] = true;
421
- }
422
- errorBool = errorBool ?? !input.validity?.valid;
423
- toggleError(input, errorBool, flag);
424
- if (errorBool) return;
425
- if (input.type === "radio")
426
- Array.from(inputs)?.filter((i) => i.name == input.name)?.forEach((radio) => toggleError(radio, errorBool, flag));
427
- }
428
- function validateFormOnClient() {
429
- Array.from(inputs).forEach((input) => validateInput(input, true));
430
- form.querySelector("input:invalid")?.focus();
431
- return Array.from(inputs).every((input) => input.checkValidity());
432
- }
433
- function toggleFormGlobalError(bool) {
434
- form.toggleAttribute("data-global-error", bool);
435
- form.querySelectorAll(".t007-input-field").forEach((field2) => {
436
- field2.querySelector(".t007-input")?.toggleAttribute("data-error", bool);
437
- if (bool) field2.querySelector(".t007-input-floating-label")?.classList.add("t007-input-shake");
438
- });
439
- }
440
- }
441
- };
442
- var { field, handleFormValidation } = formManager;
443
- if (isDef(window)) {
444
- t007.FM = t007.formManager = formManager;
445
- t007.field = field;
446
- t007.handleFormValidation = handleFormValidation;
447
- window.field ??= t007.field;
448
- window.handleFormValidation ??= t007.handleFormValidation;
449
- console.log("%cT007 Input helpers attached to window!", "color: darkturquoise");
450
- loadResource(T007_INPUT_CSS_SRC);
451
- t007.FM.init();
452
- }
453
- export {
454
- field,
455
- formManager,
456
- handleFormValidation
457
- };