@johnmorrisdotca/chikyu-earth 0.21.0 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.22.1 - 2026-11-09
6
+
7
+ - kazoku-ui 0.27: the globe and the space looks draw at most 30 frames a second while they move (KAZOKU-UI-91), as the family's freeze rule asks; nothing else changes.
8
+
9
+ ## 0.22.0 - 2026-11-09
10
+
11
+ - **When can I see the ISS? Passes over a place** (MODULES-677). A new entry point `@johnmorrisdotca/chikyu-earth/passes` (pure, needs `satellite.js`): `findPasses(sets, observer, { from, to }, options)` gives the next passes of the ISS, Tiangong, Hubble or any satellite over a place: the start, highest point and end (UTC, with the compass word and degrees at each, the height and the distance), the part that can be seen, why a pass cannot be (`daylight`, `shadow` or `faint`), the Sun's altitude and the sky it makes (`civil`, `nautical`, `astronomical`, `night`: civil twilight or darker counts as dark enough, and the pass says which), whether the satellite is in the Earth's shadow, and a magnitude from the satellite's standard magnitude (worked out from a rough size for the ISS, Tianhe and Hubble; others through `magnitudes`). Only visible passes by default, `all: true` for all. Also `satelliteAt`, `passPath`, `groundTrack`, `skySvg` (the dome as an SVG string, north up and east on the left, the track solid where lit and dashed in shadow, in any words), `sunAltitude`, `skyAt`, `compassOf`, `magnitude`, `standardMagnitude`, `ESTIMATED_CROSS_SECTIONS` and `STANDARD_MAGNITUDES`. Each pass says how old its elements are (`elementAgeDays`, `stale` after two weeks; a pass more than 30 days from its elements is left out). Checked against Skyfield with the Python `sgp4` and DE421, whose numbers are kept in `test/recorded/` (249 passes of the ISS, Tianhe and Hubble over London, Sydney, Quito and Tokyo: every rise, highest point and set within 1 second, direction within 0.06 degree, height within 0.005 degree, 746 of 747 moments agreeing on sunlight; made by `scripts/passes-reference.py`), and by hand against a sky-watching site's published predictions on 2026-11-09 (all 249 found within 2 seconds, same compass words; none of its data is kept). The brightness is a model: `standardMagnitude(area, albedo)` from the Sun's magnitude, with rough cross-sections for the ISS, Tianhe and Hubble in `ESTIMATED_CROSS_SECTIONS`, good to a magnitude or two.
12
+ - **`<chikyu-passes>`** (`/passes/element`): the list of passes, the sky dome and the facts of the one pressed, in English and Japanese; `latitude`, `longitude`, `height`, `days`, `show`, `sky`, `satellite`, `from`, `min-altitude`, `time-zone` or `utc-offset`, `lang`, `selected`; the orbit data from the `elements` property or `elements-src` (read once, through `fetchElements`; never polled); it sends `chikyu-pass-select` and takes a `slot="ground"`.
13
+ - **The demo's page `passes.html` ("Passes over me") and `passes-embed.html`**: a place by the map, a search of cities and countries (kuni), the two numbers, six quick places or "My location" (asked for only on a press), the satellite, 3 to 10 days, visible or all passes, civil or darker sky; the list, the sky dome and the ground track on the globe of the pass pressed, all in the address; the code for every way a page is made (the family's embed panel) and the iframe. The orbit data are the demo's own files, read once; the scheduled build also writes `elements/bright.json` (the ISS, Tianhe and Hubble as OMM JSON). Guide in English and Japanese: `docs/guides/passes.md`; examples `examples/node/passes.mjs` and `examples/passes.html`, tested.
14
+
5
15
  ## 0.21.0 - 2026-11-09
6
16
 
7
17
  - **kazoku-ui 0.26: a plain drag always turns, and lighter sheets for children** (KAZOKU-UI-87, KAZOKU-UI-86, MODULES-743). On the globe and the views that turn, a plain drag (and one finger) now turns at every zoom; the middle or right button, Ctrl or Command and a drag, Space and a drag, and the wheel move; the Move or Turn choice is gone. The printable sheets for children draw their outline at kazoku-ui's kid line, 1.2 mm (was 3), and the lines inside at 1 mm (was 2.5), so a sheet is lighter and the names have room; the header's Name is a line to write on.
