-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cleave-input.js
90 lines (74 loc) · 1.8 KB
/
cleave-input.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import Cleave from "./src/Cleave.js";
// Example
/*
<label for="date-input" class="form-label">Date</label>
<cleave-input type="date">
<input type="text" class="form-control" id="date-input" name="date">
</cleave-input>
*/
let counter = 0;
function getGlobalFn(fn) {
return fn.split(".").reduce((r, p) => r[p], window);
}
class CleaveInput extends HTMLElement {
connectedCallback() {
counter++;
// make sure it's parsed
setTimeout(() => {
this.init();
});
}
init() {
// If we reinitialize, destroy current instance
if (this.cleave) {
this.cleave.destroy();
}
let c = {};
const dataConfig = this.dataset.config;
if (dataConfig) {
c = Object.assign(c, JSON.parse(dataConfig));
}
const fnNames = ["onValueChanged", "onBeforeInput", "onAfterInput"];
fnNames.forEach((fnName) => {
if (typeof c[fnName] == "string") {
c[fnName] = getGlobalFn(c[fnName]);
}
});
const input = this.getInput();
const id = input.getAttribute("id") || `cleave-input-${counter}`;
input.setAttribute("id", id);
const type = this.getAttribute("type") || null;
if (type) {
if (type === "datetime") {
c.date = true;
c.time = true;
} else {
c[type] = true;
}
}
this.cleave = new Cleave(input, c);
}
disconnectedCallback() {
// This may be disconnected before it's created
if (this.cleave) {
this.cleave.destroy();
}
}
/**
* @returns {Cleave}
*/
getCleave() {
if (!this.cleave) {
throw Error("Cleave is not initialized yet");
}
return this.cleave;
}
/**
* @returns {HTMLInputElement}
*/
getInput() {
return this.querySelector("input");
}
}
customElements.define("cleave-input", CleaveInput);
export default CleaveInput;