Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript

Sun, moon and local time for a point and a date (#43)

OsintMeThat25f9fa8fb315
diff --git a/README.md b/README.md
index 5591f72..03d10ab 100644
--- a/README.md
+++ b/README.md
@@ -21,7 +21,7 @@ to fix a point on the map.*
| **Reverse Search** | Prepare an image or a video frame for keyless reverse-image services. Nothing uploads on its own. |
| **Inspect** | A scratch workspace over any photo or video: frame adjustments, editable crop, sharpest-frame capture, hand-made collage with per-piece warp/scale/rotate, auto-stitch to solve a panorama's layout, and ELA hints. Nothing enters the case until you save. |
| **Satellite** | Coordinates or a place name become an imagery crop, with select-area capture, map rotation, measurement tools, reference overlays and editable AOI grids for area review. Esri/OSM by default, plus Sentinel-2 with a date calendar and a cloud-ceiling slider; add a Mapbox or Google key for more basemaps. |
-| **Coordinates** | Convert common coordinate formats, copy the result, and open map or geocoding links. |
+| **Coords & Sky** | Convert common coordinate formats, copy the result, open map or geocoding links, and read the sun and moon at that point on a date: rise, set, azimuth, altitude, twilights, moon phase and bright-limb angle, in local time and UTC, computed offline. |
| **Geo Proof** | Start a named proof from a reusable house style, select case panels with search, compose them in a grid or free layout, annotate with colored shapes/freehand/text, and export `proof.png` plus a re-editable spec. |
| **Geo Report** | Turn a proof into a prepared thread for X, Bluesky, or Mastodon: coordinates, plus code, attribution, target-specific character counts, media, and a structured Markdown case note with linked evidence. |
| **Notebook** | Tabbed Markdown notes with local media, Mermaid diagrams, linked case evidence, broken-reference markers and a print-ready PDF view. |
diff --git a/docs/SPEC.md b/docs/SPEC.md
index 9f74c66..08ed1a7 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -103,7 +103,9 @@ proof for publication.
| Tool | What it does |
|------|--------------|
-| ✅ **Coordinates** | Converts common coordinate formats, copies results and opens map or geocoding links. |
+| ✅ **Coords & Sky** | Converts common coordinate formats, copies results, opens map or geocoding links, and borrows a point already saved in the case instead of retyping it. |
+| ✅ **Sun, moon and local time** | Rise, set, azimuth, altitude, twilights, moon phase and bright-limb angle for a point and date, each instant in civil local time and UTC, with a day chart and a compass rosette. Polar day, polar night and a date without a moonrise are states. |
+| ✅ **Sun & moon on the map** | A map mode: one date's path from an anchored point, as the arc each body sweeps while up, hour ticks, and the bearing at a draggable hour. |
| ✅ **Reverse Search** | Prepares image or video frames for keyless reverse-image services without uploading automatically. |
| ✅ **Grid Search** | Saves editable AOI grids with keyboard review states and place promotion. |
| ✅ **Templates** | Stores reusable proof styles and post-thread structures at workspace level. |
@@ -141,12 +143,14 @@ Each version delivers one complete daily workflow. Firm ideas move here from
| **Case Sheet** | The same case as a table: a row is an entity, columns are its attributes plus free ones the analyst adds, sorted, filtered and edited in place. Imports a CSV as loose rows that stay out of the graph until promoted, and exports back to CSV or GeoJSON. |
| **Camera Resection (GCP)** | Marks matching points photo↔map, then solves camera position, viewing azimuth and rough FOV (OpenCV `solvePnP`) and saves the match as evidence. Its photo canvas and pixel↔angle camera frame are built for two callers: Sky Clock fills the same frame by hand. |
| **Command palette** | Ctrl+K reaches a tool, a case or an artifact. |
-| **Sun, moon and local time** | Sunrise/sunset, solar and lunar azimuth, moon phase and bright-limb angle for a point and date, in Coordinates, each time in civil local time and UTC, plus a day chart of elevation against time and the two azimuths drawn as rays from the map marker. Polar day/night and days with no moonrise are states, not errors; the moon needs topocentric parallax and sampled rise/set, and civil time adds `timezonefinder` + `tzdata` to bundle. |
| **Capture scale and north** | Preference-controlled scale bar, north arrow and graticule on app and extension captures. |
-| **Notes to PDF** | Ticks notes in a dialog and writes them to the case's `exports/`, either one file per note or a single paginated document. The paginated form reuses the existing print path; per-note files need a generator that writes without a print dialog. |
+| **Notes to PDF** | Ticks notes in a dialog and writes one file per note, named after the note, into the case's export destination. Rendered server-side so no print dialog is involved, which means carrying fonts: a bundled Noto set, the system font for CJK, and a named error rather than empty boxes for a script nobody covers. |
+| **Export destination** | A folder of the analyst's own, remembered per case, where notes, proofs and map exports land instead of only the case's `exports/`. Validated when set, never deleted from, and a re-export overwrites rather than accumulates. |
+| **Case doctor** | Compares a case folder against its graph — missing `case.db`, files unknown to it, entities pointing at deleted files — and offers each repair as a choice. Prerequisite for letting the workspace move. |
+| **Workspace folder** | Settings moves the whole workspace, keys and presets included, by copying, verifying, switching a pointer kept outside it, then keeping the old copy until the analyst drops it. Covers adopting a hand-moved folder and a root that has gone missing. |
-Toward v2: a Settings-chosen workspace folder, once Azimut survives a user
-editing or deleting case files under it.
+Toward v2: reveal a case's folder in the system file manager; a lock so two
+Azimut instances can't share one workspace.
### v3: GEOINT expansion
@@ -157,6 +161,7 @@ editing or deleting case files under it.
| **Metadata follow-up** | Explains which common image/video fields were stripped and proposes events from capture times. |
| **Edit Provenance** | Reads a rendered video's own edit history: which source clips it was cut from, in what order, and the GPS, dates and cameras those clips still carry. |
| **Sky Clock** | Marks a shadow, the sun or the moon in an image or a video frame, with the horizon and north giving the angles, then renders the year as a day × hour heatmap of the slots that fit. A visible moon also carries phase and bright-limb angle, which usually cuts a year down to a few instants. |
+| **Case KMZ** | One self-contained file per case: a pin per place, carrying the notes and proof images it is linked to, opened in Google Earth. Frozen rather than live, because only the web Earth remains and it follows no network link. |
| **Imagery Wayback** | Esri World Imagery archive as a date slider: one view across every published release, key-less. |
| **Event layers** | Date-stamped overlays that support or contradict an event: NASA FIRMS thermal hotspots, archived weather and METAR. |
| **Shot contact sheet** | Splits a video into shots (ffmpeg scene detection) and picks frames from a clickable grid of timecodes. |
@@ -215,7 +220,7 @@ search; optional quota-aware X publishing.
| **Skyline Matching** | Trace a horizon in a photo, compare it against the DEM profile seen from candidate points. |
| **Camera Track (video SfM)** | Solves a moving camera's path from a video: frames sampled from a window, position and viewing azimuth per keyframe, and a sparse point cloud. Reports insufficient parallax instead of guessing. Bundles a native SfM binary (COLMAP/GLOMAP), CPU-capable. |
| **Vessel and Aircraft Tracks** | Historic ADS-B and AIS tracks on the map for a date, plus a watchlist that follows chosen callsigns or MMSIs. |
-| **Map Measures** | Distance, bearing/azimuth, area, FOV cone; includes measure-on-imagery, and its bearing layer absorbs the v2 sun/moon rays. |
+| **Map Measures** | Distance, bearing/azimuth, area, FOV cone; includes measure-on-imagery, and its bearing layer absorbs the v2 sun/moon arcs. |
| **Déjà Vu** | Perceptual-hash index flags recycled footage (local first; community index later). |
| **Manipulation Hints** | Add JPEG quantization, noise and AI-media hints alongside Inspect's ELA. |
| **Channel Monitor** | Watch Telegram channels, auto-archive media, queue for geolocation (rate limits, ToS care). |
diff --git a/docs/UI.md b/docs/UI.md
index 6e08fa6..c2f8c27 100644
--- a/docs/UI.md
+++ b/docs/UI.md
@@ -21,7 +21,7 @@ in `frontend/src/lib/workspaces.js` and appear as tabs, never as new rail entrie
|---|---|---|
| **Sources** | Media Library, Files, Reverse Search | Channel Monitor, Evidence Locker |
| **Examine** | Inspect (Selection / Frame / Collage / Analyze) | Edit Provenance, Shot contact sheet, OCR, Image Compare, Hints, Sky Clock, audio |
-| **Map** | Satellite, Coordinates | **one map, many modes**: Compare, Imagery Wayback, Event layers, Ground Imagery, Measures, Viewshed, OSM Query, Map Board |
+| **Map** | Satellite, Coords & Sky | **one map, many modes**: Compare, Imagery Wayback, Event layers, Ground Imagery, Measures, Viewshed, OSM Query, Map Board |
| **Compose** | Geo Proof, Geo Report, Notebook | Report Builder, GIF maker |
| *(Case)* | Sidebar | v2: Relations, Sheet; v4: Notes, Timeline; v5: Orchestrator |
@@ -168,12 +168,26 @@ Editing a place or a capture (**Edit** on any row) sets its title, note, relatio
and My-work folder in one dialog, and is the only place a new folder is created
from the map.
-Map controls sit in two clusters. **Tools** (measure, grid search, reference
-image) float top-left. **View** — fullscreen, OSM labels, saved work — continues
-the zoom column beneath `+`/`−`, because none of them changes what you are doing,
-only what you see. The saved-work layer is off by default and session-only:
-places draw as outlined pins, captures and screenshots as filled ones, items at
-the same spot collapse into one counted mark, and clicking any mark opens a card
+Map controls sit in two clusters. **Tools** (measure, sun & moon, grid search,
+reference image) float top-left. A tool with settings opens its panel beside that
+cluster, never beneath it, because beneath it is where Leaflet's own controls
+live. **View** — fullscreen, OSM labels, saved work — continues the zoom column
+beneath `+`/`−`, because none of them changes what you are doing, only what you
+see.
+
+**Sun & moon** draws one date's path from an anchored point: the arc each body
+sweeps while it is up, hour ticks along it, and the bearing at an hour you drag.
+Only azimuths are drawn, since a plan view cannot state an altitude. Height reads
+instead from where the body's own mark sits on its ray: the anchor stands for the
+zenith and the arc for the horizon, so a high sun rides close to you. The mark
+names its altitude on hover, carries the moon's phase, and is absent while the
+body is under the horizon. The anchor is a point and not the map centre, so panning
+leaves the path alone. Coords & Sky opens the same mode with its own point, date
+and time, and hands over no computed value.
+
+The saved-work layer is off by default and session-only: places draw as outlined
+pins, captures and screenshots as filled ones, items at the same spot collapse
+into one counted mark, and clicking any mark opens a card
with its preview, provider, dates and note. A mark whose capture carries proofs
wears a dot up-left; its card names the count and offers **Show proofs**, which
switches the panel and the layer to the proofs view. In that view the card opens
diff --git a/frontend/src/app.css b/frontend/src/app.css
index ef4f175..963f31f 100644
--- a/frontend/src/app.css
+++ b/frontend/src/app.css
@@ -39,6 +39,14 @@
--anno-5: #e040fb;
--anno-6: #ff9e40;
+ /* Two data series, sun and moon, for the sky chart and the map rays. Their own
+ tokens rather than --accent (reserved for selection and primary actions) or
+ the annotation palette (sized for contrast over imagery, not for chart marks
+ on a panel). Each theme gets its own step: these are the dark ones, checked
+ for lightness, chroma, contrast and colour-vision separation against --bg-1. */
+ --sky-sun: #bd8721;
+ --sky-moon: #4a93cc;
+
/* -- typography --------------------------------------------- */
--font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto,
"Helvetica Neue", Arial, sans-serif;
@@ -99,6 +107,10 @@
--info: #3b73b8;
--info-soft: rgba(59, 115, 184, 0.12);
+ /* sky series, stepped for a white surface rather than flipped from the dark set */
+ --sky-sun: #cc9526;
+ --sky-moon: #3f97d2;
+
--shadow-1: 0 1px 3px rgba(0, 0, 0, 0.12);
--shadow-2: 0 8px 28px rgba(0, 0, 0, 0.16);
diff --git a/frontend/src/components/MoonGlyph.svelte b/frontend/src/components/MoonGlyph.svelte
new file mode 100644
index 0000000..fa8df71
--- /dev/null
+++ b/frontend/src/components/MoonGlyph.svelte
@@ -0,0 +1,42 @@
+<script>
+ // The moon at its actual phase, for the places that are not a view of the sky:
+ // a table row, the map's readout. A crescent draws as a crescent, a full moon
+ // as a whole disc, a new moon as the bare outline — nothing is picked from a
+ // set of canned shapes, the terminator is where the geometry puts it.
+ import { litPath, glyphRotation } from '../lib/moonphase.js';
+
+ let {
+ illuminated = 0,
+ phaseAngle = 180,
+ waxing = true,
+ limb = null,
+ size = 15,
+ color = 'var(--sky-moon)',
+ } = $props();
+
+ const radius = $derived(size / 2 - 1);
+ const lit = $derived(litPath(radius, illuminated, phaseAngle));
+ const turn = $derived(glyphRotation(waxing, limb));
+</script>
+
+<svg
+ width={size}
+ height={size}
+ viewBox="{-size / 2} {-size / 2} {size} {size}"
+ role="img"
+ aria-label="{Math.round(illuminated * 100)}% lit"
+>
+ <g transform="rotate({turn})">
+ <circle r={radius} fill={color} opacity="0.18" />
+ <path d={lit} fill={color} />
+ </g>
+ <!-- unrotated and drawn last: at new moon this ring is the entire glyph -->
+ <circle r={radius} fill="none" stroke={color} stroke-opacity="0.5" />
+</svg>
+
+<style>
+ svg {
+ display: block;
+ flex-shrink: 0;
+ }
+</style>
diff --git a/frontend/src/lib/measure.js b/frontend/src/lib/measure.js
index b30c403..0f7201e 100644
--- a/frontend/src/lib/measure.js
+++ b/frontend/src/lib/measure.js
@@ -15,6 +15,28 @@ export function haversine(a, b) {
return 2 * R * Math.asin(Math.min(1, Math.sqrt(s)));
}
+/**
+ * The point reached from `from` on a bearing (degrees from north) after
+ * travelling `metres` along a great circle. Draws the sun and moon azimuth rays
+ * on the map, and is the primitive a bearing measure needs.
+ */
+export function destination(from, bearing, metres) {
+ const angular = metres / R;
+ const lat1 = rad(from.lat);
+ const lon1 = rad(from.lon);
+ const theta = rad(bearing);
+ const lat2 = Math.asin(
+ Math.sin(lat1) * Math.cos(angular) + Math.cos(lat1) * Math.sin(angular) * Math.cos(theta)
+ );
+ const lon2 =
+ lon1 +
+ Math.atan2(
+ Math.sin(theta) * Math.sin(angular) * Math.cos(lat1),
+ Math.cos(angular) - Math.sin(lat1) * Math.sin(lat2)
+ );
+ return { lat: (lat2 * 180) / Math.PI, lon: (((lon2 * 180) / Math.PI + 540) % 360) - 180 };
+}
+
/** Total length of a polyline through the points, in metres. */
export function pathLength(points) {
let total = 0;
diff --git a/frontend/src/lib/measure.test.js b/frontend/src/lib/measure.test.js
index 392fc01..74c08b7 100644
--- a/frontend/src/lib/measure.test.js
+++ b/frontend/src/lib/measure.test.js
@@ -7,6 +7,7 @@ import {
formatDistance,
formatArea,
formatAngle,
+ destination,
} from './measure.js';
describe('haversine', () => {
@@ -125,3 +126,29 @@ describe('imperial units', () => {
expect(formatDistance(1000, 'imperial')).toBe('3281 ft');
});
});
+
+describe('destination', () => {
+ const paris = { lat: 48.8584, lon: 2.2945 };
+
+ it('lands the requested distance away, on the requested bearing', () => {
+ for (const bearing of [0, 47, 90, 168, 270, 359]) {
+ const there = destination(paris, bearing, 5000);
+ expect(haversine(paris, there)).toBeCloseTo(5000, 0);
+ }
+ });
+
+ it('goes north, east, south and west as the compass says', () => {
+ expect(destination(paris, 0, 10000).lat).toBeGreaterThan(paris.lat);
+ expect(destination(paris, 180, 10000).lat).toBeLessThan(paris.lat);
+ expect(destination(paris, 90, 10000).lon).toBeGreaterThan(paris.lon);
+ expect(destination(paris, 270, 10000).lon).toBeLessThan(paris.lon);
+ // due east and west stay on the parallel, near enough over 10 km
+ expect(destination(paris, 90, 10000).lat).toBeCloseTo(paris.lat, 2);
+ });
+
+ it('wraps the antimeridian instead of running past 180°', () => {
+ const east = destination({ lat: 0, lon: 179.9 }, 90, 40000);
+ expect(east.lon).toBeLessThan(0);
+ expect(east.lon).toBeGreaterThan(-180);
+ });
+});
diff --git a/frontend/src/lib/moonphase.js b/frontend/src/lib/moonphase.js
new file mode 100644
index 0000000..4cd763b
--- /dev/null
+++ b/frontend/src/lib/moonphase.js
@@ -0,0 +1,37 @@
+// The shape of a lit moon, shared by everything that draws one: the compass
+// rosette (inside an SVG), the phase glyph in a table, the map's own readout.
+// Geometry lives here once; each caller renders it in its own context.
+
+/**
+ * Path of the lit part of a disc of `radius`, with the lit side towards +x.
+ *
+ * The terminator is a half-ellipse whose width follows the phase angle: as wide
+ * as the disc at new and full moon, flat at a quarter. It bulges away from the
+ * lit side when the moon is gibbous and is carved into it when it is a crescent,
+ * which is the whole difference between the two.
+ *
+ * At new moon the two arcs retrace each other, so the path encloses nothing and
+ * the moon draws as a bare outline. That is the right answer, not a special case.
+ */
+export function litPath(radius, illuminated, phaseAngle) {
+ const bulge = Math.abs(Math.cos((phaseAngle * Math.PI) / 180)) * radius;
+ const gibbous = illuminated > 0.5 ? 1 : 0;
+ return (
+ `M0,${-radius} A${radius},${radius} 0 0 1 0,${radius}` +
+ ` A${bulge.toFixed(2)},${radius} 0 0 ${gibbous} 0,${-radius} Z`
+ );
+}
+
+/**
+ * Degrees to rotate the lit shape by, clockwise, as SVG counts rotations.
+ *
+ * With a bright-limb angle the lit side ends up where it really is in the sky:
+ * that angle turns anticlockwise from the vertical, the opposite way to an SVG
+ * rotation, hence the sign. Without one the lit side falls to the right for a
+ * waxing moon — the convention almanac tables use, and a northern one, which is
+ * why a view of the actual sky passes the real angle instead.
+ */
+export function glyphRotation(waxing, limb = null) {
+ if (limb === null || limb === undefined) return waxing ? 0 : 180;
+ return -(limb + 90);
+}
diff --git a/frontend/src/lib/moonphase.test.js b/frontend/src/lib/moonphase.test.js
new file mode 100644
index 0000000..80de428
--- /dev/null
+++ b/frontend/src/lib/moonphase.test.js
@@ -0,0 +1,73 @@
+import { describe, it, expect } from 'vitest';
+import { litPath, glyphRotation } from './moonphase.js';
+
+// The path is two arcs: the lit rim, then the terminator back across the disc.
+// Its second arc's x-radius is what the phase actually changes, so that is what
+// these read, rather than comparing whole path strings.
+function terminator(path) {
+ const arcs = path.match(/A([\d.]+),/g);
+ return Number(arcs[1].slice(1, -1));
+}
+function sweep(path) {
+ return Number(path.match(/A[\d.]+,[\d.]+ 0 0 (\d)/g).pop().slice(-1));
+}
+
+describe('litPath', () => {
+ it('draws a full disc at full moon', () => {
+ const path = litPath(10, 1.0, 0);
+ // terminator as wide as the disc, bulging away from the lit side
+ expect(terminator(path)).toBeCloseTo(10, 1);
+ expect(sweep(path)).toBe(1);
+ });
+
+ it('draws a straight terminator at a quarter', () => {
+ const path = litPath(10, 0.5, 90);
+ expect(terminator(path)).toBeCloseTo(0, 1);
+ });
+
+ it('carves the terminator inwards for a crescent', () => {
+ const crescent = litPath(10, 0.2, 127);
+ const gibbous = litPath(10, 0.8, 53);
+ // same width either side of a quarter, opposite direction
+ expect(terminator(crescent)).toBeCloseTo(terminator(gibbous), 1);
+ expect(sweep(crescent)).toBe(0);
+ expect(sweep(gibbous)).toBe(1);
+ });
+
+ it('encloses nothing at new moon, so the moon reads as an outline', () => {
+ const path = litPath(10, 0, 180);
+ // the terminator retraces the lit rim: same radius, same direction
+ expect(terminator(path)).toBeCloseTo(10, 1);
+ expect(sweep(path)).toBe(0);
+ });
+
+ it('scales with the radius it is given', () => {
+ expect(litPath(7, 1, 0)).toContain('A7,7');
+ expect(litPath(20, 1, 0)).toContain('A20,20');
+ });
+
+ it('widens the terminator monotonically away from a quarter', () => {
+ const widths = [90, 70, 45, 20, 0].map((angle) => terminator(litPath(10, 0.6, angle)));
+ for (const [i, width] of widths.entries()) {
+ if (i) expect(width).toBeGreaterThan(widths[i - 1]);
+ }
+ });
+});
+
+describe('glyphRotation', () => {
+ it('lights the right side of a waxing moon, the left of a waning one', () => {
+ expect(glyphRotation(true)).toBe(0);
+ expect(glyphRotation(false)).toBe(180);
+ });
+
+ it('follows the real bright-limb angle when given one', () => {
+ // celestial position angles turn anticlockwise, SVG rotations clockwise
+ expect(glyphRotation(true, 0)).toBe(-90);
+ expect(glyphRotation(true, 90)).toBe(-180);
+ expect(glyphRotation(false, 270)).toBe(-360);
+ });
+
+ it('ignores the waxing convention once a real angle is known', () => {
+ expect(glyphRotation(true, 45)).toBe(glyphRotation(false, 45));
+ });
+});
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index 1bed83f..6fa5e65 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -164,6 +164,10 @@ export const uiState = $state({
focusMedia: null, // media path to highlight & scroll to in the Media Library
openInspect: null, // inspect-session name to reopen in the Inspect tool
gotoCoords: null, // { lat, lon } to fly to in the Satellite tool
+ // A point, a date and a time handed over by Coords & Sky: the Satellite tab
+ // opens its Sun & moon mode there. Session-only, and never part of a capture
+ // or a proof.
+ skyAt: null, // { lat, lon, date, time }
focusCapture: null, // case-relative capture path selected from another workspace
// Satellite reference viewers: floating scratch windows holding a media image
// over the map to eyeball against the imagery. Session-only — never captured
@@ -332,6 +336,7 @@ export function closeCase() {
uiState.focusMedia = null;
uiState.openInspect = null;
uiState.gotoCoords = null;
+ uiState.skyAt = null;
uiState.refViewers = [];
}
diff --git a/frontend/src/lib/workspaces.js b/frontend/src/lib/workspaces.js
index b82850e..b762919 100644
--- a/frontend/src/lib/workspaces.js
+++ b/frontend/src/lib/workspaces.js
@@ -22,7 +22,7 @@ export const TOOL_LABELS = {
reverse: 'Reverse Search',
inspect: 'Inspect',
satellite: 'Satellite',
- coordinates: 'Coordinates',
+ coordinates: 'Coords & Sky',
proof: 'Geo Proof',
post: 'Geo Report',
notebook: 'Notebook',
diff --git a/frontend/src/tools/Coordinates.svelte b/frontend/src/tools/Coordinates.svelte
index 15875bd..294d3d4 100644
--- a/frontend/src/tools/Coordinates.svelte
+++ b/frontend/src/tools/Coordinates.svelte
@@ -1,15 +1,18 @@
<script>
- // Coordinates — paste one point in any notation, read it back in every
- // other, and jump to the nine external maps. Conversion runs on the local
- // backend; converting also triggers a Nominatim reverse-geocode for the
- // place name (the app's local-first rule names geocoding as one of the
- // actions that inherently needs the network), reported as "Not available"
- // if that call fails.
+ // Coords & Sky — paste one point in any notation, read it back in every
+ // other, jump to the nine external maps, and read what the sun and the moon
+ // did there on a date. Conversion runs on the local backend; converting also
+ // triggers a Nominatim reverse-geocode for the place name (the app's
+ // local-first rule names geocoding as one of the actions that inherently
+ // needs the network), reported as "Not available" if that call fails. The
+ // sky panel below is pure local computation and never goes out.
import { api } from '../lib/api.js';
- import { toast, uiState } from '../lib/state.svelte.js';
+ import { caseState, toast, uiState } from '../lib/state.svelte.js';
import { mapLinks } from '../lib/maplinks.js';
import { bidiSafe } from '../lib/bidi.js';
import Icon from '../components/Icon.svelte';
+ import SkyPanel from './coordinates/SkyPanel.svelte';
+ import PointPicker from './coordinates/PointPicker.svelte';
// Mirrors the label order of engine/geo.py's all_formats(), so the empty
// state can preview the field list before any coordinate is parsed.
@@ -24,6 +27,7 @@
];
let text = $state('');
+ let pickerRows = $state(null); // the case's saved points, loaded when asked for
let point = $state(null); // { lat, lon, formats: [{id,label,value}] }
let parsing = $state(false);
let place = $state(null); // reverse-geocode result
@@ -66,6 +70,28 @@
}
}
+ // Borrow a coordinate from the case's own saved work rather than retyping it.
+ // The index is fetched when the picker is opened, not on mount: a tab that has
+ // not been asked anything stays quiet.
+ async function openPicker() {
+ if (!caseState.current) {
+ toast('Open a case to pick one of its points', 'warn');
+ return;
+ }
+ try {
+ pickerRows = await api.get(`/api/cases/${caseState.current.id}/satellite/index`);
+ } catch (e) {
+ toast(e.message, 'danger');
+ }
+ }
+
+ // The row's own position, read back through the same parser as typed input, so
+ // one code path fills every notation and the sky panel below.
+ function usePoint(row) {
+ text = `${row.lat}, ${row.lon}`;
+ parse();
+ }
+
// Hand the point to the Satellite map and switch tabs; it consumes
// uiState.gotoCoords on the next tick and flies there (lib/navigate.js).
function openInSatellite() {
@@ -77,7 +103,7 @@
<div class="tool">
<div class="tool-header">
- <h2>Coordinates</h2>
+ <h2>Coords &amp; Sky</h2>
</div>
<div class="tool-body">
@@ -95,15 +121,22 @@
title="Decimal, DMS, DDM, UTM, MGRS, plus code or geohash"
/>
<button type="submit" class="btn" disabled={!text.trim() || parsing}>
- <Icon name="search" size={15} /> {parsing ? '…' : 'Convert'}
+ <Icon name="search" size={15} /> {parsing ? '…' : 'Look up'}
</button>
+ <button
+ type="button"
+ class="btn btn-ghost"
+ title="Open a place or a capture saved in this case"
+ onclick={openPicker}>…</button
+ >
</form>
<div class="sheet">
<div class="head-row">
<span class="place" class:muted={!point || placeLoading}>
{#if !point}
- Paste a coordinate to read it back in every notation.
+ Paste a coordinate, or open one this case has saved, to read it back
+ in every notation.
{:else if placeLoading}
Resolving place…
{:else}
@@ -153,8 +186,17 @@
{/each}
</div>
</div>
+
+ <!-- Mounted with or without a point: with none it previews what it will
+ answer, so the sun and moon read as available rather than absent. -->
+ {#key point ? `${point.lat},${point.lon}` : 'empty'}
+ <SkyPanel {point} />
+ {/key}
</div>
</div>
+ {#if pickerRows}
+ <PointPicker rows={pickerRows} onpick={usePoint} onclose={() => (pickerRows = null)} />
+ {/if}
</div>
<style>
@@ -172,7 +214,7 @@
display: flex;
flex-direction: column;
padding: 16px;
- max-width: 720px;
+ max-width: 1120px;
}
.head-row {
display: flex;
@@ -203,7 +245,10 @@
}
.row {
display: grid;
- grid-template-columns: 150px 1fr auto;
+ /* The value column is capped rather than free: a row spans the whole sheet,
+ so the copy icon that follows it would otherwise land an arm's length from
+ the text it copies. */
+ grid-template-columns: 170px minmax(0, 480px) auto;
align-items: center;
gap: 12px;
padding: 7px 8px;
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index 3a2fd9c..ac0effa 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -9,6 +9,7 @@
} from '../lib/state.svelte.js';
import { mapLinks } from '../lib/maplinks.js';
import * as measure from '../lib/measure.js';
+ import { litPath, glyphRotation } from '../lib/moonphase.js';
import * as gridSearch from '../lib/gridSearch.js';
import { dragBearing, pivotPanOffset } from '../lib/satRotate.js';
import { clampSize, scaledCapture } from '../lib/captureSize.js';
@@ -61,6 +62,7 @@
import RelationPicker from '../components/RelationPicker.svelte';
import RefViewer from './RefViewer.svelte';
import MapToolCluster from './satellite/MapToolCluster.svelte';
+ import SunPanel from './satellite/SunPanel.svelte';
import GridSearchPanel from './satellite/GridSearchPanel.svelte';
import SentinelPicker from './satellite/SentinelPicker.svelte';
import CaptureOptions from './satellite/CaptureOptions.svelte';
@@ -499,6 +501,8 @@
if (reviewKey) return stopReview();
if (selectArmed) toggleSelect();
else if (sizeMenuOpen) sizeMenuOpen = false;
+ else if (sunPlacing) sunPlacing = false;
+ else if (sunMode) toggleSunMode();
else if (measureMode) setMeasureMode(null);
// native fullscreen already exits on Esc (handled by onFullscreenChange);
// only the CSS fallback needs an explicit toggle here
@@ -931,6 +935,13 @@
renderDraft();
return;
}
+ // Sun & moon: one click plants the anchor the day's path is drawn from
+ if (sunPlacing) {
+ sunAnchor = { lat: e.latlng.lat, lon: e.latlng.lng };
+ sunSky = null;
+ sunPlacing = false;
+ return;
+ }
if (!measureMode) return;
const pt = { lat: e.latlng.lat, lon: e.latlng.lng };
// an angle is exactly three points; a fourth click starts a fresh angle
@@ -1266,6 +1277,255 @@
}
});
+ // --- sun and moon mode ---
+ //
+ // One anchored point, one date, and an hour you drag: the day's path drawn as
+ // the arc the body sweeps while it is up, hour ticks along it, and the bearing
+ // at the chosen moment. Everything drawn is an azimuth, which is the only
+ // celestial quantity a plan view can state honestly; altitude stays in the
+ // panel. Map Measures will absorb this as its general bearing layer.
+ let sunMode = $state(false);
+ let sunAnchor = $state.raw(null); // { lat, lon } — fixed, never the moving view
+ let sunDay = $state(''); // empty: the backend's today at that point
+ let sunIndex = $state(0); // sample of the day the slider is on
+ let sunSky = $state(null);
+ let sunLoading = $state(false);
+ let sunPlacing = $state(false);
+ let sunLayer = null;
+ let sunTicket = 0;
+
+ function toggleSunMode() {
+ sunMode = !sunMode;
+ if (sunMode) {
+ if (selectArmed) toggleSelect(); // exclusive with the capture marquee…
+ if (measureMode) setMeasureMode(null); // …the measure tools…
+ if (gridMode) toggleGridMode(); // …and Grid Search
+ if (!sunAnchor) sunAnchor = markerLatLng ?? { lat: center.lat, lon: center.lon };
+ } else {
+ sunPlacing = false;
+ sunLayer?.clearLayers();
+ }
+ }
+
+ // Wall clock to land the slider on, once the day's samples are in.
+ let handedClock = null;
+
+ // Coords & Sky hands over a point, a date and a time: same mode, second way in,
+ // so there is only ever one rendering of this to keep right.
+ $effect(() => {
+ const handed = uiState.skyAt;
+ if (!mapReady || !handed) return;
+ uiState.skyAt = null;
+ sunAnchor = { lat: handed.lat, lon: handed.lon };
+ sunDay = handed.date ?? '';
+ sunSky = null;
+ sunIndex = 0;
+ handedClock = handed.time ?? null;
+ if (!sunMode) toggleSunMode();
+ });
+
+ $effect(() => {
+ if (!sunMode || !sunAnchor) return;
+ const params = new URLSearchParams({ lat: sunAnchor.lat, lon: sunAnchor.lon });
+ if (sunDay) params.set('date', sunDay);
+ const ticket = ++sunTicket;
+ sunLoading = true;
+ api
+ .get(`/api/geo/sky?${params}`)
+ .then((result) => {
+ if (ticket !== sunTicket) return;
+ sunSky = result;
+ sunDay = result.date;
+ sunIndex = nearestSample(result.curve.clock, handedClock ?? result.moment.local.slice(11, 16));
+ handedClock = null;
+ })
+ .catch(() => {
+ if (ticket === sunTicket) toast('Could not read the sky for that point', 'danger');
+ })
+ .finally(() => {
+ if (ticket === sunTicket) sunLoading = false;
+ });
+ });
+
+ // Match a wall clock against the day's own labels rather than dividing minutes
+ // by 60, which is wrong by an hour on the days daylight saving moves.
+ function nearestSample(clock, wanted) {
+ const target = Number(wanted.slice(0, 2)) * 60 + Number(wanted.slice(3, 5));
+ let best = 0;
+ let closest = Infinity;
+ clock.forEach((stamp, i) => {
+ const minutes = Number(stamp.slice(0, 2)) * 60 + Number(stamp.slice(3, 5));
+ const gap = Math.abs(minutes - target);
+ if (gap < closest) {
+ closest = gap;
+ best = i;
+ }
+ });
+ return best;
+ }
+
+ function themeColour(name, fallback) {
+ const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
+ return value || fallback;
+ }
+
+ // Runs of consecutive samples with the body above the horizon: the arc it
+ // actually sweeps in the sky. Drawing the whole 24 hours would close the circle
+ // through the bearings it holds while it is down, which says nothing.
+ function upRuns(altitudes) {
+ const runs = [];
+ let run = null;
+ altitudes.forEach((altitude, i) => {
+ if (altitude >= 0) {
+ run = run ?? [];
+ run.push(i);
+ } else if (run) {
+ runs.push(run);
+ run = null;
+ }
+ });
+ if (run) runs.push(run);
+ return runs.filter((r) => r.length > 1);
+ }
+
+ // The body itself, as a mark on its own ray: it rides between the anchor, which
+ // stands for the zenith, and the arc, which stands for the horizon, so how far
+ // up it is reads as how close to you it is. The same radial convention as the
+ // compass rosette in Coords & Sky.
+ function bodyIcon(kind, colour, illuminated, waxing) {
+ const size = 20;
+ const r = size / 2 - 2;
+ let inner = `<circle r="${r}" fill="${colour}" />`;
+ if (kind === 'moon') {
+ // Phase angle back out of the lit fraction: k = (1 + cos i) / 2 by
+ // definition, so nothing extra has to be fetched to draw it.
+ const phaseAngle = (Math.acos(Math.min(1, Math.max(-1, 2 * illuminated - 1))) * 180) / Math.PI;
+ // The bright-limb angle belongs to a view of the sky and says nothing in a
+ // plan view, so the map uses the table convention: lit side right when waxing.
+ inner =
+ `<circle r="${r}" fill="${colour}" opacity="0.25" />` +
+ `<g transform="rotate(${glyphRotation(waxing)})">` +
+ `<path d="${litPath(r, illuminated, phaseAngle)}" fill="${colour}" /></g>`;
+ }
+ return L.divIcon({
+ className: 'sky-body', // replaces Leaflet's boxed default
+ html:
+ `<svg width="${size}" height="${size}" viewBox="${-size / 2} ${-size / 2} ${size} ${size}">` +
+ `<circle r="${r + 1.5}" fill="rgba(0,0,0,0.45)" />${inner}` +
+ `<circle r="${r}" fill="none" stroke="#fff" stroke-opacity="0.85" stroke-width="1.5" />` +
+ `</svg>`,
+ iconSize: [size, size],
+ iconAnchor: [size / 2, size / 2],
+ });
+ }
+
+ function drawSun() {
+ if (!map) return;
+ if (!sunLayer) sunLayer = L.layerGroup().addTo(map);
+ sunLayer.clearLayers();
+ if (!sunMode || !sunSky || !sunAnchor) return;
+ const origin = sunAnchor;
+ const bounds = map.getBounds();
+ // Sized off the *shorter* side of the view, not its diagonal: the arc is a
+ // circle around the anchor, so a radius set by the diagonal runs off the top
+ // and bottom of a wide window.
+ const across = map.distance(bounds.getNorthWest(), bounds.getNorthEast());
+ const down = map.distance(bounds.getNorthWest(), bounds.getSouthWest());
+ const reach = Math.min(across, down) * 0.22;
+ const at = (azimuth, scale = 1) => {
+ const point = measure.destination(origin, azimuth, reach * scale);
+ return [point.lat, point.lon];
+ };
+ const curve = sunSky.curve;
+
+ for (const body of [
+ {
+ key: 'sun',
+ label: 'Sun',
+ colour: themeColour('--sky-sun', '#bd8721'),
+ azimuth: curve.sun_azimuth,
+ altitude: curve.sun_altitude,
+ },
+ {
+ key: 'moon',
+ label: 'Moon',
+ colour: themeColour('--sky-moon', '#4a93cc'),
+ azimuth: curve.moon_azimuth,
+ altitude: curve.moon_altitude,
+ },
+ ]) {
+ // Thin and translucent: the imagery underneath is what is being read.
+ for (const run of upRuns(body.altitude)) {
+ L.polyline(
+ run.map((i) => at(body.azimuth[i])),
+ { color: body.colour, weight: 2.5, opacity: 0.9 }
+ ).addTo(sunLayer);
+ }
+ curve.minutes.forEach((minute, i) => {
+ if (minute % 60 || body.altitude[i] < 0) return;
+ const long = minute % 180 === 0; // longer every three hours
+ L.polyline([at(body.azimuth[i], 0.94), at(body.azimuth[i], long ? 1.1 : 1.03)], {
+ color: body.colour,
+ weight: 2.5,
+ opacity: 0.9,
+ })
+ .bindTooltip(`${body.label} ${curve.clock[i]} · az ${Math.round(body.azimuth[i])}°`)
+ .addTo(sunLayer);
+ });
+ const altitude = body.altitude[sunIndex];
+ const below = altitude < 0;
+ const reading = `${body.label} ${curve.clock[sunIndex]} · az ${Math.round(body.azimuth[sunIndex])}° · alt ${Math.round(altitude)}°`;
+ L.polyline([[origin.lat, origin.lon], at(body.azimuth[sunIndex])], {
+ color: body.colour,
+ weight: 3.5,
+ opacity: below ? 0.6 : 1,
+ dashArray: below ? '6 6' : null,
+ })
+ .bindTooltip(reading, { sticky: true })
+ .addTo(sunLayer);
+ // Nothing rides the ray while the body is under the horizon: the dashed
+ // ray already says where it is, and a mark on it would claim it is visible.
+ if (!below) {
+ L.marker(at(body.azimuth[sunIndex], (90 - altitude) / 90), {
+ icon: bodyIcon(
+ body.key,
+ body.colour,
+ curve.moon_illuminated[sunIndex],
+ sunSky.moon.waxing
+ ),
+ keyboard: false,
+ })
+ .bindTooltip(body.key === 'moon' ? `${reading} · ${sunSky.moon.phase}` : reading)
+ .addTo(sunLayer);
+ }
+ }
+
+ L.circleMarker([origin.lat, origin.lon], {
+ radius: 4,
+ color: '#fff',
+ weight: 2,
+ fillColor: themeColour('--accent', '#e8a33d'),
+ fillOpacity: 1,
+ }).addTo(sunLayer);
+ }
+
+ // Redraw on any of: a new day, a new hour, a new anchor, the mode closing.
+ $effect(() => {
+ sunMode;
+ sunSky;
+ sunIndex;
+ sunAnchor;
+ if (mapReady) drawSun();
+ });
+
+ // The arc is drawn in metres, so a zoom or a pan has to restretch it.
+ $effect(() => {
+ if (!mapReady || !sunMode) return;
+ const redraw = () => drawSun();
+ map.on('zoomend moveend', redraw);
+ return () => map.off('zoomend moveend', redraw);
+ });
+
let searching = $state(false);
async function goTo() {
const text = coordsText.trim();
@@ -2804,8 +3064,28 @@
{measureReadout}
measureHint={MEASURE_HINT}
{clearMeasure}
+ {sunMode}
+ {toggleSunMode}
/>
+ {#if sunMode}
+ <SunPanel
+ sky={sunSky}
+ loading={sunLoading}
+ day={sunDay}
+ index={sunIndex}
+ anchor={sunAnchor}
+ placing={sunPlacing}
+ ondate={(value) => {
+ sunDay = value;
+ sunSky = null;
+ }}
+ onindex={(value) => (sunIndex = value)}
+ onplace={() => (sunPlacing = !sunPlacing)}
+ onclose={toggleSunMode}
+ />
+ {/if}
+
{#if gridMode}
<GridSearchPanel
bind:collapsed={gridCollapsed}
diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.js
index 12dddfb..5d395f5 100644
--- a/frontend/src/tools/Satellite.test.js
+++ b/frontend/src/tools/Satellite.test.js
@@ -253,3 +253,95 @@ describe('filing saved work by dragging it in the panel', () => {
expect(source).not.toContain('bind:path=');
});
});
+
+describe('sun and moon mode', () => {
+ it('is a map mode in the tool cluster, exclusive with the others', () => {
+ expect(source).toContain('let sunMode = $state(false)');
+ expect(source).toContain('{toggleSunMode}');
+ // the same exclusivity the grid mode declares
+ expect(source).toContain('if (selectArmed) toggleSelect()');
+ expect(source).toContain('if (gridMode) toggleGridMode()');
+ expect(source).toContain('else if (sunMode) toggleSunMode()'); // the Esc cascade
+ });
+
+ it('anchors the path to a fixed point, never to the moving view', () => {
+ expect(source).toContain('let sunAnchor = $state.raw(null)');
+ expect(source).toContain('sunAnchor = markerLatLng ?? { lat: center.lat, lon: center.lon }');
+ // and a click can move it
+ expect(source).toContain('if (sunPlacing) {');
+ });
+
+ it('draws only the arc the body sweeps while it is up', () => {
+ expect(source).toContain('function upRuns(altitudes)');
+ expect(source).toContain('if (altitude >= 0)');
+ expect(source).toContain('measure.destination(origin, azimuth, reach * scale)');
+ });
+
+ it('ticks the arc hourly, longer every three hours', () => {
+ expect(source).toContain('if (minute % 60 || body.altitude[i] < 0) return');
+ expect(source).toContain('const long = minute % 180 === 0');
+ });
+
+ it('rides the body along its own ray, as close to the anchor as it is high', () => {
+ // the anchor stands for the zenith and the arc for the horizon, the same
+ // radial convention as the compass rosette
+ expect(source).toContain('at(body.azimuth[sunIndex], (90 - altitude) / 90)');
+ expect(source).toContain('function bodyIcon(kind, colour, illuminated, waxing)');
+ });
+
+ it('leaves the ray bare while the body is under the horizon', () => {
+ // a mark on it would claim the body is visible
+ expect(source).toContain('if (!below) {');
+ });
+
+ it('draws the moon mark at its phase, worked out of the lit fraction', () => {
+ expect(source).toContain('Math.acos(Math.min(1, Math.max(-1, 2 * illuminated - 1)))');
+ expect(source).toContain('litPath(r, illuminated, phaseAngle)');
+ // a plan view has no vertical, so the bright-limb angle is not used here
+ expect(source).toContain('glyphRotation(waxing)');
+ expect(source).not.toContain('glyphRotation(waxing, ');
+ });
+
+ it('names the altitude on the mark and on the ray', () => {
+ expect(source).toContain('alt ${Math.round(altitude)}°');
+ expect(source).toContain("bindTooltip(body.key === 'moon'");
+ });
+
+ it('keeps a body below the horizon on the map, dashed', () => {
+ expect(source).toContain('const altitude = body.altitude[sunIndex]');
+ expect(source).toContain('const below = altitude < 0');
+ expect(source).toContain("dashArray: below ? '6 6' : null");
+ });
+
+ it('scrubs the hour without asking the backend again', () => {
+ // the whole day arrived in one response, so the slider reads an array
+ expect(source).toContain('function nearestSample(clock, wanted)');
+ expect(source).toContain('onindex={(value) => (sunIndex = value)}');
+ expect(source).toMatch(/if \(sunDay\) params\.set\('date', sunDay\)/);
+ });
+
+ it('labels a moment from the payload clock, not from arithmetic on minutes', () => {
+ expect(source).toContain('curve.clock[sunIndex]');
+ expect(source).not.toContain('Math.floor(minute / 60)');
+ });
+
+ it('sizes the arc off the shorter side of the view, so it stays on screen', () => {
+ // a radius set by the diagonal runs off the top and bottom of a wide window
+ expect(source).toContain('Math.min(across, down) * 0.22');
+ expect(source).toContain('bounds.getNorthWest(), bounds.getNorthEast()');
+ });
+
+ it('restretches the arc when the view moves, since it is drawn in metres', () => {
+ expect(source).toContain("map.on('zoomend moveend', redraw)");
+ expect(source).toContain("map.off('zoomend moveend', redraw)");
+ expect(source).toContain('bounds.getNorthWest(), bounds.getSouthWest()');
+ });
+
+ it('takes the handoff from Coords & Sky into the same mode', () => {
+ expect(source).toContain('const handed = uiState.skyAt');
+ expect(source).toContain('uiState.skyAt = null'); // consumed once, like gotoCoords
+ expect(source).toContain('if (!sunMode) toggleSunMode()');
+ // no computed value travels: the map asks for its own
+ expect(source).not.toContain('handed.sun');
+ });
+});
diff --git a/frontend/src/tools/coordinates/DayChart.svelte b/frontend/src/tools/coordinates/DayChart.svelte
new file mode 100644
index 0000000..ea5af6c
--- /dev/null
+++ b/frontend/src/tools/coordinates/DayChart.svelte
@@ -0,0 +1,250 @@
+<script>
+ // The day as altitude against local clock time: two lines, the horizon, and
+ // the twilight bands. Altitude is the y axis because that is the question the
+ // chart answers ("how high, and when"), with azimuth read off the crosshair
+ // rather than plotted, so there is one scale and no second y axis.
+ //
+ // Plain SVG. A charting library would be a dependency for one figure, and the
+ // shape is fixed: 145 points, two series.
+ // The viewBox is sized to the width the panel actually gives it, so the SVG
+ // renders near 1:1: scaled up from a narrower box, the 2px strokes and the
+ // 10px labels would grow with it and leave the design system behind.
+ const WIDTH = 1100;
+ const HEIGHT = 260;
+ const PAD = { top: 14, right: 16, bottom: 22, left: 36 };
+
+ let { curve, minutes, selected = null, sun = null, moon = null } = $props();
+
+ const plotWidth = WIDTH - PAD.left - PAD.right;
+ const plotHeight = HEIGHT - PAD.top - PAD.bottom;
+
+ const span = $derived(minutes?.length ? minutes[minutes.length - 1] : 1440);
+ // Room for the deepest line plus the astronomical band, so the horizon and the
+ // bands are always on screen even during a polar night.
+ const low = $derived(
+ Math.min(-22, ...(curve?.sun_altitude ?? [0]), ...(curve?.moon_altitude ?? [0])) - 4,
+ );
+ const high = $derived(
+ Math.max(20, ...(curve?.sun_altitude ?? [0]), ...(curve?.moon_altitude ?? [0])) + 6,
+ );
+
+ const x = (m) => PAD.left + (m / span) * plotWidth;
+ const y = (alt) => PAD.top + ((high - alt) / (high - low)) * plotHeight;
+
+ function line(values) {
+ if (!values?.length) return '';
+ return values.map((alt, i) => `${i ? 'L' : 'M'}${x(minutes[i]).toFixed(1)},${y(alt).toFixed(1)}`).join('');
+ }
+
+ // Bands of sky darkness, read straight off the sun's altitude.
+ const bands = $derived([
+ { from: 0, to: -6, opacity: 0.28 },
+ { from: -6, to: -12, opacity: 0.45 },
+ { from: -12, to: -18, opacity: 0.62 },
+ { from: -18, to: low, opacity: 0.78 },
+ ].filter((b) => b.from > low));
+
+ // Two-hourly, by index rather than by arithmetic on the minute: the label has
+ // to be the payload's own wall clock, which is not span/60 on the days
+ // daylight saving shortens or lengthens.
+ const hours = $derived(
+ (minutes ?? [])
+ .map((minute, index) => ({ minute, index }))
+ .filter(({ minute }) => minute % 120 === 0),
+ );
+
+ // Peak of each line, for the direct labels that keep identity off colour alone.
+ function peak(values) {
+ if (!values?.length) return null;
+ let best = 0;
+ values.forEach((v, i) => {
+ if (v > values[best]) best = i;
+ });
+ return { minute: minutes[best], altitude: values[best] };
+ }
+ const sunPeak = $derived(peak(curve?.sun_altitude));
+ const moonPeak = $derived(peak(curve?.moon_altitude));
+
+ let hover = $state(null);
+
+ function track(event) {
+ const box = event.currentTarget.getBoundingClientRect();
+ const at = ((event.clientX - box.left) / box.width) * WIDTH;
+ const minute = ((at - PAD.left) / plotWidth) * span;
+ if (minute < 0 || minute > span) {
+ hover = null;
+ return;
+ }
+ const step = minutes.length > 1 ? minutes[1] - minutes[0] : 10;
+ const index = Math.min(minutes.length - 1, Math.max(0, Math.round(minute / step)));
+ hover = { index, minute: minutes[index] };
+ }
+
+ // Whole degrees: the curve is sampled every ten minutes, so a decimal here
+ // would be precision the figure does not have.
+ const round = (value) => Math.round(value);
+</script>
+
+<figure class="chart">
+ <figcaption>
+ <span class="key"><i style="background: var(--sky-sun)"></i>Sun</span>
+ <span class="key"><i style="background: var(--sky-moon)"></i>Moon</span>
+ <span class="axis-note">altitude above the horizon, by local time</span>
+ </figcaption>
+
+ <svg
+ viewBox="0 0 {WIDTH} {HEIGHT}"
+ role="img"
+ aria-label="Altitude of the sun and the moon through the day"
+ onpointermove={track}
+ onpointerleave={() => (hover = null)}
+ >
+ {#each bands as band (band.from)}
+ <rect
+ x={PAD.left}
+ y={y(band.from)}
+ width={plotWidth}
+ height={Math.max(0, y(band.to) - y(band.from))}
+ fill="var(--text-1)"
+ opacity={band.opacity * 0.12}
+ />
+ {/each}
+
+ {#each hours as tick (tick.minute)}
+ <line
+ x1={x(tick.minute)}
+ y1={PAD.top}
+ x2={x(tick.minute)}
+ y2={HEIGHT - PAD.bottom}
+ stroke="var(--border)"
+ />
+ <text class="tick" x={x(tick.minute)} y={HEIGHT - 6} text-anchor="middle"
+ >{curve?.clock?.[tick.index] ?? ''}</text
+ >
+ {/each}
+
+ {#each [high > 60 ? 60 : 30, 0] as level (level)}
+ <text class="tick" x={PAD.left - 6} y={y(level) + 3} text-anchor="end">{level}°</text>
+ {/each}
+
+ <line
+ x1={PAD.left}
+ y1={y(0)}
+ x2={WIDTH - PAD.right}
+ y2={y(0)}
+ stroke="var(--border-strong)"
+ stroke-width="1"
+ />
+
+ <path d={line(curve?.moon_altitude)} fill="none" stroke="var(--sky-moon)" stroke-width="2" />
+ <path d={line(curve?.sun_altitude)} fill="none" stroke="var(--sky-sun)" stroke-width="2" />
+
+ {#if selected !== null && selected >= 0 && selected <= span}
+ <line
+ x1={x(selected)}
+ y1={PAD.top}
+ x2={x(selected)}
+ y2={HEIGHT - PAD.bottom}
+ stroke="var(--accent)"
+ stroke-width="1.5"
+ />
+ {#if sun !== null}
+ <circle cx={x(selected)} cy={y(sun)} r="4" fill="var(--sky-sun)" stroke="var(--bg-1)" stroke-width="2" />
+ {/if}
+ {#if moon !== null}
+ <circle cx={x(selected)} cy={y(moon)} r="4" fill="var(--sky-moon)" stroke="var(--bg-1)" stroke-width="2" />
+ {/if}
+ {/if}
+
+ {#if sunPeak && sunPeak.altitude > low}
+ <text class="series-label" x={x(sunPeak.minute)} y={y(sunPeak.altitude) - 7} text-anchor="middle">Sun</text>
+ {/if}
+ {#if moonPeak && moonPeak.altitude > low}
+ <text class="series-label" x={x(moonPeak.minute)} y={y(moonPeak.altitude) - 7} text-anchor="middle">Moon</text>
+ {/if}
+
+ {#if hover}
+ <line
+ x1={x(hover.minute)}
+ y1={PAD.top}
+ x2={x(hover.minute)}
+ y2={HEIGHT - PAD.bottom}
+ stroke="var(--border-strong)"
+ />
+ {/if}
+ </svg>
+
+ <div class="readout" class:muted={!hover}>
+ {#if hover}
+ <span class="mono">{curve?.clock?.[hover.index] ?? ''}</span>
+ <span
+ ><i style="background: var(--sky-sun)"></i>az {round(curve.sun_azimuth[hover.index])}° alt
+ {round(curve.sun_altitude[hover.index])}°</span
+ >
+ <span
+ ><i style="background: var(--sky-moon)"></i>az {round(curve.moon_azimuth[hover.index])}° alt
+ {round(curve.moon_altitude[hover.index])}°</span
+ >
+ {:else}
+ Hover the chart for the azimuth and altitude at any moment.
+ {/if}
+ </div>
+</figure>
+
+<style>
+ .chart {
+ margin: 0;
+ }
+ figcaption {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ padding-bottom: 6px;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ }
+ .axis-note {
+ color: var(--text-3);
+ }
+ .key,
+ .readout span {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ }
+ .key i,
+ .readout i {
+ width: 9px;
+ height: 9px;
+ border-radius: 2px;
+ }
+ svg {
+ display: block;
+ width: 100%;
+ height: auto;
+ touch-action: none;
+ }
+ .tick {
+ fill: var(--text-3);
+ font-size: 10px;
+ font-family: var(--font-mono);
+ }
+ .series-label {
+ fill: var(--text-2);
+ font-size: 10px;
+ }
+ .readout {
+ display: flex;
+ gap: 16px;
+ padding-top: 6px;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ }
+ .readout.muted {
+ color: var(--text-3);
+ }
+ .readout .mono {
+ font-family: var(--font-mono);
+ color: var(--text-1);
+ }
+</style>
diff --git a/frontend/src/tools/coordinates/PointPicker.svelte b/frontend/src/tools/coordinates/PointPicker.svelte
new file mode 100644
index 0000000..0595755
--- /dev/null
+++ b/frontend/src/tools/coordinates/PointPicker.svelte
@@ -0,0 +1,183 @@
+<script>
+ // Pick a point out of the open case instead of retyping it: the places and
+ // captures already saved, searched flat or browsed by My-work folder behind the
+ // "…", exactly like the media pickers elsewhere.
+ //
+ // Read-only on purpose. Editing or deleting saved work belongs to the Saved
+ // panel on the map, which is the one place that owns it; here a row is only a
+ // coordinate to borrow.
+ import Modal from '../../components/Modal.svelte';
+ import SearchInput from '../../components/SearchInput.svelte';
+ import FolderBrowser from '../../components/FolderBrowser.svelte';
+ import Icon from '../../components/Icon.svelte';
+ import { KINDS, filterSaved, isLocated, oneEach, sortSaved } from '../../lib/geoTree.js';
+
+ let { rows = [], onpick, onclose } = $props();
+
+ // A case can hold thousands of saved items; render a bounded page of them.
+ const CAP = 200;
+
+ let query = $state('');
+ let kind = $state('all');
+ let browsing = $state(false);
+ let path = $state('');
+
+ // Only what carries a position: this picker exists to fill a coordinate, and a
+ // row without one has nothing to give.
+ const placed = $derived(oneEach(rows).filter(isLocated));
+ // Proofs are a mode of the map's own panel, not a kind of point.
+ const kinds = KINDS.filter((k) => !k.mode);
+ const found = $derived(sortSaved(filterSaved(placed, { kind, query }), 'newest'));
+ const shown = $derived(found.slice(0, CAP));
+ const entries = $derived(
+ filterSaved(placed, { kind }).map((row) => ({
+ ...row,
+ id: row.id,
+ attrs: { folder: row.folder ?? '' },
+ })),
+ );
+
+ const glyph = (row) => (row.kind === 'place' ? 'pin' : 'image');
+ const label = (row) => row.title || `${row.lat.toFixed(5)}, ${row.lon.toFixed(5)}`;
+
+ function pick(row) {
+ onpick(row);
+ onclose();
+ }
+
+ function setKind(next) {
+ kind = next;
+ path = '';
+ }
+</script>
+
+<Modal title="Open a saved point" {onclose} width="680px">
+ <div class="bar">
+ <SearchInput bind:value={query} placeholder="Search title, note, place…" width="100%" />
+ <div class="kinds" role="group" aria-label="What this list shows">
+ {#each kinds as k (k.id)}
+ <button class="kind" class:on={kind === k.id} onclick={() => setKind(k.id)}>{k.label}</button>
+ {/each}
+ </div>
+ <button
+ class="btn btn-ghost btn-sm browse-btn"
+ class:on={browsing}
+ title="Browse My-work folders"
+ onclick={() => {
+ browsing = !browsing;
+ query = '';
+ path = '';
+ }}>…</button
+ >
+ </div>
+
+ {#if browsing}
+ <FolderBrowser
+ {entries}
+ {path}
+ rootLabel="My work"
+ icon={glyph}
+ {label}
+ emptyText="No saved point is filed here."
+ onnavigate={(next) => (path = next)}
+ onselect={(row) => pick(row)}
+ onconfirm={(row) => pick(row)}
+ />
+ {:else if !shown.length}
+ <p class="empty">
+ {placed.length ? 'Nothing matches.' : 'This case has no saved place or capture yet.'}
+ </p>
+ {:else}
+ <ul class="rows">
+ {#each shown as row (row.key)}
+ <li>
+ <button onclick={() => pick(row)}>
+ <Icon name={glyph(row)} size={14} />
+ <span class="title">{label(row)}</span>
+ <span class="coords mono">{row.lat.toFixed(5)}, {row.lon.toFixed(5)}</span>
+ {#if row.folder}<span class="folder">{row.folder}</span>{/if}
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {#if found.length > shown.length}
+ <p class="empty">Showing {shown.length} of {found.length}. Narrow the search.</p>
+ {/if}
+ {/if}
+</Modal>
+
+<style>
+ .bar {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding-bottom: 10px;
+ }
+ .kinds {
+ display: flex;
+ flex-shrink: 0;
+ }
+ .kind {
+ padding: 4px 9px;
+ font-size: var(--fs-sm);
+ color: var(--text-2);
+ background: var(--bg-2);
+ border: 1px solid var(--border);
+ cursor: pointer;
+ }
+ .kind.on {
+ color: var(--accent-text);
+ background: var(--accent);
+ border-color: var(--accent);
+ }
+ .browse-btn.on {
+ color: var(--accent);
+ }
+ .rows {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ max-height: 52vh;
+ overflow: auto;
+ }
+ .rows button {
+ display: grid;
+ grid-template-columns: auto 1fr auto auto;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ padding: 7px 8px;
+ text-align: left;
+ background: none;
+ border: 0;
+ border-radius: var(--r-sm);
+ color: inherit;
+ cursor: pointer;
+ }
+ .rows button:hover {
+ background: var(--bg-3);
+ }
+ .rows :global(svg) {
+ color: var(--text-3);
+ }
+ .title {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: var(--fs-sm);
+ }
+ .coords {
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ }
+ .folder {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .empty {
+ margin: 0;
+ padding: 12px 8px;
+ font-size: var(--fs-sm);
+ color: var(--text-3);
+ }
+</style>
diff --git a/frontend/src/tools/coordinates/PointPicker.test.js b/frontend/src/tools/coordinates/PointPicker.test.js
new file mode 100644
index 0000000..ecb80bf
--- /dev/null
+++ b/frontend/src/tools/coordinates/PointPicker.test.js
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const picker = readFileSync(new URL('./PointPicker.svelte', import.meta.url), 'utf8');
+const tool = readFileSync(new URL('../Coordinates.svelte', import.meta.url), 'utf8');
+
+describe('saved-point picker', () => {
+ it('reads the same saved index the map panel does, on demand', () => {
+ expect(tool).toContain('/satellite/index');
+ // not on mount: an untouched tab asks the backend nothing
+ expect(tool).toContain('async function openPicker()');
+ expect(tool).toContain('let pickerRows = $state(null)');
+ });
+
+ it('offers the flat search and the My-work browse behind the "…"', () => {
+ expect(picker).toContain("import FolderBrowser from '../../components/FolderBrowser.svelte'");
+ expect(picker).toContain("import SearchInput from '../../components/SearchInput.svelte'");
+ expect(picker).toContain('class="btn btn-ghost btn-sm browse-btn"');
+ expect(picker).toContain('rootLabel="My work"');
+ });
+
+ it('lists only what carries a position', () => {
+ // the picker exists to fill a coordinate field
+ expect(picker).toContain('oneEach(rows).filter(isLocated)');
+ });
+
+ it('drops the proofs position, which is a mode of the map panel', () => {
+ expect(picker).toContain('KINDS.filter((k) => !k.mode)');
+ });
+
+ it('stays read-only: editing saved work belongs to the map', () => {
+ expect(picker).not.toContain('ondelete');
+ expect(picker).not.toContain('onedit');
+ expect(picker).not.toMatch(/api\.(post|put|patch|del)/);
+ });
+
+ it('bounds what it renders', () => {
+ expect(picker).toContain('const CAP = 200');
+ expect(picker).toContain('found.slice(0, CAP)');
+ expect(picker).toContain('Showing {shown.length} of {found.length}');
+ });
+
+ it('fills the field through the same parser as typed input', () => {
+ // one code path fills every notation and the sky panel below
+ expect(tool).toContain('function usePoint(row)');
+ expect(tool).toContain('text = `${row.lat}, ${row.lon}`');
+ expect(tool).toContain('parse();');
+ });
+
+ it('asks for a case before offering the case its own points', () => {
+ expect(tool).toContain("toast('Open a case to pick one of its points', 'warn')");
+ });
+});
+
+describe('the look-up button', () => {
+ it('is named for what it does, which is more than converting', () => {
+ expect(tool).toContain("{parsing ? '…' : 'Look up'}");
+ expect(tool).not.toContain('Convert');
+ });
+});
diff --git a/frontend/src/tools/coordinates/SkyPanel.svelte b/frontend/src/tools/coordinates/SkyPanel.svelte
new file mode 100644
index 0000000..9dc811c
--- /dev/null
+++ b/frontend/src/tools/coordinates/SkyPanel.svelte
@@ -0,0 +1,390 @@
+<script>
+ // Sun and moon for the parsed point on one local day. Every instant is written
+ // twice, civil local and UTC, because an OSINT timestamp is only ever quoted in
+ // one of the two and the reader needs the other.
+ //
+ // Polar day, polar night and a day with no moonrise are printed as what they
+ // are. They are not failures, and above the Arctic Circle they are the norm.
+ import { api } from '../../lib/api.js';
+ import { toast, uiState } from '../../lib/state.svelte.js';
+ import Icon from '../../components/Icon.svelte';
+ import MoonGlyph from '../../components/MoonGlyph.svelte';
+ import DayChart from './DayChart.svelte';
+ import SkyRose from './SkyRose.svelte';
+
+ let { point = null } = $props();
+
+ let sky = $state(null);
+ let loading = $state(false);
+ let day = $state(''); // empty: the backend reads today in the point's own zone
+ let clock = $state(''); // empty: local midday, a neutral moment inside the day
+ let request = 0;
+
+ const shownDay = $derived(day || sky?.date || '');
+ const shownClock = $derived(clock || sky?.moment?.local?.slice(11, 16) || '');
+
+ // What the panel will answer, previewed before there is a point to answer for.
+ // Mirrors the row order below, the way Coordinates previews its notation list.
+ const PREVIEW_ROWS = [
+ 'Sunrise',
+ 'Solar noon',
+ 'Sunset',
+ 'Civil twilight',
+ 'Moonrise',
+ 'Moonset',
+ 'Phase',
+ ];
+
+ // One clause each, on the row rather than the label, so hovering anywhere in
+ // the line explains it. These are the conventions the numbers were computed
+ // under, which is what a reader quoting them needs to know.
+ const NOTES = {
+ sunrise: "When the sun's upper limb reaches the horizon, refraction included",
+ noon: 'When the sun crosses the meridian, its highest point of the day',
+ sunset: "When the sun's upper limb leaves the horizon, refraction included",
+ civil: 'Sun down to 6° below the horizon: outdoor detail is still readable',
+ nautical: 'Sun 6° to 12° below: the sea horizon is still visible',
+ astronomical: 'Sun 12° to 18° below: darker than this changes nothing for the eye',
+ moonrise: "When the moon's upper limb reaches the horizon, its parallax included",
+ moonset: "When the moon's upper limb leaves the horizon, its parallax included",
+ sunNow: 'Bearing from north, and height above the horizon, at the time above',
+ moonNow: 'Bearing from north, and height above the horizon, at the time above',
+ phase: 'Lit fraction, and the angle of the lit edge measured from straight up',
+ sunState: 'At this latitude and date the sun never crosses the horizon',
+ moonState: 'The moon stays up, or stays down, for the whole of this date',
+ };
+
+ $effect(() => {
+ if (!point) return;
+ const { lat, lon } = point;
+ const params = new URLSearchParams({ lat, lon });
+ if (day) params.set('date', day);
+ if (clock) params.set('time', clock);
+ const ticket = ++request;
+ loading = true;
+ api
+ .get(`/api/geo/sky?${params}`)
+ .then((result) => {
+ if (ticket !== request) return; // a later edit already won
+ sky = result;
+ })
+ .catch(() => {
+ if (ticket === request) toast('Could not read the sky for that point', 'danger');
+ })
+ .finally(() => {
+ if (ticket === request) loading = false;
+ });
+ });
+
+ const time = (stamp) => stamp?.local?.slice(11, 16) ?? '';
+ const utc = (stamp) => stamp?.utc?.slice(11, 16) ?? '';
+ // A sunset or the end of a twilight can fall after local midnight; say so
+ // rather than printing a time that looks like it belongs to the morning.
+ const carry = (stamp) => (stamp && shownDay && stamp.local.slice(0, 10) !== shownDay ? '+1' : '');
+
+ const SUN_STATES = { always_up: 'Midnight sun', always_down: 'Polar night' };
+ const TWILIGHT_STATES = { always_up: 'Never that dark', always_down: 'Never that light' };
+ const MOON_STATES = { always_up: 'Up all day', always_down: 'Down all day' };
+
+ const degrees = (value) => (value === null || value === undefined ? '' : `${Math.round(value)}°`);
+
+ const selectedMinute = $derived.by(() => {
+ if (!sky?.moment?.local) return null;
+ const [hours, mins] = sky.moment.local.slice(11, 16).split(':').map(Number);
+ return hours * 60 + mins;
+ });
+
+ // Hand the point, the date and the time to the map, which opens its own Sun &
+ // moon mode there. No computed value travels: the map asks for its own, so the
+ // two entry points cannot drift apart.
+ function showOnMap() {
+ uiState.gotoCoords = { lat: point.lat, lon: point.lon };
+ uiState.skyAt = {
+ lat: point.lat,
+ lon: point.lon,
+ date: sky.date,
+ time: sky.moment.local.slice(11, 16),
+ };
+ uiState.tool = 'satellite';
+ }
+</script>
+
+<div class="sky" class:loading>
+ <div class="sky-head">
+ <h3>Sun &amp; moon</h3>
+ <input
+ class="input input-sm"
+ type="date"
+ value={shownDay}
+ disabled={!point}
+ onchange={(e) => (day = e.currentTarget.value)}
+ title="Local date at this point"
+ />
+ <input
+ class="input input-sm"
+ type="time"
+ value={shownClock}
+ disabled={!point}
+ onchange={(e) => (clock = e.currentTarget.value)}
+ title="Local time at this point"
+ />
+ {#if !point}
+ <span class="zone">Computed here, offline, for whatever coordinate you paste.</span>
+ {/if}
+ {#if sky}
+ <span class="zone" title={sky.zone.name}>
+ {sky.zone.name} · {sky.zone.abbreviation} {sky.zone.offset}
+ </span>
+ <button class="btn btn-sm" onclick={showOnMap} title="Draw this day's path on the map">
+ <Icon name="crosshair" size={14} /> Show on map
+ </button>
+ {/if}
+ </div>
+
+ {#if sky}
+ <div class="grid">
+ <div class="table">
+ <div class="head">
+ <span></span><span>Local</span><span>UTC</span><span></span>
+ </div>
+
+ <p class="section">Sun</p>
+ {#if sky.sun.state === 'rises'}
+ <div class="row" title={NOTES.sunrise}>
+ <span class="k">Sunrise</span>
+ <span class="v mono">{time(sky.sun.rise)}<sup>{carry(sky.sun.rise)}</sup></span>
+ <span class="v mono dim">{utc(sky.sun.rise)}</span>
+ <span class="x">az {degrees(sky.sun.rise_azimuth)}</span>
+ </div>
+ <div class="row" title={NOTES.noon}>
+ <span class="k">Solar noon</span>
+ <span class="v mono">{time(sky.sun.transit)}</span>
+ <span class="v mono dim">{utc(sky.sun.transit)}</span>
+ <span class="x">alt {degrees(sky.sun.transit_altitude)}</span>
+ </div>
+ <div class="row" title={NOTES.sunset}>
+ <span class="k">Sunset</span>
+ <span class="v mono">{time(sky.sun.set)}<sup>{carry(sky.sun.set)}</sup></span>
+ <span class="v mono dim">{utc(sky.sun.set)}</span>
+ <span class="x">az {degrees(sky.sun.set_azimuth)}</span>
+ </div>
+ {:else}
+ <div class="row" title={NOTES.sunState}>
+ <span class="k">Sunrise, sunset</span>
+ <span class="v state">{SUN_STATES[sky.sun.state]}</span>
+ <span class="v"></span>
+ <span class="x">highest {degrees(sky.sun.transit_altitude)}</span>
+ </div>
+ {/if}
+ {#each Object.entries(sky.twilight) as [name, phase] (name)}
+ <div class="row" title={NOTES[name]}>
+ <span class="k">{name[0].toUpperCase() + name.slice(1)} twilight</span>
+ {#if phase.state === 'rises'}
+ <span class="v mono"
+ >{time(phase.dawn)} – {time(phase.dusk)}<sup>{carry(phase.dusk)}</sup></span
+ >
+ <span class="v mono dim">{utc(phase.dawn)} – {utc(phase.dusk)}</span>
+ {:else}
+ <span class="v state">{TWILIGHT_STATES[phase.state]}</span>
+ <span class="v"></span>
+ {/if}
+ <span class="x"></span>
+ </div>
+ {/each}
+ <div class="row row-now" title={NOTES.sunNow}>
+ <span class="k">At {shownClock}</span>
+ <span class="v mono">az {degrees(sky.sun.azimuth)}</span>
+ <span class="v mono">alt {degrees(sky.sun.altitude)}</span>
+ <span class="x">{sky.sun.altitude < 0 ? 'below the horizon' : ''}</span>
+ </div>
+
+ <p class="section">Moon</p>
+ {#if sky.moon.state === 'rises'}
+ {#each sky.moon.rises as rise, i (rise.utc)}
+ <div class="row" title={NOTES.moonrise}>
+ <span class="k">Moonrise</span>
+ <span class="v mono">{time(rise)}</span>
+ <span class="v mono dim">{utc(rise)}</span>
+ <span class="x">az {degrees(sky.moon.rise_azimuths[i])}</span>
+ </div>
+ {/each}
+ {#if !sky.moon.rises.length}
+ <div class="row" title={NOTES.moonrise}>
+ <span class="k">Moonrise</span>
+ <span class="v state">None on this date</span>
+ <span class="v"></span><span class="x"></span>
+ </div>
+ {/if}
+ {#each sky.moon.sets as set, i (set.utc)}
+ <div class="row" title={NOTES.moonset}>
+ <span class="k">Moonset</span>
+ <span class="v mono">{time(set)}</span>
+ <span class="v mono dim">{utc(set)}</span>
+ <span class="x">az {degrees(sky.moon.set_azimuths[i])}</span>
+ </div>
+ {/each}
+ {#if !sky.moon.sets.length}
+ <div class="row" title={NOTES.moonset}>
+ <span class="k">Moonset</span>
+ <span class="v state">None on this date</span>
+ <span class="v"></span><span class="x"></span>
+ </div>
+ {/if}
+ {:else}
+ <div class="row" title={NOTES.moonState}>
+ <span class="k">Moonrise, moonset</span>
+ <span class="v state">{MOON_STATES[sky.moon.state]}</span>
+ <span class="v"></span><span class="x"></span>
+ </div>
+ {/if}
+ <div class="row row-now" title={NOTES.moonNow}>
+ <span class="k">At {shownClock}</span>
+ <span class="v mono">az {degrees(sky.moon.azimuth)}</span>
+ <span class="v mono">alt {degrees(sky.moon.altitude)}</span>
+ <span class="x">{sky.moon.altitude < 0 ? 'below the horizon' : ''}</span>
+ </div>
+ <div class="row" title={NOTES.phase}>
+ <span class="k">Phase</span>
+ <!-- drawn whatever the moon's altitude: the phase is a fact about the
+ date, not about whether it happens to be up right now -->
+ <span class="v phase">
+ <MoonGlyph
+ illuminated={sky.moon.illuminated}
+ phaseAngle={sky.moon.phase_angle}
+ waxing={sky.moon.waxing}
+ />
+ {sky.moon.phase}
+ </span>
+ <span class="v mono">{Math.round(sky.moon.illuminated * 100)}% lit</span>
+ <span class="x">limb {degrees(sky.moon.limb_from_vertical)} from vertical</span>
+ </div>
+ </div>
+
+ <SkyRose sun={sky.sun} moon={sky.moon} />
+ </div>
+ <DayChart
+ curve={sky.curve}
+ minutes={sky.curve.minutes}
+ selected={selectedMinute}
+ sun={sky.sun.altitude}
+ moon={sky.moon.altitude}
+ />
+ {:else}
+ <div class="table preview">
+ <div class="head"><span></span><span>Local</span><span>UTC</span><span></span></div>
+ {#each PREVIEW_ROWS as label (label)}
+ <div class="row">
+ <span class="k">{label}</span>
+ <span class="v mono">–</span>
+ <span class="v mono">–</span>
+ <span class="x"></span>
+ </div>
+ {/each}
+ </div>
+ {/if}
+</div>
+
+<style>
+ .sky {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ padding-top: 16px;
+ transition: opacity 120ms var(--ease);
+ }
+ .sky.loading {
+ opacity: 0.6;
+ }
+ .sky-head {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ flex-wrap: wrap;
+ }
+ h3 {
+ margin: 0;
+ font-size: var(--fs-md);
+ font-weight: 600;
+ }
+ .input-sm {
+ width: auto;
+ font-family: var(--font-mono);
+ font-size: var(--fs-sm);
+ }
+ .zone {
+ flex: 1;
+ min-width: 0;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .grid {
+ display: flex;
+ align-items: flex-start;
+ gap: 20px;
+ }
+ .table {
+ flex: 1;
+ min-width: 0;
+ }
+ .preview .v {
+ color: var(--text-3);
+ }
+ .head,
+ .row {
+ display: grid;
+ /* Wide enough that a twilight range reads on one line, which it did not at
+ the narrow width. */
+ grid-template-columns: 190px 170px 150px 1fr;
+ align-items: baseline;
+ gap: 10px;
+ padding: 4px 0;
+ }
+ .head {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ border-bottom: 1px solid var(--border);
+ }
+ .section {
+ margin: 10px 0 2px;
+ font-size: var(--fs-xs);
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--text-3);
+ }
+ .k {
+ font-size: var(--fs-sm);
+ color: var(--text-2);
+ }
+ .v {
+ font-size: var(--fs-sm);
+ color: var(--text-1);
+ }
+ .v.dim {
+ color: var(--text-3);
+ }
+ .v.state,
+ .v.phase {
+ color: var(--text-2);
+ }
+ .v.phase {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ }
+ .row-now .v {
+ font-family: var(--font-mono);
+ }
+ .x {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ sup {
+ color: var(--text-3);
+ font-size: 0.7em;
+ }
+ @media (max-width: 780px) {
+ .grid {
+ flex-direction: column;
+ }
+ }
+</style>
diff --git a/frontend/src/tools/coordinates/SkyPanel.test.js b/frontend/src/tools/coordinates/SkyPanel.test.js
new file mode 100644
index 0000000..30827b4
--- /dev/null
+++ b/frontend/src/tools/coordinates/SkyPanel.test.js
@@ -0,0 +1,172 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const panel = readFileSync(new URL('./SkyPanel.svelte', import.meta.url), 'utf8');
+const chart = readFileSync(new URL('./DayChart.svelte', import.meta.url), 'utf8');
+const rose = readFileSync(new URL('./SkyRose.svelte', import.meta.url), 'utf8');
+const tool = readFileSync(new URL('../Coordinates.svelte', import.meta.url), 'utf8');
+
+describe('Sun & moon panel', () => {
+ it('reads the sky from the local backend and nothing else', () => {
+ expect(panel).toContain(".get(`/api/geo/sky?${params}`)");
+ // no third-party almanac, no ephemeris fetched at runtime
+ expect(panel).not.toMatch(/https?:\/\//);
+ });
+
+ it('writes every instant in both civil local time and UTC', () => {
+ expect(panel).toContain("stamp?.local?.slice(11, 16)");
+ expect(panel).toContain("stamp?.utc?.slice(11, 16)");
+ expect(panel).toContain('<span>Local</span><span>UTC</span>');
+ });
+
+ it('marks an event that falls after local midnight', () => {
+ // a sunset or a dusk belongs to its own evening even past 00:00
+ expect(panel).toContain("stamp.local.slice(0, 10) !== shownDay ? '+1'");
+ });
+
+ it('prints polar day, polar night and a missing moonrise as states', () => {
+ expect(panel).toContain("always_up: 'Midnight sun'");
+ expect(panel).toContain("always_down: 'Polar night'");
+ expect(panel).toContain("always_up: 'Never that dark'");
+ expect(panel).toContain("always_up: 'Up all day'");
+ expect(panel).toContain('None on this date');
+ // the state replaces the times; it is not an error path
+ expect(panel).toContain("{#if sky.sun.state === 'rises'}");
+ });
+
+ it('treats the date and time as local wall-clock readings', () => {
+ expect(panel).toContain('type="date"');
+ expect(panel).toContain('type="time"');
+ expect(panel).toContain('Local date at this point');
+ // empty means "let the backend pick", so the point's own today is used
+ expect(panel).toContain("let day = $state('')");
+ expect(panel).toContain("if (day) params.set('date', day)");
+ });
+
+ it('drops a stale response when the date changes twice quickly', () => {
+ expect(panel).toContain('const ticket = ++request');
+ expect(panel).toContain('if (ticket !== request) return');
+ });
+
+ it('sends the map a point, a date and a time, never a computed value', () => {
+ // the map opens its own Sun & moon mode and recomputes, so the two entry
+ // points into that view cannot drift apart
+ expect(panel).toContain('uiState.skyAt = {');
+ expect(panel).toContain('date: sky.date');
+ expect(panel).toContain("time: sky.moment.local.slice(11, 16)");
+ expect(panel).not.toContain('azimuth: sky.sun.azimuth');
+ expect(panel).toContain("uiState.tool = 'satellite'");
+ expect(panel).toContain('uiState.gotoCoords = { lat: point.lat, lon: point.lon }');
+ });
+
+ it('shows the phase glyph whatever the moon is doing', () => {
+ // the phase is a fact about the date, not about the moon being up right now
+ expect(panel).toContain("import MoonGlyph from '../../components/MoonGlyph.svelte'");
+ expect(panel).toContain('waxing={sky.moon.waxing}');
+ });
+
+ it('previews what it will answer before there is a coordinate', () => {
+ // the panel must read as available, not absent, on an untouched tab
+ expect(panel).toContain('const PREVIEW_ROWS = [');
+ expect(panel).toContain("'Sunrise',");
+ expect(panel).toContain("'Phase',");
+ expect(panel).toContain('Computed here, offline, for whatever coordinate you paste.');
+ expect(panel).toContain('disabled={!point}');
+ // and it asks the backend for nothing until it has a point
+ expect(panel).toContain('if (!point) return');
+ });
+
+ it('explains every row on hover, stating the convention used', () => {
+ expect(panel).toContain('const NOTES = {');
+ expect(panel).toContain("upper limb reaches the horizon, refraction included");
+ expect(panel).toContain("its parallax included");
+ expect(panel).toContain('Sun 6° to 12° below');
+ expect(panel).toContain('title={NOTES.sunrise}');
+ expect(panel).toContain('title={NOTES[name]}');
+ expect(panel).toContain('title={NOTES.phase}');
+ // the state rows explain the state, not the ordinary case
+ expect(panel).toContain('title={NOTES.sunState}');
+ expect(panel).toContain('title={NOTES.moonState}');
+ });
+
+ it('is mounted by the tool with or without a point', () => {
+ expect(tool).toContain("import SkyPanel from './coordinates/SkyPanel.svelte'");
+ expect(tool).toContain('<SkyPanel {point} />');
+ expect(tool).toContain("{#key point ? `${point.lat},${point.lon}` : 'empty'}");
+ });
+
+ it('shares one width with the rest of the tool', () => {
+ // the notations, the links, the table and the chart all span the sheet; only
+ // the value column is capped, so the copy icon stays beside what it copies
+ expect(tool).toContain('max-width: 1120px');
+ expect(tool).toContain('grid-template-columns: 170px minmax(0, 480px) auto');
+ // the paste field is the deliberate exception: a text input as wide as the
+ // page is a worse target, not a better one
+ expect(tool).toMatch(/\.go-form \{[^}]*max-width: 720px/s);
+ });
+
+ it('gives the table columns room for a twilight range on one line', () => {
+ expect(panel).toContain('grid-template-columns: 190px 170px 150px 1fr');
+ expect(panel).not.toContain('max-width: 660px');
+ });
+});
+
+describe('day chart', () => {
+ it('plots altitude against time on one scale, never two y axes', () => {
+ expect(chart).toContain('const y = (alt) =>');
+ expect(chart).toMatch(/const x = \(m\) =>/);
+ // azimuth is read from the crosshair, not plotted against a second axis
+ expect(chart).toContain('curve.sun_azimuth[hover.index]');
+ expect(chart.match(/altitude above the horizon/g)).toHaveLength(1);
+ });
+
+ it('keeps the horizon and the twilight bands on screen at any latitude', () => {
+ expect(chart).toContain('Math.min(-22');
+ expect(chart).toContain('{ from: 0, to: -6');
+ expect(chart).toContain('{ from: -12, to: -18');
+ });
+
+ it('identifies the two series by label as well as by colour', () => {
+ expect(chart).toContain('<span class="key"><i style="background: var(--sky-sun)"></i>Sun</span>');
+ expect(chart).toContain('class="series-label"');
+ expect(chart).toContain('>Sun</text>');
+ expect(chart).toContain('>Moon</text>');
+ });
+
+ it('labels its ticks from the payload clock, not by dividing minutes', () => {
+ // 120 minutes after local midnight reads 03:00 on the spring-forward day
+ expect(chart).toContain("curve?.clock?.[tick.index]");
+ expect(chart).not.toContain('Math.floor(m / 60)');
+ });
+
+ it('carries a crosshair readout in whole degrees', () => {
+ expect(chart).toContain('onpointermove={track}');
+ expect(chart).toContain('onpointerleave={() => (hover = null)}');
+ expect(chart).toContain('const round = (value) => Math.round(value)');
+ });
+
+ it('sizes its viewBox to the width it is given, so marks keep their weight', () => {
+ expect(chart).toContain('const WIDTH = 1100');
+ expect(chart).toContain('stroke-width="2"');
+ });
+
+ it('spans the local day it was given, not a fixed 24 hours', () => {
+ expect(chart).toContain('minutes[minutes.length - 1]');
+ expect(chart).not.toContain('/ 1440');
+ });
+});
+
+describe('compass rosette', () => {
+ it('puts the zenith at the centre and dashes a body below the horizon', () => {
+ expect(rose).toContain('((90 - Math.max(0, altitude)) / 90) * R');
+ expect(rose).toContain("stroke-dasharray={sun.altitude < 0 ? '3 3' : null}");
+ expect(rose).toContain('{#if moon.altitude >= 0}');
+ });
+
+ it('draws the moon at its own phase, on the shared geometry', () => {
+ expect(rose).toContain("import { litPath, glyphRotation } from '../../lib/moonphase.js'");
+ expect(rose).toContain('litPath(MOON_RADIUS, moon.illuminated, moon.phase_angle)');
+ // a view of the sky passes the real limb angle, not the table convention
+ expect(rose).toContain('moon.limb_from_vertical');
+ });
+});
diff --git a/frontend/src/tools/coordinates/SkyRose.svelte b/frontend/src/tools/coordinates/SkyRose.svelte
new file mode 100644
index 0000000..850bdd4
--- /dev/null
+++ b/frontend/src/tools/coordinates/SkyRose.svelte
@@ -0,0 +1,118 @@
+<script>
+ // The same instant seen from above: north up, azimuth around, altitude as the
+ // distance from the rim to the centre, so the centre is the zenith. It reads
+ // like the map does, which is the point — these two rays are what the Satellite
+ // tab draws from the marker.
+ //
+ // The moon is drawn at its real phase, rotated to its real bright-limb angle,
+ // because that pair is what an analyst compares against a photograph.
+ import { litPath, glyphRotation } from '../../lib/moonphase.js';
+
+ const SIZE = 168;
+ const C = SIZE / 2;
+ const R = 64;
+
+ let { sun = null, moon = null } = $props();
+
+ // Zenith at the centre; a body below the horizon has no place inside the disc,
+ // so its ray is dashed to the rim and carries no marker.
+ const radius = (altitude) => ((90 - Math.max(0, altitude)) / 90) * R;
+ const point = (azimuth, altitude) => {
+ const a = ((azimuth - 90) * Math.PI) / 180;
+ const r = radius(altitude);
+ return { x: C + r * Math.cos(a), y: C + r * Math.sin(a) };
+ };
+ const rim = (azimuth) => point(azimuth, 0);
+
+ const MOON_RADIUS = 7;
+</script>
+
+<svg viewBox="0 0 {SIZE} {SIZE}" role="img" aria-label="Compass with the sun and moon directions">
+ <circle cx={C} cy={C} r={R} fill="none" stroke="var(--border-strong)" />
+ <circle cx={C} cy={C} r={R / 2} fill="none" stroke="var(--border)" />
+ {#each [0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330] as bearing (bearing)}
+ {@const outer = rim(bearing)}
+ <line
+ x1={C + (outer.x - C) * 0.94}
+ y1={C + (outer.y - C) * 0.94}
+ x2={outer.x}
+ y2={outer.y}
+ stroke="var(--border)"
+ />
+ {/each}
+ {#each [['N', 0], ['E', 90], ['S', 180], ['W', 270]] as [label, bearing] (label)}
+ {@const at = rim(bearing)}
+ <text
+ class="cardinal"
+ x={C + (at.x - C) * 1.16}
+ y={C + (at.y - C) * 1.16 + 3.5}
+ text-anchor="middle">{label}</text
+ >
+ {/each}
+
+ {#if sun}
+ {@const tip = point(sun.azimuth, sun.altitude)}
+ <line
+ x1={C}
+ y1={C}
+ x2={tip.x}
+ y2={tip.y}
+ stroke="var(--sky-sun)"
+ stroke-width="2"
+ stroke-dasharray={sun.altitude < 0 ? '3 3' : null}
+ opacity={sun.altitude < 0 ? 0.55 : 1}
+ />
+ {#if sun.altitude >= 0}
+ <circle cx={tip.x} cy={tip.y} r="6" fill="var(--sky-sun)" stroke="var(--bg-1)" stroke-width="2" />
+ {/if}
+ {/if}
+
+ {#if moon}
+ {@const tip = point(moon.azimuth, moon.altitude)}
+ <line
+ x1={C}
+ y1={C}
+ x2={tip.x}
+ y2={tip.y}
+ stroke="var(--sky-moon)"
+ stroke-width="2"
+ stroke-dasharray={moon.altitude < 0 ? '3 3' : null}
+ opacity={moon.altitude < 0 ? 0.55 : 1}
+ />
+ {#if moon.altitude >= 0}
+ <!-- the real bright-limb angle, not the table convention: this is a view of
+ the sky, so the lit side has to point where it actually points -->
+ <circle cx={tip.x} cy={tip.y} r={MOON_RADIUS + 1} fill="var(--bg-1)" />
+ <g
+ transform="translate({tip.x} {tip.y}) rotate({glyphRotation(
+ moon.waxing,
+ moon.limb_from_vertical,
+ )})"
+ >
+ <circle r={MOON_RADIUS} fill="var(--sky-moon)" opacity="0.18" />
+ <path d={litPath(MOON_RADIUS, moon.illuminated, moon.phase_angle)} fill="var(--sky-moon)" />
+ </g>
+ <circle
+ cx={tip.x}
+ cy={tip.y}
+ r={MOON_RADIUS}
+ fill="none"
+ stroke="var(--sky-moon)"
+ stroke-opacity="0.5"
+ />
+ {/if}
+ {/if}
+</svg>
+
+<style>
+ svg {
+ display: block;
+ width: 168px;
+ height: 168px;
+ flex-shrink: 0;
+ }
+ .cardinal {
+ fill: var(--text-3);
+ font-size: 10px;
+ }
+</style>
diff --git a/frontend/src/tools/satellite/MapToolCluster.svelte b/frontend/src/tools/satellite/MapToolCluster.svelte
index 28097b5..8dd7236 100644
--- a/frontend/src/tools/satellite/MapToolCluster.svelte
+++ b/frontend/src/tools/satellite/MapToolCluster.svelte
@@ -16,6 +16,8 @@
referenceCount,
openRefPicker,
setMeasureMode,
+ sunMode,
+ toggleSunMode,
measureReadout,
measureHint,
clearMeasure,
@@ -38,6 +40,13 @@
title="Sweep an area cell by cell"
aria-label="Grid Search"
><Icon name="grid" size={16} /></button>
+ <button
+ class="mtbtn"
+ class:on={sunMode}
+ onclick={toggleSunMode}
+ title="Sun and moon path for a date"
+ aria-label="Sun and moon"
+ ><Icon name="sun" size={16} /></button>
<button
class="mtbtn"
class:on={referenceCount}
diff --git a/frontend/src/tools/satellite/SunPanel.svelte b/frontend/src/tools/satellite/SunPanel.svelte
new file mode 100644
index 0000000..c3364ce
--- /dev/null
+++ b/frontend/src/tools/satellite/SunPanel.svelte
@@ -0,0 +1,276 @@
+<script>
+ // Sun & moon mode: the day's path drawn from one anchored point, with an hour
+ // you can drag. Anchored beside the tool cluster like the measure panel, so it
+ // can never end up under Leaflet's own controls.
+ //
+ // Dragging the hour costs nothing: the whole day arrived in one response at
+ // ten-minute steps, so the slider reads an array. Only a new date asks the
+ // backend again.
+ import Icon from '../../components/Icon.svelte';
+ import MoonGlyph from '../../components/MoonGlyph.svelte';
+
+ let {
+ sky = null,
+ loading = false,
+ day = '',
+ index = 0,
+ anchor = null,
+ placing = false,
+ ondate,
+ onindex,
+ onplace,
+ onclose,
+ } = $props();
+
+ const curve = $derived(sky?.curve ?? null);
+ const last = $derived(curve ? curve.minutes.length - 1 : 0);
+ const at = $derived(curve?.clock?.[index] ?? '--:--');
+ const bodies = $derived(
+ curve
+ ? [
+ {
+ key: 'sun',
+ label: 'Sun',
+ colour: 'var(--sky-sun)',
+ azimuth: curve.sun_azimuth[index],
+ altitude: curve.sun_altitude[index],
+ },
+ {
+ key: 'moon',
+ label: 'Moon',
+ colour: 'var(--sky-moon)',
+ azimuth: curve.moon_azimuth[index],
+ altitude: curve.moon_altitude[index],
+ },
+ ]
+ : [],
+ );
+ const round = (value) => Math.round(value);
+
+ // Draggable, because the panel sits over the very imagery it is describing.
+ // Only the grip starts a drag: the date field and the hour slider need their
+ // own pointer events. Kept inside the map, so it cannot be lost off an edge.
+ let panelEl;
+ let offset = $state({ x: 0, y: 0 });
+ let drag = null;
+
+ function startDrag(event) {
+ event.preventDefault();
+ drag = { x: event.clientX, y: event.clientY, from: { ...offset } };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ }
+
+ function onDrag(event) {
+ if (!drag) return;
+ const wanted = {
+ x: drag.from.x + (event.clientX - drag.x),
+ y: drag.from.y + (event.clientY - drag.y),
+ };
+ const map = panelEl?.closest('.map-wrap')?.getBoundingClientRect();
+ const box = panelEl?.getBoundingClientRect();
+ if (map && box) {
+ // where the panel would sit with no offset at all
+ const restX = box.left - offset.x;
+ const restY = box.top - offset.y;
+ wanted.x = Math.min(
+ Math.max(wanted.x, map.left + 8 - restX),
+ map.right - 8 - box.width - restX,
+ );
+ wanted.y = Math.min(
+ Math.max(wanted.y, map.top + 8 - restY),
+ map.bottom - 8 - box.height - restY,
+ );
+ }
+ offset = wanted;
+ }
+
+ function endDrag(event) {
+ drag = null;
+ event.currentTarget.releasePointerCapture?.(event.pointerId);
+ }
+</script>
+
+<div
+ class="sun-panel card"
+ class:loading
+ bind:this={panelEl}
+ style="transform: translate({offset.x}px, {offset.y}px)"
+>
+ <div class="line">
+ <button
+ class="grip"
+ onpointerdown={startDrag}
+ onpointermove={onDrag}
+ onpointerup={endDrag}
+ onpointercancel={endDrag}
+ title="Drag to move this panel"
+ aria-label="Move panel"
+ ><Icon name="grip" size={14} /></button>
+ <input
+ class="input input-sm"
+ type="date"
+ value={day}
+ onchange={(e) => ondate(e.currentTarget.value)}
+ title="Local date at the anchored point"
+ />
+ <span class="zone">{sky?.zone?.abbreviation ?? ''}</span>
+ <button class="btn btn-ghost btn-sm" onclick={onclose} title="Close (Esc)">
+ <Icon name="x" size={13} />
+ </button>
+ </div>
+
+ <div class="scrub">
+ <input
+ type="range"
+ min="0"
+ max={last}
+ value={index}
+ disabled={!curve}
+ oninput={(e) => onindex(Number(e.currentTarget.value))}
+ aria-label="Time of day"
+ />
+ <span class="now mono">{at}</span>
+ </div>
+
+ {#each bodies as body (body.key)}
+ <div class="body">
+ <span class="swatch" style="background: {body.colour}"></span>
+ <span class="name">{body.label}</span>
+ <span class="mono">az {round(body.azimuth)}°</span>
+ <span class="mono dim">alt {round(body.altitude)}°</span>
+ {#if body.altitude < 0}<span class="down">down</span>{/if}
+ </div>
+ {/each}
+
+ {#if sky}
+ <div class="body">
+ <MoonGlyph
+ illuminated={sky.moon.illuminated}
+ phaseAngle={sky.moon.phase_angle}
+ waxing={sky.moon.waxing}
+ size={13}
+ />
+ <span class="phase">{sky.moon.phase}, {Math.round(sky.moon.illuminated * 100)}% lit</span>
+ </div>
+ {/if}
+
+ <div class="anchor">
+ <span class="mono dim">
+ {anchor ? `${anchor.lat.toFixed(4)}, ${anchor.lon.toFixed(4)}` : 'no point'}
+ </span>
+ <button class="btn btn-sm" class:on={placing} onclick={onplace}>
+ {placing ? 'Click the map' : 'Move'}
+ </button>
+ </div>
+ <p class="note">The path is drawn from this point, so panning the map leaves it alone.</p>
+</div>
+
+<style>
+ .sun-panel {
+ position: absolute;
+ /* beside the cluster, but below the band the centred coordinates readout
+ occupies: on a narrow map the two would otherwise cross */
+ top: 46px;
+ left: calc(100% + 8px);
+ width: max-content;
+ min-width: 234px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 10px;
+ background: rgba(24, 24, 24, 0.92);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-2);
+ transition: opacity 120ms var(--ease);
+ }
+ .sun-panel.loading {
+ opacity: 0.65;
+ }
+ .line {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .grip {
+ display: grid;
+ place-items: center;
+ padding: 2px;
+ color: var(--text-3);
+ cursor: grab;
+ touch-action: none;
+ }
+ .grip:hover {
+ color: var(--text-1);
+ }
+ .grip:active {
+ cursor: grabbing;
+ }
+ .line .input {
+ flex: 1;
+ font-family: var(--font-mono);
+ font-size: var(--fs-sm);
+ }
+ .zone {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .scrub {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .scrub input {
+ flex: 1;
+ accent-color: var(--accent);
+ }
+ .now {
+ font-size: var(--fs-md);
+ font-weight: 700;
+ color: var(--accent);
+ }
+ .body {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ font-size: var(--fs-sm);
+ }
+ .swatch {
+ width: 9px;
+ height: 9px;
+ border-radius: 2px;
+ }
+ .body .name {
+ width: 38px;
+ color: var(--text-2);
+ }
+ .dim {
+ color: var(--text-3);
+ }
+ .down {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .phase {
+ color: var(--text-2);
+ }
+ .anchor {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding-top: 6px;
+ border-top: 1px solid var(--border);
+ font-size: var(--fs-sm);
+ }
+ .anchor .btn.on {
+ background: var(--accent);
+ color: var(--accent-text);
+ border-color: var(--accent);
+ }
+ .note {
+ margin: 0;
+ max-width: 220px;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+</style>
diff --git a/frontend/src/tools/satellite/SunPanel.test.js b/frontend/src/tools/satellite/SunPanel.test.js
new file mode 100644
index 0000000..68bcc62
--- /dev/null
+++ b/frontend/src/tools/satellite/SunPanel.test.js
@@ -0,0 +1,56 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const panel = readFileSync(new URL('./SunPanel.svelte', import.meta.url), 'utf8');
+const cluster = readFileSync(new URL('./MapToolCluster.svelte', import.meta.url), 'utf8');
+
+describe('Sun & moon panel', () => {
+ it('opens beside the tool cluster, clear of the centred coordinates readout', () => {
+ expect(panel).toContain('left: calc(100% + 8px)');
+ expect(panel).toContain('top: 46px');
+ });
+
+ it('can be dragged out of the way of the imagery it describes', () => {
+ // the panel covers the very picture being read, so it has to move
+ expect(panel).toContain('onpointerdown={startDrag}');
+ expect(panel).toContain('setPointerCapture(event.pointerId)');
+ expect(panel).toContain('style="transform: translate({offset.x}px, {offset.y}px)"');
+ });
+
+ it('drags from the grip only, leaving the date and the slider their own pointer', () => {
+ expect(panel).toContain('class="grip"');
+ expect(panel).not.toContain('<div class="line" onpointerdown');
+ });
+
+ it('cannot be dragged off the map', () => {
+ expect(panel).toContain("panelEl?.closest('.map-wrap')");
+ expect(panel).toContain('map.right - 8 - box.width - restX');
+ expect(panel).toContain('map.bottom - 8 - box.height - restY');
+ });
+
+ it('reads the hour out of the day already fetched', () => {
+ expect(panel).toContain('curve?.clock?.[index]');
+ expect(panel).toContain('max={last}');
+ expect(panel).toContain('oninput={(e) => onindex(Number(e.currentTarget.value))}');
+ });
+
+ it('names both bodies and marks one that is below the horizon', () => {
+ expect(panel).toContain("label: 'Sun'");
+ expect(panel).toContain("label: 'Moon'");
+ expect(panel).toContain('{#if body.altitude < 0}<span class="down">down</span>{/if}');
+ });
+
+ it('shows the moon at its phase, and says the anchor does not follow the view', () => {
+ expect(panel).toContain("import MoonGlyph from '../../components/MoonGlyph.svelte'");
+ expect(panel).toContain('panning the map leaves it alone');
+ expect(panel).toContain("{placing ? 'Click the map' : 'Move'}");
+ });
+});
+
+describe('map tool cluster', () => {
+ it('carries Sun & moon among the tools, not among the view toggles', () => {
+ const tools = cluster.slice(cluster.indexOf('tool-cluster'), cluster.indexOf('view-cluster'));
+ expect(tools).toContain('aria-label="Sun and moon"');
+ expect(tools).toContain('class:on={sunMode}');
+ });
+});
diff --git a/packaging/azimut.spec b/packaging/azimut.spec
index 92206a8..c7e8f7a 100644
--- a/packaging/azimut.spec
+++ b/packaging/azimut.spec
@@ -36,6 +36,20 @@ if sys.platform == "linux":
# Grabs azimut/static/** (index.html, assets, favicon) from the installed package.
datas = collect_data_files("azimut")
+# The IANA timezone database, which `zoneinfo` falls back to when the OS has none
+# — that is Windows. Nothing imports `tzdata` by name, so PyInstaller cannot
+# discover it, and a missing database would not crash: engine/localtime.py would
+# quietly answer UTC and every local time in the sun and moon panel would be wrong
+# on Windows only. Collected explicitly for all three platforms, at 3 MB.
+#
+# Both halves are needed. `zoneinfo` reaches a zone as
+# `importlib.resources.files("tzdata.zoneinfo.Europe")`, so every region folder has
+# to be an importable package (the submodules) as well as a file on disk (the data)
+# — naming `tzdata` alone would ship the TZif files under a package Python cannot
+# import, which is the same silent UTC.
+datas += collect_data_files("tzdata")
+hiddenimports += collect_submodules("tzdata")
+
# Static ffmpeg / ffprobe, when the release CI has dropped them in
# packaging/vendor/. They land at the bundle root, where engine/ffmpeg.py looks
# for them (sys._MEIPASS). Absent (a plain local build), the binary just falls
diff --git a/pyproject.toml b/pyproject.toml
index c676f46..84629c7 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -37,6 +37,13 @@ dependencies = [
"numpy>=1.26,<3",
"requests>=2.31,<3",
"python-multipart>=0.0.9,<1.0",
+ # Timezone from a latitude/longitude, for the civil local time the sun and
+ # moon panel shows beside UTC (engine/sky.py). Chosen over timezonefinder,
+ # which carries 65 MB of tz polygons into each of the three binaries where
+ # this ships prebuilt abi3 wheels at 9 MB. tzdata is what zoneinfo reads on
+ # Windows, which has no system tz database.
+ "tzfpy>=1.3,<2",
+ "tzdata>=2024.1,<2027",
# Whole-bundle AES-GCM encryption. Version 49 dropped Intel macOS wheels,
# while the other release targets can stay current within the tested major.
"cryptography>=45,<49; sys_platform == 'darwin' and platform_machine == 'x86_64'",
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index dd2a1dc..bb8ba3c 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -8,7 +8,9 @@ import os
import re
import tempfile
import time
-from datetime import datetime, timezone
+# Aliased: this module already imports the ``time`` module for tile timing, and
+# the sky routes need the datetime classes of the same names.
+from datetime import date as calendar_date, datetime, time as wall_clock, timezone
from pathlib import Path
from typing import Any
@@ -22,9 +24,11 @@ from .. import config
from ..engine import (
geo,
google_tiles,
+ localtime,
media as media_engine,
satellite as satellite_engine,
sentinel,
+ sky,
tilecache,
tiles,
)
@@ -485,6 +489,131 @@ def reverse(lat: float, lon: float) -> dict[str, Any]:
return result
+def _dated(moment: datetime | None, zone: str) -> dict[str, Any] | None:
+ return localtime.both(moment, zone)
+
+
[email protected]("/geo/sky")
+def sky_for_point(
+ lat: float = Query(ge=-90, le=90),
+ lon: float = Query(ge=-180, le=180),
+ day: str | None = Query(default=None, alias="date"),
+ at: str | None = Query(default=None, alias="time"),
+ zone: str | None = None,
+) -> dict[str, Any]:
+ """Sun and moon for a point on one local day, plus the track of that day.
+
+ Pure computation, unlike the reverse geocode two routes up: nothing here goes
+ to the network, so the panel works offline.
+
+ ``date`` and ``time`` are read as local wall-clock readings in the point's own
+ zone, since that is how the analyst writes them. Every instant comes back in
+ both civil local time and UTC, and polar day, polar night and a day without a
+ moonrise arrive as a ``state`` rather than as an error.
+ """
+ # A zone resolved from the coordinate always loads. One the caller named is
+ # checked here rather than falling back to UTC, which would answer in UTC
+ # under the name that was asked for — every time in the response wrong, and
+ # nothing saying so.
+ if zone and not localtime.known_zone(zone):
+ raise HTTPException(status_code=422, detail="zone must be an IANA zone name")
+ zone_name = zone or localtime.zone_for(lat, lon)
+ tz = localtime.zone_info(zone_name)
+ try:
+ target = calendar_date.fromisoformat(day) if day else datetime.now(tz=tz).date()
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail="date must be YYYY-MM-DD") from exc
+ if at:
+ try:
+ clock = wall_clock.fromisoformat(at)
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail="time must be HH:MM") from exc
+ moment = localtime.at_local(target, clock, zone_name)
+ else:
+ # No time asked for: read the sky at local midday, a neutral instant that
+ # is inside the day the caller named whatever the zone does.
+ moment = localtime.local_noon(target, zone_name)
+
+ start, end = localtime.day_bounds(target, zone_name)
+ events = sky.day_events(lat, lon, start, end)
+ now = sky.position_at(lat, lon, moment)
+ curve = sky.day_curve(lat, lon, start, end, step_minutes=10)
+ # The offset is the one in force at the moment asked about, not the zone's
+ # standard one, so the local column can be labelled CEST rather than CET.
+ stamped = localtime.both(moment, zone_name) or {}
+
+ return {
+ "lat": lat,
+ "lon": lon,
+ "date": target.isoformat(),
+ "zone": {
+ "name": zone_name,
+ "abbreviation": stamped.get("abbreviation"),
+ "offset": stamped.get("offset"),
+ "offset_minutes": stamped.get("offset_minutes"),
+ },
+ "moment": _dated(moment, zone_name),
+ "sun": {
+ "rise": _dated(events["sun"]["rise"], zone_name),
+ "rise_azimuth": events["sun"]["rise_azimuth"],
+ "set": _dated(events["sun"]["set"], zone_name),
+ "set_azimuth": events["sun"]["set_azimuth"],
+ "transit": _dated(events["sun"]["transit"], zone_name),
+ "transit_altitude": events["sun"]["transit_altitude"],
+ "state": events["sun"]["state"],
+ "azimuth": round(now["sun_azimuth"], 1),
+ "altitude": round(now["sun_altitude"], 1),
+ "apparent_altitude": round(now["sun_apparent_altitude"], 1),
+ },
+ "twilight": {
+ name: {
+ "dawn": _dated(phase["dawn"], zone_name),
+ "dusk": _dated(phase["dusk"], zone_name),
+ "state": phase["state"],
+ }
+ for name, phase in events["twilight"].items()
+ },
+ "moon": {
+ "rises": [_dated(m, zone_name) for m in events["moon"]["rises"]],
+ "rise_azimuths": events["moon"]["rise_azimuths"],
+ "sets": [_dated(m, zone_name) for m in events["moon"]["sets"]],
+ "set_azimuths": events["moon"]["set_azimuths"],
+ "transit": _dated(events["moon"]["transit"], zone_name),
+ "transit_altitude": events["moon"]["transit_altitude"],
+ "state": events["moon"]["state"],
+ "azimuth": round(now["moon_azimuth"], 1),
+ "altitude": round(now["moon_altitude"], 1),
+ "apparent_altitude": round(now["moon_apparent_altitude"], 1),
+ "illuminated": round(now["moon_illuminated"], 4),
+ "phase": now["moon_phase"],
+ "phase_angle": round(now["moon_phase_angle"], 1),
+ "waxing": now["moon_waxing"],
+ "limb_angle": round(now["moon_limb_angle"], 1),
+ "limb_from_vertical": round(now["moon_limb_from_vertical"], 1),
+ "distance_km": round(now["moon_distance_km"]),
+ },
+ "curve": {
+ # Minutes from local midnight: the x axis of the chart, which has to
+ # stay right on the 23- and 25-hour days.
+ "minutes": [
+ round((point - start).total_seconds() / 60) for point in curve["times"]
+ ],
+ # …and the wall clock at each of those samples, which is not derivable
+ # from the minute: on the spring-forward day, 120 minutes after local
+ # midnight reads 03:00, not 02:00. Whatever labels a time to the reader
+ # takes it from here rather than dividing by 60.
+ "clock": [
+ point.astimezone(tz).strftime("%H:%M") for point in curve["times"]
+ ],
+ "sun_altitude": curve["sun_altitude"],
+ "sun_azimuth": curve["sun_azimuth"],
+ "moon_altitude": curve["moon_altitude"],
+ "moon_azimuth": curve["moon_azimuth"],
+ "moon_illuminated": curve["moon_illuminated"],
+ },
+ }
+
+
@router.post("/cases/{case_id}/satellite/capture")
def capture(case_id: str, body: CaptureIn) -> dict[str, Any]:
case = get_case(case_id)
diff --git a/src/azimut/engine/localtime.py b/src/azimut/engine/localtime.py
new file mode 100644
index 0000000..0756310
--- /dev/null
+++ b/src/azimut/engine/localtime.py
@@ -0,0 +1,108 @@
+"""Civil local time at a coordinate: which zone, and where its days begin.
+
+Kept apart from ``engine.sky`` on purpose. A day is a civil notion, not a
+geometric one, so the geometry works on plain UTC instants and this module is
+the only place that knows about zones. It also keeps the astronomy testable
+without a timezone database.
+
+``tzfpy`` resolves the zone from its own bundled boundaries and ``zoneinfo``
+reads the offsets, so nothing here touches the network either.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, date, datetime, time, timedelta
+from typing import Any
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
+
+import tzfpy
+
+
+def zone_for(lat: float, lon: float) -> str:
+ """IANA zone name at a point. Falls back to UTC where there is no answer.
+
+ Open sea returns a nautical zone (``Etc/GMT+2`` and friends) rather than
+ nothing, so the fallback is for the poles and for a zone name the installed
+ database has never heard of.
+ """
+ try:
+ name = tzfpy.get_tz(lon, lat)
+ except (ValueError, OverflowError):
+ name = None
+ if not name:
+ return "UTC"
+ if not known_zone(name):
+ return "UTC"
+ return name
+
+
+# What ``ZoneInfo`` raises for a name it will not load. ``ValueError`` covers the
+# ones it rejects outright (absolute paths, ``..`` segments), and ``OSError`` the
+# ones it takes as far as the filesystem, where an over-long name is ENAMETOOLONG
+# rather than a miss — so a caller handing us an arbitrary string gets UTC, not a
+# traceback.
+_UNLOADABLE = (ZoneInfoNotFoundError, ValueError, OSError)
+
+
+def known_zone(name: str) -> bool:
+ """Whether this installation can load ``name`` as a zone."""
+ try:
+ ZoneInfo(name)
+ except _UNLOADABLE:
+ return False
+ return True
+
+
+def zone_info(name: str) -> ZoneInfo:
+ """The zone, or UTC if this installation's database lacks it."""
+ try:
+ return ZoneInfo(name)
+ except _UNLOADABLE:
+ return ZoneInfo("UTC")
+
+
+def day_bounds(day: date, zone: str) -> tuple[datetime, datetime]:
+ """The UTC instants bounding one local civil day.
+
+ Uses the following local midnight rather than 24 hours, so the interval keeps
+ covering exactly one day across a daylight-saving change, when the local day
+ is 23 or 25 hours long.
+ """
+ tz = zone_info(zone)
+ start = datetime.combine(day, time(0, 0), tzinfo=tz)
+ end = datetime.combine(day + timedelta(days=1), time(0, 0), tzinfo=tz)
+ return start.astimezone(UTC), end.astimezone(UTC)
+
+
+def local_noon(day: date, zone: str) -> datetime:
+ """Midday local, as a UTC instant: the default moment for a date with no time."""
+ tz = zone_info(zone)
+ return datetime.combine(day, time(12, 0), tzinfo=tz).astimezone(UTC)
+
+
+def at_local(day: date, clock: time, zone: str) -> datetime:
+ """A local wall-clock reading on a local date, as a UTC instant."""
+ tz = zone_info(zone)
+ return datetime.combine(day, clock, tzinfo=tz).astimezone(UTC)
+
+
+def both(moment: datetime | None, zone: str) -> dict[str, Any] | None:
+ """One instant written twice: civil local and UTC, as the panel shows it.
+
+ ``abbreviation`` is what the zone calls itself at that moment (CEST, not
+ CET), because that is the label a reader checks the local column against.
+ """
+ if moment is None:
+ return None
+ tz = zone_info(zone)
+ local = moment.astimezone(tz)
+ offset = local.utcoffset() or timedelta(0)
+ minutes = int(offset.total_seconds() // 60)
+ sign = "-" if minutes < 0 else "+"
+ return {
+ "utc": moment.astimezone(UTC).isoformat().replace("+00:00", "Z"),
+ "local": local.isoformat(),
+ "abbreviation": local.tzname() or "UTC",
+ "offset_minutes": minutes,
+ "offset": f"{sign}{abs(minutes) // 60:02d}:{abs(minutes) % 60:02d}",
+ }
diff --git a/src/azimut/engine/sky.py b/src/azimut/engine/sky.py
new file mode 100644
index 0000000..d92f13d
--- /dev/null
+++ b/src/azimut/engine/sky.py
@@ -0,0 +1,604 @@
+"""Sun and moon geometry for a point and a moment.
+
+Pure computation. Nothing here reaches the network and nothing loads a data
+file, so it answers offline and inside the frozen binaries — an ephemeris that
+had to be downloaded on first use would break the local-first rule for a
+question as ordinary as "when did the sun set".
+
+Everything is vectorised over numpy arrays of instants. The Coordinates panel
+asks for one day at ten-minute steps; the year scan behind a future Sky Clock
+asks for hundreds of thousands of instants, and both go through the same code.
+
+Accuracy, and why it is enough:
+
+- Sun, Meeus chapter 25 (the short series): about 0.01°.
+- Moon, mean elements plus the twelve longitude, five latitude and two distance
+ perturbation terms of the classic truncation: about 0.03°.
+- The moon's topocentric parallax, applied here, reaches 0.95° — thirty times
+ the series error, and the term that actually decides a moonrise.
+- One pixel of a 1080p frame at a 60° field of view spans 0.03°, and the moon's
+ own disc spans 0.5°. Measurement dominates the ephemeris by a wide margin,
+ which is why a heavier ephemeris would buy nothing here.
+
+Two approximations are deliberate. Parallax is applied along the vertical as an
+altitude-only correction, ignoring the up-to-11.5' tilt between the geodetic and
+the geocentric vertical: that leaves under 0.01° in azimuth. And ΔT follows the
+Espenak-Meeus polynomial fitted for 2005-2050, extrapolated outside it, which
+costs a few seconds of ephemeris time — under 0.01° for the moon.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import numpy as np
+
+# Equatorial radius, the one the parallax of the moon is defined against.
+EARTH_RADIUS_KM = 6378.14
+AU_KM = 149597870.7
+
+# Rise and set conventions. Both bodies are timed on their upper limb touching
+# the apparent horizon, which is what almanacs publish. For the sun the whole
+# thing is the familiar constant: 34' of refraction plus its 16' semidiameter.
+# The moon's semidiameter follows its distance, so its threshold is computed
+# per instant from the parallax (semidiameter = 0.2725 × parallax).
+REFRACTION_DEG = -0.5667
+SUN_HORIZON_DEG = -0.8333
+MOON_SEMIDIAMETER_RATIO = 0.2725
+
+# Sun-centre altitudes that define the ends of each twilight.
+TWILIGHTS: dict[str, float] = {"civil": -6.0, "nautical": -12.0, "astronomical": -18.0}
+
+# Elongation bands for the phase name, each centred on its exact moment.
+_PHASE_NAMES = [
+ (22.5, "new moon"),
+ (67.5, "waxing crescent"),
+ (112.5, "first quarter"),
+ (157.5, "waxing gibbous"),
+ (202.5, "full moon"),
+ (247.5, "waning gibbous"),
+ (292.5, "last quarter"),
+ (337.5, "waning crescent"),
+]
+
+_J2000 = 2451545.0
+_UNIX_EPOCH_JD = 2440587.5
+# The classic lunar series is fitted to days counted from 1999-12-31 00:00 UT.
+_MOON_EPOCH_OFFSET = 1.5
+
+
+# -- time ----------------------------------------------------------------------
+
+
+def _julian_day(times: Sequence[datetime] | np.ndarray) -> np.ndarray:
+ """Julian days (UT) for aware datetimes, or for a numpy datetime64 array."""
+ if isinstance(times, np.ndarray) and np.issubdtype(times.dtype, np.datetime64):
+ micros = times.astype("datetime64[us]").astype("int64")
+ else:
+ micros = np.array(
+ [
+ int(
+ (
+ t.astimezone(UTC) - datetime(1970, 1, 1, tzinfo=UTC)
+ ).total_seconds()
+ * 1_000_000
+ )
+ for t in times
+ ],
+ dtype="int64",
+ )
+ return _UNIX_EPOCH_JD + micros / 86_400_000_000.0
+
+
+def _to_datetime(jd: float) -> datetime:
+ """Back to an aware UTC datetime, rounded to the second we display."""
+ seconds = round((float(jd) - _UNIX_EPOCH_JD) * 86400.0)
+ return datetime(1970, 1, 1, tzinfo=UTC) + timedelta(seconds=seconds)
+
+
+def _delta_t(jd_ut: np.ndarray) -> np.ndarray:
+ """TT − UT in seconds (Espenak-Meeus, fitted 2005-2050)."""
+ t = (jd_ut - _J2000) / 365.25
+ return 62.92 + 0.32217 * t + 0.005589 * t * t
+
+
+def _centuries_tt(jd_ut: np.ndarray) -> np.ndarray:
+ """Julian centuries of TT from J2000, the argument every series below wants."""
+ return (jd_ut + _delta_t(jd_ut) / 86400.0 - _J2000) / 36525.0
+
+
+def _gmst(jd_ut: np.ndarray) -> np.ndarray:
+ """Greenwich mean sidereal time in degrees. Earth rotation runs on UT."""
+ d = jd_ut - _J2000
+ t = d / 36525.0
+ theta = (
+ 280.46061837
+ + 360.98564736629 * d
+ + 0.000387933 * t * t
+ - t * t * t / 38_710_000.0
+ )
+ return theta % 360.0
+
+
+# -- ephemerides ---------------------------------------------------------------
+
+
+def _sun_ecliptic(t: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """Apparent geocentric longitude (deg), distance (AU), nutation argument."""
+ mean_lon = 280.46646 + 36000.76983 * t + 0.0003032 * t * t
+ anomaly = 357.52911 + 35999.05029 * t - 0.0001537 * t * t
+ eccentricity = 0.016708634 - 0.000042037 * t - 0.0000001267 * t * t
+ m = np.radians(anomaly)
+ centre = (
+ (1.914602 - 0.004817 * t - 0.000014 * t * t) * np.sin(m)
+ + (0.019993 - 0.000101 * t) * np.sin(2 * m)
+ + 0.000289 * np.sin(3 * m)
+ )
+ true_lon = mean_lon + centre
+ true_anomaly = np.radians(anomaly + centre)
+ distance = (
+ 1.000001018
+ * (1 - eccentricity * eccentricity)
+ / (1 + eccentricity * np.cos(true_anomaly))
+ )
+ # Ascending node of the moon's orbit: it drives both the nutation in
+ # longitude applied here and the one in obliquity applied below.
+ node = 125.04 - 1934.136 * t
+ apparent_lon = true_lon - 0.00569 - 0.00478 * np.sin(np.radians(node))
+ return apparent_lon % 360.0, distance, node
+
+
+def _moon_ecliptic(t: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """Geocentric ecliptic longitude, latitude (deg) and distance (km)."""
+ d = t * 36525.0 + _MOON_EPOCH_OFFSET
+
+ node = 125.1228 - 0.0529538083 * d
+ inclination = 5.1454
+ perigee = 318.0634 + 0.1643573223 * d
+ axis = 60.2666 # Earth radii
+ eccentricity = 0.054900
+ anomaly = 115.3654 + 13.0649929509 * d
+
+ sun_perihelion = 282.9404 + 4.70935e-5 * d
+ sun_anomaly = 356.0470 + 0.9856002585 * d
+
+ # Kepler, twice round: the eccentricity is small enough that a seed plus one
+ # Newton step lands well inside the series' own error.
+ m = np.radians(anomaly)
+ ecc_anomaly = anomaly + np.degrees(
+ eccentricity * np.sin(m) * (1 + eccentricity * np.cos(m))
+ )
+ e0 = np.radians(ecc_anomaly)
+ ecc_anomaly = ecc_anomaly - (
+ ecc_anomaly - np.degrees(eccentricity * np.sin(e0)) - anomaly
+ ) / (1 - eccentricity * np.cos(e0))
+ e1 = np.radians(ecc_anomaly)
+
+ x = axis * (np.cos(e1) - eccentricity)
+ y = axis * np.sqrt(1 - eccentricity * eccentricity) * np.sin(e1)
+ radius = np.hypot(x, y)
+ true_anomaly = np.degrees(np.arctan2(y, x))
+
+ arg = np.radians(true_anomaly + perigee)
+ node_r = np.radians(node)
+ inc_r = np.radians(inclination)
+ xe = radius * (np.cos(node_r) * np.cos(arg) - np.sin(node_r) * np.sin(arg) * np.cos(inc_r))
+ ye = radius * (np.sin(node_r) * np.cos(arg) + np.cos(node_r) * np.sin(arg) * np.cos(inc_r))
+ ze = radius * np.sin(arg) * np.sin(inc_r)
+
+ lon = np.degrees(np.arctan2(ye, xe))
+ lat = np.degrees(np.arctan2(ze, np.hypot(xe, ye)))
+
+ # Perturbations, in the order of their size. The named ones are the classical
+ # inequalities: evection, variation, the yearly equation, the parallactic.
+ sun_lon = sun_anomaly + sun_perihelion
+ moon_lon = anomaly + perigee + node
+ elong = np.radians(moon_lon - sun_lon) # D
+ argl = np.radians(moon_lon - node) # F
+ ms = np.radians(sun_anomaly)
+ mm = np.radians(anomaly)
+
+ lon = (
+ lon
+ - 1.274 * np.sin(mm - 2 * elong) # evection
+ + 0.658 * np.sin(2 * elong) # variation
+ - 0.186 * np.sin(ms) # yearly equation
+ - 0.059 * np.sin(2 * mm - 2 * elong)
+ - 0.057 * np.sin(mm - 2 * elong + ms)
+ + 0.053 * np.sin(2 * elong + ms)
+ + 0.046 * np.sin(2 * elong - ms)
+ + 0.041 * np.sin(mm - ms)
+ - 0.035 * np.sin(elong) # parallactic
+ - 0.031 * np.sin(mm + ms)
+ - 0.015 * np.sin(2 * argl - 2 * elong)
+ + 0.011 * np.sin(mm - 4 * elong)
+ )
+ lat = (
+ lat
+ - 0.173 * np.sin(argl - 2 * elong)
+ - 0.055 * np.sin(mm - argl - 2 * elong)
+ - 0.046 * np.sin(mm + argl - 2 * elong)
+ + 0.033 * np.sin(argl + 2 * elong)
+ + 0.017 * np.sin(2 * mm + argl)
+ )
+ radius = radius - 0.58 * np.cos(mm - 2 * elong) - 0.46 * np.cos(2 * elong)
+
+ return lon % 360.0, lat, radius * EARTH_RADIUS_KM
+
+
+def _obliquity(t: np.ndarray, node: np.ndarray) -> np.ndarray:
+ """True obliquity of the ecliptic in degrees (Meeus 22.2, plus nutation)."""
+ mean = (
+ 23.4392911
+ - 0.0130041667 * t
+ - 1.6666667e-7 * t * t
+ + 5.0277778e-7 * t * t * t
+ )
+ return mean + 0.00256 * np.cos(np.radians(node))
+
+
+def _to_equatorial(
+ lon: np.ndarray, lat: np.ndarray, obliquity: np.ndarray
+) -> tuple[np.ndarray, np.ndarray]:
+ """Ecliptic to right ascension and declination, both in degrees."""
+ lon_r = np.radians(lon)
+ lat_r = np.radians(lat)
+ eps = np.radians(obliquity)
+ ra = np.degrees(
+ np.arctan2(
+ np.sin(lon_r) * np.cos(eps) - np.tan(lat_r) * np.sin(eps), np.cos(lon_r)
+ )
+ )
+ dec = np.degrees(
+ np.arcsin(np.sin(lat_r) * np.cos(eps) + np.cos(lat_r) * np.sin(eps) * np.sin(lon_r))
+ )
+ return ra % 360.0, dec
+
+
+def _to_horizontal(
+ hour_angle: np.ndarray, dec: np.ndarray, latitude: float
+) -> tuple[np.ndarray, np.ndarray]:
+ """Hour angle and declination to azimuth from north, and true altitude."""
+ h = np.radians(hour_angle)
+ d = np.radians(dec)
+ phi = np.radians(latitude)
+ altitude = np.degrees(
+ np.arcsin(np.sin(phi) * np.sin(d) + np.cos(phi) * np.cos(d) * np.cos(h))
+ )
+ # Meeus measures azimuth from the south, westward; turn it to the compass.
+ azimuth = np.degrees(
+ np.arctan2(np.sin(h), np.cos(h) * np.sin(phi) - np.tan(d) * np.cos(phi))
+ )
+ return (azimuth + 180.0) % 360.0, altitude
+
+
+def _refracted(altitude: np.ndarray) -> np.ndarray:
+ """Apparent altitude: what an observer sees, given standard refraction.
+
+ Bennett's formula, which the atmosphere only ever loosely obeys. Below the
+ horizon it is held at the horizon's own value rather than diverging.
+ """
+ h = np.maximum(altitude, -1.0)
+ minutes = 1.02 / np.tan(np.radians(h + 10.3 / (h + 5.11)))
+ return altitude + minutes / 60.0
+
+
+# -- positions -----------------------------------------------------------------
+
+
+def _positions(lat: float, lon: float, jd_ut: np.ndarray) -> dict[str, np.ndarray]:
+ t = _centuries_tt(jd_ut)
+ sun_lon, sun_dist_au, node = _sun_ecliptic(t)
+ moon_lon, moon_lat, moon_dist_km = _moon_ecliptic(t)
+ obliquity = _obliquity(t, node)
+
+ sun_ra, sun_dec = _to_equatorial(sun_lon, np.zeros_like(sun_lon), obliquity)
+ moon_ra, moon_dec = _to_equatorial(moon_lon, moon_lat, obliquity)
+
+ sidereal = (_gmst(jd_ut) + lon) % 360.0
+ sun_ha = sidereal - sun_ra
+ moon_ha = sidereal - moon_ra
+
+ sun_az, sun_alt = _to_horizontal(sun_ha, sun_dec, lat)
+ moon_az, moon_alt_geocentric = _to_horizontal(moon_ha, moon_dec, lat)
+
+ # The correction that matters: the moon seen from the ground sits up to 0.95°
+ # lower than the moon seen from the centre of the Earth.
+ parallax = np.degrees(np.arcsin(EARTH_RADIUS_KM / moon_dist_km))
+ moon_alt = moon_alt_geocentric - parallax * np.cos(np.radians(moon_alt_geocentric))
+
+ # Phase: elongation first, then the phase angle from the triangle
+ # sun-earth-moon, which gives the illuminated fraction.
+ delta_ra = np.radians(sun_ra - moon_ra)
+ sd = np.radians(sun_dec)
+ md = np.radians(moon_dec)
+ cos_elong = np.sin(sd) * np.sin(md) + np.cos(sd) * np.cos(md) * np.cos(delta_ra)
+ elongation = np.arccos(np.clip(cos_elong, -1.0, 1.0))
+ sun_dist_km = sun_dist_au * AU_KM
+ phase_angle = np.arctan2(
+ sun_dist_km * np.sin(elongation), moon_dist_km - sun_dist_km * cos_elong
+ )
+ illuminated = (1 + np.cos(phase_angle)) / 2
+
+ # Position angle of the bright limb, from the celestial north pole; then the
+ # same angle referred to the observer's vertical, which is the one a photo
+ # shows. The difference is the parallactic angle.
+ limb_pa = np.degrees(
+ np.arctan2(
+ np.cos(sd) * np.sin(delta_ra),
+ np.sin(sd) * np.cos(md) - np.cos(sd) * np.sin(md) * np.cos(delta_ra),
+ )
+ )
+ phi = np.radians(lat)
+ mh = np.radians(moon_ha)
+ parallactic = np.degrees(
+ np.arctan2(np.sin(mh), np.tan(phi) * np.cos(md) - np.sin(md) * np.cos(mh))
+ )
+
+ return {
+ "sun_azimuth": sun_az,
+ "sun_altitude": sun_alt,
+ "sun_apparent_altitude": _refracted(sun_alt),
+ "sun_distance_km": sun_dist_km,
+ "moon_azimuth": moon_az,
+ "moon_altitude": moon_alt,
+ "moon_apparent_altitude": _refracted(moon_alt),
+ "moon_distance_km": moon_dist_km,
+ "moon_parallax": parallax,
+ "moon_illuminated": illuminated,
+ "moon_phase_angle": np.degrees(phase_angle),
+ "moon_elongation": (moon_lon - sun_lon) % 360.0,
+ "moon_limb_angle": limb_pa % 360.0,
+ "moon_limb_from_vertical": (limb_pa - parallactic) % 360.0,
+ }
+
+
+def positions(
+ lat: float, lon: float, times: Sequence[datetime] | np.ndarray
+) -> dict[str, np.ndarray]:
+ """Sun and moon geometry at each instant, as arrays parallel to ``times``."""
+ return _positions(lat, lon, _julian_day(times))
+
+
+def phase_name(elongation: float) -> str:
+ """Name the phase from the moon's elongation in longitude, in degrees."""
+ value = elongation % 360.0
+ for limit, name in _PHASE_NAMES:
+ if value < limit:
+ return name
+ return "new moon"
+
+
+def position_at(lat: float, lon: float, when: datetime) -> dict[str, Any]:
+ """One instant, as plain floats, with the phase named."""
+ values = positions(lat, lon, [when])
+ out: dict[str, Any] = {key: float(arr[0]) for key, arr in values.items()}
+ out["moon_phase"] = phase_name(out["moon_elongation"])
+ out["moon_waxing"] = out["moon_elongation"] < 180.0
+ return out
+
+
+# -- events --------------------------------------------------------------------
+
+
+def _grid(start: datetime, end: datetime, step_seconds: int) -> np.ndarray:
+ span = int((end - start).total_seconds())
+ steps = span // step_seconds
+ offsets = np.arange(steps + 1, dtype="float64") * step_seconds
+ return _julian_day([start])[0] + offsets / 86400.0
+
+
+def _crossings(
+ jd: np.ndarray, value: np.ndarray, refine: Any
+) -> tuple[list[float], list[float]]:
+ """Instants where ``value`` changes sign, split into rising and falling.
+
+ ``value`` is altitude minus the threshold on a one-minute grid, where the
+ curve is near enough to a line that a linear guess lands within a second;
+ ``refine`` then re-evaluates the real function to place it exactly.
+ """
+ rising: list[float] = []
+ falling: list[float] = []
+ sign = np.sign(value)
+ # A sample landing exactly on the threshold would otherwise swallow a
+ # crossing; nudge it to the side the previous sample came from.
+ for index in np.nonzero(sign == 0)[0]:
+ sign[index] = sign[index - 1] if index > 0 else 1.0
+ changes = np.nonzero(sign[:-1] != sign[1:])[0]
+ for index in changes:
+ moment = refine(jd[index], jd[index + 1])
+ if sign[index] < 0:
+ rising.append(moment)
+ else:
+ falling.append(moment)
+ return rising, falling
+
+
+def _secant(fn: Any, low: float, high: float, iterations: int = 4) -> float:
+ """Place a crossing of ``fn`` bracketed by ``low``/``high`` to the second.
+
+ False position, returning the last interpolated root rather than the middle
+ of the surviving bracket: on a curve this straight one side of the bracket
+ never moves, so its midpoint would sit a good ten seconds off.
+ """
+ f_low = fn(low)
+ f_high = fn(high)
+ estimate = (low + high) / 2
+ for _ in range(iterations):
+ if f_high == f_low:
+ break
+ estimate = low + (high - low) * f_low / (f_low - f_high)
+ estimate = min(max(estimate, low), high)
+ f_estimate = fn(estimate)
+ if f_estimate == 0:
+ break
+ if (f_estimate < 0) == (f_low < 0):
+ low, f_low = estimate, f_estimate
+ else:
+ high, f_high = estimate, f_estimate
+ return estimate
+
+
+def _extremum(jd: np.ndarray, altitude: np.ndarray) -> tuple[float, float] | None:
+ """The interior peak of an altitude curve, sharpened by a parabola fit."""
+ index = int(np.argmax(altitude))
+ if index == 0 or index == len(altitude) - 1:
+ return None
+ before, peak, after = altitude[index - 1 : index + 2]
+ denominator = before - 2 * peak + after
+ shift = 0.0 if denominator == 0 else 0.5 * (before - after) / denominator
+ step = jd[index + 1] - jd[index]
+ top = peak - 0.25 * (before - after) * shift
+ return float(jd[index] + shift * step), float(top)
+
+
+def _state(rises: list[float], sets: list[float], above: bool) -> str:
+ if rises or sets:
+ return "rises"
+ return "always_up" if above else "always_down"
+
+
+def _before(moments: list[float], anchor: float) -> float | None:
+ """The latest of ``moments`` at or before the anchor."""
+ earlier = [m for m in moments if m <= anchor]
+ return max(earlier) if earlier else None
+
+
+def _after(moments: list[float], anchor: float) -> float | None:
+ """The earliest of ``moments`` at or after the anchor."""
+ later = [m for m in moments if m >= anchor]
+ return min(later) if later else None
+
+
+# How far past the civil day the search runs. A sunset or the end of a twilight
+# belongs to the evening of its date even when it falls after local midnight,
+# which is routine in summer at high latitude and for astronomical twilight in
+# temperate ones. Eight hours covers both ends.
+_EVENING_MARGIN = timedelta(hours=8)
+
+
+def day_events(
+ lat: float, lon: float, start: datetime, end: datetime
+) -> dict[str, Any]:
+ """Rises, sets, transits and twilights for one local day of UTC instants.
+
+ ``start`` and ``end`` bound the local day the caller cares about; a day is
+ a civil notion, so working out those two instants belongs to the caller (see
+ ``engine.localtime``) and this stays pure geometry.
+
+ Solar events are paired around that day's culmination, the way an almanac
+ pairs them: the morning event is the last one before the sun's transit, the
+ evening event the first one after it. Picking "first and last inside the civil
+ day" instead would report this evening's dusk as tomorrow's and, once past
+ midnight, hand back yesterday's. Lunar events have no such anchor, so they
+ are simply the ones falling on the date, as a list.
+
+ Polar day and night, and the days on which the moon does not rise, come back
+ as a ``state`` on the body rather than as a missing value or an error: they
+ are answers, and at high latitude they are the usual answer.
+ """
+ # One grid, wide enough for the evening overflow; the state of the day is
+ # then read from the civil-day slice of it alone, so a day inside the polar
+ # day is never called "rises" because a neighbouring day has a sunrise.
+ jd = _grid(start - _EVENING_MARGIN, end + _EVENING_MARGIN, 60)
+ day_start = _julian_day([start])[0]
+ day_end = _julian_day([end])[0]
+ inside = (jd >= day_start) & (jd <= day_end)
+
+ values = _positions(lat, lon, jd)
+ sun_alt = values["sun_altitude"]
+ moon_alt = values["moon_altitude"]
+ # The moon's threshold rides its distance, so it is an array, not a constant.
+ moon_horizon = REFRACTION_DEG - MOON_SEMIDIAMETER_RATIO * values["moon_parallax"]
+
+ def sun_offset(threshold: float) -> Any:
+ return lambda point: float(
+ _positions(lat, lon, np.array([point]))["sun_altitude"][0] - threshold
+ )
+
+ def moon_offset(point: float) -> float:
+ one = _positions(lat, lon, np.array([point]))
+ limit = REFRACTION_DEG - MOON_SEMIDIAMETER_RATIO * float(one["moon_parallax"][0])
+ return float(one["moon_altitude"][0] - limit)
+
+ def azimuth_at(moment: float, body: str) -> float:
+ return float(_positions(lat, lon, np.array([moment]))[body][0])
+
+ def within_day(moments: list[float]) -> list[float]:
+ return [m for m in moments if day_start <= m <= day_end]
+
+ transit = _extremum(jd[inside], sun_alt[inside])
+ anchor = transit[0] if transit else (day_start + day_end) / 2
+
+ def solar_pair(threshold: float) -> tuple[float | None, float | None, str]:
+ fn = sun_offset(threshold)
+ rising, falling = _crossings(
+ jd, sun_alt - threshold, lambda low, high: _secant(fn, low, high)
+ )
+ state = _state(
+ within_day(rising),
+ within_day(falling),
+ bool(sun_alt[inside][0] > threshold),
+ )
+ if state != "rises":
+ return None, None, state
+ return _before(rising, anchor), _after(falling, anchor), state
+
+ rise, set_, sun_state = solar_pair(SUN_HORIZON_DEG)
+ sun: dict[str, Any] = {
+ "rise": _to_datetime(rise) if rise else None,
+ "rise_azimuth": round(azimuth_at(rise, "sun_azimuth"), 1) if rise else None,
+ "set": _to_datetime(set_) if set_ else None,
+ "set_azimuth": round(azimuth_at(set_, "sun_azimuth"), 1) if set_ else None,
+ "transit": _to_datetime(transit[0]) if transit else None,
+ "transit_altitude": round(transit[1], 2) if transit else None,
+ "state": sun_state,
+ }
+
+ twilight: dict[str, Any] = {}
+ for name, threshold in TWILIGHTS.items():
+ dawn, dusk, state = solar_pair(threshold)
+ twilight[name] = {
+ "dawn": _to_datetime(dawn) if dawn else None,
+ "dusk": _to_datetime(dusk) if dusk else None,
+ "state": state,
+ }
+
+ moon_rises, moon_sets = _crossings(
+ jd, moon_alt - moon_horizon, lambda low, high: _secant(moon_offset, low, high)
+ )
+ moon_rises = within_day(moon_rises)
+ moon_sets = within_day(moon_sets)
+ moon_transit = _extremum(jd[inside], moon_alt[inside])
+ moon: dict[str, Any] = {
+ # Whether a date holds one event, two or none is what the crossing search
+ # finds, not something assumed here, so these stay lists.
+ "rises": [_to_datetime(m) for m in moon_rises],
+ "rise_azimuths": [round(azimuth_at(m, "moon_azimuth"), 1) for m in moon_rises],
+ "sets": [_to_datetime(m) for m in moon_sets],
+ "set_azimuths": [round(azimuth_at(m, "moon_azimuth"), 1) for m in moon_sets],
+ "transit": _to_datetime(moon_transit[0]) if moon_transit else None,
+ "transit_altitude": round(moon_transit[1], 2) if moon_transit else None,
+ "state": _state(
+ moon_rises, moon_sets, bool(moon_alt[inside][0] > moon_horizon[inside][0])
+ ),
+ }
+ return {"sun": sun, "twilight": twilight, "moon": moon}
+
+
+def day_curve(
+ lat: float, lon: float, start: datetime, end: datetime, step_minutes: int = 10
+) -> dict[str, Any]:
+ """Sampled altitude and azimuth tracks, for the chart of a day."""
+ jd = _grid(start, end, step_minutes * 60)
+ values = _positions(lat, lon, jd)
+ return {
+ "times": [_to_datetime(point) for point in jd],
+ "sun_altitude": [round(v, 3) for v in values["sun_altitude"].tolist()],
+ "sun_azimuth": [round(v, 2) for v in values["sun_azimuth"].tolist()],
+ "moon_altitude": [round(v, 3) for v in values["moon_altitude"].tolist()],
+ "moon_azimuth": [round(v, 2) for v in values["moon_azimuth"].tolist()],
+ "moon_illuminated": [round(v, 4) for v in values["moon_illuminated"].tolist()],
+ }
diff --git a/tests/test_geo_api.py b/tests/test_geo_api.py
index 00c0985..4f34896 100644
--- a/tests/test_geo_api.py
+++ b/tests/test_geo_api.py
@@ -132,3 +132,184 @@ def test_parse_accepts_the_formats_it_emits(client):
def test_parse_rejects_gibberish_with_422(client):
assert client.post("/api/geo/parse", json={"text": "hello world"}).status_code == 422
+
+
+# -- /api/geo/sky ---------------------------------------------------------------
+#
+# The geometry itself is covered in tests/test_sky.py. What matters here is the
+# contract the panel reads: local and UTC side by side, states instead of errors,
+# a curve that spans the day, and validation at the edge.
+
+
+def test_sky_reports_every_instant_in_local_time_and_utc(client):
+ response = client.get(
+ "/api/geo/sky",
+ params={"lat": 48.8584, "lon": 2.2945, "date": "2026-07-30", "time": "14:20"},
+ )
+ assert response.status_code == 200
+ body = response.json()
+ assert body["zone"]["name"] == "Europe/Paris"
+ assert body["zone"]["abbreviation"] == "CEST"
+ assert body["moment"]["local"].startswith("2026-07-30T14:20")
+ assert body["moment"]["utc"] == "2026-07-30T12:20:00Z"
+ for stamp in (body["sun"]["rise"], body["sun"]["set"], body["sun"]["transit"]):
+ assert stamp["utc"].endswith("Z")
+ assert stamp["offset"] == "+02:00"
+ assert stamp["abbreviation"] == "CEST"
+
+
+def test_sky_gives_the_positions_at_the_moment_asked_for(client):
+ response = client.get(
+ "/api/geo/sky",
+ params={"lat": 48.8584, "lon": 2.2945, "date": "2026-07-30", "time": "14:20"},
+ )
+ body = response.json()
+ assert 180 < body["sun"]["azimuth"] < 220 # early afternoon, past due south
+ assert body["sun"]["altitude"] > 50
+ assert 0 <= body["moon"]["illuminated"] <= 1
+ assert body["moon"]["phase"]
+ assert isinstance(body["moon"]["waxing"], bool)
+ assert body["moon"]["distance_km"] > 300_000
+
+
+def test_sky_defaults_to_local_midday_today(client):
+ """No date and no time: the point's own today, read at local noon."""
+ body = client.get("/api/geo/sky", params={"lat": 48.8584, "lon": 2.2945}).json()
+ assert body["moment"]["local"][11:16] == "12:00"
+ assert body["date"] == body["moment"]["local"][:10]
+
+
+def test_sky_reports_the_midnight_sun_as_a_state(client):
+ body = client.get(
+ "/api/geo/sky", params={"lat": 69.6492, "lon": 18.9553, "date": "2026-06-21"}
+ ).json()
+ assert body["sun"]["state"] == "always_up"
+ assert body["sun"]["rise"] is None
+ assert body["sun"]["set"] is None
+ assert body["sun"]["transit_altitude"] > 40
+
+
+def test_sky_reports_polar_night_as_a_state(client):
+ body = client.get(
+ "/api/geo/sky", params={"lat": -89.0, "lon": 0.0, "date": "2026-06-21"}
+ ).json()
+ assert body["sun"]["state"] == "always_down"
+ assert body["twilight"]["astronomical"]["state"] == "always_down"
+
+
+def test_sky_carries_the_moon_events_as_lists(client):
+ body = client.get(
+ "/api/geo/sky", params={"lat": 48.8584, "lon": 2.2945, "date": "2026-07-30"}
+ ).json()
+ assert isinstance(body["moon"]["rises"], list)
+ assert len(body["moon"]["rise_azimuths"]) == len(body["moon"]["rises"])
+ assert len(body["moon"]["set_azimuths"]) == len(body["moon"]["sets"])
+
+
+def test_sky_curve_spans_the_day_in_minutes_from_local_midnight(client):
+ body = client.get(
+ "/api/geo/sky", params={"lat": 48.8584, "lon": 2.2945, "date": "2026-07-30"}
+ ).json()
+ curve = body["curve"]
+ assert curve["minutes"][0] == 0
+ assert curve["minutes"][-1] == 1440
+ for key in ("sun_altitude", "sun_azimuth", "moon_altitude", "moon_azimuth"):
+ assert len(curve[key]) == len(curve["minutes"])
+
+
+def test_sky_curve_follows_a_daylight_saving_day(client):
+ """The x axis is minutes of the local day, so it is 23 hours long in March."""
+ body = client.get(
+ "/api/geo/sky", params={"lat": 48.8584, "lon": 2.2945, "date": "2026-03-29"}
+ ).json()
+ assert body["curve"]["minutes"][-1] == 1380
+ assert body["zone"]["abbreviation"] == "CEST"
+
+
+def test_sky_curve_carries_the_wall_clock_of_each_sample(client):
+ """Anything that labels a sample to the reader reads this, because the wall
+ clock cannot be divided out of the minute count."""
+ body = client.get(
+ "/api/geo/sky", params={"lat": 48.8584, "lon": 2.2945, "date": "2026-07-30"}
+ ).json()
+ curve = body["curve"]
+ assert len(curve["clock"]) == len(curve["minutes"])
+ assert curve["clock"][0] == "00:00"
+ assert curve["clock"][6] == "01:00"
+ assert curve["clock"][-1] == "00:00" # the following midnight
+
+
+def test_sky_clock_skips_the_hour_daylight_saving_took(client):
+ """On the spring-forward day the local clock jumps from 02:00 to 03:00, so no
+ sample reads 02:xx while the minute count runs straight through."""
+ body = client.get(
+ "/api/geo/sky", params={"lat": 48.8584, "lon": 2.2945, "date": "2026-03-29"}
+ ).json()
+ curve = body["curve"]
+ assert not [stamp for stamp in curve["clock"] if stamp.startswith("02:")]
+ assert "03:00" in curve["clock"]
+ # the sample two hours of elapsed time in reads 03:00, not 02:00
+ assert curve["clock"][curve["minutes"].index(120)] == "03:00"
+
+
+def test_sky_clock_repeats_the_hour_daylight_saving_gave_back(client):
+ """And on the autumn day 02:00 to 03:00 happens twice."""
+ body = client.get(
+ "/api/geo/sky", params={"lat": 48.8584, "lon": 2.2945, "date": "2026-10-25"}
+ ).json()
+ assert body["curve"]["clock"].count("02:00") == 2
+
+
+def test_sky_accepts_a_zone_override(client):
+ body = client.get(
+ "/api/geo/sky",
+ params={
+ "lat": 48.8584,
+ "lon": 2.2945,
+ "date": "2026-07-30",
+ "time": "12:00",
+ "zone": "UTC",
+ },
+ ).json()
+ assert body["zone"]["name"] == "UTC"
+ assert body["moment"]["utc"] == "2026-07-30T12:00:00Z"
+
+
[email protected]("zone", ["Mars/Olympus", "../../../etc/passwd", "A" * 5000])
+def test_sky_refuses_a_zone_it_cannot_load(client, zone):
+ """Rather than answering in UTC under the name that was asked for, which would
+ put every time in the response an offset out with nothing saying so."""
+ response = client.get(
+ "/api/geo/sky",
+ params={"lat": 48.8584, "lon": 2.2945, "date": "2026-07-30", "zone": zone},
+ )
+ assert response.status_code == 422
+
+
+ "params",
+ [
+ {"lat": 91, "lon": 0},
+ {"lat": 0, "lon": 181},
+ {"lat": 0, "lon": 0, "date": "30-07-2026"},
+ {"lat": 0, "lon": 0, "time": "25h"},
+ ],
+)
+def test_sky_validates_at_the_edge(client, params):
+ assert client.get("/api/geo/sky", params=params).status_code == 422
+
+
+def test_sky_never_touches_the_network(client, monkeypatch):
+ """Opening the panel must not phone out. The reverse geocode beside it in the
+ same tool does; this route is pure computation, and stays that way."""
+ import httpx
+
+ def explode(*args, **kwargs):
+ raise AssertionError("the sky is computed locally")
+
+ monkeypatch.setattr(httpx.Client, "get", explode)
+ monkeypatch.setattr(httpx.Client, "send", explode)
+ response = client.get(
+ "/api/geo/sky", params={"lat": 48.8584, "lon": 2.2945, "date": "2026-07-30"}
+ )
+ assert response.status_code == 200
diff --git a/tests/test_sky.py b/tests/test_sky.py
new file mode 100644
index 0000000..036e894
--- /dev/null
+++ b/tests/test_sky.py
@@ -0,0 +1,457 @@
+"""Sun and moon geometry: published references, physical invariants, edge states.
+
+Two kinds of check, because no single one is enough. The ephemerides are pinned
+to Meeus's own worked examples, which are external truth. The events — rises,
+sets, twilights — have no memorised reference to lean on, so they are held to
+invariants the geometry cannot fake: the altitude at the returned instant *is*
+the horizon, the day is symmetric about the transit, and the equinox behaves at
+the equator the way spherical trigonometry says it must.
+
+Polar day, polar night and the days with no moonrise get their own tests. They
+are the reason ``state`` exists, and they are the common answer at high latitude
+rather than an exotic one.
+"""
+
+from datetime import UTC, date, datetime, time, timedelta
+
+import numpy as np
+import pytest
+
+from azimut.engine import localtime, sky
+
+PARIS = (48.8584, 2.2945)
+TROMSO = (69.6492, 18.9553)
+SOUTH_POLE_ISH = (-89.0, 0.0)
+EQUATOR = (0.0, 0.0)
+
+
+def _events(lat, lon, day, zone=None):
+ zone = zone or localtime.zone_for(lat, lon)
+ start, end = localtime.day_bounds(day, zone)
+ return sky.day_events(lat, lon, start, end), zone
+
+
+def _altitude(lat, lon, moment, body="sun_altitude"):
+ return float(sky.positions(lat, lon, [moment])[body][0])
+
+
+# -- ephemerides against Meeus -------------------------------------------------
+
+
+def test_sun_matches_meeus_example_25b():
+ """1992-10-13.0 TD: apparent longitude 199.90895°, distance 0.99766 AU."""
+ t = np.array([(2448908.5 - 2451545.0) / 36525.0])
+ lon, distance, _node = sky._sun_ecliptic(t)
+ assert abs(lon[0] - 199.90895) < 1e-4
+ assert abs(distance[0] - 0.99766) < 1e-4
+
+
+def test_moon_matches_meeus_example_47a():
+ """1992-04-12.0 TD: longitude 133.162655°, latitude -3.229126°, 368409.7 km.
+
+ The truncated series is not the full one, so the tolerances are its own
+ documented error: hundredths of a degree, and a tenth of a percent of the
+ distance. Both are far below the parallax correction they feed.
+ """
+ t = np.array([(2448724.5 - 2451545.0) / 36525.0])
+ lon, lat, distance = sky._moon_ecliptic(t)
+ assert abs(lon[0] - 133.162655) < 0.02
+ assert abs(lat[0] - (-3.229126)) < 0.02
+ assert abs(distance[0] - 368409.7) < 400
+
+
+def test_obliquity_is_current_at_j2000():
+ """23.4392911° mean at J2000, shifted by the nutation term in obliquity."""
+ obliquity = sky._obliquity(np.array([0.0]), np.array([125.04]))
+ assert abs(obliquity[0] - 23.4392911) < 0.005
+
+
+# -- the corrections that decide an event --------------------------------------
+
+
+def test_moon_parallax_lowers_it_by_up_to_a_degree():
+ """Seen from the ground the moon sits below where the centre of the Earth
+ sees it, by nearly a degree at the zenith. This is the term that moves a
+ moonrise by minutes, so it is asserted rather than trusted."""
+ moment = datetime(2026, 7, 30, 12, 0, tzinfo=UTC)
+ values = sky.positions(*PARIS, [moment])
+ parallax = float(values["moon_parallax"][0])
+ assert 0.89 < parallax < 1.02
+ geocentric = float(values["moon_altitude"][0]) + parallax * np.cos(
+ np.radians(float(values["moon_altitude"][0]))
+ )
+ assert geocentric > float(values["moon_altitude"][0])
+
+
+def test_refraction_lifts_a_body_at_the_horizon():
+ """Half a degree of lift at the horizon, and next to none overhead."""
+ assert 0.4 < float(sky._refracted(np.array([0.0]))[0]) < 0.7
+ assert abs(float(sky._refracted(np.array([80.0]))[0]) - 80.0) < 0.01
+
+
+# -- events, held to invariants -------------------------------------------------
+
+
+def test_sunrise_and_sunset_land_on_the_horizon():
+ """At the instants returned, the sun's altitude is the rise/set convention."""
+ events, _zone = _events(*PARIS, date(2026, 7, 30))
+ for moment in (events["sun"]["rise"], events["sun"]["set"]):
+ assert abs(_altitude(*PARIS, moment) - sky.SUN_HORIZON_DEG) < 0.005
+
+
+def test_twilight_instants_land_on_their_own_threshold():
+ events, _zone = _events(*PARIS, date(2026, 7, 30))
+ for name, threshold in sky.TWILIGHTS.items():
+ for moment in (events["twilight"][name]["dawn"], events["twilight"][name]["dusk"]):
+ assert abs(_altitude(*PARIS, moment) - threshold) < 0.005
+
+
+def test_moonrise_lands_on_the_moons_own_threshold():
+ """The moon's threshold rides its distance, so this also checks that the
+ per-instant semidiameter is the one used, not a constant."""
+ events, _zone = _events(*PARIS, date(2026, 7, 30))
+ assert events["moon"]["rises"]
+ for moment in events["moon"]["rises"] + events["moon"]["sets"]:
+ values = sky.positions(*PARIS, [moment])
+ threshold = sky.REFRACTION_DEG - sky.MOON_SEMIDIAMETER_RATIO * float(
+ values["moon_parallax"][0]
+ )
+ assert abs(float(values["moon_altitude"][0]) - threshold) < 0.005
+
+
+def test_day_is_symmetric_about_solar_noon():
+ """Sunrise and sunset sit equally far from the transit, to within the
+ seconds the sun's own motion in declination adds over half a day."""
+ events, _zone = _events(*PARIS, date(2026, 7, 30))
+ before = events["sun"]["transit"] - events["sun"]["rise"]
+ after = events["sun"]["set"] - events["sun"]["transit"]
+ assert abs((after - before).total_seconds()) < 60
+
+
+def test_solar_noon_altitude_follows_latitude_and_declination():
+ """At the June solstice the transit altitude is 90° − lat + 23.44°, which is
+ a closed form the series has to reproduce."""
+ events, _zone = _events(*TROMSO, date(2026, 6, 21))
+ expected = 90.0 - TROMSO[0] + 23.44
+ assert abs(events["sun"]["transit_altitude"] - expected) < 0.1
+
+
+def test_equinox_at_the_equator_rises_due_east():
+ events, _zone = _events(*EQUATOR, date(2026, 3, 20))
+ assert abs(events["sun"]["rise_azimuth"] - 90.0) < 1.0
+ assert abs(events["sun"]["set_azimuth"] - 270.0) < 1.0
+ # Twelve hours plus the few minutes refraction and the sun's disc add.
+ length = (events["sun"]["set"] - events["sun"]["rise"]).total_seconds() / 3600
+ assert 12.0 < length < 12.2
+
+
+def test_transit_altitude_is_the_peak_of_the_curve():
+ """The parabola fit must not overshoot the sampled maximum by more than the
+ curvature it is correcting for."""
+ zone = localtime.zone_for(*PARIS)
+ start, end = localtime.day_bounds(date(2026, 7, 30), zone)
+ events = sky.day_events(*PARIS, start, end)
+ curve = sky.day_curve(*PARIS, start, end, step_minutes=1)
+ # Both values are rounded for display, so they agree to that rounding.
+ assert events["sun"]["transit_altitude"] >= max(curve["sun_altitude"]) - 0.01
+ assert events["sun"]["transit_altitude"] <= max(curve["sun_altitude"]) + 0.01
+
+
+# -- states, not errors ---------------------------------------------------------
+
+
+def test_midnight_sun_is_a_state():
+ events, _zone = _events(*TROMSO, date(2026, 6, 21))
+ assert events["sun"]["state"] == "always_up"
+ assert events["sun"]["rise"] is None
+ assert events["sun"]["set"] is None
+ # The transit is still real, and still the answer to "how high did it get".
+ assert events["sun"]["transit_altitude"] > 40
+
+
+def test_polar_night_is_a_state():
+ events, _zone = _events(*SOUTH_POLE_ISH, date(2026, 6, 21))
+ assert events["sun"]["state"] == "always_down"
+ assert events["sun"]["transit_altitude"] < 0
+ assert events["twilight"]["astronomical"]["state"] == "always_down"
+
+
+def test_short_summer_night_never_gets_dark():
+ """North of about 48.5° there is no astronomical night at the solstice, while
+ civil twilight still ends: the three twilights carry independent states."""
+ events, _zone = _events(*PARIS, date(2026, 6, 21))
+ assert events["twilight"]["astronomical"]["state"] == "always_up"
+ assert events["twilight"]["civil"]["state"] == "rises"
+
+
+def test_a_day_with_no_moonrise_exists_and_is_a_state():
+ """The moon rises about 50 minutes later each day, so roughly monthly a civil
+ day holds no moonrise at all. Scanning a lunation must find one."""
+ zone = localtime.zone_for(*PARIS)
+ missing = []
+ for offset in range(30):
+ day = date(2026, 7, 1) + timedelta(days=offset)
+ start, end = localtime.day_bounds(day, zone)
+ events = sky.day_events(*PARIS, start, end)
+ if not events["moon"]["rises"]:
+ missing.append((day, events["moon"]["state"]))
+ assert missing, "a lunation always holds a day without a moonrise"
+ for _day, state in missing:
+ assert state in {"rises", "always_up", "always_down"}
+
+
+def test_successive_moonrises_are_more_than_a_day_apart():
+ """The reason the skipped day exists: consecutive moonrises are 24 h 50 m
+ apart, never less, so a civil day holds one or none — never two. The engine
+ returns lists anyway, since it is the crossing search that decides, not an
+ assumption about how many there can be."""
+ zone = localtime.zone_for(*PARIS)
+ rises = []
+ for offset in range(40):
+ day = date(2026, 7, 1) + timedelta(days=offset)
+ start, end = localtime.day_bounds(day, zone)
+ events = sky.day_events(*PARIS, start, end)
+ assert len(events["moon"]["rises"]) <= 1
+ rises.extend(events["moon"]["rises"])
+ gaps = [
+ (later - earlier).total_seconds() / 3600
+ for earlier, later in zip(rises, rises[1:], strict=False)
+ ]
+ assert min(gaps) > 24.0
+ assert max(gaps) < 26.0
+
+
+# -- phase and limb -------------------------------------------------------------
+
+
+def test_phase_names_cover_the_cycle():
+ assert sky.phase_name(0) == "new moon"
+ assert sky.phase_name(90) == "first quarter"
+ assert sky.phase_name(180) == "full moon"
+ assert sky.phase_name(270) == "last quarter"
+ assert sky.phase_name(359) == "new moon"
+ assert sky.phase_name(45) == "waxing crescent"
+ assert sky.phase_name(315) == "waning crescent"
+
+
+def test_illumination_tracks_elongation_over_a_lunation():
+ """Full near opposition, dark near conjunction — checked over a month rather
+ than at one instant, so a sign error anywhere in the phase triangle shows."""
+ moments = [datetime(2026, 7, 1, tzinfo=UTC) + timedelta(days=n) for n in range(30)]
+ values = sky.positions(*PARIS, moments)
+ for elongation, illuminated in zip(
+ values["moon_elongation"], values["moon_illuminated"], strict=True
+ ):
+ expected = (1 - np.cos(np.radians(elongation))) / 2
+ assert abs(illuminated - expected) < 0.03
+
+
+def test_illumination_stays_in_range_across_a_year():
+ moments = [datetime(2026, 1, 1, tzinfo=UTC) + timedelta(hours=n) for n in range(8760)]
+ values = sky.positions(*PARIS, moments)
+ assert values["moon_illuminated"].min() >= 0.0
+ assert values["moon_illuminated"].max() <= 1.0
+ # A year contains both a nearly dark and a nearly full moon.
+ assert values["moon_illuminated"].min() < 0.01
+ assert values["moon_illuminated"].max() > 0.99
+
+
+def _sky_bearing(alt1: float, az1: float, alt2: float, az2: float) -> float:
+ """Great-circle position angle from one point of the local sky to another,
+ measured from the zenith direction towards increasing azimuth.
+
+ The flat approximation is not usable here: sun and moon can sit 90° apart,
+ where it is wrong by tens of degrees.
+ """
+ a1, a2 = np.radians(alt1), np.radians(alt2)
+ delta = np.radians(az2 - az1)
+ return float(
+ np.degrees(
+ np.arctan2(
+ np.cos(a2) * np.sin(delta),
+ np.cos(a1) * np.sin(a2) - np.sin(a1) * np.cos(a2) * np.cos(delta),
+ )
+ )
+ % 360
+ )
+
+
+def test_bright_limb_points_at_the_sun():
+ """The lit side faces the sun, so the limb angle referred to the vertical is
+ the direction of the sun from the moon, mirrored: celestial position angles
+ run north through east, which is the opposite turn to rising azimuth.
+
+ Near new moon the direction is degenerate — there is no lit side to point,
+ and the two bodies are nearly coincident — so that part of the cycle is
+ excluded rather than given a loose tolerance.
+ """
+ checked = 0
+ for offset in range(2000):
+ moment = datetime(2026, 5, 1, tzinfo=UTC) + timedelta(hours=offset)
+ values = sky.positions(*PARIS, [moment])
+ sun_alt = float(values["sun_altitude"][0])
+ moon_alt = float(values["moon_altitude"][0])
+ elongation = float(values["moon_elongation"][0])
+ if sun_alt < 5 or moon_alt < 5 or min(elongation, 360 - elongation) < 15:
+ continue
+ towards_sun = _sky_bearing(
+ moon_alt, float(values["moon_azimuth"][0]), sun_alt, float(values["sun_azimuth"][0])
+ )
+ limb = float(values["moon_limb_from_vertical"][0])
+ # Mirrored, so the two should cancel; what is left is the parallax the
+ # limb angle is computed geocentrically without.
+ difference = abs((limb + towards_sun + 180) % 360 - 180)
+ assert difference < 3, f"{moment}: limb {limb:.1f} vs sun at {towards_sun:.1f}"
+ checked += 1
+ assert checked > 100
+
+
+def test_position_at_names_the_phase_and_direction():
+ values = sky.position_at(*PARIS, datetime(2026, 7, 30, 12, tzinfo=UTC))
+ assert isinstance(values["moon_phase"], str)
+ assert isinstance(values["moon_waxing"], bool)
+ assert values["moon_waxing"] == (values["moon_elongation"] < 180)
+
+
+# -- shape and cost -------------------------------------------------------------
+
+
+def test_positions_are_vectorised_over_instants():
+ """One call, many instants: the property the year-long inverse scan needs."""
+ moments = [datetime(2026, 7, 30, tzinfo=UTC) + timedelta(minutes=n) for n in range(1440)]
+ values = sky.positions(*PARIS, moments)
+ for array in values.values():
+ assert array.shape == (1440,)
+ single = sky.positions(*PARIS, [moments[500]])
+ assert abs(single["sun_azimuth"][0] - values["sun_azimuth"][500]) < 1e-9
+
+
+def test_day_curve_samples_the_whole_interval():
+ zone = localtime.zone_for(*PARIS)
+ start, end = localtime.day_bounds(date(2026, 7, 30), zone)
+ curve = sky.day_curve(*PARIS, start, end, step_minutes=10)
+ assert len(curve["times"]) == 145
+ assert curve["times"][0] == start
+ assert curve["times"][-1] == end
+ assert len(curve["sun_altitude"]) == len(curve["times"])
+
+
+def test_a_year_of_minutes_stays_interactive():
+ """The cost budget for the inverse scan: a year, minute by minute, in one
+ call. If this regresses into a Python loop the test notices."""
+ jd = 2461000.0 + np.arange(525_600) / 1440.0
+ values = sky._positions(*PARIS, jd)
+ assert values["sun_azimuth"].shape == (525_600,)
+
+
+# -- civil time ----------------------------------------------------------------
+
+
+def test_zone_is_resolved_from_the_coordinate():
+ assert localtime.zone_for(*PARIS) == "Europe/Paris"
+ assert localtime.zone_for(27.7172, 85.3240) == "Asia/Kathmandu"
+
+
+def test_open_sea_gets_a_nautical_zone_not_an_error():
+ zone = localtime.zone_for(-30.0, -40.0)
+ assert zone
+ assert localtime.zone_info(zone)
+
+
+def test_unknown_zone_falls_back_to_utc():
+ assert localtime.zone_info("Mars/Olympus").key == "UTC"
+ assert not localtime.known_zone("Mars/Olympus")
+
+
+ "name",
+ [
+ "../../../etc/passwd", # rejected before the filesystem
+ "/etc/passwd",
+ "..",
+ "A" * 5000, # reaches the filesystem, where it is ENAMETOOLONG
+ "",
+ ],
+)
+def test_a_zone_name_that_is_not_one_gives_utc_not_a_traceback(name):
+ assert not localtime.known_zone(name)
+ assert localtime.zone_info(name).key == "UTC"
+
+
+def test_both_writes_an_instant_in_local_and_utc():
+ written = localtime.both(datetime(2026, 7, 30, 4, 21, tzinfo=UTC), "Europe/Paris")
+ assert written["utc"] == "2026-07-30T04:21:00Z"
+ assert written["local"].startswith("2026-07-30T06:21:00")
+ assert written["abbreviation"] == "CEST"
+ assert written["offset"] == "+02:00"
+ assert written["offset_minutes"] == 120
+
+
+def test_offset_carries_a_fractional_hour():
+ written = localtime.both(datetime(2026, 7, 30, 6, 15, tzinfo=UTC), "Asia/Kathmandu")
+ assert written["offset"] == "+05:45"
+ assert written["local"].startswith("2026-07-30T12:00:00")
+
+
+def test_negative_offset_is_signed():
+ written = localtime.both(datetime(2026, 1, 15, 12, 0, tzinfo=UTC), "America/New_York")
+ assert written["offset"] == "-05:00"
+ assert written["offset_minutes"] == -300
+
+
+def test_both_passes_none_through():
+ assert localtime.both(None, "Europe/Paris") is None
+
+
+ ("day", "hours"),
+ [
+ (date(2026, 3, 29), 23), # European clocks go forward
+ (date(2026, 10, 25), 25), # and back
+ (date(2026, 7, 30), 24),
+ ],
+)
+def test_local_day_bounds_follow_daylight_saving(day, hours):
+ """A day is midnight to the next local midnight, which is 23 or 25 hours on
+ the changeover days. Adding 24 hours would clip or double-count an hour of
+ the sky."""
+ start, end = localtime.day_bounds(day, "Europe/Paris")
+ assert (end - start).total_seconds() / 3600 == hours
+
+
+def test_events_span_a_daylight_saving_change():
+ """Nothing about the change should lose a sunrise."""
+ events, zone = _events(*PARIS, date(2026, 3, 29))
+ assert events["sun"]["state"] == "rises"
+ local = events["sun"]["rise"].astimezone(localtime.zone_info(zone))
+ assert local.date() == date(2026, 3, 29)
+ assert events["sun"]["set"].astimezone(localtime.zone_info(zone)).date() == date(2026, 3, 29)
+
+
+def test_at_local_reads_a_wall_clock():
+ moment = localtime.at_local(date(2026, 7, 30), time(14, 20), "Europe/Paris")
+ assert moment == datetime(2026, 7, 30, 12, 20, tzinfo=UTC)
+
+
+def test_local_noon_is_midday_on_the_clock():
+ moment = localtime.local_noon(date(2026, 1, 15), "Europe/Paris")
+ assert moment == datetime(2026, 1, 15, 11, 0, tzinfo=UTC)
+
+
+# -- nothing reaches the network -----------------------------------------------
+
+
+def test_sky_does_not_touch_the_network(monkeypatch):
+ """Reading the sky for a point is pure computation, unlike the reverse
+ geocode next to it in the same tool. Make any socket explode to prove it."""
+ import socket
+
+ def explode(*args, **kwargs):
+ raise AssertionError("the sky must be computed offline")
+
+ monkeypatch.setattr(socket, "socket", explode)
+ monkeypatch.setattr(socket, "create_connection", explode)
+ zone = localtime.zone_for(*PARIS)
+ start, end = localtime.day_bounds(date(2026, 7, 30), zone)
+ assert sky.day_events(*PARIS, start, end)["sun"]["rise"]
+ assert sky.position_at(*PARIS, start)
diff --git a/uv.lock b/uv.lock
index 93dd068..4a60ca3 100644
--- a/uv.lock
+++ b/uv.lock
@@ -108,6 +108,8 @@ dependencies = [
{ name = "python-multipart" },
{ name = "requests" },
{ name = "secretstorage", marker = "sys_platform == 'linux'" },
+ { name = "tzdata" },
+ { name = "tzfpy" },
{ name = "uvicorn", extra = ["standard"] },
{ name = "yt-dlp" },
]
@@ -149,6 +151,8 @@ requires-dist = [
{ name = "requests", specifier = ">=2.31,<3" },
{ name = "ruff", marker = "extra == 'dev'", specifier = ">=0.15,<0.16" },
{ name = "secretstorage", marker = "sys_platform == 'linux'", specifier = ">=3.3,<4" },
+ { name = "tzdata", specifier = ">=2024.1,<2027" },
+ { name = "tzfpy", specifier = ">=1.3,<2" },
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.30,<1.0" },
{ name = "yt-dlp", specifier = ">=2024.4.9" },
]
@@ -1473,6 +1477,37 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/dc/9b/47798a6c91d8bdb567fe2698fe81e0c6b7cb7ef4d13da4114b41d239f65d/typing_inspection-0.4.2-py3-none-any.whl", hash = "sha256:4ed1cacbdc298c220f1bd249ed5287caa16f34d44ef4e9c3d0cbad5b521545e7", size = 14611, upload-time = "2025-10-01T02:14:40.154Z" },
]
+[[package]]
+name = "tzdata"
+version = "2026.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/92/ff/5a28bdfd8c3ebec42564ac7d0e54ca3db65044a9314a97f9564fa7a1e926/tzdata-2026.3.tar.gz", hash = "sha256:4a1518b8993086a7982523e071643f3c0e5f213e75b21318e78bcabfff9d1415", size = 198674, upload-time = "2026-07-10T08:50:37.887Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e5/6d/b53b99a9f2766d095985947a5782f1702cabb129a34f7a802d7197af832f/tzdata-2026.3-py2.py3-none-any.whl", hash = "sha256:dc096730c87af6cab1b171c9d532be840741ff5d459015e7f6947bd7d7e54931", size = 348168, upload-time = "2026-07-10T08:50:36.46Z" },
+]
+
+[[package]]
+name = "tzfpy"
+version = "1.3.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/7b/16/7311f6449ba0b391e146a52684f3b32a18dd4775f6890ca08ef3f3f103aa/tzfpy-1.3.2.tar.gz", hash = "sha256:5f4dbe9be6957ba6eb16fb4deb67f0c14e8da2e46674ead2bd38dffa9c58da08", size = 424831, upload-time = "2026-07-12T01:35:11.586Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/60/9f/2363f8c714ea66c8d6e1368a20db39cdcc13cda8ed19ec614cea9eb05bdb/tzfpy-1.3.2-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:5e240beda40a3de8e16ede62c61bf568ba59bf63e375940a9c7e770f001aff41", size = 4452036, upload-time = "2026-07-12T01:34:42.594Z" },
+ { url = "https://files.pythonhosted.org/packages/ae/cf/38d031b1e796439bf713323fa917859c2fbb45e6e73bec514f8646202baa/tzfpy-1.3.2-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:3f8ff5e13bd88259064678b1aeed3de0892e0f22c462173c49adc938ceb6496e", size = 4519176, upload-time = "2026-07-12T01:34:45.143Z" },
+ { url = "https://files.pythonhosted.org/packages/1d/29/68cea2d25ecfbf3a0c13f17c820d90e12729568c395128d1d4bea0a835ee/tzfpy-1.3.2-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b604acdf93d0fe6959d2242bc94857889e17c180a5b73e19f2052adb1d6a98b2", size = 4487592, upload-time = "2026-07-12T01:34:47.22Z" },
+ { url = "https://files.pythonhosted.org/packages/a3/e1/670b2cadb15b75c53d42ba828533eee07bf0297113373825475291851d36/tzfpy-1.3.2-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c16fe691c99390b6f1ca5245a11c846eaa336eb21276ce6ea3cc8d2d639a89a", size = 4497177, upload-time = "2026-07-12T01:34:49.253Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/bf/47efc11c2bb816f7e65d173b93286279ffdfff0ac6dfefef54f95be50e0e/tzfpy-1.3.2-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:f1d21ad1be0c98ee54bc98e7a34d14ab26dcad8870d347db51e5285033fca6dc", size = 4663052, upload-time = "2026-07-12T01:34:51.58Z" },
+ { url = "https://files.pythonhosted.org/packages/de/e5/36960c3c78bab5c1864ebd1d7331d63fab3d10092fc2ec4bd5b6ab106cbe/tzfpy-1.3.2-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:0b3ec412c2e4b4e9799091d09210c858ee6dfa3b1edda747c2b3d82a9ca8ff80", size = 4697037, upload-time = "2026-07-12T01:34:53.567Z" },
+ { url = "https://files.pythonhosted.org/packages/e7/eb/e5f6dcda9d44f228ae5e1a27ed9e5c28fd70b0442ac98516e44e0c554842/tzfpy-1.3.2-cp310-abi3-win_amd64.whl", hash = "sha256:47f5853af4d7759a0ca10a4f036b0f4f20873089c124d38d79a4018c380182fc", size = 4341633, upload-time = "2026-07-12T01:34:55.573Z" },
+ { url = "https://files.pythonhosted.org/packages/a1/1a/100a12c4608beff8d4cd388e4ec91458ef7cef5b9d93e4f6363b779d4946/tzfpy-1.3.2-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:a92706caa3ee760dee55d73c0a9c92af6bde9d73a4748711b798800e2e2f5de2", size = 4449419, upload-time = "2026-07-12T01:34:57.48Z" },
+ { url = "https://files.pythonhosted.org/packages/d0/a0/839e0669a513127d94248c6bc0471a644f6d91a202ab4359b05f62585177/tzfpy-1.3.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:4e9baecc74295fff884d063b8fdda683d9e723b81d27ed620be4b71551866d64", size = 4515316, upload-time = "2026-07-12T01:34:59.39Z" },
+ { url = "https://files.pythonhosted.org/packages/45/63/8db24f761f84f2352d2aaf3e3e187f33f1d33cf9ba39aa888be2b68e1e21/tzfpy-1.3.2-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ee4e782b6ccb7c58eb22e9d668c1fd2aad698d31241d3f54d02d2b9007079d90", size = 4483710, upload-time = "2026-07-12T01:35:01.472Z" },
+ { url = "https://files.pythonhosted.org/packages/14/b5/1193cc98390877bac735ad5467dd1b561e0314d959fc61225ad1a9d1cf8f/tzfpy-1.3.2-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:670b02462e81cf0a63013d801e677e14da115e851aef80c4f1870b75f4cd873e", size = 4494346, upload-time = "2026-07-12T01:35:03.462Z" },
+ { url = "https://files.pythonhosted.org/packages/7a/ab/75d5adc5a47d86da4637bc77b3ea6d86302e735b9f8efd18782b78a9b25a/tzfpy-1.3.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d3432bedb6ced68a8da045e526d9e77bcc51a46c2b50bb8308ebd3f0db887def", size = 4659520, upload-time = "2026-07-12T01:35:05.361Z" },
+ { url = "https://files.pythonhosted.org/packages/51/99/bd762e903c116b6ffdecd479f5ac91977f80e857079bba0cd278e4668f3d/tzfpy-1.3.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:716898e6e024b5c9d09ca8fd9d9fa3abb05eb515dbd3e5443b3de88dfa290587", size = 4693789, upload-time = "2026-07-12T01:35:07.316Z" },
+ { url = "https://files.pythonhosted.org/packages/8f/b1/b4344e06435c001ce20078751cab7190d6fa180c2d62ae756f788c6620be/tzfpy-1.3.2-cp314-cp314t-win_amd64.whl", hash = "sha256:408af2823d88c4e709dc264d8025941829f04cffcb8613e7093bc567a2f21349", size = 4340205, upload-time = "2026-07-12T01:35:09.619Z" },
+]
+
[[package]]
name = "urllib3"
version = "2.7.0"