Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
401 lines (349 loc) · 14.6 KB
/
Copy pathapp.js
File metadata and controls
401 lines (349 loc) · 14.6 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
'use strict';
const DateTime = luxon.DateTime;
let barsData = [];
let currentTimeIntervals = [];
let renderVersion = 0;
let overrideDate = ''; // empty => local "today" per bar
const newBarBubble = document.getElementById('new-bar-bubble');
const newBarBubbleLocationInput = document.getElementById('new-bar-bubble-location-input');
const newBarBubbleSubmitBtn = document.getElementById('new-bar-bubble-submit');
const newBarBubbleCancelBtn = document.getElementById('new-bar-bubble-cancel');
const dateOverrideInput = document.getElementById('date-override-input');
const errorMessage = document.getElementById('error-message');
const barsContainer = document.getElementById('bars-container');
function getLocationsFromURL() {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.getAll('location');
}
function updateURLWithLocations() {
const urlParams = new URLSearchParams(window.location.search);
urlParams.delete('location');
barsData.forEach(bar => {
if (bar.location && bar.location.trim() !== '') {
urlParams.append('location', bar.location.trim());
}
});
const newUrl = window.location.pathname + (urlParams.size ? '?' + urlParams.toString() : '') + window.location.hash;
window.history.replaceState({}, '', newUrl);
}
async function fetchJSON(url, signal) {
const response = await fetch(url, { signal });
if (!response.ok) throw new Error(`Request failed (${response.status}).`);
return response.json();
}
async function fetchCoordinates(locationString, signal) {
const data = await fetchJSON(
`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(locationString)}&format=json&limit=1`, signal);
if (!Array.isArray(data) || !data.length) throw new Error('Location not found.');
const latitude = Number(data[0].lat);
const longitude = Number(data[0].lon);
if (!Number.isFinite(latitude) || Math.abs(latitude) > 90 ||
!Number.isFinite(longitude) || Math.abs(longitude) > 180) {
throw new Error('Invalid location coordinates.');
}
return { latitude, longitude, displayName: data[0].display_name,
timeZone: tzlookup(latitude, longitude) };
}
async function fetchSunTimes(lat, lon, date, signal) {
const data = await fetchJSON(
`https://api.sunrise-sunset.org/json?lat=${lat}&lng=${lon}&formatted=0&date=${date}`, signal);
if (data.status !== 'OK' || !data.results) throw new Error('Unable to fetch sun times.');
return data.results;
}
function formatTimeMinutes(dt) {
return dt?.isValid ? dt.toFormat('HH:mm') : 'N/A';
}
function removeBar(index) {
if (currentTimeIntervals[index]) {
clearInterval(currentTimeIntervals[index]);
currentTimeIntervals[index] = null;
}
barsData[index].controller?.abort();
barsData.splice(index, 1);
renderAllBars();
updateURLWithLocations();
}
function addNewBar(locationString) {
errorMessage.textContent = '';
barsData.push({ location: locationString });
renderAllBars();
updateURLWithLocations();
}
function showNewBarBubble(addButtonRect) {
newBarBubble.style.display = 'block';
const bubbleWidth = newBarBubble.offsetWidth;
const offsetY = 10;
if (window.innerWidth <= 900) {
const bubbleLeft = (addButtonRect.right + window.scrollX) - bubbleWidth;
const bubbleTop = (addButtonRect.bottom + window.scrollY + offsetY);
newBarBubble.style.left = bubbleLeft + 'px';
newBarBubble.style.top = bubbleTop + 'px';
const arrowLeft = bubbleWidth - 28;
newBarBubble.style.setProperty('--arrow-left', arrowLeft + 'px');
} else {
const plusCenterX = addButtonRect.left + (addButtonRect.width / 2);
const desiredLeft = (plusCenterX - (bubbleWidth / 2)) + window.scrollX;
newBarBubble.style.left = desiredLeft + 'px';
newBarBubble.style.top = (addButtonRect.bottom + window.scrollY + offsetY) + 'px';
const arrowLeft = (bubbleWidth / 2) - 8;
newBarBubble.style.setProperty('--arrow-left', arrowLeft + 'px');
}
newBarBubbleLocationInput.value = '';
newBarBubbleLocationInput.focus();
}
function hideNewBarBubble() {
newBarBubble.style.display = 'none';
}
function submitNewBarBubble() {
const loc = newBarBubbleLocationInput.value.trim();
if (!loc) {
alert('Please enter a location.');
return;
}
hideNewBarBubble();
addNewBar(loc);
}
async function renderAllBars() {
const version = ++renderVersion;
barsData.forEach(bar => bar.controller?.abort());
// 1) Clear any running intervals (so we don’t have leftover updaters).
currentTimeIntervals.forEach(intervalId => {
if (intervalId) clearInterval(intervalId);
});
currentTimeIntervals = [];
// 2) Clear the container DOM
barsContainer.innerHTML = '';
// 3) Rebuild the bars
for (let i = 0; i < barsData.length; i++) {
const barDOM = createTimeBarDOM(i);
barsContainer.appendChild(barDOM);
}
// 4) If exactly 1 bar, center it in mobile mode
if (barsData.length === 1) {
barsContainer.classList.add('single-bar-only');
} else {
barsContainer.classList.remove('single-bar-only');
}
// 5) Add the + button at the end
const addButtonItem = createAddBarButtonDOM();
barsContainer.appendChild(addButtonItem);
// 6) Initialize each bar (and create intervals anew)
for (let i = 0; i < barsData.length; i++) {
if (version !== renderVersion) return;
await initializeBar(i);
}
}
function createAddBarButtonDOM() {
const container = document.createElement('div');
container.className = 'add-bar-button-container';
const button = document.createElement('button');
button.id = 'add-bar-button';
button.textContent = '+';
button.title = 'Add a new bar';
button.addEventListener('click', () => {
const rect = button.getBoundingClientRect();
showNewBarBubble(rect);
});
container.appendChild(button);
return container;
}
function createTimeBarDOM(barId) {
const barContainer = document.createElement('div');
barContainer.className = 'time-bar';
barContainer.id = `time-bar-${barId}`;
const closeBtn = document.createElement('button');
closeBtn.className = 'close-bar-button';
closeBtn.textContent = 'x';
closeBtn.title = 'Remove this bar';
closeBtn.addEventListener('click', () => removeBar(barId));
barContainer.appendChild(closeBtn);
const barControlsDiv = document.createElement('div');
barControlsDiv.className = 'bar-controls';
const locInput = document.createElement('input');
locInput.className = 'location-input';
locInput.type = 'text';
locInput.setAttribute('aria-label', 'Location');
locInput.value = barsData[barId].location || '';
locInput.addEventListener('change', async (e) => {
barsData[barId].location = e.target.value.trim();
updateURLWithLocations();
await initializeBar(barId);
});
barControlsDiv.appendChild(locInput);
const infoDiv = document.createElement('div');
infoDiv.className = 'info';
infoDiv.id = `info-${barId}`;
const timeLineContainer = document.createElement('div');
timeLineContainer.className = 'time-line-container';
const backgroundTypes = [
['morning-night', 'morning-night-background'],
['morning-civil', 'morning-civil-twilight-background'],
['day-bg', 'day-background'],
['evening-civil', 'evening-civil-twilight-background'],
['evening-night', 'evening-night-background'],
];
for (const [id, className] of backgroundTypes) {
const background = document.createElement('div');
background.className = `day-night-background ${className}`;
background.id = `${id}-${barId}`;
timeLineContainer.appendChild(background);
}
const timeLine = document.createElement('div');
timeLine.className = 'time-line';
timeLine.id = `time-line-${barId}`;
timeLineContainer.appendChild(timeLine);
barContainer.appendChild(barControlsDiv);
barContainer.appendChild(infoDiv);
barContainer.appendChild(timeLineContainer);
return barContainer;
}
async function initializeBar(barId) {
const barData = barsData[barId];
barData.controller?.abort();
clearInterval(currentTimeIntervals[barId]);
const controller = new AbortController();
barData.controller = controller;
const version = renderVersion;
const location = barData.location;
const requestedDate = overrideDate;
const isCurrent = () => !controller.signal.aborted && version === renderVersion &&
barsData[barId] === barData && barData.controller === controller;
// Do not leave the previous location/date visible while loading or on failure.
document.getElementById(`time-line-${barId}`).replaceChildren();
document.getElementById(`info-${barId}`).textContent = 'Loading…';
for (const prefix of ['morning-night', 'morning-civil', 'day-bg', 'evening-civil', 'evening-night']) {
document.getElementById(`${prefix}-${barId}`).style.setProperty('--size-percent', '0%');
}
try {
if (!location) throw new Error('Please enter a location.');
const coords = barData.resolvedLocation === location ? barData.coords :
await fetchCoordinates(location, controller.signal);
if (!isCurrent()) return;
barData.coords = coords;
barData.resolvedLocation = location;
const selectedDate = requestedDate || DateTime.now().setZone(coords.timeZone).toISODate();
const sunTimes = await fetchSunTimes(coords.latitude, coords.longitude, selectedDate, controller.signal);
if (!isCurrent()) return;
Object.assign(barData, coords, { selectedDate, sunTimes });
buildTimeLine(barId);
} catch (err) {
if (!isCurrent()) return;
document.getElementById(`info-${barId}`).textContent = err.message;
}
}
function buildTimeLine(barId) {
const barData = barsData[barId];
const infoDiv = document.getElementById(`info-${barId}`);
const timeLine = document.getElementById(`time-line-${barId}`);
timeLine.innerHTML = '';
infoDiv.innerHTML = '';
const morningNightBg = document.getElementById(`morning-night-${barId}`);
const morningCivilBg = document.getElementById(`morning-civil-${barId}`);
const dayBg = document.getElementById(`day-bg-${barId}`);
const eveningCivilBg = document.getElementById(`evening-civil-${barId}`);
const eveningNightBg = document.getElementById(`evening-night-${barId}`);
const timeZone = barData.timeZone;
const selectedDate = barData.selectedDate;
const day = LinearClock.createDay(selectedDate, timeZone);
const { start: dateStart, end: dateEnd } = day;
const sun = LinearClock.sunModel(barData.sunTimes, day);
const { sunrise, sunset, dawn, dusk } = sun;
const addInfo = text => {
const div = document.createElement('div');
div.textContent = text;
infoDiv.appendChild(div);
return div;
};
addInfo(`Location: ${barData.displayName || barData.location}`);
addInfo(`Time Zone: ${timeZone}`);
const currentTimeDisplay = addInfo('');
currentTimeDisplay.id = `current-time-display-${barId}`;
currentTimeDisplay.style.fontWeight = 'bold';
if (sun.kind === 'normal') {
addInfo(`Night: ${formatTimeMinutes(dateStart)} - ${formatTimeMinutes(dawn)} & ${formatTimeMinutes(dusk)} - ${formatTimeMinutes(dateEnd)}`);
addInfo(`Twilight: ${formatTimeMinutes(dawn)} - ${formatTimeMinutes(sunrise)} & ${formatTimeMinutes(sunset)} - ${formatTimeMinutes(dusk)}`);
addInfo(`Day: ${formatTimeMinutes(sunrise)} - ${formatTimeMinutes(sunset)}`);
} else {
addInfo(sun.kind === 'polar-day' ? 'Day: sun does not set' :
sun.kind === 'polar-night' ? 'Day: sun does not rise' : 'Sun times unavailable for this day.');
}
const backgrounds = [morningNightBg, morningCivilBg, dayBg, eveningCivilBg, eveningNightBg];
sun.segments.forEach((segment, index) => {
backgrounds[index].style.setProperty('--start-percent', `${segment.startPercent}%`);
backgrounds[index].style.setProperty('--size-percent', `${segment.sizePercent}%`);
});
for (const tick of LinearClock.hourTicks(day)) {
const hourMarker = document.createElement('div');
hourMarker.className = 'hour-marker';
hourMarker.style.setProperty('--position-percent', `${tick.percent}%`);
timeLine.appendChild(hourMarker);
const hourLabel = document.createElement('div');
hourLabel.className = 'hour-label';
hourLabel.style.setProperty('--position-percent', `${tick.percent}%`);
hourLabel.textContent = tick.label;
hourLabel.title = tick.time.toFormat('yyyy-MM-dd HH:mm ZZ');
timeLine.appendChild(hourLabel);
}
// Current time marker
const currentTimeMarker = document.createElement('div');
currentTimeMarker.className = 'current-time-marker';
currentTimeMarker.id = `current-time-marker-${barId}`;
timeLine.appendChild(currentTimeMarker);
// If we had an older interval for this index, clear it
if (currentTimeIntervals[barId]) {
clearInterval(currentTimeIntervals[barId]);
}
function updateCurrentTimeMarker() {
const now = DateTime.now().setZone(timeZone);
const isToday = now.toISODate() === selectedDate;
currentTimeMarker.style.display = isToday ? 'block' : 'none';
currentTimeDisplay.textContent = isToday ?
`Current Time: ${now.toFormat('cccc, LLL d yyyy, HH:mm:ss')}` : '';
if (isToday) {
currentTimeMarker.style.setProperty('--current-time-percent', `${LinearClock.percentage(now, day)}%`);
} else if (!overrideDate) {
// Stop the timer before fetching so midnight causes just one refresh.
clearInterval(currentTimeIntervals[barId]);
initializeBar(barId);
}
}
currentTimeIntervals[barId] = setInterval(updateCurrentTimeMarker, 1000);
updateCurrentTimeMarker();
}
document.addEventListener('DOMContentLoaded', async () => {
dateOverrideInput.value = '';
dateOverrideInput.addEventListener('change', (e) => {
overrideDate = e.target.value.trim();
renderAllBars();
});
// Bubble event handlers
newBarBubbleSubmitBtn.addEventListener('click', submitNewBarBubble);
newBarBubbleCancelBtn.addEventListener('click', hideNewBarBubble);
newBarBubbleLocationInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
submitNewBarBubble();
}
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
hideNewBarBubble();
}
});
const locations = getLocationsFromURL().map(location => location.trim()).filter(Boolean);
if (locations.length) {
barsData = locations.map(location => ({ location }));
renderAllBars();
} else {
// Controls work even while the optional IP lookup is pending.
renderAllBars();
const initialVersion = renderVersion;
try {
const ipData = await fetchJSON('https://ipapi.co/json/');
const location = [ipData.city, ipData.region, ipData.country_name].filter(Boolean).join(', ');
if (!location) throw new Error('No IP location available.');
if (renderVersion === initialVersion) addNewBar(location);
} catch (err) {
if (renderVersion === initialVersion) errorMessage.textContent = 'Could not detect your location. Add a location using +.';
}
}
});