Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
240 lines (205 loc) · 7.77 KB
/
Copy pathmain.js
File metadata and controls
240 lines (205 loc) · 7.77 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
// Page entry point: picks a location, computes sunsets and renders them.
import { sunsetSummary, formatHours, calendarDaysBetween } from "./calc.js";
import {
CLOCK_SIZE, clear, drawFace, drawNose, drawMinuteHand, drawTodayHands, drawRimMarker,
} from "./clock.js";
const DEFAULT_LOCATION = { lat: 42.3653766, lon: -71.1853512 };
const STORAGE_KEYS = { lat: "sunsetLat", lon: "sunsetLon" };
const DATE_FORMAT = { weekday: "short", day: "numeric", month: "short", year: "numeric" };
const canvas = document.getElementById("clock");
const info = document.getElementById("sunset-info");
const locationLine = document.getElementById("location");
// The most recent render, so the clock can be redrawn on resize or theme change.
let current = null;
// ---------- Location ----------
function loadStoredLocation() {
try {
const lat = localStorage.getItem(STORAGE_KEYS.lat);
const lon = localStorage.getItem(STORAGE_KEYS.lon);
if (lat && lon) return { lat: parseFloat(lat), lon: parseFloat(lon) };
} catch {
// Storage can be unavailable (private mode, blocked site data).
}
return null;
}
function storeLocation({ lat, lon }) {
try {
localStorage.setItem(STORAGE_KEYS.lat, lat);
localStorage.setItem(STORAGE_KEYS.lon, lon);
} catch {
// Not fatal: we just won't remember it next time.
}
}
function formatCoords({ lat, lon }) {
const ns = lat >= 0 ? "N" : "S";
const ew = lon >= 0 ? "E" : "W";
return `${Math.abs(lat).toFixed(2)}° ${ns}, ${Math.abs(lon).toFixed(2)}° ${ew}`;
}
// ---------- Clock ----------
function readTheme() {
const css = getComputedStyle(document.documentElement);
const v = (name) => css.getPropertyValue(name).trim();
return {
face: v("--clock-face"),
ink: v("--clock-ink"),
muted: v("--clock-muted"),
sun: v("--sun"),
upcoming: v("--upcoming"),
crep: v("--crep"),
faceEdge: v("--clock-face-edge"),
fontDisplay: v("--font-display"),
};
}
// Size the canvas backing store to its displayed size, so it stays sharp.
function prepareCanvas() {
const ratio = window.devicePixelRatio || 1;
const size = Math.max(1, Math.round(canvas.clientWidth * ratio));
if (canvas.width !== size || canvas.height !== size) {
canvas.width = size;
canvas.height = size;
}
const ctx = canvas.getContext("2d");
const scale = size / CLOCK_SIZE;
ctx.setTransform(scale, 0, 0, scale, 0, 0);
return ctx;
}
function renderClock(summary) {
const ctx = prepareCanvas();
const theme = readTheme();
clear(ctx);
drawFace(ctx, theme);
// Next 14 days: fade from strong (tomorrow) to faint (two weeks out).
const count = summary.upcomingHours.length;
summary.upcomingHours.forEach((hours, i) => {
drawMinuteHand(ctx, hours, theme.upcoming, 1.5, 0.9 - 0.75 * (i / count));
});
drawMinuteHand(ctx, summary.earliestHours, theme.crep, 2);
drawRimMarker(ctx, summary.earliestHours, theme.crep);
drawTodayHands(ctx, summary.todayHours, theme.ink);
drawNose(ctx, theme);
}
// ---------- Text ----------
// "4:23:49 PM" with the seconds and AM/PM de-emphasized.
function timeHtml(hours) {
const text = formatHours(hours);
const match = text.match(/^(\d+:\d\d)(:\d\d) (AM|PM)$/);
if (!match) return text;
return `${match[1]}<span class="sec">${match[2]}</span> <span class="ampm">${match[3]}</span>`;
}
function changeText(todayHours, tomorrowHours) {
if (todayHours === null || tomorrowHours === null) return "";
const seconds = Math.round((tomorrowHours - todayHours) * 3600);
if (seconds === 0) return "Same as today";
return seconds < 0 ? `${-seconds} s earlier` : `${seconds} s later`;
}
function countdownHtml(days) {
if (days === 0) {
return {
number: "Today",
label: "is Crepusculus",
};
}
return {
number: String(days),
label: `${days === 1 ? "day" : "days"} until Crepusculus`,
};
}
function renderInfo(summary) {
const { today, todayHours, tomorrowHours, earliestDay, earliestHours, daysUntilEarliest } = summary;
const countdown = countdownHtml(daysUntilEarliest);
info.innerHTML = `
<div class="countdown">
<div class="countdown-number">${countdown.number}</div>
<div>
<p class="countdown-label">${countdown.label}</p>
<p class="countdown-detail">
Today's date: <strong>${today.toLocaleDateString("en-US", DATE_FORMAT)}</strong><br>
Earliest sunset: <strong>${earliestDay.toLocaleDateString("en-US", DATE_FORMAT)}</strong>
at <strong>${formatHours(earliestHours)}</strong>
</p>
</div>
</div>
<div class="tiles">
<div class="tile">
<div class="tile-label">Sunset today</div>
<div class="tile-value">${timeHtml(todayHours)}</div>
</div>
<div class="tile">
<div class="tile-label">Sunset tomorrow</div>
<div class="tile-value">${timeHtml(tomorrowHours)}</div>
<div class="tile-note">${changeText(todayHours, tomorrowHours)}</div>
</div>
</div>
<ul class="legend" aria-label="Clock legend">
<li><span class="swatch swatch-today"></span>Today</li>
<li><span class="swatch swatch-upcoming"></span>Next 14 days</li>
<li><span class="swatch swatch-crep"></span>Earliest sunset</li>
</ul>`;
}
function mapsUrl({ lat, lon }) {
return `https://www.google.com/maps/search/?api=1&query=${lat.toFixed(5)},${lon.toFixed(5)}`;
}
// "Sunsets for 42.37° N, 71.19° W · <your current location>", where the
// location phrase links to Google Maps so people can check the place.
function renderLocation(location, source) {
const link = document.createElement("a");
link.href = mapsUrl(location);
link.target = "_blank";
link.rel = "noopener noreferrer";
link.textContent = source;
link.title = "Show this location in Google Maps";
locationLine.replaceChildren(`Sunsets for ${formatCoords(location)} · `, link);
}
// ---------- Main ----------
// The location shown most recently, so the page can be re-rendered for a new day.
let shown = null;
function render(location, source) {
const summary = sunsetSummary(location.lat, location.lon);
current = summary;
shown = { location, source };
renderClock(summary);
renderInfo(summary);
renderLocation(location, source);
}
// If the calendar day has changed since the last render (a tab left open
// overnight), recompute everything for the new day.
function refreshIfNewDay() {
if (shown && current && calendarDaysBetween(current.today, new Date()) !== 0) {
render(shown.location, shown.source);
}
}
async function start() {
// Make sure the clock numbers are drawn in the page font, not a fallback.
try {
await document.fonts.load(`500 26px ${readTheme().fontDisplay}`);
} catch {
// Draw with whatever font is available.
}
// Draw right away with the last known location (or the default),
// then ask for the current position and redraw if we get one.
const stored = loadStoredLocation();
if (stored) {
render(stored, "last known location");
} else {
render(DEFAULT_LOCATION, "default location");
}
navigator.geolocation?.getCurrentPosition(
({ coords }) => {
const location = { lat: coords.latitude, lon: coords.longitude };
storeLocation(location);
render(location, "your current location");
},
() => {} // Keep showing the stored or default location.
);
// Redraw the clock when its size or the light/dark theme changes.
new ResizeObserver(() => current && renderClock(current)).observe(canvas);
window.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", () => current && renderClock(current));
// Catch the day changing: when the tab comes back into view, and once a
// minute while it stays open.
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") refreshIfNewDay();
});
setInterval(refreshIfNewDay, 60 * 1000);
}
start();