package/NOTICE.md CHANGED
@@ -71,6 +71,19 @@ terms: a snapshot with credit, never a live fetch. The catalogue (`src/satellite
71
71
 
72
72
  The same build may take a group's element sets from **Space-Track.org** (https://www.space-track.org, U.S. Space Command) when CelesTrak has left the group more than 12 hours old, at most once a day, through its API with John Morris's own account (the login is a repository secret, never in a file). The group's file and `manifest.json` say `"source": "spacetrack"` and the demo says so under the globe. The citation is **"Data from Space-Track.org (USSPACECOM)"**. Terms: the documentation page https://www.space-track.org/documentation, section "Redistribution of Basic SSA Information", read 2026-11-08: "USSPACECOM has provided express blanket approval for transfer/redistribution of basic SSA data and services accessed via www.Space-Track.org conditioned on appropriate citation." Basic SSA data are "Two-Line Elements (TLEs) and Orbital Mean-element Messages (OMMs); SATCAT; and Satellite Decay and Reentry Data." (The page needs a browser; the section was read through a page-reading tool, which returned each sentence in quoted pieces. TODO: John or a browser check of the section's wording.) The page gives no citation form, so this sentence is the package's own. The package ships none of these element sets.
73
73
 
74
+ ## Satellite passes
75
+
76
+ `src/passes/` (the `/passes` entry and `<chikyu-passes>`) works out passes with SGP4 by **satellite.js** (see Satellites above), this package's own Sun position (see Sun position above) and a cylinder of the Earth's shadow; the code is this package's own and MIT. The brightness is a model of this package's own: the phase function of a diffuse (Lambertian) sphere, a textbook result, with the standard magnitude (brightness from 1000 km with half of the satellite lit, the convention satellite observers use) worked out from the Sun's apparent magnitude of -26.74 (the IAU's 2015 nominal solar values), an assumed albedo of 0.2 and a rough average cross-section for each of the ISS (2,000 square metres), Tianhe (200) and the Hubble Space Telescope (70). The cross-sections are this package's own rough estimates, made from the sizes the space agencies publish (for the ISS, NASA's "Space Station Facts and Figures" page, read 2026-11-09: solar array length 73 m, wingspan 109 m, truss 94 m); they are not measurements, and no observer's table of standard magnitudes is used or kept.
77
+
78
+ The tests' references (`test/recorded/`, never in the npm package; `scripts/passes-reference.py` makes the first):
79
+
80
+ - `passes-skyfield-2026-11-09.json`: times, directions, heights, distances, Sun altitudes and sunlight computed on 2026-11-09 with **Skyfield** (https://rhodesmill.org/skyfield/, MIT, by Brandon Rhodes), the Python **sgp4** package (MIT, by the same author, from David Vallado's reference code) and NASA JPL's DE421 planetary ephemeris (public domain, https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/de421.bsp, not kept in the repository). Numbers only.
81
+ - `passes-elements-2026-11-09.json`: one element set each of the ISS, Tianhe and Hubble from **CelesTrak** (https://celestrak.org), one download of each on 2026-11-09 about 17:01 UTC, within its usage policy (see Satellites above).
82
+
83
+ The guide says that the results were also compared by hand on 2026-11-09 with the published predictions of a sky-watching site. None of that site's data, text or design is in this repository: the figures were read once for the comparison and kept outside it.
84
+
85
+ The demo's `elements/bright.json` is made by the scheduled build from the files described under Satellites, with the same source, citation and grey tier.
86
+
74
87
  ## Space Shuttle missions
75
88
 
76
89
  `src/satellites/missions-data.ts` (in the package) holds the 135 Space Shuttle flights, STS-1 to STS-135: the orbiter, the liftoff and landing, the number of people NASA's page lists, and a few words on the main payload, in English and Japanese. The facts are read from **NASA's mission pages**, `https://www.nasa.gov/mission/sts-<id>/` with `<id>` one of `1 2 3 4 5 6 7 8 9 4 1 b 4 1 c 4 1 d 4 1 g 5 1 a 5 1 c 5 1 d 5 1 b 5 1 g 5 1 f 5 1 i 5 1 j 6 1 a 6 1 b 6 1 c 5 1 l 2 6 2 7 2 9 3 0 2 8 3 4 3 3 3 2 3 6 3 1 4 1 3 8 3 5 3 7 3 9 4 0 4 3 4 8 4 4 4 2 4 5 4 9 5 0 4 6 4 7 5 2 5 3 5 4 5 6 5 5 5 7 5 1 5 8 6 1 6 0 6 2 5 9 6 5 6 4 6 8 6 6 6 3 6 7 7 1 7 0 6 9 7 3 7 4 7 2 7 5 7 6 7 7 7 8 7 9 8 0 8 1 8 2 8 3 8 4 9 4 8 5 8 6 8 7 8 9 9 0 9 1 9 5 8 8 9 6 9 3 1 0 3 9 9 1 0 1 1 0 6 9 2 9 7 9 8 1 0 2 1 0 0 1 0 4 1 0 5 1 0 8 1 0 9 1 1 0 1 1 1 1 1 2 1 1 3 1 0 7 1 1 4 1 2 1 1 1 5 1 1 6 1 1 7 1 1 8 1 2 0 1 2 2 1 2 3 1 2 4 1 2 6 1 1 9 1 2 5 1 2 7 1 2 8 1 2 9 1 3 0 1 3 1 1 3 2 1 3 3 1 3 4 1 3 5`, each read once on 2026-11-08 (a two-second pause between pages; the source list as read is `test/recorded/nasa-sts-2026-11-08.json`, made by `scripts/missions.ts facts`, and `test/missions.test.ts` holds the package's facts to it). NASA content "generally are not subject to copyright in the United States" and NASA is acknowledged as the source; no NASA insignia, logotype or picture is used, and the payload lines are our own words from the pages. STS-107's landing time is the page's "about 9 a.m. EST" on 2003-02-01; the page gives STS-51L no time of liftoff, so it has the date alone.
package/README.md CHANGED
@@ -30,6 +30,7 @@ Country outlines in the same thin-line style as Hako Devices and Uchusen Rockets
30
30
  - It opens centred on where the reader is, or where you say. Auto-turn runs at the Earth's own rate: one sidereal day a turn, and the family's speed buttons (0.5×, 1×, 2×) are multiples of it.
31
31
  - The Earth from space (`/realistic`): day and night by the real Sun, city lights, sun glint, clouds and the atmosphere, drawn with three.js through one shared WebGL context.
32
32
  - The Sun, the Moon and the planets where they are on a date and time (`/space`), and satellites at the places SGP4 puts them (`/satellites`), with a camera that rides along.
33
+ - When you can see the ISS (`/passes`): the next passes of the ISS, Tiangong and Hubble over any place, with direction, height, brightness and whether the satellite is lit while the sky is dark, a sky dome that draws each, and `<chikyu-passes>`.
33
34
  - Markers with labels, groups, clusters and events (`/markers`), on either globe.
34
35
  - Pure parts that run on a server: `globe()`, the rotation and view maths, `COUNTRIES` and `countryList()`.
35
36
  - Every live view zooms, pans and turns by itself, with no bar: drag, two-finger pinch, Ctrl and the wheel (a plain wheel at Fit scrolls the page) and the keys, through kazoku-ui's controls, from a tenth of Fit to 20 times on the line globe ([each range and why](docs/guides/zoom-and-pan.md)). Add `<kazoku-view-controls>` for buttons and the address.
@@ -186,6 +187,35 @@ const elements: ElementSet[] = await (await fetch("/my-celestrak-copy.json")).js
186
187
  document.querySelector("chikyu-space")!.setSatellites("stations", createSatellites(elements), { orbits: true });
187
188
  ```
188
189
 
190
+ ## Passes: when can I see the ISS?
191
+
192
+ `findPasses(elements, place, { from, to })` gives the next passes of a satellite over a place: when it comes up, is highest and goes down (UTC, with the compass word and degrees at each, and the height), how bright it looks, and whether it can be seen, which needs the satellite in sunlight while the watcher's sky is in civil twilight or darker (each pass says which). It is a pure function over the same SGP4 as the rest, with no DOM and no clock. `skySvg` draws a pass across the sky as an SVG string, `groundTrack` gives the path under the satellite for a globe, and `<chikyu-passes>` lists the passes and draws the dome, in English and Japanese. The ISS, Tianhe and Hubble have estimated standard magnitudes (from their size and an assumed albedo); give better ones with `magnitudes`.
193
+
194
+ ```ts
195
+ import { findPasses } from "@johnmorrisdotca/chikyu-earth/passes";
196
+
197
+ const iss = {
198
+ OBJECT_NAME: "ISS (ZARYA)",
199
+ EPOCH: "2026-11-09T04:58:46.240896",
200
+ MEAN_MOTION: 15.49270212,
201
+ ECCENTRICITY: 0.00072974,
202
+ INCLINATION: 51.6321,
203
+ RA_OF_ASC_NODE: 302.4538,
204
+ ARG_OF_PERICENTER: 5.2479,
205
+ MEAN_ANOMALY: 354.8585,
206
+ NORAD_CAT_ID: 25544,
207
+ BSTAR: 0.0001553356,
208
+ MEAN_MOTION_DOT: 8.201e-5,
209
+ MEAN_MOTION_DDOT: 0,
210
+ };
211
+ const from = Date.UTC(2026, 10, 10);
212
+ const tokyo = { latitude: 35.69, longitude: 139.69 };
213
+ const [next] = findPasses(iss, tokyo, { from, to: from + 5 * 86_400_000 });
214
+ console.log(next ? `${new Date(next.highest.ms).toISOString()}: ${next.highest.compass}, ${Math.round(next.highest.altitude)} degrees, ${next.sky}` : "none");
215
+ ```
216
+
217
+ Passes are only as good as the orbit data are new: each pass says how old its elements are, and the ISS's change with every reboost. Checked against Skyfield (249 passes: every time within a second, directions within 0.06 degree), and by hand against a sky-watching site's published predictions (all found, times within two seconds). Brightness is a model from the satellite's size, good to a magnitude or two. The guide has the numbers and the rules: [passes guide](docs/guides/passes.md). The demo's page [Passes over me](https://johnmorrisdotca.github.io/chikyu-earth/passes.html) has a map, a search, "My location" (asked for only when pressed) and the code for every way a page is made.
218
+
189
219
  ## Riding along
190
220
 
191
221
  <p align="center"><img alt="Riding along with the ISS, tipped towards the horizon: the Earth's curve and atmosphere, and the orbits of the other stations in the sky" src="docs/images/space-ride-horizon.png" width="420"></p>
@@ -382,6 +412,7 @@ The reference is a site, made from the source's own doc comments: every export h
382
412
  | `.../markers` | `attachMarkers` and the pure projection, clusters and labels. |
383
413
  | `.../space`, `.../space/element` | The Sun, the Moon and the planets; `astronomy-engine` and `three`. |
384
414
  | `.../satellites` | SGP4 for a group of satellites; `satellite.js`. |
415
+ | `.../passes`, `.../passes/element` | Passes of a satellite over a place, the sky dome, `<chikyu-passes>`; `satellite.js`. |
385
416
 
386
417
  ## Guides
387
418
 
@@ -397,6 +428,7 @@ Each guide has a Japanese twin in [docs/guides/ja](docs/guides/ja/getting-starte
397
428
  | [TypeScript and Node](docs/guides/typescript-and-node.md) | Types and the pure side |
398
429
  | [The realistic Earth and markers](docs/guides/realistic-and-markers.md) | The Earth from space, markers |
399
430
  | [Satellites](docs/guides/satellites.md) | SGP4 and the space view |
431
+ | [When can I see the ISS?](docs/guides/passes.md) | Passes over a place, the sky dome, how it was checked |
400
432
  | [Ride along](docs/guides/ride-along.md) | A camera on a moving body |
401
433
  | [Zoom, pan and turn](docs/guides/zoom-and-pan.md) | The hands every view carries, each zoom range and why |
402
434
  | [Printable sheets](docs/guides/printable-sheets.md) | The globe, a world map, my country, day and night and the seasons to print and colour |
@@ -0,0 +1,47 @@
1
+ import type { ElementSet } from "../satellites/types.ts";
2
+ import { type SatellitePass } from "./passes.ts";
3
+ type Lang = "en" | "ja";
4
+ /**
5
+ * The `<chikyu-passes>` custom element: the passes of satellites over a place as a list, with the sky dome and the facts of the one pressed. Importing this entry point registers the tag once; it needs `satellite.js` (an optional peer).
6
+ * Give it the place with `latitude`, `longitude` and `height` (metres), the orbit data with the `elements` property (OMM `ElementSet`s) or `elements-src` (an address, read once when the element comes into the page, through `fetchElements`' politeness rules),
7
+ * and choose what it lists with `days` (1 to 14, 5 by default), `show` (`visible`, the default, or `all`), `sky` (`civil`, `nautical`, `astronomical` or `night`: the lightest sky a pass may be seen in), `satellite` (a NORAD number, to list one of several sets),
8
+ * `from` (the first moment, an ISO date; the time of the page's first use by default), `min-altitude`, and `lang` (`en` or `ja`; the page's language by default). The times are in the browser's time zone unless `time-zone` names one (`Asia/Tokyo`) or
9
+ * `utc-offset` gives hours from UTC (`9`, `-3.5`); UTC is always shown beside them. `selected` (the ISO time of a pass's highest point) is the pass pressed. It sends `chikyu-pass-select` with the pass when one is pressed, and `chikyu-passes` each time the list is made.
10
+ *
11
+ * @example
12
+ * ```ts no-run
13
+ * import type { ChikyuPasses } from "@johnmorrisdotca/chikyu-earth/passes/element";
14
+ *
15
+ * const passes = document.createElement("chikyu-passes") as ChikyuPasses;
16
+ * passes.setAttribute("latitude", "35.68");
17
+ * passes.setAttribute("longitude", "139.69");
18
+ * passes.setAttribute("elements-src", "https://example.org/elements/bright.json");
19
+ * document.body.append(passes);
20
+ * passes.addEventListener("chikyu-pass-select", (event) => console.log((event as CustomEvent).detail.pass.highest.compass));
21
+ * ```
22
+ */
23
+ export declare class ChikyuPasses extends HTMLElement {
24
+ #private;
25
+ static observedAttributes: string[];
26
+ /** The orbit data the passes are worked out from. Setting it works the passes out again. */
27
+ get elements(): readonly ElementSet[];
28
+ set elements(sets: readonly ElementSet[]);
29
+ /** The passes listed now, earliest first. */
30
+ get passes(): readonly SatellitePass[];
31
+ /** The pass pressed, or undefined. */
32
+ get selectedPass(): SatellitePass | undefined;
33
+ /** The first moment the list covers, milliseconds since the Unix epoch. */
34
+ get from(): number;
35
+ /** The language of the words: the `lang` attribute, else the page's. */
36
+ get language(): Lang;
37
+ connectedCallback(): void;
38
+ attributeChangedCallback(name: string): void;
39
+ /** Press the pass at `index` in `passes` (or none). */
40
+ select(index: number | undefined): void;
41
+ }
42
+ declare global {
43
+ interface HTMLElementTagNameMap {
44
+ "chikyu-passes": ChikyuPasses;
45
+ }
46
+ }
47
+ export {};
@@ -0,0 +1,409 @@
1
+ // <chikyu-passes>: the next passes of the ISS (and the other bright satellites) over a place, as a list and a sky dome for the one pressed. Importing registers it once.
2
+ // Nothing runs on a timer: it works the passes out when something it shows changes, and reads the clock once, when it first comes into a page (or never, when `from` is given).
3
+ import { adoptStyles } from "../adopt.js";
4
+ import { fetchElements } from "../satellites/source.js";
5
+ import { DEFAULT_DIM_AFTER_DAYS } from "../satellites/limits.js";
6
+ import { findPasses, passPath } from "./passes.js";
7
+ import { skySvg } from "./sky.js";
8
+ const WORDS = {
9
+ en: {
10
+ list: "Passes",
11
+ waiting: "Waiting for orbit data.",
12
+ unreadable: "The orbit data could not be read: {why}",
13
+ none: "No visible pass in the next {days} days. Try All passes, or more days.",
14
+ noneAll: "No pass in the next {days} days.",
15
+ visible: "Visible",
16
+ daylight: "Daytime",
17
+ shadow: "In shadow",
18
+ faint: "Too faint",
19
+ reasonDaylight: "The sky is too bright to see it.",
20
+ reasonShadow: "It is in the Earth's shadow, so the Sun is not lighting it.",
21
+ reasonFaint: "It is lit and the sky is dark, but it is too faint to see.",
22
+ start: "Starts",
23
+ highest: "Highest",
24
+ end: "Ends",
25
+ seen: "Can be seen",
26
+ seenFromTo: "{from} to {to}",
27
+ brightness: "Brightness",
28
+ sky: "Sky",
29
+ light: "Satellite",
30
+ lit: "In sunlight",
31
+ partLit: "In sunlight for part of the pass",
32
+ notLit: "In the Earth's shadow",
33
+ elements: "Orbit data",
34
+ elementsLine: "{name}: from {date}, {age} days before this pass",
35
+ stale: "older than two weeks: the times are less sure",
36
+ reboost: "Passes are only as good as the orbit data are new: a reboost of the station moves it.",
37
+ zone: "Times are in {zone}; UTC is shown beside them.",
38
+ zoneUtc: "Times are in UTC.",
39
+ zoneAbout: "Times are about local time (UTC{offset}, from the longitude).",
40
+ up: "{altitude}° up",
41
+ day: "daylight",
42
+ civil: "civil twilight",
43
+ nautical: "nautical twilight",
44
+ astronomical: "astronomical twilight",
45
+ night: "night",
46
+ sunBelow: "the Sun is {degrees}° below the horizon",
47
+ sunAbove: "the Sun is {degrees}° above the horizon",
48
+ mag1: "as bright as Venus, the brightest planet",
49
+ mag2: "brighter than any star",
50
+ mag3: "as bright as the brightest stars",
51
+ mag4: "like a bright star",
52
+ mag5: "faint: a dark sky helps",
53
+ magUnknown: "not known for this satellite",
54
+ magShown: "{value} ({words})",
55
+ N: "N", NNE: "NNE", NE: "NE", ENE: "ENE", E: "E", ESE: "ESE", SE: "SE", SSE: "SSE", S: "S", SSW: "SSW", SW: "SW", WSW: "WSW", W: "W", WNW: "WNW", NW: "NW", NNW: "NNW",
56
+ skyN: "N", skyE: "E", skyS: "S", skyW: "W", skyStart: "start", skyHighest: "highest", skyEnd: "end", skyZenith: "overhead",
57
+ skyDescription: "{name} crosses the sky from the {from} to the {to}, highest {altitude} degrees up in the {where}.",
58
+ wait: "Working out the passes.",
59
+ count: "{count} passes",
60
+ elementsOld: "Orbit data are {days} days old.",
61
+ },
62
+ ja: {
63
+ list: "通過",
64
+ waiting: "軌道データを待っています。",
65
+ unreadable: "軌道データを読み取れませんでした: {why}",
66
+ none: "これから{days}日間に見える通過はありません。「すべての通過」か、日数を増やしてみてください。",
67
+ noneAll: "これから{days}日間に通過はありません。",
68
+ visible: "見える",
69
+ daylight: "昼間",
70
+ shadow: "影の中",
71
+ faint: "暗すぎる",
72
+ reasonDaylight: "空が明るすぎて見えません。",
73
+ reasonShadow: "地球の影に入っていて、太陽の光が当たっていないので見えません。",
74
+ reasonFaint: "光は当たっていて空も暗いのですが、衛星が暗すぎて見えません。",
75
+ start: "出る",
76
+ highest: "いちばん高い",
77
+ end: "入る",
78
+ seen: "見える時間",
79
+ seenFromTo: "{from} から {to} まで",
80
+ brightness: "明るさ",
81
+ sky: "空の暗さ",
82
+ light: "衛星",
83
+ lit: "太陽の光が当たっている",
84
+ partLit: "通過の一部で光が当たっている",
85
+ notLit: "地球の影の中",
86
+ elements: "軌道データ",
87
+ elementsLine: "{name}: {date} のデータ (この通過の {age} 日前)",
88
+ stale: "2週間より古く、時刻の確かさが下がります",
89
+ reboost: "通過の時刻は、軌道データが新しいほど正確です。ステーションが高度を上げると、位置が変わります。",
90
+ zone: "時刻は {zone} です。UTC もそばに表示します。",
91
+ zoneUtc: "時刻は UTC です。",
92
+ zoneAbout: "時刻はおよそ現地時間です (経度から求めた UTC{offset})。",
93
+ up: "高さ {altitude}°",
94
+ day: "昼",
95
+ civil: "市民薄明",
96
+ nautical: "航海薄明",
97
+ astronomical: "天文薄明",
98
+ night: "夜",
99
+ sunBelow: "太陽は地平線の {degrees}° 下です",
100
+ sunAbove: "太陽は地平線の {degrees}° 上です",
101
+ mag1: "いちばん明るい惑星の金星くらいか、それより明るい",
102
+ mag2: "どの恒星よりも明るい",
103
+ mag3: "いちばん明るい恒星くらい",
104
+ mag4: "明るい星のよう",
105
+ mag5: "暗め: 空が暗いほうが見つけやすい",
106
+ magUnknown: "この衛星ではわかっていません",
107
+ magShown: "{value} 等 ({words})",
108
+ N: "北", NNE: "北北東", NE: "北東", ENE: "東北東", E: "東", ESE: "東南東", SE: "南東", SSE: "南南東", S: "南", SSW: "南南西", SW: "南西", WSW: "西南西", W: "西", WNW: "西北西", NW: "北西", NNW: "北北西",
109
+ skyN: "北", skyE: "東", skyS: "南", skyW: "西", skyStart: "出", skyHighest: "最高", skyEnd: "入", skyZenith: "真上",
110
+ skyDescription: "{name} は{from}から{to}へ空を横切ります。いちばん高くなるのは{where}の空で、高さは{altitude}度です。",
111
+ wait: "通過を計算しています。",
112
+ count: "{count} 回の通過",
113
+ elementsOld: "軌道データは {days} 日前のものです。",
114
+ },
115
+ };
116
+ /** The short names of the satellites this element knows, in each language; any other satellite is shown under the name in its elements. */
117
+ const SHORT = {
118
+ 25544: { en: "ISS", ja: "ISS" },
119
+ 48274: { en: "Tiangong", ja: "天宮" },
120
+ 20580: { en: "Hubble", ja: "ハッブル" },
121
+ };
122
+ const CSS = `
123
+ :host{display:block;color:inherit;font:inherit;container-type:inline-size}
124
+ *{box-sizing:border-box}
125
+ .note,.zone{margin:0 0 8px;font-size:.85em;opacity:.8}
126
+ .layout{display:grid;gap:16px;grid-template-columns:minmax(0,1fr)}
127
+ @container (min-width:760px){.layout{grid-template-columns:minmax(0,2fr) minmax(0,3fr)}}
128
+ .list{display:grid;gap:6px;align-content:start;max-height:30rem;overflow:auto;padding:2px;margin:0;list-style:none}
129
+ .row{display:grid;grid-template-columns:1fr auto;gap:2px 10px;text-align:left;width:100%;min-height:48px;padding:8px 12px;border:1px solid color-mix(in srgb,currentColor 30%,transparent);border-radius:10px;background:transparent;color:inherit;font:inherit;cursor:pointer}
130
+ .row[aria-pressed="true"]{background:color-mix(in srgb,currentColor 14%,transparent);border-color:currentColor}
131
+ .row:focus-visible{outline:3px solid #6cd0ff;outline-offset:2px}
132
+ .when{font-weight:600}
133
+ .badge{justify-self:end;font-size:.8em;padding:1px 8px;border-radius:999px;border:1px solid currentColor}
134
+ .badge[data-reason="visible"]{background:#ffb454;color:#10192b;border-color:#ffb454}
135
+ .track{grid-column:1/-1;font-size:.9em;opacity:.9;font-variant-numeric:tabular-nums}
136
+ .mag{font-variant-numeric:tabular-nums;opacity:.85}
137
+ .detail{display:grid;gap:12px;align-content:start;justify-items:center}
138
+ .pictures{display:flex;flex-wrap:wrap;gap:12px;justify-content:center;width:100%}
139
+ .dome,.ground{width:min(100%,var(--chikyu-picture,270px))}
140
+ .dome svg{display:block;width:100%;height:auto}
141
+ .facts{margin:0;width:100%;display:grid;grid-template-columns:auto 1fr;gap:4px 12px;font-size:.92em}
142
+ .facts dt{opacity:.75}
143
+ .facts dd{margin:0;font-variant-numeric:tabular-nums}
144
+ .empty{margin:12px 0;opacity:.85}
145
+ .credit{margin:8px 0 0;font-size:.8em;opacity:.7}
146
+ `;
147
+ const escape = (text) => text.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
148
+ const fill = (text, values = {}) => text.replace(/\{(\w+)\}/g, (all, key) => String(values[key] ?? all));
149
+ /** A magnitude to a tenth, with no minus sign on a zero. */
150
+ const tenths = (value) => value.toFixed(1).replace(/^-0\.0$/, "0.0");
151
+ const number = (value, fallback) => (value === null || value.trim() === "" || !Number.isFinite(Number(value)) ? fallback : Number(value));
152
+ /**
153
+ * The `<chikyu-passes>` custom element: the passes of satellites over a place as a list, with the sky dome and the facts of the one pressed. Importing this entry point registers the tag once; it needs `satellite.js` (an optional peer).
154
+ * Give it the place with `latitude`, `longitude` and `height` (metres), the orbit data with the `elements` property (OMM `ElementSet`s) or `elements-src` (an address, read once when the element comes into the page, through `fetchElements`' politeness rules),
155
+ * and choose what it lists with `days` (1 to 14, 5 by default), `show` (`visible`, the default, or `all`), `sky` (`civil`, `nautical`, `astronomical` or `night`: the lightest sky a pass may be seen in), `satellite` (a NORAD number, to list one of several sets),
156
+ * `from` (the first moment, an ISO date; the time of the page's first use by default), `min-altitude`, and `lang` (`en` or `ja`; the page's language by default). The times are in the browser's time zone unless `time-zone` names one (`Asia/Tokyo`) or
157
+ * `utc-offset` gives hours from UTC (`9`, `-3.5`); UTC is always shown beside them. `selected` (the ISO time of a pass's highest point) is the pass pressed. It sends `chikyu-pass-select` with the pass when one is pressed, and `chikyu-passes` each time the list is made.
158
+ *
159
+ * @example
160
+ * ```ts no-run
161
+ * import type { ChikyuPasses } from "@johnmorrisdotca/chikyu-earth/passes/element";
162
+ *
163
+ * const passes = document.createElement("chikyu-passes") as ChikyuPasses;
164
+ * passes.setAttribute("latitude", "35.68");
165
+ * passes.setAttribute("longitude", "139.69");
166
+ * passes.setAttribute("elements-src", "https://example.org/elements/bright.json");
167
+ * document.body.append(passes);
168
+ * passes.addEventListener("chikyu-pass-select", (event) => console.log((event as CustomEvent).detail.pass.highest.compass));
169
+ * ```
170
+ */
171
+ export class ChikyuPasses extends HTMLElement {
172
+ static observedAttributes = ["latitude", "longitude", "height", "days", "show", "sky", "satellite", "from", "min-altitude", "lang", "time-zone", "utc-offset", "selected", "elements-src", "credit"];
173
+ #sets = [];
174
+ #passes = [];
175
+ #chosen;
176
+ #problem = "";
177
+ #waiting = true;
178
+ #scheduled = false;
179
+ #started;
180
+ #loaded;
181
+ #fetch = 0;
182
+ #announced;
183
+ /** The orbit data the passes are worked out from. Setting it works the passes out again. */
184
+ get elements() {
185
+ return this.#sets;
186
+ }
187
+ set elements(sets) {
188
+ this.#sets = [...sets];
189
+ this.#waiting = false;
190
+ this.#problem = "";
191
+ this.#schedule();
192
+ }
193
+ /** The passes listed now, earliest first. */
194
+ get passes() {
195
+ return this.#passes;
196
+ }
197
+ /** The pass pressed, or undefined. */
198
+ get selectedPass() {
199
+ return this.#chosen;
200
+ }
201
+ /** The first moment the list covers, milliseconds since the Unix epoch. */
202
+ get from() {
203
+ const given = this.getAttribute("from");
204
+ const asked = given ? Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(given) || !/T/.test(given) ? given : `${given}Z`) : Number.NaN;
205
+ if (Number.isFinite(asked))
206
+ return asked;
207
+ // the clock is read once, when the element first needs it
208
+ this.#started ??= Date.now();
209
+ return this.#started;
210
+ }
211
+ /** The language of the words: the `lang` attribute, else the page's. */
212
+ get language() {
213
+ const asked = (this.getAttribute("lang") ?? this.ownerDocument.documentElement.lang ?? "en").toLowerCase();
214
+ return asked.startsWith("ja") ? "ja" : "en";
215
+ }
216
+ connectedCallback() {
217
+ const root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
218
+ adoptStyles(root, CSS, this.getAttribute("nonce") ?? "");
219
+ this.#load();
220
+ this.#schedule();
221
+ }
222
+ attributeChangedCallback(name) {
223
+ if (!this.isConnected)
224
+ return;
225
+ if (name === "elements-src")
226
+ this.#load();
227
+ this.#schedule();
228
+ }
229
+ /** Press the pass at `index` in `passes` (or none). */
230
+ select(index) {
231
+ const pass = index === undefined ? undefined : this.#passes[index];
232
+ this.#chosen = pass;
233
+ if (pass)
234
+ this.setAttribute("selected", new Date(pass.highest.ms).toISOString().replace(/\.\d+Z$/, "Z"));
235
+ else
236
+ this.removeAttribute("selected");
237
+ }
238
+ #load() {
239
+ const address = this.getAttribute("elements-src");
240
+ if (!address || address === this.#loaded)
241
+ return;
242
+ this.#loaded = address;
243
+ const turn = (this.#fetch += 1);
244
+ this.#waiting = true;
245
+ // one polite request when the element comes into the page: fetchElements keeps the answer and leaves a source that failed alone, and nothing here asks again
246
+ void fetchElements(address).then((got) => {
247
+ if (turn !== this.#fetch)
248
+ return;
249
+ this.#sets = got.sets;
250
+ this.#waiting = false;
251
+ this.#problem = "";
252
+ this.#schedule();
253
+ }, (error) => {
254
+ if (turn !== this.#fetch)
255
+ return;
256
+ this.#waiting = false;
257
+ this.#problem = error instanceof Error ? error.message : "no answer";
258
+ this.#schedule();
259
+ });
260
+ }
261
+ #schedule() {
262
+ if (this.#scheduled)
263
+ return;
264
+ this.#scheduled = true;
265
+ queueMicrotask(() => {
266
+ this.#scheduled = false;
267
+ if (this.isConnected)
268
+ this.#draw();
269
+ });
270
+ }
271
+ #formats() {
272
+ const lang = this.language;
273
+ const zoneName = this.getAttribute("time-zone");
274
+ const offset = this.getAttribute("utc-offset");
275
+ const hour = { hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" };
276
+ const utc = new Intl.DateTimeFormat(lang, { ...hour, timeZone: "UTC" });
277
+ const sign = (hours) => `${hours < 0 ? "-" : "+"}${Math.abs(hours)}`;
278
+ if (offset !== null && offset.trim() !== "" && Number.isFinite(Number(offset))) {
279
+ const hours = Number(offset);
280
+ const shifted = (ms) => ms + hours * 3_600_000;
281
+ const clock = new Intl.DateTimeFormat(lang, { ...hour, timeZone: "UTC" });
282
+ const date = new Intl.DateTimeFormat(lang, { weekday: "short", day: "numeric", month: "short", timeZone: "UTC" });
283
+ return { clock: (ms) => clock.format(shifted(ms)), utc: (ms) => utc.format(ms), date: (ms) => date.format(shifted(ms)), zone: fill(WORDS[lang]["zoneAbout"], { offset: sign(hours) }) };
284
+ }
285
+ let zone = zoneName ?? undefined;
286
+ let clock;
287
+ try {
288
+ clock = new Intl.DateTimeFormat(lang, { ...hour, ...(zone ? { timeZone: zone } : {}) });
289
+ }
290
+ catch {
291
+ zone = undefined;
292
+ clock = new Intl.DateTimeFormat(lang, hour);
293
+ }
294
+ const date = new Intl.DateTimeFormat(lang, { weekday: "short", day: "numeric", month: "short", ...(zone ? { timeZone: zone } : {}) });
295
+ const label = zone ?? new Intl.DateTimeFormat().resolvedOptions().timeZone;
296
+ return {
297
+ clock: (ms) => clock.format(ms),
298
+ utc: (ms) => utc.format(ms),
299
+ date: (ms) => date.format(ms),
300
+ zone: label === "UTC" ? WORDS[lang]["zoneUtc"] : fill(WORDS[lang]["zone"], { zone: label, utc: "UTC" }),
301
+ };
302
+ }
303
+ #draw() {
304
+ const root = this.shadowRoot;
305
+ if (!root)
306
+ return;
307
+ const lang = this.language;
308
+ const say = (key, values) => fill(WORDS[lang][key] ?? WORDS["en"][key] ?? key, values);
309
+ const days = Math.min(14, Math.max(1, Math.round(number(this.getAttribute("days"), 5))));
310
+ const latitude = number(this.getAttribute("latitude"), Number.NaN);
311
+ const longitude = number(this.getAttribute("longitude"), Number.NaN);
312
+ const holder = root.querySelector(".root") ?? Object.assign(root.ownerDocument.createElement("div"), { className: "root" });
313
+ if (!holder.isConnected) {
314
+ holder.addEventListener("click", (event) => {
315
+ const row = event.target?.closest("[data-i]");
316
+ if (row)
317
+ this.select(Number(row.dataset["i"]));
318
+ });
319
+ root.append(holder);
320
+ }
321
+ if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) {
322
+ holder.innerHTML = `<p class="empty" role="status">${escape(say("waiting"))}</p>`;
323
+ return;
324
+ }
325
+ if (this.#problem) {
326
+ holder.innerHTML = `<p class="empty" role="status">${escape(say("unreadable", { why: this.#problem }))}</p>`;
327
+ return;
328
+ }
329
+ const chosenSet = this.getAttribute("satellite");
330
+ const sets = chosenSet ? this.#sets.filter((one) => String(one.NORAD_CAT_ID) === chosenSet) : this.#sets;
331
+ if (this.#waiting && sets.length === 0) {
332
+ holder.innerHTML = `<p class="empty" role="status">${escape(say("waiting"))}</p>`;
333
+ return;
334
+ }
335
+ const from = this.from;
336
+ const all = this.getAttribute("show") === "all";
337
+ const skyAsked = this.getAttribute("sky");
338
+ const sky = skyAsked === "nautical" || skyAsked === "astronomical" || skyAsked === "night" ? skyAsked : "civil";
339
+ const place = { latitude, longitude, heightM: number(this.getAttribute("height"), 0) };
340
+ this.#passes = findPasses(sets, place, { from, to: from + days * 86_400_000 }, { all, sky, minAltitude: number(this.getAttribute("min-altitude"), 10) });
341
+ const wanted = this.getAttribute("selected");
342
+ const target = wanted ? Date.parse(wanted) : Number.NaN;
343
+ // the pass asked for, else the first: the dome is never empty when there is a pass
344
+ this.#chosen = (Number.isFinite(target) ? this.#passes.find((one) => Math.abs(one.highest.ms - target) < 90_000) : undefined) ?? this.#passes[0];
345
+ const f = this.#formats();
346
+ const name = (pass) => SHORT[pass.noradId]?.[lang] ?? pass.name;
347
+ const badge = (pass) => `<span class="badge" data-reason="${pass.reason}">${escape(say(pass.reason))}</span>`;
348
+ const many = new Set(this.#passes.map((one) => one.noradId)).size > 1;
349
+ const rows = this.#passes
350
+ .map((pass, i) => {
351
+ const shown = pass.visible ?? pass;
352
+ const mag = pass.magnitude !== undefined && Number.isFinite(pass.magnitude) ? ` <span class="mag">${tenths(pass.magnitude)}</span>` : "";
353
+ return (`<li><button type="button" class="row" data-i="${i}" aria-pressed="${pass === this.#chosen}">` +
354
+ `<span class="when">${escape(f.date(pass.highest.ms))}${many ? ` · ${escape(name(pass))}` : ""}</span>${badge(pass)}` +
355
+ `<span class="track">${escape(f.clock(shown.start.ms).slice(0, 5))} ${escape(say(shown.start.compass))} → ${escape(f.clock(shown.highest.ms).slice(0, 5))} ${escape(say(shown.highest.compass))} ${Math.round(shown.highest.altitude)}° → ${escape(f.clock(shown.end.ms).slice(0, 5))} ${escape(say(shown.end.compass))}${mag}</span>` +
356
+ `</button></li>`);
357
+ })
358
+ .join("");
359
+ // the age of the orbit data for the first pass of each satellite
360
+ const ages = new Map();
361
+ for (const pass of this.#passes)
362
+ if (!ages.has(pass.noradId))
363
+ ages.set(pass.noradId, pass);
364
+ const oldest = Math.max(0, ...[...ages.values()].map((one) => one.elementAgeDays));
365
+ const note = `<p class="note">${escape(f.zone)} ${escape(say("reboost"))}${oldest > DEFAULT_DIM_AFTER_DAYS ? ` ${escape(say("stale"))}${lang === "ja" ? "。" : "."}` : ""}</p>`;
366
+ const credit = this.getAttribute("credit");
367
+ const list = this.#passes.length === 0 ? `<p class="empty" role="status">${escape(say(all ? "noneAll" : "none", { days }))}</p>` : `<ul class="list" aria-label="${escape(say("list"))}">${rows}</ul>`;
368
+ holder.innerHTML = `${note}<div class="layout"><div>${list}</div><div class="detail">${this.#chosen ? this.#detail(this.#chosen, f, say, lang) : ""}</div></div>${credit ? `<p class="credit">${escape(credit)}</p>` : ""}`;
369
+ this.dispatchEvent(new CustomEvent("chikyu-passes", { detail: { passes: this.#passes, ageDays: oldest }, bubbles: true, composed: true }));
370
+ // tell the page which pass is shown when that changed (the page draws its own pictures of it)
371
+ const shown = this.#chosen?.highest.ms;
372
+ if (shown !== this.#announced) {
373
+ this.#announced = shown;
374
+ this.dispatchEvent(new CustomEvent("chikyu-pass-select", { detail: { pass: this.#chosen, set: this.#chosen ? this.#sets.find((one) => one.NORAD_CAT_ID === this.#chosen.noradId) : undefined }, bubbles: true, composed: true }));
375
+ }
376
+ }
377
+ #detail(pass, f, say, lang) {
378
+ const set = this.#sets.find((one) => one.NORAD_CAT_ID === pass.noradId);
379
+ const place = { latitude: number(this.getAttribute("latitude"), 0), longitude: number(this.getAttribute("longitude"), 0), heightM: number(this.getAttribute("height"), 0) };
380
+ const short = SHORT[pass.noradId]?.[lang] ?? pass.name;
381
+ const labels = { north: say("skyN"), east: say("skyE"), south: say("skyS"), west: say("skyW"), start: say("skyStart"), highest: say("skyHighest"), end: say("skyEnd"), zenith: say("skyZenith") };
382
+ const clock = (ms) => f.clock(ms);
383
+ const description = say("skyDescription", { name: short, from: say(pass.start.compass), to: say(pass.end.compass), altitude: Math.round(pass.highest.altitude), where: say(pass.highest.compass) });
384
+ const dome = set ? skySvg(pass, passPath(set, place, pass), { size: 300, labels, times: { start: clock(pass.start.ms).slice(0, 5), highest: clock(pass.highest.ms).slice(0, 5), end: clock(pass.end.ms).slice(0, 5) }, description }) : "";
385
+ const point = (p) => `${escape(clock(p.ms))} (UTC ${escape(f.utc(p.ms))}) · ${escape(say(p.compass))} ${Math.round(p.azimuth)}° · ${escape(say("up", { altitude: Math.round(p.altitude) }))}`;
386
+ const sun = pass.sunAltitude < 0 ? say("sunBelow", { degrees: Math.abs(pass.sunAltitude).toFixed(1) }) : say("sunAbove", { degrees: pass.sunAltitude.toFixed(1) });
387
+ const sky = pass.sky;
388
+ let magnitudeText = say("magUnknown");
389
+ if (pass.magnitude !== undefined && Number.isFinite(pass.magnitude)) {
390
+ const m = pass.magnitude;
391
+ magnitudeText = say("magShown", { value: tenths(m), words: say(m < -4 ? "mag1" : m < -1.5 ? "mag2" : m < 0.5 ? "mag3" : m < 2.5 ? "mag4" : "mag5") });
392
+ }
393
+ const lit = pass.sunlit ? (pass.visible ? say("lit") : say("partLit")) : say("notLit");
394
+ const rows = [
395
+ [say("start"), point(pass.start)],
396
+ [say("highest"), point(pass.highest)],
397
+ [say("end"), point(pass.end)],
398
+ [say("seen"), pass.visible ? escape(say("seenFromTo", { from: `${clock(pass.visible.start.ms)} ${say(pass.visible.start.compass)}`, to: `${clock(pass.visible.end.ms)} ${say(pass.visible.end.compass)}` })) : escape(say(pass.reason === "daylight" ? "reasonDaylight" : pass.reason === "shadow" ? "reasonShadow" : "reasonFaint"))],
399
+ [say("brightness"), escape(magnitudeText)],
400
+ [say("sky"), escape(`${say(sky)}${lang === "ja" ? "、" : ", "}${sun}`)],
401
+ [say("light"), escape(lit)],
402
+ [say("elements"), escape(say("elementsLine", { name: short, date: new Intl.DateTimeFormat(lang, { day: "numeric", month: "short", timeZone: "UTC" }).format(pass.elementEpochMs), age: Math.abs(pass.elementAgeDays).toFixed(1) }) + (pass.stale ? `${lang === "ja" ? "、" : ", "}${say("stale")}` : ""))],
403
+ ];
404
+ return `<div class="pictures"><div class="dome">${dome}</div><div class="ground"><slot name="ground"></slot></div></div><dl class="facts">${rows.map(([key, value]) => `<dt>${escape(key)}</dt><dd>${value}</dd>`).join("")}</dl>`;
405
+ }
406
+ }
407
+ if (typeof customElements !== "undefined" && !customElements.get("chikyu-passes")) {
408
+ customElements.define("chikyu-passes", ChikyuPasses);
409
+ }
@@ -0,0 +1,3 @@
1
+ export { compassOf, findPasses, groundTrack, passPath, satelliteAt, skyAt, sunAltitude, type Compass, type GroundPoint, type Observer, type PassOptions, type PassPoint, type PassReason, type PassWindow, type PathPoint, type SatellitePass, type SkyName, type VisiblePart, } from "./passes.ts";
2
+ export { ESTIMATED_CROSS_SECTIONS, magnitude, standardMagnitude, STANDARD_MAGNITUDES } from "./magnitudes.ts";
3
+ export { skySvg, type SkyLabels, type SkyOptions } from "./sky.ts";
@@ -0,0 +1,4 @@
1
+ // The passes' pure parts: when a satellite crosses the sky over a place, how it looks, and the sky dome that draws it. They need satellite.js (an optional peer) and import in a browser or on a server.
2
+ export { compassOf, findPasses, groundTrack, passPath, satelliteAt, skyAt, sunAltitude, } from "./passes.js";
3
+ export { ESTIMATED_CROSS_SECTIONS, magnitude, standardMagnitude, STANDARD_MAGNITUDES } from "./magnitudes.js";
4
+ export { skySvg } from "./sky.js";