-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs
82 lines (70 loc) · 1.83 KB
/
index.mjs
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
export const autoWidth = (node) => {
/* Constants */
const update = new Event("update");
const buffer = 5;
/* Functions */
const init = () => {
addStyles();
observeElement();
addEventListeners();
setInitialWidth();
};
const dispatchUpdateEvent = () => {
node.dispatchEvent(update);
};
const setInitialWidth = () => {
let width;
if (node.placeholder && !node.value) {
node.value = node.placeholder;
node.style.width = "0px";
width = node.scrollWidth;
node.value = "";
} else {
node.style.width = "0px";
width = node.scrollWidth;
}
node.style.width = width + buffer + "px";
};
const setWidth = () => {
node.style.width = "0px";
node.style.width = node.scrollWidth + buffer + "px";
};
const addStyles = () => {
node.style.boxSizing = "border-box";
};
const observeElement = () => {
let elementPrototype = Object.getPrototypeOf(node);
let descriptor = Object.getOwnPropertyDescriptor(elementPrototype, "value");
Object.defineProperty(node, "value", {
get: function () {
return descriptor.get.apply(this, arguments);
},
set: function () {
descriptor.set.apply(this, arguments);
dispatchUpdateEvent();
},
});
};
const addEventListeners = () => {
node.addEventListener("input", () => {
dispatchUpdateEvent();
});
node.addEventListener("update", setWidth);
};
const removeEventListeners = () => {
node.removeEventListener("input", dispatchUpdateEvent);
node.removeEventListener("update", setWidth);
};
if (node.tagName.toLowerCase() !== "input") {
throw new Error(
"svelte-input-auto-width can only be used on input elements."
);
} else {
init();
return {
destroy() {
removeEventListeners();
},
};
}
};