-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
412 lines (336 loc) · 11.8 KB
/
script.js
File metadata and controls
412 lines (336 loc) · 11.8 KB
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
document.addEventListener("DOMContentLoaded", function () {
// DOM Elements
const sourceTimeInput = document.getElementById("sourceTime");
const targetTimeInput = document.getElementById("targetTime");
const swapBtn = document.getElementById("swap-btn");
const fromModeElement = document.getElementById("from-mode");
const toModeElement = document.getElementById("to-mode");
const sourceHint = document.getElementById("sourceHint");
const targetHint = document.getElementById("targetHint");
const ampmToggleContainer = document.getElementById("ampm-toggle");
const ampmSwitch = document.getElementById("ampm-switch");
const copyBtn = document.getElementById("copy-btn");
const clearBtn = document.getElementById("clear-btn");
const ampmIndicator = document.getElementById("ampm-indicator");
// App State
let is24to12Mode = true; // Default mode is 24-hour to 12-hour
// Initialize the app
function init() {
updateModeDisplay();
setupEventListeners();
// Set a default example
sourceTimeInput.value = "14:30";
convertTime();
updateAmPmIndicator();
}
// Set up event listeners
function setupEventListeners() {
// Input event for instant conversion with validation
sourceTimeInput.addEventListener("input", function (e) {
formatTimeInput(e.target);
convertTime();
});
// Swap button
swapBtn.addEventListener("click", toggleConversionMode);
// AM/PM toggle switch
ampmSwitch.addEventListener("change", function () {
updateAmPmIndicator();
convertTime();
});
// Copy button
copyBtn.addEventListener("click", copyToClipboard);
// Clear button
clearBtn.addEventListener("click", clearInputs);
// Quick example buttons
document.querySelectorAll(".example-btn").forEach((btn) => {
btn.addEventListener("click", function () {
sourceTimeInput.value = this.getAttribute("data-time");
convertTime();
});
});
// Keyboard shortcuts
document.addEventListener("keydown", handleKeyboardShortcuts);
}
// Feature 1: Copy to Clipboard
function copyToClipboard() {
const result = targetTimeInput.value;
if (!result || result.includes("Invalid")) {
return;
}
navigator.clipboard
.writeText(result)
.then(() => {
// Visual feedback
const originalIcon = copyBtn.innerHTML;
copyBtn.innerHTML = '<i class="fas fa-check"></i>';
copyBtn.classList.add("success");
setTimeout(() => {
copyBtn.innerHTML = originalIcon;
copyBtn.classList.remove("success");
}, 2000);
})
.catch((err) => {
console.error("Failed to copy: ", err);
});
}
// Feature 2: Input Validation & Formatting
function formatTimeInput(input) {
let value = input.value;
// Remove all non-digit and non-colon characters
value = value.replace(/[^0-9:]/g, "");
// If input contains a colon, format as HH:MM
if (value.includes(":")) {
const parts = value.split(":");
// Handle hours part (max 2 digits)
if (parts[0].length > 2) {
parts[0] = parts[0].substring(0, 2);
}
// Handle minutes part (max 2 digits)
if (parts[1] && parts[1].length > 2) {
parts[1] = parts[1].substring(0, 2);
}
value = parts.join(":");
// Set max length to 5 (HH:MM)
if (value.length > 5) {
value = value.substring(0, 5);
}
} else {
// No colon - just hours, limit to 2 digits
if (value.length > 2) {
value = value.substring(0, 2);
}
}
input.value = value;
}
// Feature 3: Keyboard Shortcuts
function handleKeyboardShortcuts(e) {
// Ctrl/Cmd + S to swap modes
if ((e.ctrlKey || e.metaKey) && e.key === "s") {
e.preventDefault();
toggleConversionMode();
}
// Ctrl/Cmd + C to copy result when target has focus
if ((e.ctrlKey || e.metaKey) && e.key === "c") {
// Check if target input has value and we're not in the middle of editing source
if (targetTimeInput.value && !targetTimeInput.value.includes("Invalid")) {
e.preventDefault();
copyToClipboard();
}
}
// Escape to clear both fields
if (e.key === "Escape") {
e.preventDefault();
clearInputs();
}
// Tab to toggle AM/PM when in 12-to-24 mode and source has focus
if (
e.key === "Tab" &&
!is24to12Mode &&
document.activeElement === sourceTimeInput
) {
e.preventDefault();
ampmSwitch.checked = !ampmSwitch.checked;
ampmSwitch.dispatchEvent(new Event("change"));
}
}
// Helper function: Clear inputs
function clearInputs() {
sourceTimeInput.value = "";
targetTimeInput.value = "";
sourceTimeInput.focus();
}
// Update AM/PM indicator
function updateAmPmIndicator() {
ampmIndicator.textContent = ampmSwitch.checked ? "PM" : "AM";
}
// Toggle between 24h-to-12h and 12h-to-24h modes
function toggleConversionMode() {
is24to12Mode = !is24to12Mode;
updateModeDisplay();
// Swap the values between source and target
const temp = sourceTimeInput.value;
sourceTimeInput.value = targetTimeInput.value;
targetTimeInput.value = temp;
// Trigger conversion with new source value
convertTime();
}
// Update mode display
function updateModeDisplay() {
if (is24to12Mode) {
// 24h to 12h mode
fromModeElement.textContent = "24-Hour";
toModeElement.textContent = "12-Hour";
ampmToggleContainer.style.display = "none";
sourceTimeInput.placeholder = "e.g., 14:30 or 14";
targetTimeInput.placeholder = "e.g., 2:30 PM";
sourceHint.textContent = "Format: HH:MM or HH (00-24)";
targetHint.textContent = "Converted time with AM/PM";
} else {
// 12h to 24h mode
fromModeElement.textContent = "12-Hour";
toModeElement.textContent = "24-Hour";
ampmToggleContainer.style.display = "flex";
sourceTimeInput.placeholder = "e.g., 2:30 or 2";
targetTimeInput.placeholder = "e.g., 14:30";
sourceHint.textContent = "Format: HH:MM or HH (1-12)";
targetHint.textContent = "Converted time (00-24)";
updateAmPmIndicator();
}
// Update the input field with current formatting rules
formatTimeInput(sourceTimeInput);
}
// Main conversion function
function convertTime() {
const sourceValue = sourceTimeInput.value.trim();
if (!sourceValue) {
targetTimeInput.value = "";
return;
}
try {
let result;
if (is24to12Mode) {
result = convert24to12(sourceValue);
} else {
result = convert12to24(sourceValue, !ampmSwitch.checked); // Note: checkbox checked means PM
}
targetTimeInput.value = result;
} catch (error) {
// Don't show errors while user is typing
// Only show error if input is clearly invalid
if (
sourceValue.length > 1 &&
!isValidPartialInput(sourceValue, is24to12Mode)
) {
targetTimeInput.value = "Invalid format";
} else {
targetTimeInput.value = "";
}
}
}
// Convert 24-hour format to 12-hour format
function convert24to12(timeStr) {
// Handle partial inputs gracefully
if (!timeStr || timeStr === ":") return "";
// Normalize input: remove spaces, handle different separators
timeStr = timeStr.replace(/\s/g, "").replace(/\./g, ":");
// If no colon is present, assume it's just hours and add :00
if (!timeStr.includes(":")) {
const hours = parseInt(timeStr, 10);
// Handle special cases
if (hours === 0) return "12:00 AM";
if (hours === 12) return "12:00 PM";
if (hours >= 0 && hours <= 24) {
const period = hours >= 12 ? "PM" : "AM";
const displayHours = hours % 12 || 12;
return `${displayHours}:00 ${period}`;
}
return "Invalid hour";
}
// Split into hours and minutes
const parts = timeStr.split(":");
if (parts.length !== 2) return "Invalid format";
let hours = parseInt(parts[0], 10);
let minutes = parseInt(parts[1], 10);
// If minutes are NaN or empty, default to 00
if (isNaN(minutes) || parts[1] === "") {
minutes = 0;
}
// Validate hours and minutes
if (isNaN(hours) || hours < 0 || hours > 24) return "Invalid hour";
if (minutes < 0 || minutes > 59) return "Invalid minute";
// Handle special cases
if (hours === 0 && minutes === 0) return "12:00 AM";
if (hours === 12 && minutes === 0) return "12:00 PM";
// Convert to 12-hour format
const period = hours >= 12 ? "PM" : "AM";
const displayHours = hours % 12 || 12;
// Format minutes with leading zero if needed
const formattedMinutes = minutes < 10 ? `0${minutes}` : minutes.toString();
return `${displayHours}:${formattedMinutes} ${period}`;
}
// Convert 12-hour format to 24-hour format
function convert12to24(timeStr, isAm) {
// Handle partial inputs gracefully
if (!timeStr || timeStr === ":") return "";
// Normalize input: remove spaces, handle different separators
timeStr = timeStr.replace(/\s/g, "").replace(/\./g, ":");
// If no colon is present, assume it's just hours and add :00
if (!timeStr.includes(":")) {
const hours = parseInt(timeStr, 10);
if (hours >= 1 && hours <= 12) {
let militaryHours = hours;
// Handle 12 AM and 12 PM special cases
if (isAm) {
militaryHours = hours === 12 ? 0 : hours;
} else {
militaryHours = hours === 12 ? 12 : hours + 12;
}
return `${militaryHours < 10 ? "0" : ""}${militaryHours}:00`;
}
return "Invalid hour";
}
// Split into hours and minutes
const parts = timeStr.split(":");
if (parts.length !== 2) return "Invalid format";
let hours = parseInt(parts[0], 10);
let minutes = parseInt(parts[1], 10);
// If minutes are NaN or empty, default to 00
if (isNaN(minutes) || parts[1] === "") {
minutes = 0;
}
// Validate hours and minutes
if (isNaN(hours) || hours < 1 || hours > 12) return "Invalid hour";
if (minutes < 0 || minutes > 59) return "Invalid minute";
// Convert to 24-hour format
let militaryHours = hours;
if (isAm) {
// AM: 12 AM becomes 0, others stay the same
militaryHours = hours === 12 ? 0 : hours;
} else {
// PM: 12 PM stays 12, others add 12
militaryHours = hours === 12 ? 12 : hours + 12;
}
// Format with leading zeros
const formattedHours =
militaryHours < 10 ? `0${militaryHours}` : militaryHours.toString();
const formattedMinutes = minutes < 10 ? `0${minutes}` : minutes.toString();
return `${formattedHours}:${formattedMinutes}`;
}
// Check if input is valid while user is still typing
function isValidPartialInput(input, is24to12) {
if (!input) return true;
// Remove any spaces
input = input.replace(/\s/g, "");
// If no colon, check if it's a valid number
if (!input.includes(":")) {
const num = parseInt(input, 10);
if (is24to12) {
// For 24-hour input
return !isNaN(num) && num >= 0 && num <= 24;
} else {
// For 12-hour input, allow 1-12
return !isNaN(num) && num >= 1 && num <= 12;
}
}
// If colon is present, check both parts
const parts = input.split(":");
if (parts.length > 2) return false;
const hours = parseInt(parts[0], 10);
const minutes = parts[1] ? parseInt(parts[1], 10) : 0;
if (isNaN(hours)) return false;
if (is24to12) {
// For 24-hour input
if (hours < 0 || hours > 24) return false;
} else {
// For 12-hour input
if (hours < 1 || hours > 12) return false;
}
// Check minutes if they exist
if (parts[1] && (isNaN(minutes) || minutes < 0 || minutes > 59)) {
return false;
}
return true;
}
// Initialize the app
init();
});