-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
74 lines (71 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
/**
* Svelte Demo: @link https://svelte.dev/repl/a4a95ad06d1f4714882e76c56604b84f?version=3.44.2
*/
/**
* @typedef {'1','2','3','4','5','6','7','8','9','0','.'} AllowedKeys
*/
/**
* Allowed Input Keys
* @type {AllowedKeys[]}
*/
export const allowedKeys = [
'1','2','3','4','5','6','7','8','9','0','.',
];
/**
* Date Input helper for German Date Format 'TT.MM.YYYY'
* @return {{handleInput: (function(*=): string), prevValue: string}}
*/
export const useDateInput = () => {
let prevValue = '';
/**
* Handle Form Input
* @param {AllowedKeys} value
* @return {string}
*/
const handleInput = (value) => {
let newVal = value || '';
if (prevValue.length < newVal.length) {
const newChar = newVal.slice(newVal.length - 1);
if (allowedKeys.indexOf(newChar) === -1) {
newVal = newVal.slice(0, newVal.length - 1);
} else {
if (newChar === '.') {
switch(newVal.length) {
case 2:
newVal = `0${newVal}`;
break;
case 5:
newVal = `${newVal.slice(0,3)}0${newVal.slice(newVal.length-2)}`;
break;
case 3:
case 6:
// Case for 1.. @TODO need?
break;
default:
newVal = newVal.slice(0, newVal.length - 1);
break;
}
} else {
switch (newVal.length) {
case 2:
case 5:
console.log('newVal.length', newVal.length);
newVal = `${newVal}.`;
break;
case 3:
case 6:
newVal = `${newVal.slice(0, newVal.length -1)}.${newChar}`;
break;
}
}
}
}
newVal = newVal.slice(0, 10);
prevValue = newVal;
return newVal;
}
return {
// prevValue,
handleInput,
}
}