-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
769 lines (712 loc) · 26.3 KB
/
Copy pathscript.js
File metadata and controls
769 lines (712 loc) · 26.3 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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
// script.js
(() => {
const { DateTime } = luxon;
const baseTzSelect = document.getElementById("base-tz");
const targetTzSelect = document.getElementById("target-tz");
const timezoneSearch = document.getElementById("timezone-search");
const tzSelectedFeedback = document.getElementById("target-tz-selected");
const dateInput = document.getElementById("date");
const timeInput = document.getElementById("time");
const endDateInput = document.getElementById("end-date");
const endTimeInput = document.getElementById("end-time");
const eventNameInput = document.getElementById("event-name");
const eventLocationInput = document.getElementById("event-location");
const eventDetailsInput = document.getElementById("event-details");
const eventDurationSelect = document.getElementById("event-duration");
const customDurationGroup = document.getElementById("custom-duration-group");
const customDurationInput = document.getElementById("custom-duration");
const inviteesContainer = document.getElementById("invitees-container");
const addInviteeButton = document.getElementById("add-invitee");
const generateButton = document.getElementById("generate");
const allDayCheckbox = document.getElementById("all-day-event");
const timedEventFields = document.getElementById("timed-event-fields");
const durationFields = document.getElementById("duration-fields");
const endtimeFields = document.getElementById("endtime-fields");
const endTypeRadios = document.getElementsByName("end-type");
const baseTzSearch = document.getElementById("base-tz-search");
const tzTableContainer = document.getElementById("tz-table-container");
const tzTable = document.getElementById("tz-table");
const tzTableBody = tzTable ? tzTable.querySelector("tbody") : null;
const originTzHeader = document.getElementById("origin-tz-header");
const targetTzHeader = document.getElementById("target-tz-header");
const additionalTimezonesContainer = document.getElementById(
"additional-timezones"
);
const addTimezoneButton = document.getElementById("add-timezone");
// Set default date to today
dateInput.valueAsDate = new Date();
if (endDateInput) endDateInput.valueAsDate = new Date();
// Common city timezones to ensure they're included
const commonCityTimezones = [
"Asia/Tel_Aviv",
"Asia/Jerusalem",
"America/New_York",
"America/Los_Angeles",
"America/Chicago",
"Europe/London",
"Europe/Paris",
"Europe/Berlin",
"Asia/Tokyo",
"Asia/Shanghai",
"Asia/Singapore",
"Australia/Sydney",
"Pacific/Auckland",
"Asia/Dubai",
"Asia/Kolkata",
"Europe/Moscow",
"America/Sao_Paulo",
"Africa/Johannesburg",
"Asia/Bangkok",
"Asia/Seoul",
];
// Get GMT offset for a timezone
function getGMTOffset(timezone) {
try {
const now = DateTime.now().setZone(timezone);
const offset = now.toFormat("ZZZZ");
return offset;
} catch (e) {
return "Unknown";
}
}
// Format timezone option text with GMT offset and pretty city name
function formatTimezoneOption(timezone) {
const offset = getGMTOffset(timezone);
// Replace underscores with spaces for display
const prettyTz = timezone.replace(/_/g, " ");
return `${prettyTz} (${offset})`;
}
// Detect user's timezone with fallbacks
function detectUserTimezone() {
try {
const browserTz = Intl.DateTimeFormat().resolvedOptions().timeZone;
if (browserTz) return browserTz;
} catch (e) {
console.warn("Browser timezone detection failed:", e);
}
try {
const date = new Date();
const offset = -date.getTimezoneOffset();
const hours = Math.floor(Math.abs(offset) / 60);
const minutes = Math.abs(offset) % 60;
const sign = offset >= 0 ? "+" : "-";
const gmtOffset = `GMT${sign}${hours
.toString()
.padStart(2, "0")}:${minutes.toString().padStart(2, "0")}`;
const matchingTz = commonCityTimezones.find((tz) => {
try {
return DateTime.now().setZone(tz).toFormat("ZZZZ") === gmtOffset;
} catch (e) {
return false;
}
});
if (matchingTz) return matchingTz;
} catch (e) {
console.warn("System time fallback failed:", e);
}
return "America/New_York";
}
// Get all available timezones
let allTimeZones = [];
try {
allTimeZones = Intl.supportedValuesOf("timeZone");
} catch (e) {
console.warn("Failed to get supported timezones:", e);
allTimeZones = commonCityTimezones;
}
allTimeZones = [...new Set([...commonCityTimezones, ...allTimeZones])];
allTimeZones.sort();
// Populate time zones
function populateTimeZones() {
const userTimezone = detectUserTimezone();
// Populate both selects
allTimeZones.forEach((tz) => {
const baseOption = document.createElement("option");
const targetOption = document.createElement("option");
baseOption.value = targetOption.value = tz;
baseOption.textContent = targetOption.textContent =
formatTimezoneOption(tz);
// Store searchable text for each option (with and without underscores)
baseOption.setAttribute(
"data-search",
`${tz.toLowerCase()} ${tz.replace(/_/g, " ").toLowerCase()}`
);
targetOption.setAttribute(
"data-search",
`${tz.toLowerCase()} ${tz.replace(/_/g, " ").toLowerCase()}`
);
baseTzSelect.appendChild(baseOption);
targetTzSelect.appendChild(targetOption);
});
baseTzSelect.value = userTimezone;
targetTzSelect.value = "UTC";
updateTzSelectedFeedback();
generateTzTable();
}
// --- Target Time Zone Selection Feedback ---
function updateTzSelectedFeedback() {
const selected = targetTzSelect.options[targetTzSelect.selectedIndex];
if (selected) {
tzSelectedFeedback.textContent = `Selected: ${selected.textContent}`;
} else {
tzSelectedFeedback.textContent = "";
}
}
// When user clicks or changes selection in the target time zone
targetTzSelect.addEventListener("change", () => {
collapseTargetList();
updateTzSelectedFeedback();
generateTzTable();
});
targetTzSelect.addEventListener("click", () => {
collapseTargetList();
updateTzSelectedFeedback();
generateTzTable();
});
targetTzSelect.addEventListener("keyup", () => {
updateTzSelectedFeedback();
generateTzTable();
});
// When user types in the search, filter and auto-select first visible
timezoneSearch.addEventListener("input", (e) => {
filterTimezones(e.target.value);
// Auto-select first visible option
const firstVisible = Array.from(targetTzSelect.options).find(
(opt) => opt.style.display !== "none"
);
if (firstVisible) {
targetTzSelect.value = firstVisible.value;
updateTzSelectedFeedback();
}
});
function filterTimezones(searchTerm) {
const options = targetTzSelect.options;
searchTerm = searchTerm.toLowerCase().replace(/ /g, "_");
for (let i = 0; i < options.length; i++) {
const option = options[i];
// Search both the original and pretty version
const searchAttr = option.getAttribute("data-search");
const prettyText = option.textContent.toLowerCase();
// Allow search by either underscores or spaces
const searchMatch =
searchAttr.includes(searchTerm.replace(/_/g, " ")) ||
searchAttr.includes(searchTerm) ||
prettyText.includes(searchTerm.replace(/_/g, " ")) ||
prettyText.includes(searchTerm);
option.style.display = searchMatch ? "" : "none";
}
}
// --- All Day Event Logic ---
allDayCheckbox.addEventListener("change", function () {
if (allDayCheckbox.checked) {
timedEventFields.setAttribute("hidden", "");
} else {
timedEventFields.removeAttribute("hidden");
}
});
// --- Duration vs End Time Toggle ---
function updateEndTypeFields() {
const endType = Array.from(endTypeRadios).find((r) => r.checked).value;
if (endType === "duration") {
durationFields.removeAttribute("hidden");
endtimeFields.setAttribute("hidden", "");
} else {
durationFields.setAttribute("hidden", "");
endtimeFields.removeAttribute("hidden");
// Always set end date to start date if not set
if (
dateInput.value &&
(!endDateInput.value || endDateInput.value < dateInput.value)
) {
endDateInput.value = dateInput.value;
}
}
}
endTypeRadios.forEach((radio) =>
radio.addEventListener("change", updateEndTypeFields)
);
// Ensure correct fields are shown on page load
updateEndTypeFields();
// --- End Date Auto-Update Logic ---
function updateEndDateIfNeeded() {
if (!dateInput.value || !timeInput.value) return;
if (!endTimeInput.value) return;
const start = DateTime.fromFormat(
`${dateInput.value} ${timeInput.value}`,
"yyyy-MM-dd HH:mm"
);
const end = DateTime.fromFormat(
`${endDateInput.value} ${endTimeInput.value}`,
"yyyy-MM-dd HH:mm"
);
if (end < start) {
// If end is before start, set end date to next day
const nextDay = start.plus({ days: 1 }).toFormat("yyyy-MM-dd");
endDateInput.value = nextDay;
}
}
if (endTimeInput && endDateInput) {
timeInput.addEventListener("change", updateEndDateIfNeeded);
dateInput.addEventListener("change", function () {
endDateInput.value = dateInput.value;
updateEndDateIfNeeded();
});
endTimeInput.addEventListener("change", updateEndDateIfNeeded);
}
eventDurationSelect.addEventListener("change", () => {
customDurationGroup.style.display =
eventDurationSelect.value === "custom" ? "block" : "none";
});
function addInviteeRow() {
const row = document.createElement("div");
row.className = "invitee-row";
const emailInput = document.createElement("input");
emailInput.type = "email";
emailInput.className = "invitee-email";
emailInput.placeholder = "email@example.com";
const removeButton = document.createElement("button");
removeButton.type = "button";
removeButton.className = "remove-invitee";
removeButton.textContent = "×";
removeButton.style.display = "block";
removeButton.addEventListener("click", () => {
row.remove();
updateRemoveButtons();
});
row.appendChild(emailInput);
row.appendChild(removeButton);
inviteesContainer.appendChild(row);
updateRemoveButtons();
}
function updateRemoveButtons() {
const rows = inviteesContainer.querySelectorAll(".invitee-row");
rows.forEach((row) => {
const removeButton = row.querySelector(".remove-invitee");
removeButton.style.display = rows.length > 1 ? "block" : "none";
});
}
addInviteeButton.addEventListener("click", addInviteeRow);
function generateICS() {
// All Day Event
if (allDayCheckbox.checked) {
const eventName = eventNameInput.value;
const eventLocation = eventLocationInput.value;
const eventDetails = eventDetailsInput.value;
const baseTz = baseTzSelect.value;
const targetTz = targetTzSelect.value;
const date = dateInput.value;
const invitees = Array.from(document.querySelectorAll(".invitee-email"))
.map((input) => input.value)
.filter((email) => email.trim() !== "");
// All day event: DTSTART/DTEND as DATE only
const icsContent = [
"BEGIN:VCALENDAR",
"VERSION:2.0",
"PRODID:-//TimeSync//EN",
"CALSCALE:GREGORIAN",
"BEGIN:VEVENT",
`DTSTART;VALUE=DATE:${date.replace(/-/g, "")}`,
`DTEND;VALUE=DATE:${date.replace(/-/g, "")}`,
`SUMMARY:${eventName}`,
`LOCATION:${eventLocation}`,
`DESCRIPTION:${eventDetails}`,
...invitees.map(
(email) => `ATTENDEE;RSVP=TRUE;ROLE=REQ-PARTICIPANT:mailto:${email}`
),
"END:VEVENT",
"END:VCALENDAR",
].join("\r\n");
const blob = new Blob([icsContent], {
type: "text/calendar;charset=utf-8",
});
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = `${eventName
.replace(/[^a-z0-9]/gi, "_")
.toLowerCase()}.ics`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
return;
}
// Timed Event
const eventName = eventNameInput.value;
const eventLocation = eventLocationInput.value;
const eventDetails = eventDetailsInput.value;
const baseTz = baseTzSelect.value;
const targetTz = targetTzSelect.value;
const date = dateInput.value;
const time = timeInput.value;
let startTime = DateTime.fromFormat(`${date} ${time}`, "yyyy-MM-dd HH:mm", {
zone: baseTz,
});
let endTime;
let endDate;
// Duration or End Time
const endType = Array.from(endTypeRadios).find((r) => r.checked).value;
if (endType === "duration") {
let durationMinutes = parseInt(eventDurationSelect.value);
if (eventDurationSelect.value === "custom") {
durationMinutes = parseInt(customDurationInput.value);
}
endTime = startTime.plus({ minutes: durationMinutes });
endDate = endTime.toFormat("yyyy-MM-dd");
} else {
// End time and end date
const endDateVal = endDateInput.value || date;
const endTimeVal = endTimeInput.value || time;
endTime = DateTime.fromFormat(
`${endDateVal} ${endTimeVal}`,
"yyyy-MM-dd HH:mm",
{ zone: baseTz }
);
endDate = endDateVal;
// If end is before start, auto-increment end date
if (endTime < startTime) {
endTime = startTime.plus({ days: 1 });
endDate = endTime.toFormat("yyyy-MM-dd");
}
}
// Convert to target timezone
const targetStartTime = startTime.setZone(targetTz);
const targetEndTime = endTime.setZone(targetTz);
const invitees = Array.from(document.querySelectorAll(".invitee-email"))
.map((input) => input.value)
.filter((email) => email.trim() !== "");
const icsContent = [
"BEGIN:VCALENDAR",
"VERSION:2.0",
"PRODID:-//TimeSync//EN",
"CALSCALE:GREGORIAN",
"BEGIN:VEVENT",
`DTSTART;TZID=${targetTz}:${targetStartTime.toFormat(
"yyyyMMdd'T'HHmmss"
)}`,
`DTEND;TZID=${targetTz}:${targetEndTime.toFormat("yyyyMMdd'T'HHmmss")}`,
`SUMMARY:${eventName}`,
`LOCATION:${eventLocation}`,
`DESCRIPTION:${eventDetails}`,
...invitees.map(
(email) => `ATTENDEE;RSVP=TRUE;ROLE=REQ-PARTICIPANT:mailto:${email}`
),
"END:VEVENT",
"END:VCALENDAR",
].join("\r\n");
const blob = new Blob([icsContent], {
type: "text/calendar;charset=utf-8",
});
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = `${eventName
.replace(/[^a-z0-9]/gi, "_")
.toLowerCase()}.ics`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
populateTimeZones();
generateButton.addEventListener("click", generateICS);
updateEndTypeFields();
// --- Base Time Zone Search ---
function filterBaseTimezones(searchTerm) {
const options = baseTzSelect.options;
searchTerm = searchTerm.toLowerCase().replace(/ /g, "_");
for (let i = 0; i < options.length; i++) {
const option = options[i];
const searchAttr = option.getAttribute("data-search");
const prettyText = option.textContent.toLowerCase();
const searchMatch =
searchAttr.includes(searchTerm.replace(/_/g, " ")) ||
searchAttr.includes(searchTerm) ||
prettyText.includes(searchTerm.replace(/_/g, " ")) ||
prettyText.includes(searchTerm);
option.style.display = searchMatch ? "" : "none";
}
}
baseTzSearch.addEventListener("input", (e) => {
filterBaseTimezones(e.target.value);
// Auto-select first visible option
const firstVisible = Array.from(baseTzSelect.options).find(
(opt) => opt.style.display !== "none"
);
if (firstVisible) {
baseTzSelect.value = firstVisible.value;
}
});
// Close search bar on selection
baseTzSelect.addEventListener("change", function () {
baseTzSearch.value = "";
baseTzSearch.blur();
});
baseTzSelect.addEventListener("click", function () {
baseTzSearch.value = "";
baseTzSearch.blur();
});
baseTzSelect.addEventListener("keyup", function (e) {
if (e.key === "Enter" || e.key === "Tab") {
baseTzSearch.value = "";
baseTzSearch.blur();
}
});
// Helper to collapse/expand target select
function showTargetSelect(expand) {
if (expand) {
targetTzSelect.size = 5;
targetTzSelect.style.display = "";
} else {
targetTzSelect.size = 1;
targetTzSelect.style.display = "";
}
}
// Expand list when searching
timezoneSearch.addEventListener("focus", () => showTargetSelect(true));
timezoneSearch.addEventListener("input", () => showTargetSelect(true));
// Collapse list when a timezone is chosen
function collapseTargetList() {
showTargetSelect(false);
timezoneSearch.value = "";
timezoneSearch.blur();
}
// --- Time Zone Comparison Table ---
function generateTzTable() {
if (!tzTableBody) return;
tzTableBody.innerHTML = "";
const originTz = baseTzSelect.value;
const targetTz = targetTzSelect.value;
const additionalTzs = Array.from(
document.querySelectorAll(".timezone-select")
).map((select) => select.value);
let date = dateInput.value;
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
date = DateTime.now().toFormat("yyyy-MM-dd");
}
// Update headers
const headerRow = document.createElement("tr");
const originHeader = document.createElement("th");
originHeader.textContent = formatTimezoneOption(originTz);
headerRow.appendChild(originHeader);
const targetHeader = document.createElement("th");
targetHeader.textContent = formatTimezoneOption(targetTz);
headerRow.appendChild(targetHeader);
additionalTzs.forEach((tz) => {
const th = document.createElement("th");
th.textContent = formatTimezoneOption(tz);
headerRow.appendChild(th);
});
tzTable.querySelector("thead").innerHTML = "";
tzTable.querySelector("thead").appendChild(headerRow);
// Starting point: midnight in origin tz
let startOfDay = DateTime.fromFormat(`${date} 00:00`, "yyyy-MM-dd HH:mm", {
zone: originTz,
});
if (!startOfDay.isValid) {
startOfDay = DateTime.now().setZone(originTz).startOf("day");
}
// Determine selected row index for highlighting
let selectedRowIndex = -1;
if (timeInput.value) {
const selectedTime = DateTime.fromFormat(
`${date} ${timeInput.value}`,
"yyyy-MM-dd HH:mm",
{ zone: originTz }
);
if (selectedTime.isValid) {
const diffMinutes = selectedTime.diff(startOfDay, "minutes").minutes;
selectedRowIndex = Math.round(diffMinutes / 15);
}
}
const rowsFragment = document.createDocumentFragment();
for (let i = 0; i < 96; i++) {
const originTime = startOfDay.plus({ minutes: 15 * i });
const tr = document.createElement("tr");
tr.dataset.index = i;
const inSelectedRange = selectedRowIndex !== -1 && i === selectedRowIndex;
if (inSelectedRange) tr.classList.add("selected");
// Origin time
const tdOrigin = document.createElement("td");
tdOrigin.textContent = originTime.toFormat("HH:mm");
tr.appendChild(tdOrigin);
// Target time
const tdTarget = document.createElement("td");
tdTarget.textContent = originTime.setZone(targetTz).toFormat("HH:mm");
tr.appendChild(tdTarget);
// Additional timezones
additionalTzs.forEach((tz) => {
const td = document.createElement("td");
td.textContent = originTime.setZone(tz).toFormat("HH:mm");
tr.appendChild(td);
});
const clickHandler = () => {
selectedStartIndex = i;
selectedEndIndex = i;
timeInput.value = originTime.toFormat("HH:mm");
dateInput.value = originTime.toFormat("yyyy-MM-dd");
const nextTime = originTime.plus({ minutes: 15 });
endTimeInput.value = nextTime.toFormat("HH:mm");
endDateInput.value = nextTime.toFormat("yyyy-MM-dd");
document.querySelector(
'input[name="end-type"][value="endtime"]'
).checked = true;
updateEndTypeFields();
generateTzTable();
};
tr.addEventListener("click", clickHandler);
rowsFragment.appendChild(tr);
}
tzTableBody.appendChild(rowsFragment);
}
// Regenerate table on relevant changes
[baseTzSelect, targetTzSelect, dateInput].forEach((el) => {
if (el) el.addEventListener("change", generateTzTable);
});
if (timeInput) timeInput.addEventListener("change", generateTzTable);
// Also regenerate on search selection
baseTzSelect.addEventListener("change", generateTzTable);
targetTzSelect.addEventListener("change", generateTzTable);
dateInput.addEventListener("change", generateTzTable);
// Variables for drag selection
let dragStartIndex = null;
let dragCurrentIndex = null;
let isDragging = false;
let selectedStartIndex = null;
let selectedEndIndex = null;
function updateRangeHighlight() {
Array.from(tzTableBody.children).forEach((row) => {
const idx = parseInt(row.dataset.index, 10);
const inDragRange =
isDragging &&
dragStartIndex !== null &&
dragCurrentIndex !== null &&
idx >= Math.min(dragStartIndex, dragCurrentIndex) &&
idx <= Math.max(dragStartIndex, dragCurrentIndex);
const inSelectedRange =
selectedStartIndex !== null &&
selectedEndIndex !== null &&
idx >= selectedStartIndex &&
idx <= selectedEndIndex;
row.classList.toggle("range-selected", inDragRange || inSelectedRange);
});
}
function finalizeSelection() {
if (dragStartIndex === null || dragCurrentIndex === null) return;
selectedStartIndex = Math.min(dragStartIndex, dragCurrentIndex);
selectedEndIndex = Math.max(dragStartIndex, dragCurrentIndex);
const originTz = baseTzSelect.value;
let date = dateInput.value;
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
date = DateTime.now().toFormat("yyyy-MM-dd");
}
let startOfDay = DateTime.fromFormat(`${date} 00:00`, "yyyy-MM-dd HH:mm", {
zone: originTz,
});
if (!startOfDay.isValid)
startOfDay = DateTime.now().setZone(originTz).startOf("day");
const startTime = startOfDay.plus({ minutes: 15 * selectedStartIndex });
const endTime = startOfDay.plus({ minutes: 15 * (selectedEndIndex + 1) });
// Update form fields
timeInput.value = startTime.toFormat("HH:mm");
dateInput.value = startTime.toFormat("yyyy-MM-dd");
endTimeInput.value = endTime.toFormat("HH:mm");
endDateInput.value = endTime.toFormat("yyyy-MM-dd");
// Switch to End Time mode
document.querySelector(
'input[name="end-type"][value="endtime"]'
).checked = true;
updateEndTypeFields();
generateTzTable(); // refresh highlights
}
// Event delegation for drag selection
tzTableBody.addEventListener("mousedown", (e) => {
const tr = e.target.closest("tr");
if (!tr) return;
isDragging = true;
dragStartIndex = parseInt(tr.dataset.index, 10);
dragCurrentIndex = dragStartIndex;
updateRangeHighlight();
});
tzTableBody.addEventListener("mouseover", (e) => {
if (!isDragging) return;
const tr = e.target.closest("tr");
if (!tr) return;
dragCurrentIndex = parseInt(tr.dataset.index, 10);
updateRangeHighlight();
});
document.addEventListener("mouseup", () => {
if (!isDragging) return;
isDragging = false;
finalizeSelection();
dragStartIndex = dragCurrentIndex = null;
});
// Add timezone row
function addTimezoneRow() {
const timezoneId = `tz-${Date.now()}`;
const row = document.createElement("div");
row.className = "field-group additional-timezone";
row.innerHTML = `
<div class="timezone-header">
<label>Additional Time Zone</label>
<button type="button" class="remove-timezone" data-timezone="${timezoneId}">×</button>
</div>
<input type="text" class="timezone-search" placeholder="Search timezone..." />
<select class="timezone-select" id="${timezoneId}" size="5"></select>
<div class="tz-selected-feedback"></div>
`;
// Populate the select with timezones
const select = row.querySelector(".timezone-select");
allTimeZones.forEach((tz) => {
const option = document.createElement("option");
option.value = tz;
option.textContent = formatTimezoneOption(tz);
option.setAttribute(
"data-search",
`${tz.toLowerCase()} ${tz.replace(/_/g, " ").toLowerCase()}`
);
select.appendChild(option);
});
// Add event listeners
const searchInput = row.querySelector(".timezone-search");
const removeButton = row.querySelector(".remove-timezone");
const feedback = row.querySelector(".tz-selected-feedback");
searchInput.addEventListener("input", (e) => {
filterAdditionalTimezone(e.target.value, select);
const firstVisible = Array.from(select.options).find(
(opt) => opt.style.display !== "none"
);
if (firstVisible) {
select.value = firstVisible.value;
feedback.textContent = `Selected: ${firstVisible.textContent}`;
generateTzTable();
}
});
removeButton.addEventListener("click", () => {
row.remove();
generateTzTable();
});
select.addEventListener("change", () => {
const selected = select.options[select.selectedIndex];
if (selected) {
feedback.textContent = `Selected: ${selected.textContent}`;
generateTzTable();
}
});
additionalTimezonesContainer.appendChild(row);
generateTzTable();
}
function filterAdditionalTimezone(searchTerm, select) {
const options = select.options;
searchTerm = searchTerm.toLowerCase().replace(/ /g, "_");
for (let i = 0; i < options.length; i++) {
const option = options[i];
const searchAttr = option.getAttribute("data-search");
const prettyText = option.textContent.toLowerCase();
const searchMatch =
searchAttr.includes(searchTerm.replace(/_/g, " ")) ||
searchAttr.includes(searchTerm) ||
prettyText.includes(searchTerm.replace(/_/g, " ")) ||
prettyText.includes(searchTerm);
option.style.display = searchMatch ? "" : "none";
}
}
// Add event listener for the add timezone button
addTimezoneButton.addEventListener("click", addTimezoneRow);
})();