-
Notifications
You must be signed in to change notification settings - Fork 61
/
html-duration-picker.js
317 lines (285 loc) · 11 KB
/
html-duration-picker.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/**
* @preserve
* html-duration-picker.js
*
* @description Turn an html input box to a duration picker, without jQuery
* @version [AIV]{version}[/AIV]
* @author Chif <nadchif@gmail.com>
* @license GPL v3
*
*/
export default (function() {
// The following keys will not be blocked from working within the input field
const acceptedKeys = [
'Backspace',
'ArrowDown',
'ArrowUp',
'Tab',
];
// Gets the current select block hhh or mm or ss
// and selects the entire block
const selectFocus = (event) => {
// get cursor position and select nearest block;
const cursorPosition = event.target.selectionStart;
const hourMarker = event.target.value.indexOf(':');
const minuteMarker = event.target.value.lastIndexOf(':');
if (hourMarker < 0 || minuteMarker < 0) {
// something wrong with the format. just return;
return;
}
// cursor is in the hours region
if (cursorPosition < hourMarker) {
event.target.setAttribute('data-adjustment-mode', 60 * 60);
event.target.setSelectionRange(0, hourMarker);
return;
}
// cursor is in the minutes region
if (cursorPosition > hourMarker && cursorPosition < minuteMarker) {
event.target.setAttribute('data-adjustment-mode', 60);
event.target.setSelectionRange(hourMarker + 1, minuteMarker);
return;
}
// cursor is in the seconds region
if (cursorPosition > minuteMarker) {
event.target.setAttribute('data-adjustment-mode', 1);
event.target.setSelectionRange(minuteMarker + 1, minuteMarker + 3);
return;
}
event.target.setAttribute('data-adjustment-mode', 'ss');
event.target.setSelectionRange(minuteMarker + 1, minuteMarker + 3);
return;
};
// Inserts a formatted value into the input box
const insertFormatted = (inputBox, secondsValue) => {
let hours = Math.floor(secondsValue / 3600);
secondsValue %= 3600;
let minutes = Math.floor(secondsValue / 60);
let seconds = secondsValue % 60;
minutes = String(minutes).padStart(2, '0');
hours = String(hours).padStart(2, '0');
seconds = String(seconds).padStart(2, '0');
inputBox.value = hours + ':' + minutes + ':' + seconds;
};
const highlightIncrementArea = (inputBox, adjustmentFactor) => {
const hourMarker = inputBox.value.indexOf(':');
const minuteMarker = inputBox.value.lastIndexOf(':');
inputBox.focus();
inputBox.select();
if (adjustmentFactor >= 60 * 60) {
inputBox.selectionStart = 0; // hours mode
inputBox.selectionEnd = hourMarker;
return;
}
if (adjustmentFactor >= 60) {
inputBox.selectionStart = hourMarker + 1; // minutes mode
inputBox.selectionEnd = minuteMarker;
return;
}
inputBox.selectionStart = minuteMarker + 1; // seconds mode
inputBox.selectionEnd = minuteMarker + 3;
return;
};
// gets the adjustment factor for a picker
const getAdjustmentFactor = (picker) => {
let adjustmentFactor = 1;
if (Number(picker.getAttribute('data-adjustment-mode')) > 0) {
adjustmentFactor = Number(picker.getAttribute('data-adjustment-mode'));
}
return adjustmentFactor;
};
// increase time value;
const increaseValue = (inputBox) => {
const rawValue = inputBox.value;
const sectioned = rawValue.split(':');
const adjustmentFactor = getAdjustmentFactor(inputBox);
let secondsValue = 0;
if (sectioned.length === 3) {
secondsValue =
Number(sectioned[2]) +
Number(sectioned[1] * 60) +
Number(sectioned[0] * 60 * 60);
}
secondsValue += adjustmentFactor;
insertFormatted(inputBox, secondsValue);
highlightIncrementArea(inputBox, adjustmentFactor);
};
// decrease time value;
const decreaseValue = (inputBox) => {
const rawValue = inputBox.value;
const sectioned = rawValue.split(':');
const adjustmentFactor = getAdjustmentFactor(inputBox);
let secondsValue = 0;
if (sectioned.length === 3) {
secondsValue =
Number(sectioned[2]) +
Number(sectioned[1] * 60) +
Number(sectioned[0] * 60 * 60);
}
secondsValue -= adjustmentFactor;
if (secondsValue < 0) {
secondsValue = 0;
}
insertFormatted(inputBox, secondsValue);
highlightIncrementArea(inputBox, adjustmentFactor);
};
// shift focus from one unit to another;
const shiftFocus = (inputBox, toSide) => {
const adjustmentFactor = getAdjustmentFactor(inputBox);
switch (toSide) {
case 'left':
highlightIncrementArea(inputBox, adjustmentFactor * 60);
break;
case 'right':
highlightIncrementArea(inputBox, adjustmentFactor / 60);
break;
}
};
// validate any input in the box;
const validateInput = (event) => {
const sectioned = event.target.value.split(':');
if (sectioned.length !== 3) {
event.target.value = '00:00:00'; // fallback to default
return;
}
if (isNaN(sectioned[0])) {
sectioned[0] = '00';
}
if (isNaN(sectioned[1]) || sectioned[1] < 0) {
sectioned[1] = '00';
}
if (sectioned[1] > 59 || sectioned[1].length > 2) {
sectioned[1] = '59';
}
if (isNaN(sectioned[2]) || sectioned[2] < 0) {
sectioned[2] = '00';
}
if (sectioned[2] > 59 || sectioned[2].length > 2) {
sectioned[2] = '59';
}
event.target.value = sectioned.join(':');
};
const handleKeydown = (event) => {
if (event.key === 'ArrowDown' || event.key === 'ArrowUp' || event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
switch (event.key) {
// use up and down arrow keys to increase value;
case 'ArrowDown':
decreaseValue(event.target);
break;
case 'ArrowUp':
increaseValue(event.target);
break;
// use left and right arrow keys to shift focus;
case 'ArrowLeft':
shiftFocus(event.target, 'left');
break;
case 'ArrowRight':
shiftFocus(event.target, 'right');
break;
}
event.preventDefault(); // prevent default
}
if (isNaN(event.key) && !acceptedKeys.includes(event.key)) {
event.preventDefault(); // prevent default
return false;
}
};
// Ugrading the pickers
const _init = () => { // select all input fields with the attribute "html-duration-picker"
document.querySelectorAll('input[html-duration-picker]').forEach((picker) => {
// Set default text and Apply some basic styling to the picker
if (picker.getAttribute('data-upgraded') == 'true') {
return; // in case some developer calls this or includes it twice
}
const currentPickerStyle = picker.currentStyle || window.getComputedStyle(picker);
const pickerRightMargin = currentPickerStyle.marginRight;
const pickerLeftMargin = currentPickerStyle.marginLeft;
const totalPickerWidth = currentPickerStyle.width;
picker.setAttribute('data-upgraded', true);
picker.value = '00:00:00';
picker.style.textAlign = 'right';
picker.style.paddingRight = '20px';
picker.style.boxSizing = 'border-box';
picker.style.width = '100%';
picker.style.margin = 0;
picker.style.cursor = 'text';
picker.setAttribute('aria-label', 'Duration Picker');
picker.addEventListener('keydown', handleKeydown);
picker.addEventListener('select', selectFocus); // selects a block of hours, minutes etc
picker.addEventListener('mouseup', selectFocus); // selects a block of hours, minutes etc
picker.addEventListener('change', validateInput);
picker.addEventListener('blur', validateInput);
picker.addEventListener('keyup', validateInput);
picker.addEventListener('drop', (event) => event.preventDefault());
// These are the carets in the buttons.
// Can be replaced by images/font icons or text
const caretUp = document.createElement('div');
const caretDown = document.createElement('div');
caretUp.setAttribute('style', `width:0;height:0;
border-style:solid;border-width:0 4px 5px 4px; border-color:transparent transparent #000 transparent`);
caretDown.setAttribute('style', `width:0;height:0;
border-style:solid;border-width:5px 4px 0 4px; border-color:#000 transparent transparent transparent`);
// These are action buttons for scrolling values up or down
const scrollUpBtn = document.createElement('button');
const scrollDownBtn = document.createElement('button');
const scrollButtons = [scrollUpBtn, scrollDownBtn];
scrollUpBtn.setAttribute('aria-label', 'Increase duration');
scrollDownBtn.setAttribute('aria-label', 'Decrease duration');
scrollUpBtn.setAttribute('style', `text-align:center; width: 16px;padding: 0px 4px; border:none; cursor:default;
height:${(picker.offsetHeight/2)-1}px !important; position:absolute; top: 1px;`);
scrollDownBtn.setAttribute('style', `text-align:center; width: 16px;padding: 0px 4px; border:none; cursor:default;
height:${(picker.offsetHeight/2)-1}px !important; position:absolute; top: ${(picker.offsetHeight/2)-1}px;`);
// insert carets into buttons
scrollDownBtn.appendChild(caretDown);
scrollUpBtn.appendChild(caretUp);
// add event listeners to buttons
let intervalId;
scrollButtons.forEach((btn) => {
btn.addEventListener('mousedown', (event) => {
event.preventDefault();
if (btn == scrollUpBtn) {
increaseValue(picker);
intervalId = setInterval(increaseValue, 200, picker);
} else {
decreaseValue(picker);
intervalId = setInterval(decreaseValue, 200, picker);
}
});
btn.addEventListener('mouseup', () => {
clearInterval(intervalId);
});
btn.addEventListener('mouseleave', () => {
clearInterval(intervalId);
});
});
// this div houses the increase/decrease buttons
const controlsDiv = document.createElement('div');
controlsDiv.setAttribute('style', `display:inline-block; position: absolute;top:1px;left: ${parseFloat(totalPickerWidth) - 20}px;
height:${picker.offsetHeight}px; padding:2px 0`);
// add buttons to controls div;
controlsDiv.appendChild(scrollUpBtn);
controlsDiv.appendChild(scrollDownBtn);
// this div wraps around existing input, then appends control div
const controlWrapper = document.createElement('div');
controlWrapper.style.padding = '0px';
controlWrapper.style.display = 'inline-block';
controlWrapper.style.background = 'transparent';
controlWrapper.style.width = totalPickerWidth;
controlWrapper.style.position = 'relative';
controlWrapper.style.marginLeft = pickerLeftMargin;
controlWrapper.style.marginRight = pickerRightMargin;
picker.parentNode.insertBefore(controlWrapper, picker);
controlWrapper.appendChild(picker);
controlWrapper.appendChild(controlsDiv);
return;
});
return true;
};
// listen for document ready
window.addEventListener('DOMContentLoaded', () => {
_init();
});
return {
init: _init,
refresh: _init,
};
})();