A horizon-style chart drawn from the vendored suncalc, so fully offline: real sun and moon altitude over the 24 h around solar noon, sunrise/ sunset lines, dawn/noon/dusk on the time axis, the moon in its current phase, plus moonrise/set, phase and current sun/moon position below. Polar day/night now shows as a label instead of hiding the readout.
180 lines
8.6 KiB
JavaScript
180 lines
8.6 KiB
JavaScript
import { getMoonIllumination, getMoonPosition, getMoonTimes, getPosition, getTimes } from "/vendor/suncalc/suncalc.js";
|
|
|
|
// A Locus Pro-style toolbar readout: DMS coordinates (plain decimal degrees
|
|
// read less like a "GPS unit" and are harder to scan at a glance) plus
|
|
// sunrise/sunset and a countdown to whichever comes next — both computed
|
|
// for the map's current center, the same point the coordinates already
|
|
// describe, not a GNSS fix (this app's coordinate readout was never tied
|
|
// to having one).
|
|
|
|
function toDMS(value, positiveLabel, negativeLabel) {
|
|
const label = value >= 0 ? positiveLabel : negativeLabel;
|
|
const abs = Math.abs(value);
|
|
const degrees = Math.floor(abs);
|
|
const minutesFull = (abs - degrees) * 60;
|
|
let minutes = Math.floor(minutesFull);
|
|
let seconds = Math.round((minutesFull - minutes) * 60);
|
|
// A seconds value that rounds up to 60 has to carry into minutes (and
|
|
// from there, in the rare case, into degrees) rather than print "60".
|
|
if (seconds === 60) {
|
|
seconds = 0;
|
|
minutes += 1;
|
|
}
|
|
const carriedDegrees = minutes === 60 ? degrees + 1 : degrees;
|
|
const carriedMinutes = minutes === 60 ? 0 : minutes;
|
|
return `${carriedDegrees}°${String(carriedMinutes).padStart(2, "0")}'${String(seconds).padStart(2, "0")}"${label}`;
|
|
}
|
|
|
|
export function formatCoords(lat, lng) {
|
|
return `${toDMS(lat, "N", "S")} ${toDMS(lng, "E", "W")}`;
|
|
}
|
|
|
|
function formatTime(date) {
|
|
return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
|
|
}
|
|
|
|
function formatCountdown(ms) {
|
|
const totalMinutes = Math.max(0, Math.round(ms / 60000));
|
|
const hours = Math.floor(totalMinutes / 60);
|
|
const minutes = totalMinutes % 60;
|
|
return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
|
|
}
|
|
|
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
|
// null when there's no sunrise/sunset to show at all — getTimes returns
|
|
// null (not Invalid Date) for both on a polar day/night, per its own
|
|
// comment in suncalc.js — the caller just hides the readout in that case
|
|
// rather than showing something misleading. Returns the three pieces
|
|
// separately (not one joined string) so the caller can put its own icon in
|
|
// front of each rather than this module owning any markup.
|
|
export function formatSunInfo(lat, lng, now = new Date()) {
|
|
const today = getTimes(now, lat, lng);
|
|
// Polar day/night: no rise/set to count down to, but still worth a label
|
|
// — it's also what opens the sun/moon chart below.
|
|
if (today.alwaysUp) return { polar: "Polar day" };
|
|
if (today.alwaysDown) return { polar: "Polar night" };
|
|
if (today.sunrise === null || today.sunset === null) return null;
|
|
|
|
let next;
|
|
if (now < today.sunrise) {
|
|
next = { label: "sunrise", at: today.sunrise };
|
|
} else if (now < today.sunset) {
|
|
next = { label: "sunset", at: today.sunset };
|
|
} else {
|
|
// Already past today's sunset — the next event is tomorrow's sunrise.
|
|
const tomorrow = getTimes(new Date(now.getTime() + DAY_MS), lat, lng);
|
|
next = tomorrow.sunrise === null ? null : { label: "sunrise", at: tomorrow.sunrise };
|
|
}
|
|
|
|
return {
|
|
sunrise: formatTime(today.sunrise),
|
|
sunset: formatTime(today.sunset),
|
|
countdown: next ? `${formatCountdown(next.at - now)} to ${next.label}` : null,
|
|
};
|
|
}
|
|
|
|
// --- Sun & moon chart (click on the topbar's sun readout) ----------------
|
|
// Horizon-card style: 24 h centered on the solar noon nearest to now, real
|
|
// sun/moon altitudes from suncalc (vendored, so fully offline), horizon at
|
|
// 0°, sunrise/sunset lines, the moon drawn in its current phase. Times are
|
|
// in the browser's own time zone, same as the topbar readout.
|
|
|
|
const STEP_MS = 10 * 60 * 1000;
|
|
const W = 320;
|
|
const H = 130;
|
|
const LABEL_BAND = 14; // above the graph: sunrise/sunset; below it: dawn, solar noon, dusk
|
|
|
|
const PHASE_NAMES = [
|
|
"New moon", "Waxing crescent", "First quarter", "Waxing gibbous",
|
|
"Full moon", "Waning gibbous", "Last quarter", "Waning crescent",
|
|
];
|
|
|
|
function phaseName(phase) {
|
|
return PHASE_NAMES[Math.round(phase * 8) % 8];
|
|
}
|
|
|
|
// Lit part of a moon disk of radius r centered on 0,0: the bright half
|
|
// (right side; the caller mirrors it while waning) closed by the
|
|
// terminator, an elliptical arc whose width follows the phase.
|
|
// ponytail: northern-hemisphere orientation, no tilt from
|
|
// getMoonIllumination().angle - parallacticAngle — add if this travels south.
|
|
export function moonPhasePath(phase, r) {
|
|
const rx = (r * Math.abs(Math.cos(2 * Math.PI * phase))).toFixed(2);
|
|
const gibbous = phase > 0.25 && phase < 0.75 ? 1 : 0;
|
|
return `M0,${-r} A${r},${r} 0 0 1 0,${r} A${rx},${r} 0 0 ${gibbous} 0,${-r}Z`;
|
|
}
|
|
|
|
function nearestSolarNoon(now, lat, lng) {
|
|
const noon = getTimes(now, lat, lng).solarNoon;
|
|
if (now - noon > DAY_MS / 2) return getTimes(new Date(now.getTime() + DAY_MS), lat, lng).solarNoon;
|
|
if (noon - now > DAY_MS / 2) return getTimes(new Date(now.getTime() - DAY_MS), lat, lng).solarNoon;
|
|
return noon;
|
|
}
|
|
|
|
const time = (date) => (date ? formatTime(date) : "—");
|
|
const degrees = (value) => `${Math.round(value)}°`;
|
|
|
|
export function sunChartHtml(lat, lng, now = new Date()) {
|
|
const noon = nearestSolarNoon(now, lat, lng);
|
|
const start = noon.getTime() - DAY_MS / 2;
|
|
const samples = [];
|
|
for (let t = start; t <= start + DAY_MS; t += STEP_MS) {
|
|
const date = new Date(t);
|
|
samples.push({ t, sun: getPosition(date, lat, lng).altitude, moon: getMoonPosition(date, lat, lng).altitude });
|
|
}
|
|
const alts = samples.flatMap((sample) => [sample.sun, sample.moon]);
|
|
const top = Math.max(...alts, 10) + 8;
|
|
const bottom = Math.min(...alts, -10) - 8;
|
|
const x = (t) => (((t - start) / DAY_MS) * W).toFixed(1);
|
|
const y = (alt) => (((top - alt) / (top - bottom)) * H).toFixed(1);
|
|
const path = (key) => samples.map((sample, i) => `${i ? "L" : "M"}${x(sample.t)},${y(sample[key])}`).join("");
|
|
|
|
const sunTimes = getTimes(noon, lat, lng);
|
|
const moonTimes = getMoonTimes(noon, lat, lng);
|
|
const sunNow = getPosition(now, lat, lng);
|
|
const moonNow = getMoonPosition(now, lat, lng);
|
|
const illumination = getMoonIllumination(now);
|
|
const horizon = y(0);
|
|
const inWindow = (date) => date && date.getTime() >= start && date.getTime() <= start + DAY_MS;
|
|
const marker = (date) =>
|
|
inWindow(date) ? `<line class="sun-chart__mark" x1="${x(date.getTime())}" x2="${x(date.getTime())}" y1="0" y2="${H}"/>` : "";
|
|
const tick = (date) =>
|
|
inWindow(date) ? `<line class="sun-chart__tick" x1="${x(date.getTime())}" x2="${x(date.getTime())}" y1="${H - 5}" y2="${H}"/>` : "";
|
|
// Kept clear of the edges so a label for an event near the window's
|
|
// ends doesn't get cut off.
|
|
const label = (date, name, y) =>
|
|
inWindow(date)
|
|
? `<text class="sun-chart__label" x="${Math.min(Math.max(x(date.getTime()), 34), W - 34)}" y="${y}">${name} ${time(date)}</text>`
|
|
: "";
|
|
|
|
const svg = `
|
|
<svg class="sun-chart__graph" viewBox="0 ${-LABEL_BAND} ${W} ${H + 2 * LABEL_BAND}" role="img" aria-label="Sun and moon altitude over the day">
|
|
<defs><clipPath id="sun-chart-day"><rect width="${W}" height="${horizon}"/></clipPath></defs>
|
|
<rect class="sun-chart__night" y="${horizon}" width="${W}" height="${H - horizon}"/>
|
|
${marker(sunTimes.sunrise)}${marker(sunTimes.sunset)}
|
|
${tick(sunTimes.dawn)}${tick(sunTimes.solarNoon)}${tick(sunTimes.dusk)}
|
|
${label(sunTimes.sunrise, "Sunrise", -4)}${label(sunTimes.sunset, "Sunset", -4)}
|
|
${label(sunTimes.dawn, "Dawn", H + 10)}${label(sunTimes.solarNoon, "Noon", H + 10)}${label(sunTimes.dusk, "Dusk", H + 10)}
|
|
<path class="sun-chart__moon-path" d="${path("moon")}"/>
|
|
<path class="sun-chart__sun-path" d="${path("sun")}"/>
|
|
<path class="sun-chart__sun-path sun-chart__sun-path--day" d="${path("sun")}" clip-path="url(#sun-chart-day)"/>
|
|
<line class="sun-chart__horizon" x1="0" x2="${W}" y1="${horizon}" y2="${horizon}"/>
|
|
<circle class="sun-chart__sun" cx="${x(now.getTime())}" cy="${y(sunNow.altitude)}" r="7"/>
|
|
<g transform="translate(${x(now.getTime())},${y(moonNow.altitude)})">
|
|
<circle class="sun-chart__moon-shadow" r="7"/>
|
|
<path class="sun-chart__moon" d="${moonPhasePath(illumination.phase, 7)}"${illumination.waxing ? "" : ` transform="scale(-1,1)"`}/>
|
|
</g>
|
|
</svg>`;
|
|
|
|
const field = (label, value) => `<dt>${label}</dt><dd>${value}</dd>`;
|
|
return `${svg}
|
|
<dl class="sun-chart__fields">
|
|
${field("Sun now", `${degrees(sunNow.altitude)} alt · ${degrees(sunNow.azimuth)} az`)}
|
|
${field("Moonrise", time(moonTimes.rise))}
|
|
${field("Moonset", time(moonTimes.set))}
|
|
${field("Moon", `${phaseName(illumination.phase)} · ${Math.round(illumination.fraction * 100)}%`)}
|
|
${field("Moon now", `${degrees(moonNow.altitude)} alt · ${degrees(moonNow.azimuth)} az`)}
|
|
</dl>`;
|
|
}
|