@johnmorrisdotca/chikyu-earth 0.52.0 → 0.54.0

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.
Files changed (41) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +4 -2
  3. package/dist/flat/colours.d.ts +55 -0
  4. package/dist/flat/colours.js +71 -0
  5. package/dist/flat/define.d.ts +3 -0
  6. package/dist/flat/define.js +6 -0
  7. package/dist/flat/element.d.ts +188 -0
  8. package/dist/flat/element.js +1541 -0
  9. package/dist/flat/facts.d.ts +172 -0
  10. package/dist/flat/facts.js +168 -0
  11. package/dist/flat/geometry.d.ts +160 -0
  12. package/dist/flat/geometry.js +156 -0
  13. package/dist/flat/index.d.ts +6 -0
  14. package/dist/flat/index.js +7 -0
  15. package/dist/flat/track-state.d.ts +174 -0
  16. package/dist/flat/track-state.js +223 -0
  17. package/dist/flat/words.d.ts +25 -0
  18. package/dist/flat/words.js +78 -0
  19. package/dist/passes/index.d.ts +2 -1
  20. package/dist/passes/index.js +1 -1
  21. package/dist/passes/passes.d.ts +34 -0
  22. package/dist/passes/passes.js +43 -2
  23. package/dist/realistic/element-base.d.ts +6 -0
  24. package/dist/realistic/element-base.js +15 -2
  25. package/dist/space/compass.d.ts +36 -0
  26. package/dist/space/compass.js +72 -0
  27. package/dist/space/element-base.d.ts +48 -1
  28. package/dist/space/element-base.js +95 -6
  29. package/dist/space/index.d.ts +2 -1
  30. package/dist/space/index.js +1 -0
  31. package/dist/space/north-up.d.ts +86 -0
  32. package/dist/space/north-up.js +104 -0
  33. package/dist/space/path-controls.d.ts +1 -1
  34. package/dist/space/path-controls.js +13 -2
  35. package/dist/space/path-ribbons.d.ts +4 -0
  36. package/dist/space/path-ribbons.js +8 -4
  37. package/dist/space/satellite-layer.d.ts +5 -0
  38. package/dist/space/satellite-layer.js +16 -4
  39. package/dist/space/scene.d.ts +23 -0
  40. package/dist/space/scene.js +18 -1
  41. package/package.json +13 -1
@@ -0,0 +1,1541 @@
1
+ var _a;
2
+ // <chikyu-flat>: satellites on a flat map of the world. A canvas for the map (land, day and night) and a canvas for the dots, the places worked out in the browser by SGP4 (satellite.js, an optional peer) from the elements the page hands over.
3
+ // Nothing runs on a timer when the clock is held, and nothing is drawn at rest, out of sight or in a hidden tab. This file registers nothing: `@johnmorrisdotca/chikyu-earth/flat/define` does.
4
+ import { geoCircle, geoEquirectangular, geoGraticule10, geoPath } from "d3-geo";
5
+ import { adoptStyles } from "../adopt.js";
6
+ import { footprintAngle, BEAM_ELEVATION } from "../beam/geometry.js";
7
+ import { orbitShape } from "../catalogue/orbit.js";
8
+ import { COUNTRIES } from "../countries.js";
9
+ import { groundTrack } from "../passes/passes.js";
10
+ import { subsolarPoint, greenwichSidereal } from "../realistic/sun.js";
11
+ import { SATELLITE_GROUPS } from "../satellites/catalogue.js";
12
+ import { SHORT_NAMES } from "../satellites/names.js";
13
+ import { MAX_SATELLITE_SPEED } from "../satellites/limits.js";
14
+ import { fetchElements } from "../satellites/source.js";
15
+ import { createSatellites } from "../satellites/track.js";
16
+ import { GROUP_COLOURS, PLANE_COLOURS, SPARE_COLOUR, TRACK_SHADOW, TRACK_SUNLIT } from "./colours.js";
17
+ import { clusterPlanes, groupFacts } from "./facts.js";
18
+ import { FLATTENED, MAX_ZOOM, clampView, pixelsPerDegree, projectFlat, wrapLongitude, zoomAbout } from "./geometry.js";
19
+ import { trackStateOfScene } from "./track-state.js";
20
+ import { say } from "./words.js";
21
+ const RAD = Math.PI / 180;
22
+ /** The most satellites whose footprints are drawn at once when none is chosen. */
23
+ const FOOTPRINT_MAX = 80;
24
+ const TIME_EVENT_MS = 250;
25
+ /** How long, in real seconds, a fast clock's streak covers, and the longest it is drawn, in pixels. */
26
+ const STREAK_SECONDS = 0.25;
27
+ const STREAK_PX = 28;
28
+ /** ...and for a crowd (thousands of dots), where long streaks would be a tangle. */
29
+ const STREAK_PX_CROWD = 10;
30
+ /** The furthest a pointer may move between going down and coming up and still be a tap, pixels. */
31
+ const TAP_SLOP = 5;
32
+ /** Cut a ground track into stretches of sunlight and shadow. Each stretch ends on the first point of the next, so the line has no gap where the light changes. */
33
+ const trackRuns = (points) => {
34
+ const runs = [];
35
+ let run = null;
36
+ for (const p of points) {
37
+ if (!run || run.sunlit !== p.sunlit) {
38
+ const next = { sunlit: p.sunlit, points: [] };
39
+ if (run && run.points.length > 0)
40
+ next.points.push(run.points[run.points.length - 1]);
41
+ runs.push(next);
42
+ run = next;
43
+ }
44
+ run.points.push([p.lon, p.lat]);
45
+ }
46
+ return runs;
47
+ };
48
+ const sameRef = (a, b) => a === b || (a !== null && b !== null && a.g === b.g && a.i === b.i);
49
+ const escape = (text) => text.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
50
+ const flag = (value) => value !== null && !/^(off|false|no|0)$/i.test(value.trim());
51
+ const finite = (value, fallback) => (value === null || value.trim() === "" || !Number.isFinite(Number(value)) ? fallback : Number(value));
52
+ const readTime = (value) => {
53
+ if (value === null || value.trim() === "" || value.trim().toLowerCase() === "now")
54
+ return "now";
55
+ const text = value.trim();
56
+ const ms = Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(text) || !/T/.test(text) ? text : `${text}Z`);
57
+ return Number.isFinite(ms) ? ms : "now";
58
+ };
59
+ const prefersLessMotion = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
60
+ const hidden = () => typeof document !== "undefined" && document.visibilityState === "hidden";
61
+ const CSS = `
62
+ :host{display:flex;flex-direction:column;gap:8px;color:inherit;font:inherit;container-type:inline-size;min-width:0}
63
+ :host([hidden]){display:none}
64
+ *{box-sizing:border-box}
65
+ .bar{display:grid;gap:6px}
66
+ .bar:empty{display:none}
67
+ .row{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
68
+ .chips{flex-wrap:nowrap;overflow-x:auto;scrollbar-width:thin;padding-bottom:2px}
69
+ .chips>*{flex:none}
70
+ @container (min-width:600px){.chips{flex-wrap:wrap;overflow:visible}}
71
+ .gap{flex:1 1 0}
72
+ button{font:inherit;color:inherit;background:transparent;border:1px solid color-mix(in srgb,currentColor 35%,transparent);border-radius:999px;padding:3px 12px;min-height:32px;cursor:pointer;display:inline-flex;align-items:center;gap:6px}
73
+ button[aria-pressed="true"]{background:color-mix(in srgb,currentColor 14%,transparent);border-color:currentColor}
74
+ button:disabled{opacity:.45;cursor:default}
75
+ button:focus-visible{outline:3px solid #6cd0ff;outline-offset:2px}
76
+ @media (pointer:coarse){button{min-height:44px;padding:6px 14px}}
77
+ .chip .swatch{width:10px;height:10px;border-radius:50%;background:var(--c,#9aa5b1);flex:none}
78
+ .chip .n{opacity:.7;font-variant-numeric:tabular-nums;font-size:.85em}
79
+ .stage{position:relative;flex:1 1 auto;min-height:0;aspect-ratio:var(--chikyu-flat-aspect,2/1);overflow:hidden;border-radius:var(--chikyu-flat-radius,10px);background:var(--chikyu-flat-sea,#0b1830)}
80
+ @container (max-width:599px){.stage{aspect-ratio:var(--chikyu-flat-aspect-narrow,4/3)}}
81
+ canvas{position:absolute;inset:0;width:100%;height:100%;display:block}
82
+ .dots{outline:none;cursor:grab;touch-action:pan-y}
83
+ .dots[data-zoomed]{touch-action:none}
84
+ .dots:focus-visible{outline:3px solid #6cd0ff;outline-offset:-3px}
85
+ .ring{position:absolute;left:0;top:0;width:20px;height:20px;margin:-10px 0 0 -10px;border:2px solid #fff;border-radius:50%;pointer-events:none;box-shadow:0 0 0 1px #000,inset 0 0 0 1px #000}
86
+ .ring.hov{width:14px;height:14px;margin:-7px 0 0 -7px;border-width:1px}
87
+ .ring[hidden],.tip[hidden]{display:none}
88
+ .tip{position:absolute;left:0;top:0;pointer-events:none;background:rgba(8,14,28,.94);color:#fff;padding:4px 8px;border-radius:6px;font-size:.85em;line-height:1.3;white-space:nowrap;border:1px solid rgba(255,255,255,.3)}
89
+ .key{position:absolute;left:8px;bottom:8px;display:flex;flex-wrap:wrap;gap:4px 12px;margin:0;padding:3px 8px;border-radius:6px;background:rgba(8,14,28,.82);color:#fff;font-size:.8em;line-height:1.3;pointer-events:none;max-width:calc(100% - 16px)}
90
+ .key[hidden]{display:none}
91
+ .key span{display:inline-flex;align-items:center;gap:6px}
92
+ .key i{display:inline-block;width:18px;height:0;border-top:3px solid var(--k,#fff);border-radius:2px;box-shadow:0 0 0 1px rgba(0,0,0,.55)}
93
+ .msg{position:absolute;inset:0;display:grid;place-items:center;margin:0;padding:12px;text-align:center;color:#cfe0f5;pointer-events:none}
94
+ .msg:empty{display:none}
95
+ .sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
96
+ `;
97
+ /**
98
+ * The `<chikyu-flat>` custom element: satellites on a flat map of the world, at the places SGP4 puts them for the time shown. Import `@johnmorrisdotca/chikyu-earth/flat/define` to register the tag; it needs `satellite.js` (an optional peer).
99
+ *
100
+ * The page gives it orbital elements: `setGroup(id, sets)` for each group (the ids of `SATELLITE_GROUPS` are known by name and colour), or the `elements` property for one, or `elements-src` (an address, read once, through `fetchElements`' rules). The package fetches nothing of its own.
101
+ * Attributes: `center` (the longitude in the middle, degrees; 0, Greenwich, by default; the map wraps round the date line), `home-lon` and `home-lat` (the reader's place: a marker, and the "My place" button, which appear only when given; the element never asks the browser for a place),
102
+ * `group` (which groups to show: `all`, one id, or several with commas), `off` (groups that are loaded but start off when `group` names none, such as `starlink`: the filter chip turns one on), `colour-by` (`group`, or `plane` to colour by orbital plane), `plane` (a plane letter: show that plane only), `footprint` and `track` (draw the coverage circle and the ground track, which is amber in sunlight and blue in the Earth's shadow, a cylinder, with a key: `--chikyu-flat-track-sun` and `--chikyu-flat-track-shadow` change the colours; the footprint is of the chosen satellite, or of every one shown when there are 80 or fewer),
103
+ * `paused` (hold the clock and keep the speed; nothing is drawn while it is held), `trails` (`off` for no streaks at a fast clock), `footprint-elevation` (degrees above the horizon the circle is drawn for; 25 like the 3D beam), `selected` (a NORAD number: the chosen satellite), `time` (`now` or an ISO date; live when absent), `speed` (1 is real time, 0 holds, 86400 is a day a second, negative runs backwards), `estimate-far`, `shade` (`off` for no night),
104
+ * `dot-size` (pixels), `controls` (`none`, or any of `centre zoom footprint track chips`: the built-in buttons and filter chips shown; all by default) and `lang` (`en` or `ja`; the page's language by default).
105
+ *
106
+ * Events: `chikyu-flat-pick` (a satellite under the pointer, tapped, or reached by the keyboard: a `FlatPick`; `detail.id` is null when a tap lands on nothing and clears the choice), `chikyu-flat-filter` (a chip changed which groups or plane are shown: `{ groups, plane }`),
107
+ * `chikyu-flat-planes` (the planes were worked out: `{ planes }`), `chikyu-flat-view` (the reader panned or zoomed: `{ center, zoom }`) and `chikyu-timechange` (`{ time, running }`, at most four a second while time runs).
108
+ * Style it with the custom properties `--chikyu-flat-sea`, `--chikyu-flat-land`, `--chikyu-flat-line`, `--chikyu-flat-night`, `--chikyu-flat-aspect`, `--chikyu-flat-aspect-narrow` and `--chikyu-flat-radius`.
109
+ *
110
+ * @example
111
+ * ```ts no-run
112
+ * import "@johnmorrisdotca/chikyu-earth/flat/define";
113
+ * import type { ChikyuFlat } from "@johnmorrisdotca/chikyu-earth/flat/define";
114
+ * import type { ElementSet } from "@johnmorrisdotca/chikyu-earth/satellites";
115
+ *
116
+ * declare const gpsElements: ElementSet[]; // your page's own element sets
117
+ * const flat = document.createElement("chikyu-flat") as ChikyuFlat;
118
+ * flat.setAttribute("center", "139.7");
119
+ * flat.setAttribute("colour-by", "plane");
120
+ * flat.setGroup("gps", gpsElements);
121
+ * document.body.append(flat);
122
+ * flat.addEventListener("chikyu-flat-pick", (event) => console.log((event as CustomEvent).detail.name));
123
+ * ```
124
+ */
125
+ export class ChikyuFlat extends HTMLElement {
126
+ static observedAttributes = ["paused", "trails", "off", "center", "home-lon", "home-lat", "group", "colour-by", "color-by", "plane", "footprint", "track", "footprint-elevation", "selected", "time", "speed", "estimate-far", "shade", "dot-size", "controls", "lang", "elements-src"];
127
+ #groups = new Map();
128
+ #index = new Map();
129
+ #shown = null;
130
+ /** Groups that start off when `group` names none: loaded, and one tap on their chip away. */
131
+ #off = new Set();
132
+ #plane = "";
133
+ #selected = null;
134
+ #cursor = null;
135
+ #hover = null;
136
+ #footprint = false;
137
+ #track = false;
138
+ #view = { width: 0, height: 0, centerLon: 0, centerLat: 0, zoom: 1 };
139
+ #dpr = 1;
140
+ #mode = "now";
141
+ #time = 0;
142
+ #speed = 1;
143
+ #last = 0;
144
+ #paused = false;
145
+ /** The moment shown jumped (the page set it, the speed changed, the tab came back): fast placement pins every satellite again before it turns them. */
146
+ #jump = true;
147
+ #lastDraw = 0;
148
+ #totalMs = 0;
149
+ #timer;
150
+ #exact = new Float64Array(6);
151
+ #frame = 0;
152
+ #inView = true;
153
+ #connected = false;
154
+ #problem = "";
155
+ #waiting = false;
156
+ #loaded;
157
+ #fetch = 0;
158
+ #viewSent = "";
159
+ #announced = -Infinity;
160
+ #mapKey = "";
161
+ #trackKey = "";
162
+ #trackLines = null;
163
+ #key;
164
+ #stage;
165
+ #bar;
166
+ #mapCanvas;
167
+ #dotCanvas;
168
+ #selRing;
169
+ #hovRing;
170
+ #tip;
171
+ #live;
172
+ #msg;
173
+ #sizer;
174
+ #watcher;
175
+ #pointers = new Map();
176
+ #drag = null;
177
+ #counts = { draws: 0, mapDraws: 0, dots: 0, lastMs: 0, maxMs: 0 };
178
+ #buckets = new Map();
179
+ #streaks = new Map();
180
+ // --- the page's data -------------------------------------------------------------------------------------------------------------------------
181
+ /**
182
+ * Hand over a group's orbital elements, or take the group away with `null`. The satellites start SGP4 here (a Starlink-sized group takes a fraction of a second), the facts and orbital planes are worked out, and the next draw shows them.
183
+ * `id` is a name of `SATELLITE_GROUPS` (`gps`, `starlink`: its words and colour are known) or any name of the page's own, with `style` for its colour and words.
184
+ *
185
+ * @param id - The group's name.
186
+ * @param sets - Its element sets, as `createSatellites` takes them; `null` removes the group.
187
+ * @param style - The colour and the English and Japanese names of a group the package does not know.
188
+ */
189
+ setGroup(id, sets, style = {}) {
190
+ const old = this.#groups.get(id);
191
+ if (old) {
192
+ for (const set of old.sats.sets)
193
+ if (this.#index.get(set.NORAD_CAT_ID)?.g === old)
194
+ this.#index.delete(set.NORAD_CAT_ID);
195
+ if (this.#selected?.g === old)
196
+ this.#selected = null;
197
+ if (this.#cursor?.g === old)
198
+ this.#cursor = null;
199
+ if (this.#hover?.g === old)
200
+ this.#hover = null;
201
+ this.#groups.delete(id);
202
+ }
203
+ if (sets !== null) {
204
+ const sats = createSatellites(sets);
205
+ sats.estimateFar = flag(this.getAttribute("estimate-far"));
206
+ const known = SATELLITE_GROUPS.find((one) => one.id === id);
207
+ const n = sats.count;
208
+ const clusters = clusterPlanes(sats.sets);
209
+ const group = {
210
+ id,
211
+ label: style.label ?? known?.label ?? id,
212
+ labelJa: style.labelJa ?? known?.labelJa ?? style.label ?? id,
213
+ colour: style.colour ?? GROUP_COLOURS[id] ?? PLANE_COLOURS[this.#groups.size % PLANE_COLOURS.length],
214
+ sats,
215
+ n,
216
+ buf: new Float32Array(n * 3),
217
+ lon: new Float32Array(n),
218
+ lat: new Float32Array(n),
219
+ alt: new Float32Array(n),
220
+ sx: new Float32Array(n),
221
+ sy: new Float32Array(n),
222
+ seg: null,
223
+ cursor: 0,
224
+ on: new Uint8Array(n),
225
+ clusters,
226
+ facts: groupFacts(sats.sets),
227
+ };
228
+ this.#groups.set(id, group);
229
+ sats.sets.forEach((set, i) => this.#index.set(set.NORAD_CAT_ID, { g: group, i }));
230
+ this.#waiting = false;
231
+ this.#problem = "";
232
+ this.#syncSpeed();
233
+ }
234
+ const wanted = Number(this.getAttribute("selected"));
235
+ if (this.#selected === null && Number.isFinite(wanted) && this.#index.has(wanted))
236
+ this.#selected = this.#index.get(wanted) ?? null;
237
+ this.#trackKey = "";
238
+ this.#buildBar();
239
+ this.dispatchEvent(new CustomEvent("chikyu-flat-planes", { detail: { planes: this.planes }, bubbles: true, composed: true }));
240
+ this.#request();
241
+ this.#schedule();
242
+ }
243
+ /** The element sets of the group the attributes name (`group`, else `satellites`): a shorthand for one group. Setting it calls `setGroup`. */
244
+ get elements() {
245
+ return this.#groups.get(this.#defaultId())?.sats.sets ?? [];
246
+ }
247
+ set elements(sets) {
248
+ this.setGroup(this.#defaultId(), sets);
249
+ }
250
+ /** The groups loaded, in the order they were given: their name, words, colour and how many satellites started SGP4. */
251
+ get groups() {
252
+ return [...this.#groups.values()].map((g) => ({ id: g.id, label: g.label, labelJa: g.labelJa, colour: g.colour, count: g.n }));
253
+ }
254
+ /** The facts (`groupFacts`) of a loaded group, or undefined. */
255
+ facts(id) {
256
+ return this.#groups.get(id)?.facts;
257
+ }
258
+ /** The orbital planes of every loaded group (by right ascension of the ascending node; see `clusterPlanes`): the letter, how many satellites, the colour the map gives it. A group with no planes to show has none here. */
259
+ get planes() {
260
+ const out = [];
261
+ for (const g of this.#groups.values())
262
+ for (const plane of g.clusters.planes)
263
+ out.push({ ...plane, group: g.id, colour: PLANE_COLOURS[plane.index % PLANE_COLOURS.length] });
264
+ return out;
265
+ }
266
+ /** The groups on show: those the `group` attribute names, or the ones a chip chose; every loaded group when none is chosen. Set to a list of ids, or `null` for all. */
267
+ get visibleGroups() {
268
+ return this.#shownGroups().map((g) => g.id);
269
+ }
270
+ set visibleGroups(ids) {
271
+ this.#shown = ids === null ? null : new Set(ids);
272
+ this.#afterFilter();
273
+ }
274
+ /** The NORAD number of the chosen satellite, or null. Set it to choose one from code (no `chikyu-flat-pick` is sent), `null` to clear. */
275
+ get selected() {
276
+ return this.#selected ? (this.#selected.g.sats.sets[this.#selected.i]?.NORAD_CAT_ID ?? null) : null;
277
+ }
278
+ set selected(id) {
279
+ this.#selected = id === null ? null : (this.#index.get(id) ?? null);
280
+ this.#trackKey = "";
281
+ this.#sync();
282
+ this.#request();
283
+ }
284
+ /** The longitude in the middle, degrees. Set it to centre the map there; a reader's pan changes it, and `chikyu-flat-view` tells the page. */
285
+ get center() {
286
+ return this.#view.centerLon;
287
+ }
288
+ set center(lon) {
289
+ this.#view = clampView({ ...this.#view, centerLon: lon });
290
+ this.#sync();
291
+ this.#request();
292
+ }
293
+ /** The zoom: 1 shows the whole world, up to 8. */
294
+ get zoom() {
295
+ return this.#view.zoom;
296
+ }
297
+ set zoom(value) {
298
+ this.#view = clampView({ ...this.#view, zoom: value });
299
+ this.#sync();
300
+ this.#request();
301
+ }
302
+ /** The moment shown, in milliseconds since the Unix epoch. Set it to a number (or a `Date`) to move the clock, or "now" to go live. */
303
+ get time() {
304
+ this.#advance(performance.now());
305
+ return this.#time;
306
+ }
307
+ set time(value) {
308
+ this.#mode = value === "now" ? "now" : typeof value === "number" ? value : value.getTime();
309
+ this.#time = this.#mode === "now" ? Date.now() : this.#mode;
310
+ this.#last = performance.now();
311
+ // a jump: the dots are placed again at once, from the new moment
312
+ this.#jump = true;
313
+ this.#request();
314
+ this.#schedule();
315
+ }
316
+ /** How fast the clock runs: 1 is real time, 0 holds, 86400 is a day a second, negative runs backwards. */
317
+ get speed() {
318
+ return this.#speed;
319
+ }
320
+ set speed(value) {
321
+ this.#advance(performance.now());
322
+ this.#speed = Number.isFinite(value) ? value : 1;
323
+ this.#jump = true;
324
+ this.#syncSpeed();
325
+ this.#schedule();
326
+ this.#request();
327
+ }
328
+ /** True while the clock is held with its speed kept (the page's Pause): nothing is drawn but what the reader changes. Setting it false carries on from the moment shown at the same speed. */
329
+ get paused() {
330
+ return this.#paused;
331
+ }
332
+ set paused(value) {
333
+ const now = performance.now();
334
+ this.#advance(now);
335
+ if (value === this.#paused)
336
+ return;
337
+ this.#paused = value;
338
+ // held, the moment stays where it is even in real time (it does not jump to the clock's now when carried on)
339
+ if (value && this.#mode === "now")
340
+ this.#mode = this.#time;
341
+ this.#last = now;
342
+ this.#jump = true;
343
+ this.#schedule();
344
+ this.#request();
345
+ this.dispatchEvent(new CustomEvent("chikyu-timechange", { detail: { time: this.#time, running: this.#running(), paused: value }, bubbles: true, composed: true }));
346
+ }
347
+ /** The language of the words: the `lang` attribute, else the page's. */
348
+ get language() {
349
+ return (this.getAttribute("lang") ?? this.ownerDocument.documentElement.lang ?? "en").toLowerCase().startsWith("ja") ? "ja" : "en";
350
+ }
351
+ /** Counters for a test or a page: draws of the dots, draws of the map, the dots drawn at the last draw, the milliseconds the last draw and the slowest took, and the canvases' size in pixels. */
352
+ get stats() {
353
+ const canvases = [this.#mapCanvas, this.#dotCanvas].filter((c) => c !== undefined).map((c) => ({ width: c.width, height: c.height }));
354
+ return { draws: this.#counts.draws, mapDraws: this.#counts.mapDraws, dots: this.#counts.dots, lastDrawMs: this.#counts.lastMs, maxDrawMs: this.#counts.maxMs, running: this.#running(), paused: this.#paused, fast: this.#fast(), averageDrawMs: this.#counts.draws > 0 ? this.#totalMs / this.#counts.draws : 0, canvases };
355
+ }
356
+ /** Where a satellite is on the screen as of the last draw, in CSS pixels from the map's top left, or null when it is not drawn (not loaded, filtered out, off the map or too old). */
357
+ placeOf(id) {
358
+ const ref = this.#index.get(id);
359
+ if (!ref || ref.g.on[ref.i] !== 1)
360
+ return null;
361
+ return { x: ref.g.sx[ref.i], y: ref.g.sy[ref.i], lon: ref.g.lon[ref.i], lat: ref.g.lat[ref.i], altitudeKm: ref.g.alt[ref.i] };
362
+ }
363
+ // --- the element's life ----------------------------------------------------------------------------------------------------------------------
364
+ connectedCallback() {
365
+ const root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
366
+ adoptStyles(root, CSS, this.getAttribute("nonce") ?? "");
367
+ if (!this.#stage)
368
+ this.#build(root);
369
+ this.#connected = true;
370
+ this.#readAll();
371
+ this.#advance(performance.now());
372
+ this.#sizer = new ResizeObserver(() => {
373
+ this.#measure();
374
+ this.#request();
375
+ });
376
+ this.#sizer.observe(this.#stage);
377
+ if (typeof IntersectionObserver === "function") {
378
+ this.#watcher = new IntersectionObserver((entries) => {
379
+ const was = this.#visibleNow();
380
+ this.#inView = entries[entries.length - 1]?.isIntersecting ?? true;
381
+ if (!was && this.#visibleNow())
382
+ this.#wake();
383
+ });
384
+ this.#watcher.observe(this);
385
+ }
386
+ document.addEventListener("visibilitychange", this.#onVisibility);
387
+ this.#measure();
388
+ this.#buildBar();
389
+ this.#request();
390
+ this.#schedule();
391
+ }
392
+ disconnectedCallback() {
393
+ this.#connected = false;
394
+ clearTimeout(this.#timer);
395
+ this.#timer = undefined;
396
+ if (this.#frame)
397
+ cancelAnimationFrame(this.#frame);
398
+ this.#frame = 0;
399
+ this.#sizer?.disconnect();
400
+ this.#watcher?.disconnect();
401
+ this.#sizer = undefined;
402
+ this.#watcher = undefined;
403
+ document.removeEventListener("visibilitychange", this.#onVisibility);
404
+ }
405
+ attributeChangedCallback(name) {
406
+ if (!this.#connected)
407
+ return;
408
+ this.#read(name);
409
+ if (name === "selected" || name === "footprint-elevation")
410
+ this.#trackKey = "";
411
+ if (name === "lang" || name === "controls" || name === "group" || name === "colour-by" || name === "color-by" || name === "home-lon" || name === "home-lat" || name === "plane")
412
+ this.#buildBar();
413
+ this.#sync();
414
+ this.#request();
415
+ this.#schedule();
416
+ }
417
+ #onVisibility = () => {
418
+ if (this.#visibleNow())
419
+ this.#wake();
420
+ else {
421
+ clearTimeout(this.#timer);
422
+ this.#timer = undefined;
423
+ }
424
+ };
425
+ #visibleNow() {
426
+ return this.#connected && this.#inView && !hidden();
427
+ }
428
+ /** Back in sight: bring the clock up to date, draw once, and start the timer again. */
429
+ #wake() {
430
+ this.#advance(performance.now());
431
+ this.#jump = true;
432
+ this.#request();
433
+ this.#schedule();
434
+ }
435
+ /** Take in every attribute the element has: when it comes into the page. */
436
+ #readAll() {
437
+ for (const name of _a.observedAttributes)
438
+ this.#read(name);
439
+ }
440
+ /** Take in one attribute. A change to one never undoes what the reader did with another (a chosen satellite, the pan). */
441
+ #read(name) {
442
+ const value = this.getAttribute(name);
443
+ if (name === "center") {
444
+ const lon = finite(value, Number.NaN);
445
+ if (Number.isFinite(lon))
446
+ this.#view = clampView({ ...this.#view, centerLon: lon });
447
+ this.#mapKey = "";
448
+ }
449
+ else if (name === "group") {
450
+ const ids = (value ?? "").split(/[\s,]+/).filter((one) => one !== "" && one.toLowerCase() !== "all");
451
+ this.#shown = ids.length === 0 ? null : new Set(ids);
452
+ }
453
+ else if (name === "off")
454
+ this.#off = new Set((value ?? "").split(/[\s,]+/).filter((one) => one !== ""));
455
+ else if (name === "plane")
456
+ this.#plane = (value ?? "").trim().toUpperCase();
457
+ else if (name === "footprint")
458
+ this.#footprint = flag(value);
459
+ else if (name === "track")
460
+ this.#track = flag(value);
461
+ else if (name === "selected") {
462
+ const id = value === null || value.trim() === "" ? null : Number(value);
463
+ this.#selected = id !== null && Number.isFinite(id) ? (this.#index.get(id) ?? null) : null;
464
+ }
465
+ else if (name === "paused") {
466
+ if (flag(value) !== this.#paused)
467
+ this.paused = flag(value);
468
+ }
469
+ else if (name === "time" || name === "speed")
470
+ this.#readClock();
471
+ else if (name === "estimate-far")
472
+ for (const g of this.#groups.values())
473
+ g.sats.estimateFar = flag(value);
474
+ else if (name === "elements-src")
475
+ this.#load();
476
+ else if (name === "shade" || name === "dot-size")
477
+ this.#mapKey = "";
478
+ }
479
+ #readClock() {
480
+ this.#advance(performance.now());
481
+ this.#mode = readTime(this.getAttribute("time"));
482
+ this.#time = this.#mode === "now" ? Date.now() : this.#mode;
483
+ const raw = this.getAttribute("speed");
484
+ const speed = raw === null || raw.trim() === "" ? 1 : Number(raw);
485
+ this.#speed = Number.isFinite(speed) ? speed : 1;
486
+ this.#last = performance.now();
487
+ this.#jump = true;
488
+ this.#syncSpeed();
489
+ }
490
+ /** How far apart the two SGP4 batches are, so a fast clock does not run SGP4 more than once a (game) second. */
491
+ #syncSpeed() {
492
+ const step = Math.max(1000, Math.abs(this.#speed) * 1000);
493
+ for (const g of this.#groups.values())
494
+ g.sats.setStep(step);
495
+ }
496
+ #defaultId() {
497
+ return (this.getAttribute("group") ?? "").split(/[\s,]+/).find((one) => one !== "" && one.toLowerCase() !== "all") ?? "satellites";
498
+ }
499
+ #load() {
500
+ const address = this.getAttribute("elements-src");
501
+ if (!address || address === this.#loaded)
502
+ return;
503
+ this.#loaded = address;
504
+ const turn = (this.#fetch += 1);
505
+ this.#waiting = true;
506
+ this.#showMessage();
507
+ // 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
508
+ void fetchElements(address).then((got) => {
509
+ if (turn === this.#fetch)
510
+ this.elements = got.sets;
511
+ }, (error) => {
512
+ if (turn !== this.#fetch)
513
+ return;
514
+ this.#waiting = false;
515
+ this.#problem = error instanceof Error ? error.message : "no answer";
516
+ this.#showMessage();
517
+ });
518
+ }
519
+ // --- the clock -------------------------------------------------------------------------------------------------------------------------------
520
+ #advance(now) {
521
+ if (this.#paused || this.#speed === 0) {
522
+ // held: the moment stays
523
+ }
524
+ else if (this.#speed === 1 && this.#mode === "now")
525
+ this.#time = Date.now();
526
+ else
527
+ this.#time += (now - this.#last) * this.#speed;
528
+ this.#last = now;
529
+ }
530
+ /** The clock is running and the element is in sight: it asks for frames. A held clock, a hidden tab and a view out of sight ask for none. */
531
+ #running() {
532
+ return this.#visibleNow() && this.#speed !== 0 && !this.#paused;
533
+ }
534
+ /** Is the clock fast enough that SGP4 cannot be run for every frame (the satellites turn along their orbits and are drawn as streaks)? */
535
+ #fast() {
536
+ return !this.#paused && Math.abs(this.#speed) > MAX_SATELLITE_SPEED;
537
+ }
538
+ /**
539
+ * How often a running clock draws: as often as a satellite in a low orbit (about 0.07 degree of the map a second) moves half a pixel, up to every frame, and at least once a second; once a second at most for a reader who asked for reduced motion.
540
+ * With nothing to show, the pace of the night's edge (the Earth turns 0.004 degree a second).
541
+ */
542
+ #rate() {
543
+ const k = pixelsPerDegree(this.#view.width > 0 ? this.#view : { ...this.#view, width: 600, height: 300 });
544
+ const dots = this.#shownGroups().length > 0;
545
+ let perSecond = ((dots ? 0.07 : 0.0042) * Math.abs(this.#speed) * k) / 0.5;
546
+ perSecond = Math.min(60, Math.max(dots ? 1 : 1 / 30, perSecond));
547
+ if (prefersLessMotion())
548
+ perSecond = Math.min(perSecond, 1);
549
+ return perSecond;
550
+ }
551
+ /** After a draw, or when something about the clock changed: ask for the next frame in time, a frame a time at the pace `#rate` gives, by a timer when frames are far apart. Nothing at all when the clock is held or out of sight. */
552
+ #schedule() {
553
+ clearTimeout(this.#timer);
554
+ this.#timer = undefined;
555
+ if (!this.#running())
556
+ return;
557
+ const wait = 1000 / this.#rate() - (performance.now() - this.#lastDraw);
558
+ if (wait > 14) {
559
+ this.#timer = setTimeout(() => {
560
+ this.#timer = undefined;
561
+ this.#request();
562
+ }, wait);
563
+ }
564
+ else
565
+ this.#request();
566
+ }
567
+ /** `chikyu-timechange`: the moment shown, at most four times a second while time runs. */
568
+ #announceTime() {
569
+ const now = performance.now();
570
+ if (!this.#running() || now - this.#announced < TIME_EVENT_MS)
571
+ return;
572
+ this.#announced = now;
573
+ this.dispatchEvent(new CustomEvent("chikyu-timechange", { detail: { time: this.#time, running: true, paused: false }, bubbles: true, composed: true }));
574
+ }
575
+ // --- drawing ---------------------------------------------------------------------------------------------------------------------------------
576
+ /** Ask for one draw at the next frame, however many reasons there are. Nothing is asked for out of sight or in a hidden tab: the draw is made when the element comes back. */
577
+ #request() {
578
+ if (!this.#connected)
579
+ return;
580
+ // out of sight or in a hidden tab nothing is asked for: `#wake` draws once when the element comes back
581
+ if (!this.#visibleNow())
582
+ return;
583
+ if (this.#frame)
584
+ return;
585
+ this.#frame = requestAnimationFrame(() => {
586
+ this.#frame = 0;
587
+ this.#draw();
588
+ });
589
+ }
590
+ #shownGroups() {
591
+ const out = [];
592
+ for (const g of this.#groups.values())
593
+ if (this.#shown === null ? !this.#off.has(g.id) : this.#shown.has(g.id))
594
+ out.push(g);
595
+ return out;
596
+ }
597
+ /** The plane letter the filter keeps, when exactly one group is on show and it has that plane. */
598
+ #planeIndex(groups) {
599
+ if (this.#plane === "" || groups.length !== 1)
600
+ return -1;
601
+ return groups[0].clusters.planes.find((one) => one.id === this.#plane)?.index ?? -1;
602
+ }
603
+ #byPlane(groups) {
604
+ const by = (this.getAttribute("colour-by") ?? this.getAttribute("color-by") ?? "group").trim().toLowerCase();
605
+ return by === "plane" && groups.some((g) => g.clusters.clustered);
606
+ }
607
+ #measure() {
608
+ const stage = this.#stage;
609
+ if (!stage)
610
+ return;
611
+ const width = stage.clientWidth;
612
+ const height = stage.clientHeight;
613
+ // the canvases stay inside 6 million pixels and 4096 a side, whatever the screen
614
+ const dpr = Math.max(0.5, Math.min(window.devicePixelRatio || 1, 3, width > 0 && height > 0 ? Math.sqrt(6_000_000 / (width * height)) : 3, width > 0 || height > 0 ? 4096 / Math.max(width, height) : 3));
615
+ if (width === this.#view.width && height === this.#view.height && dpr === this.#dpr)
616
+ return;
617
+ this.#dpr = dpr;
618
+ this.#view = clampView({ ...this.#view, width, height });
619
+ for (const canvas of [this.#mapCanvas, this.#dotCanvas]) {
620
+ if (!canvas)
621
+ continue;
622
+ canvas.width = Math.max(1, Math.round(width * dpr));
623
+ canvas.height = Math.max(1, Math.round(height * dpr));
624
+ }
625
+ this.#mapKey = "";
626
+ }
627
+ #colours() {
628
+ const style = getComputedStyle(this);
629
+ const pick = (name, fallback) => style.getPropertyValue(name).trim() || fallback;
630
+ return { sea: pick("--chikyu-flat-sea", "#0b1830"), land: pick("--chikyu-flat-land", "#1d3557"), line: pick("--chikyu-flat-line", "#46628a"), night: pick("--chikyu-flat-night", "rgba(2,6,18,0.16)"), grid: "rgba(150,180,220,0.13)" };
631
+ }
632
+ #projection() {
633
+ const v = this.#view;
634
+ const k = pixelsPerDegree(v);
635
+ return geoEquirectangular()
636
+ .rotate([-v.centerLon, 0])
637
+ .scale(k / RAD)
638
+ .translate([v.width / 2, v.height / 2 + v.centerLat * k])
639
+ .precision(0.4);
640
+ }
641
+ #drawMap(ms) {
642
+ const canvas = this.#mapCanvas;
643
+ const v = this.#view;
644
+ if (!canvas || v.width === 0)
645
+ return;
646
+ const sun = subsolarPoint(ms);
647
+ const shade = this.getAttribute("shade") !== "off";
648
+ const home = this.#home();
649
+ // the map is drawn again only when the view, the home or the sun's place (about a quarter of a degree) changed
650
+ const c = this.#colours();
651
+ const key = [v.width, v.height, this.#dpr, v.centerLon.toFixed(3), v.centerLat.toFixed(3), v.zoom.toFixed(3), shade ? Math.round(sun.lon * 4) : "x", shade ? Math.round(sun.lat * 4) : "x", home ? `${home.lon},${home.lat}` : "", c.sea, c.land, c.line, c.night].join("|");
652
+ if (key === this.#mapKey)
653
+ return;
654
+ this.#mapKey = key;
655
+ this.#counts.mapDraws += 1;
656
+ const ctx = canvas.getContext("2d", { willReadFrequently: true });
657
+ if (!ctx)
658
+ return;
659
+ ctx.setTransform(this.#dpr, 0, 0, this.#dpr, 0, 0);
660
+ ctx.fillStyle = c.sea;
661
+ ctx.fillRect(0, 0, v.width, v.height);
662
+ const projection = this.#projection();
663
+ const path = geoPath(projection, ctx);
664
+ ctx.beginPath();
665
+ path(geoGraticule10());
666
+ ctx.strokeStyle = c.grid;
667
+ ctx.lineWidth = 1;
668
+ ctx.stroke();
669
+ ctx.beginPath();
670
+ path(COUNTRIES);
671
+ ctx.fillStyle = c.land;
672
+ ctx.fill();
673
+ ctx.strokeStyle = c.line;
674
+ ctx.lineWidth = 0.6;
675
+ ctx.stroke();
676
+ if (shade) {
677
+ // the night side: four bands from the sunset line towards midnight, each a little darker
678
+ const anti = [wrapLongitude(sun.lon + 180), -sun.lat];
679
+ ctx.fillStyle = c.night;
680
+ for (const radius of [90, 96, 102, 108]) {
681
+ ctx.beginPath();
682
+ path(geoCircle().center(anti).radius(radius).precision(2)());
683
+ ctx.fill();
684
+ }
685
+ const at = projectFlat(v, sun.lon, sun.lat);
686
+ for (const x of [at.x, at.x - 360 * pixelsPerDegree(v), at.x + 360 * pixelsPerDegree(v)]) {
687
+ if (x < -8 || x > v.width + 8)
688
+ continue;
689
+ ctx.beginPath();
690
+ ctx.arc(x, at.y, 5, 0, Math.PI * 2);
691
+ ctx.fillStyle = "#ffd54f";
692
+ ctx.fill();
693
+ ctx.lineWidth = 1;
694
+ ctx.strokeStyle = "rgba(0,0,0,.5)";
695
+ ctx.stroke();
696
+ ctx.fillStyle = c.night;
697
+ }
698
+ }
699
+ if (home) {
700
+ const at = projectFlat(v, home.lon, home.lat);
701
+ const wrap = 360 * pixelsPerDegree(v);
702
+ for (const x of [at.x, at.x - wrap, at.x + wrap]) {
703
+ if (x < -10 || x > v.width + 10)
704
+ continue;
705
+ ctx.save();
706
+ ctx.translate(x, at.y);
707
+ ctx.rotate(Math.PI / 4);
708
+ ctx.fillStyle = "#ffffff";
709
+ ctx.strokeStyle = "#0b1830";
710
+ ctx.lineWidth = 2;
711
+ ctx.strokeRect(-4.5, -4.5, 9, 9);
712
+ ctx.fillRect(-4.5, -4.5, 9, 9);
713
+ ctx.restore();
714
+ }
715
+ }
716
+ }
717
+ #home() {
718
+ const lon = finite(this.getAttribute("home-lon"), Number.NaN);
719
+ const lat = finite(this.getAttribute("home-lat"), Number.NaN);
720
+ return Number.isFinite(lon) && Number.isFinite(lat) ? { lon: wrapLongitude(lon), lat } : null;
721
+ }
722
+ #draw() {
723
+ const started = performance.now();
724
+ const canvas = this.#dotCanvas;
725
+ const v = this.#view;
726
+ if (!canvas || v.width === 0 || v.height === 0)
727
+ return;
728
+ this.#advance(started);
729
+ const ms = this.#time;
730
+ const gmst = greenwichSidereal(ms);
731
+ this.#drawMap(ms);
732
+ // a canvas the processor draws, not the graphics card: thousands of small shapes a frame are quicker that way (a machine with no graphics card, or drawing in software, ran 1 frame a second against 60) and the picture is small
733
+ const ctx = canvas.getContext("2d", { willReadFrequently: true });
734
+ if (!ctx)
735
+ return;
736
+ ctx.setTransform(this.#dpr, 0, 0, this.#dpr, 0, 0);
737
+ ctx.clearRect(0, 0, v.width, v.height);
738
+ const groups = this.#shownGroups();
739
+ const k = pixelsPerDegree(v);
740
+ const wrapPx = 360 * k;
741
+ const planeAt = this.#planeIndex(groups);
742
+ const byPlane = this.#byPlane(groups);
743
+ const total = groups.reduce((sum, g) => sum + g.n, 0);
744
+ const size = finite(this.getAttribute("dot-size"), 0);
745
+ const r = size > 0 ? size / 2 : total > 5000 ? 1.1 : total > 1500 ? 1.5 : total > 300 ? 2 : 3;
746
+ const radius = r * Math.min(1.8, 0.85 + v.zoom * 0.15);
747
+ const pad = radius + 1;
748
+ const buckets = this.#buckets;
749
+ for (const list of buckets.values())
750
+ list.length = 0;
751
+ const streaks = this.#streaks;
752
+ for (const list of streaks.values())
753
+ list.length = 0;
754
+ // a clock too fast for SGP4 to run for every frame: the satellites are turned along their orbits from a pinned place (SGP4 itself a slice of the group a frame, the whole group once a second) and drawn as streaks
755
+ const fast = this.#fast();
756
+ const streak = fast && this.getAttribute("trails") !== "off";
757
+ const dtReal = this.#lastDraw === 0 ? 16 : Math.min(1000, Math.max(0, started - this.#lastDraw));
758
+ const chosen = this.#selected;
759
+ const streakPx = total > 3000 ? STREAK_PX_CROWD : STREAK_PX;
760
+ let dots = 0;
761
+ for (const g of groups) {
762
+ if (fast) {
763
+ g.seg ??= new Float32Array(g.n * 6);
764
+ if (this.#jump) {
765
+ g.sats.pin(ms);
766
+ g.cursor = 0;
767
+ }
768
+ else {
769
+ const slice = Math.max(1, Math.ceil(g.n * (dtReal / 1000)));
770
+ g.sats.pin(ms, g.cursor, slice);
771
+ g.cursor = g.cursor + slice >= g.n ? 0 : g.cursor + slice;
772
+ }
773
+ g.sats.arc(ms, this.#speed * 1000 * STREAK_SECONDS, g.buf, g.seg, (streakPx / k) * RAD);
774
+ }
775
+ else
776
+ g.sats.at(ms, g.buf);
777
+ // the chosen satellite is always where SGP4 puts it, to the frame
778
+ if (chosen && chosen.g === g && g.sats.exact(chosen.i, ms, this.#exact)) {
779
+ g.buf[chosen.i * 3] = this.#exact[0];
780
+ g.buf[chosen.i * 3 + 1] = this.#exact[1];
781
+ g.buf[chosen.i * 3 + 2] = this.#exact[2];
782
+ }
783
+ const { buf, lon, lat, alt, sx, sy, on, sats, seg } = g;
784
+ const planeOf = g.clusters.planeOf;
785
+ const dimmed = sats.dimmed;
786
+ for (let i = 0; i < g.n; i += 1) {
787
+ on[i] = 0;
788
+ if (!sats.visible(i))
789
+ continue;
790
+ if (planeAt >= 0 && planeOf[i] !== planeAt)
791
+ continue;
792
+ const x = buf[i * 3];
793
+ const y = buf[i * 3 + 1];
794
+ const z = buf[i * 3 + 2];
795
+ const rr = Math.sqrt(x * x + y * y + z * z);
796
+ const longitude = wrapLongitude((Math.atan2(-z, x) / RAD) - gmst);
797
+ const latitude = (Math.atan(Math.tan(Math.asin(y / rr)) / FLATTENED)) / RAD;
798
+ lon[i] = longitude;
799
+ lat[i] = latitude;
800
+ alt[i] = (rr - 1) * 6371;
801
+ const px = v.width / 2 + wrapLongitude(longitude - v.centerLon) * k;
802
+ const py = v.height / 2 - (latitude - v.centerLat) * k;
803
+ if (py < -pad || py > v.height + pad || px < -pad || px > v.width + pad) {
804
+ // the world is wider than the box when the box is wide, and the dot may be in view at the other copy of the world
805
+ if (px < -pad && px + wrapPx <= v.width + pad && py >= -pad && py <= v.height + pad) {
806
+ sx[i] = px + wrapPx;
807
+ }
808
+ else if (px > v.width + pad && px - wrapPx >= -pad && py >= -pad && py <= v.height + pad) {
809
+ sx[i] = px - wrapPx;
810
+ }
811
+ else
812
+ continue;
813
+ }
814
+ else
815
+ sx[i] = px;
816
+ sy[i] = py;
817
+ on[i] = 1;
818
+ dots += 1;
819
+ const colour = byPlane ? (planeOf[i] >= 0 ? PLANE_COLOURS[planeOf[i] % PLANE_COLOURS.length] : SPARE_COLOUR) : g.colour;
820
+ const key = dimmed[i] > 0 ? `${colour}~` : colour;
821
+ let list = buckets.get(key);
822
+ if (!list)
823
+ buckets.set(key, (list = []));
824
+ list.push(sx[i], py);
825
+ // a dot on the map's edge is drawn again at the other side, so it wraps cleanly
826
+ if (sx[i] < pad && sx[i] + wrapPx < v.width + pad)
827
+ list.push(sx[i] + wrapPx, py);
828
+ else if (sx[i] > v.width - pad && sx[i] - wrapPx > -pad)
829
+ list.push(sx[i] - wrapPx, py);
830
+ if (streak && seg) {
831
+ // where it was a moment ago, on the same turn of the map as the dot
832
+ const j = i * 6;
833
+ const bx = seg[j];
834
+ const by = seg[j + 1];
835
+ const bz = seg[j + 2];
836
+ const br = Math.sqrt(bx * bx + by * by + bz * bz);
837
+ if (br > 0) {
838
+ const lon0 = (Math.atan2(-bz, bx) / RAD) - gmst;
839
+ const lat0 = Math.atan(Math.tan(Math.asin(by / br)) / FLATTENED) / RAD;
840
+ const x0 = sx[i] + wrapLongitude(lon0 - longitude) * k;
841
+ const y0 = v.height / 2 - (lat0 - v.centerLat) * k;
842
+ if (Math.abs(x0 - sx[i]) < streakPx * 2 && Math.abs(y0 - py) < streakPx * 2) {
843
+ let trail = streaks.get(colour);
844
+ if (!trail)
845
+ streaks.set(colour, (trail = []));
846
+ trail.push(x0, y0, sx[i], py);
847
+ }
848
+ }
849
+ }
850
+ }
851
+ }
852
+ // the coverage circles and the track, under the dots
853
+ this.#drawOver(ctx, groups, ms);
854
+ if (streak) {
855
+ // a butt cap and a hairline for a crowd: thousands of round, wide strokes cost the rasteriser more than the whole of the rest of the draw
856
+ ctx.lineCap = "butt";
857
+ ctx.lineWidth = total > 3000 ? 1 : Math.max(1, radius * 1.4);
858
+ ctx.globalAlpha = 0.7;
859
+ for (const [colour, list] of streaks) {
860
+ if (list.length === 0)
861
+ continue;
862
+ ctx.strokeStyle = colour;
863
+ ctx.beginPath();
864
+ for (let j = 0; j < list.length; j += 4) {
865
+ ctx.moveTo(list[j], list[j + 1]);
866
+ ctx.lineTo(list[j + 2], list[j + 3]);
867
+ }
868
+ ctx.stroke();
869
+ }
870
+ ctx.globalAlpha = 1;
871
+ }
872
+ for (const [key, list] of buckets) {
873
+ if (list.length === 0)
874
+ continue;
875
+ const faint = key.endsWith("~");
876
+ ctx.fillStyle = faint ? key.slice(0, -1) : key;
877
+ ctx.globalAlpha = faint ? 0.45 : 1;
878
+ if (radius <= 1.7) {
879
+ const side = radius * 2;
880
+ for (let j = 0; j < list.length; j += 2)
881
+ ctx.fillRect(list[j] - radius, list[j + 1] - radius, side, side);
882
+ }
883
+ else {
884
+ ctx.beginPath();
885
+ for (let j = 0; j < list.length; j += 2) {
886
+ ctx.moveTo(list[j] + radius, list[j + 1]);
887
+ ctx.arc(list[j], list[j + 1], radius, 0, Math.PI * 2);
888
+ }
889
+ ctx.fill();
890
+ }
891
+ }
892
+ ctx.globalAlpha = 1;
893
+ this.#counts.draws += 1;
894
+ this.#counts.dots = dots;
895
+ this.#placeMarks();
896
+ this.#showMessage(dots, groups.length);
897
+ this.#jump = false;
898
+ this.#lastDraw = started;
899
+ const took = performance.now() - started;
900
+ this.#totalMs += took;
901
+ this.#counts.lastMs = took;
902
+ if (took > this.#counts.maxMs)
903
+ this.#counts.maxMs = took;
904
+ this.#announceView();
905
+ this.#announceTime();
906
+ this.#schedule();
907
+ }
908
+ /** The footprints and the ground track, drawn before the dots so the dots lie on them. */
909
+ #drawOver(ctx, groups, ms) {
910
+ const wantFootprint = this.#footprint;
911
+ const wantTrack = this.#track;
912
+ const chosen = this.#selected && this.#selected.g.on[this.#selected.i] === 1 ? this.#selected : null;
913
+ if (!wantFootprint && !(wantTrack && chosen)) {
914
+ this.#showKey(false);
915
+ return;
916
+ }
917
+ const path = geoPath(this.#projection(), ctx);
918
+ if (wantFootprint) {
919
+ const elevation = finite(this.getAttribute("footprint-elevation"), BEAM_ELEVATION);
920
+ const one = (g, i) => {
921
+ const angle = footprintAngle(g.alt[i], elevation) / RAD;
922
+ if (!(angle > 0))
923
+ return;
924
+ ctx.beginPath();
925
+ path(geoCircle().center([g.lon[i], g.lat[i]]).radius(angle).precision(3)());
926
+ ctx.fillStyle = "rgba(255,255,255,0.07)";
927
+ ctx.fill();
928
+ ctx.strokeStyle = "rgba(255,255,255,0.45)";
929
+ ctx.lineWidth = 1;
930
+ ctx.stroke();
931
+ };
932
+ if (chosen)
933
+ one(chosen.g, chosen.i);
934
+ else {
935
+ let shown = 0;
936
+ for (const g of groups)
937
+ shown += g.on.reduce((sum, flagged) => sum + flagged, 0);
938
+ if (shown <= FOOTPRINT_MAX)
939
+ for (const g of groups)
940
+ for (let i = 0; i < g.n; i += 1)
941
+ if (g.on[i] === 1)
942
+ one(g, i);
943
+ }
944
+ }
945
+ if (wantTrack && chosen) {
946
+ const lines = this.#trackOf(chosen, ms);
947
+ if (lines) {
948
+ const colours = this.#trackColours();
949
+ // each stretch is drawn over a dark edge, so it reads on a dark sea and on a light one; the part behind the satellite is dashed, the part ahead solid
950
+ const stroke = (runs, dash, sun) => {
951
+ ctx.setLineDash(dash);
952
+ for (const run of runs) {
953
+ if (run.sunlit !== sun || run.points.length < 2)
954
+ continue;
955
+ ctx.beginPath();
956
+ path({ type: "LineString", coordinates: run.points });
957
+ ctx.stroke();
958
+ }
959
+ };
960
+ for (const pass of [0, 1]) {
961
+ ctx.lineCap = "butt";
962
+ for (const [runs, dash] of [[lines.past, [4, 4]], [lines.future, []]]) {
963
+ for (const sun of [true, false]) {
964
+ ctx.lineWidth = pass === 0 ? 4 : 2;
965
+ ctx.strokeStyle = pass === 0 ? "rgba(4,8,18,0.55)" : sun ? colours.sun : colours.shadow;
966
+ stroke(runs, [...dash], sun);
967
+ }
968
+ }
969
+ }
970
+ ctx.setLineDash([]);
971
+ }
972
+ }
973
+ this.#showKey(wantTrack && chosen !== null);
974
+ }
975
+ /** The colours of the ground track: amber in sunlight, blue in the Earth's shadow, or the page's own (`--chikyu-flat-track-sun`, `--chikyu-flat-track-shadow`). */
976
+ #trackColours() {
977
+ const style = getComputedStyle(this);
978
+ return { sun: style.getPropertyValue("--chikyu-flat-track-sun").trim() || TRACK_SUNLIT, shadow: style.getPropertyValue("--chikyu-flat-track-shadow").trim() || TRACK_SHADOW };
979
+ }
980
+ /** The key to the track's two colours, shown while the track is. It changes only when the track appears or goes, or the language does. */
981
+ #showKey(on) {
982
+ const key = this.#key;
983
+ if (!key)
984
+ return;
985
+ if (key.hidden === !on && (!on || key.lang === this.language))
986
+ return;
987
+ key.hidden = !on;
988
+ if (!on)
989
+ return;
990
+ const lang = this.language;
991
+ const colours = this.#trackColours();
992
+ key.lang = lang;
993
+ key.setAttribute("aria-label", say(lang, "trackKey"));
994
+ key.replaceChildren(...[["trackSunlit", colours.sun], ["trackShadow", colours.shadow]].map(([word, colour]) => {
995
+ const item = key.ownerDocument.createElement("span");
996
+ const line = key.ownerDocument.createElement("i");
997
+ line.style.setProperty("--k", colour);
998
+ item.append(line, say(lang, word));
999
+ return item;
1000
+ }));
1001
+ }
1002
+ /** The ground track of the chosen satellite for one orbit, half behind it and half ahead, worked out again when the clock has moved a fortieth of an orbit. */
1003
+ #trackOf(ref, ms) {
1004
+ const set = ref.g.sats.sets[ref.i];
1005
+ if (!set)
1006
+ return null;
1007
+ const shape = orbitShape(set.MEAN_MOTION, set.ECCENTRICITY);
1008
+ if (!shape)
1009
+ return null;
1010
+ const period = shape.periodMinutes * 60_000;
1011
+ // worked out again when the clock has moved a fortieth of an orbit, and, at a fast clock, once a (real) second: it would flicker if it were drawn for every frame
1012
+ const every = Math.max(period / 40, this.#fast() ? Math.abs(this.#speed) * 1000 : 0);
1013
+ const key = `${set.NORAD_CAT_ID}:${Math.round(ms / every)}`;
1014
+ if (key !== this.#trackKey || !this.#trackLines) {
1015
+ this.#trackKey = key;
1016
+ const step = Math.max(5, period / 1000 / 160);
1017
+ const points = groundTrack(set, ms - period / 2, ms + period / 2, step);
1018
+ this.#trackLines = { past: trackRuns(points.filter((p) => p.ms <= ms)), future: trackRuns(points.filter((p) => p.ms >= ms)) };
1019
+ }
1020
+ return this.#trackLines;
1021
+ }
1022
+ #announceView() {
1023
+ const v = this.#view;
1024
+ const key = `${v.centerLon.toFixed(2)},${v.centerLat.toFixed(2)},${v.zoom.toFixed(2)}`;
1025
+ if (key === this.#viewSent)
1026
+ return;
1027
+ const first = this.#viewSent === "";
1028
+ this.#viewSent = key;
1029
+ if (!first)
1030
+ this.dispatchEvent(new CustomEvent("chikyu-flat-view", { detail: { center: v.centerLon, zoom: v.zoom }, bubbles: true, composed: true }));
1031
+ }
1032
+ /** The rings round the chosen and the hovered satellite, and the name beside the one pointed at: a few DOM nodes moved, so they never ask for a draw of the dots. */
1033
+ #placeMarks() {
1034
+ const mark = (ring, ref) => {
1035
+ if (!ring)
1036
+ return null;
1037
+ if (!ref || ref.g.on[ref.i] !== 1) {
1038
+ ring.hidden = true;
1039
+ return null;
1040
+ }
1041
+ const x = ref.g.sx[ref.i];
1042
+ const y = ref.g.sy[ref.i];
1043
+ ring.hidden = false;
1044
+ ring.style.transform = `translate(${x.toFixed(1)}px,${y.toFixed(1)}px)`;
1045
+ return { x, y };
1046
+ };
1047
+ const picked = this.#cursor ?? this.#selected;
1048
+ const at = mark(this.#selRing, picked);
1049
+ const over = mark(this.#hovRing, this.#hover && !sameRef(this.#hover, picked) ? this.#hover : null);
1050
+ const tip = this.#tip;
1051
+ if (!tip)
1052
+ return;
1053
+ const ref = this.#hover ?? picked;
1054
+ const where = this.#hover ? (over ?? at) : at;
1055
+ if (!ref || !where || ref.g.on[ref.i] !== 1) {
1056
+ tip.hidden = true;
1057
+ return;
1058
+ }
1059
+ tip.hidden = false;
1060
+ tip.textContent = this.#describe(ref);
1061
+ const wide = tip.offsetWidth;
1062
+ const left = where.x + 14 + wide > this.#view.width ? Math.max(0, where.x - 14 - wide) : where.x + 14;
1063
+ const top = Math.max(0, Math.min(this.#view.height - tip.offsetHeight, where.y - 10));
1064
+ tip.style.transform = `translate(${left.toFixed(1)}px,${top.toFixed(1)}px)`;
1065
+ }
1066
+ #nameOf(ref) {
1067
+ const set = ref.g.sats.sets[ref.i];
1068
+ return SHORT_NAMES[set.NORAD_CAT_ID]?.[this.language] ?? set.OBJECT_NAME;
1069
+ }
1070
+ #planeOfRef(ref) {
1071
+ const p = ref.g.clusters.planeOf[ref.i] ?? -1;
1072
+ return p >= 0 ? (ref.g.clusters.planes[p]?.id ?? null) : null;
1073
+ }
1074
+ #describe(ref) {
1075
+ const lang = this.language;
1076
+ const plane = this.#planeOfRef(ref);
1077
+ return say(lang, "announce", { name: this.#nameOf(ref), group: lang === "ja" ? ref.g.labelJa : ref.g.label, altitude: Math.round(ref.g.alt[ref.i]).toLocaleString(lang) }) + (plane && ref.g.clusters.clustered && this.#byPlane([ref.g]) ? say(lang, "announcePlane", { id: plane }) : "");
1078
+ }
1079
+ #showMessage(dots = -1, shown = this.#shownGroups().length) {
1080
+ const msg = this.#msg;
1081
+ if (!msg)
1082
+ return;
1083
+ const lang = this.language;
1084
+ if (this.#problem)
1085
+ msg.textContent = say(lang, "unreadable", { why: this.#problem });
1086
+ else if (this.#groups.size === 0)
1087
+ msg.textContent = say(lang, this.#waiting || this.hasAttribute("elements-src") ? "waiting" : "nothing");
1088
+ else
1089
+ msg.textContent = dots === 0 && shown > 0 ? say(lang, "nothing") : "";
1090
+ }
1091
+ // --- the controls ----------------------------------------------------------------------------------------------------------------------------
1092
+ #build(root) {
1093
+ const d = root.ownerDocument;
1094
+ const bar = Object.assign(d.createElement("div"), { className: "bar" });
1095
+ bar.addEventListener("click", this.#onBar);
1096
+ const stage = Object.assign(d.createElement("div"), { className: "stage" });
1097
+ const map = Object.assign(d.createElement("canvas"), { className: "map" });
1098
+ map.setAttribute("aria-hidden", "true");
1099
+ const dots = Object.assign(d.createElement("canvas"), { className: "dots", tabIndex: 0 });
1100
+ dots.setAttribute("role", "application");
1101
+ const selRing = Object.assign(d.createElement("div"), { className: "ring sel", hidden: true });
1102
+ const hovRing = Object.assign(d.createElement("div"), { className: "ring hov", hidden: true });
1103
+ const tip = Object.assign(d.createElement("div"), { className: "tip", hidden: true });
1104
+ tip.setAttribute("aria-hidden", "true");
1105
+ const msg = Object.assign(d.createElement("p"), { className: "msg" });
1106
+ msg.setAttribute("role", "status");
1107
+ const key = Object.assign(d.createElement("p"), { className: "key", hidden: true });
1108
+ key.setAttribute("role", "group");
1109
+ const live = Object.assign(d.createElement("p"), { className: "sr", id: "live" });
1110
+ live.setAttribute("role", "status");
1111
+ live.setAttribute("aria-live", "polite");
1112
+ const help = Object.assign(d.createElement("p"), { className: "sr", id: "help" });
1113
+ dots.setAttribute("aria-describedby", "help live");
1114
+ stage.append(map, dots, selRing, hovRing, tip, key, msg);
1115
+ this.#key = key;
1116
+ root.append(bar, stage, live, help);
1117
+ this.#bar = bar;
1118
+ this.#stage = stage;
1119
+ this.#mapCanvas = map;
1120
+ this.#dotCanvas = dots;
1121
+ this.#selRing = selRing;
1122
+ this.#hovRing = hovRing;
1123
+ this.#tip = tip;
1124
+ this.#msg = msg;
1125
+ this.#live = live;
1126
+ dots.addEventListener("pointerdown", this.#onDown);
1127
+ dots.addEventListener("pointermove", this.#onMove);
1128
+ dots.addEventListener("pointerup", this.#onUp);
1129
+ dots.addEventListener("pointercancel", this.#onCancel);
1130
+ dots.addEventListener("pointerleave", this.#onLeave);
1131
+ dots.addEventListener("wheel", this.#onWheel, { passive: false });
1132
+ dots.addEventListener("keydown", this.#onKey);
1133
+ dots.addEventListener("blur", () => {
1134
+ if (this.#cursor) {
1135
+ this.#cursor = null;
1136
+ this.#placeMarks();
1137
+ }
1138
+ });
1139
+ }
1140
+ /** Which controls the `controls` attribute asks for. */
1141
+ #wants() {
1142
+ const raw = (this.getAttribute("controls") ?? "").trim().toLowerCase();
1143
+ if (raw === "none" || raw === "off")
1144
+ return new Set();
1145
+ const all = ["centre", "zoom", "footprint", "track", "chips"];
1146
+ if (raw === "" || raw === "all")
1147
+ return new Set(all);
1148
+ return new Set(raw.split(/[\s,]+/).map((one) => (one === "center" ? "centre" : one)));
1149
+ }
1150
+ /** The buttons and the filter chips, made again when the words, the groups, the planes or the home change. */
1151
+ #buildBar() {
1152
+ const bar = this.#bar;
1153
+ const dots = this.#dotCanvas;
1154
+ if (!bar || !dots)
1155
+ return;
1156
+ const lang = this.language;
1157
+ const wants = this.#wants();
1158
+ dots.setAttribute("aria-label", say(lang, "map"));
1159
+ this.shadowRoot.querySelector("#help").textContent = say(lang, "help");
1160
+ bar.setAttribute("role", "toolbar");
1161
+ bar.setAttribute("aria-label", say(lang, "controls"));
1162
+ const button = (act, label, extra = "") => `<button type="button" data-act="${act}"${extra}>${escape(label)}</button>`;
1163
+ const rows = [];
1164
+ const first = [];
1165
+ if (wants.has("centre")) {
1166
+ first.push(button("greenwich", say(lang, "greenwich"), ` aria-label="${escape(say(lang, "centreGreenwich"))}" aria-pressed="false"`));
1167
+ if (Number.isFinite(finite(this.getAttribute("home-lon"), Number.NaN)))
1168
+ first.push(button("home", say(lang, "myPlace"), ` aria-label="${escape(say(lang, "centreHome"))}" aria-pressed="false"`));
1169
+ }
1170
+ if (wants.has("zoom"))
1171
+ first.push(`<span class="gap"></span>`, button("zoomout", "−", ` aria-label="${escape(say(lang, "zoomOut"))}"`), button("zoomin", "+", ` aria-label="${escape(say(lang, "zoomIn"))}"`));
1172
+ else
1173
+ first.push(`<span class="gap"></span>`);
1174
+ if (wants.has("footprint"))
1175
+ first.push(button("footprint", say(lang, "footprint"), ` aria-pressed="false"`));
1176
+ if (wants.has("track"))
1177
+ first.push(button("track", say(lang, "groundTrack"), ` aria-pressed="false"`));
1178
+ if (first.length > 1)
1179
+ rows.push(`<div class="row">${first.join("")}</div>`);
1180
+ if (wants.has("chips")) {
1181
+ const groups = this.#shownGroupsForChips();
1182
+ const one = this.#shownGroups();
1183
+ if (groups === "planes" && one.length === 1) {
1184
+ const g = one[0];
1185
+ const chips = [button("plane", say(lang, "all"), ` class="chip" data-plane="" aria-pressed="false"`)];
1186
+ for (const plane of g.clusters.planes)
1187
+ chips.push(`<button type="button" class="chip" data-act="plane" data-plane="${plane.id}" data-i="${plane.index}" aria-pressed="false" aria-label="${escape(say(lang, "planeChip", { id: plane.id, count: plane.count }))}"><span class="swatch"></span>${escape(plane.id)} <span class="n">${plane.count}</span></button>`);
1188
+ rows.push(`<div class="row chips" role="group" aria-label="${escape(say(lang, "planesFilter"))}">${chips.join("")}</div>`);
1189
+ }
1190
+ else if (groups === "groups") {
1191
+ const chips = [`<button type="button" class="chip" data-act="group" data-group="*" aria-pressed="false">${escape(say(lang, "all"))}</button>`];
1192
+ for (const g of this.#groups.values())
1193
+ chips.push(`<button type="button" class="chip" data-act="group" data-group="${escape(g.id)}" aria-pressed="false"><span class="swatch"></span>${escape(lang === "ja" ? g.labelJa : g.label)} <span class="n">${g.n.toLocaleString(lang)}</span></button>`);
1194
+ rows.push(`<div class="row chips" role="group" aria-label="${escape(say(lang, "groupsFilter"))}">${chips.join("")}</div>`);
1195
+ }
1196
+ }
1197
+ bar.innerHTML = rows.join("");
1198
+ // colours go on through the CSS object model: an inline style attribute in the markup would be refused by a strict Content-Security-Policy
1199
+ bar.querySelectorAll("[data-group] .swatch").forEach((swatch) => {
1200
+ const id = swatch.parentElement.dataset["group"];
1201
+ swatch.style.setProperty("--c", this.#groups.get(id)?.colour ?? SPARE_COLOUR);
1202
+ });
1203
+ bar.querySelectorAll("[data-i] .swatch").forEach((swatch) => {
1204
+ const i = Number(swatch.parentElement.dataset["i"]);
1205
+ swatch.style.setProperty("--c", PLANE_COLOURS[i % PLANE_COLOURS.length]);
1206
+ });
1207
+ this.#sync();
1208
+ }
1209
+ /** Which chips to offer: planes when one group with planes is on show and the map is coloured by plane; groups when there are two or more loaded. */
1210
+ #shownGroupsForChips() {
1211
+ const shown = this.#shownGroups();
1212
+ if (this.#byPlane(shown) && shown.length === 1 && shown[0].clusters.clustered)
1213
+ return "planes";
1214
+ if (this.#groups.size >= 2)
1215
+ return "groups";
1216
+ return "none";
1217
+ }
1218
+ /** Bring the pressed states of the buttons and chips up to date without making them again (a reader may be using one). */
1219
+ #sync() {
1220
+ const bar = this.#bar;
1221
+ if (!bar)
1222
+ return;
1223
+ const set = (selector, on) => bar.querySelectorAll(selector).forEach((el) => el.setAttribute("aria-pressed", String(on)));
1224
+ const home = this.#home() ?? { lon: finite(this.getAttribute("home-lon"), Number.NaN), lat: 0 };
1225
+ set('[data-act="greenwich"]', Math.abs(wrapLongitude(this.#view.centerLon)) < 0.5);
1226
+ set('[data-act="home"]', Number.isFinite(home.lon) && Math.abs(wrapLongitude(this.#view.centerLon - home.lon)) < 0.5);
1227
+ set('[data-act="footprint"]', this.#footprint);
1228
+ set('[data-act="track"]', this.#track);
1229
+ const shown = this.#shownGroups();
1230
+ bar.querySelectorAll('[data-act="group"]').forEach((chip) => {
1231
+ const id = chip.dataset["group"];
1232
+ chip.setAttribute("aria-pressed", String(id === "*" ? this.#shown === null : shown.some((g) => g.id === id)));
1233
+ });
1234
+ bar.querySelectorAll('[data-act="plane"]').forEach((chip) => chip.setAttribute("aria-pressed", String((chip.dataset["plane"] ?? "") === this.#plane)));
1235
+ bar.querySelector('[data-act="zoomin"]')?.toggleAttribute("disabled", this.#view.zoom >= MAX_ZOOM);
1236
+ bar.querySelector('[data-act="zoomout"]')?.toggleAttribute("disabled", this.#view.zoom <= 1);
1237
+ if (this.#dotCanvas)
1238
+ this.#dotCanvas.toggleAttribute("data-zoomed", this.#view.zoom > 1);
1239
+ }
1240
+ #afterFilter() {
1241
+ this.#buildBar();
1242
+ this.#request();
1243
+ this.#schedule();
1244
+ this.dispatchEvent(new CustomEvent("chikyu-flat-filter", { detail: { groups: this.visibleGroups, plane: this.#plane }, bubbles: true, composed: true }));
1245
+ }
1246
+ #onBar = (event) => {
1247
+ const target = event.target?.closest("button[data-act]");
1248
+ if (!target || target.hasAttribute("disabled"))
1249
+ return;
1250
+ const act = target.dataset["act"];
1251
+ const v = this.#view;
1252
+ if (act === "greenwich")
1253
+ this.#setView({ ...v, centerLon: 0 });
1254
+ else if (act === "home") {
1255
+ const home = this.#home();
1256
+ const lon = finite(this.getAttribute("home-lon"), 0);
1257
+ this.#setView({ ...v, centerLon: lon, centerLat: v.zoom > 1 && home ? home.lat : v.centerLat });
1258
+ }
1259
+ else if (act === "zoomin")
1260
+ this.#setView(zoomAbout(v, 1.6));
1261
+ else if (act === "zoomout")
1262
+ this.#setView(zoomAbout(v, 1 / 1.6));
1263
+ else if (act === "footprint") {
1264
+ this.#footprint = !this.#footprint;
1265
+ this.#sync();
1266
+ this.#request();
1267
+ }
1268
+ else if (act === "track") {
1269
+ this.#track = !this.#track;
1270
+ this.#trackKey = "";
1271
+ this.#sync();
1272
+ this.#request();
1273
+ }
1274
+ else if (act === "group") {
1275
+ const id = target.dataset["group"];
1276
+ if (id === "*")
1277
+ this.#shown = null;
1278
+ else {
1279
+ const now = new Set(this.#shownGroups().map((g) => g.id));
1280
+ if (now.has(id))
1281
+ now.delete(id);
1282
+ else
1283
+ now.add(id);
1284
+ const usual = [...this.#groups.keys()].filter((one) => !this.#off.has(one));
1285
+ this.#shown = now.size === usual.length && usual.every((one) => now.has(one)) ? null : now;
1286
+ }
1287
+ this.#plane = "";
1288
+ this.#afterFilter();
1289
+ }
1290
+ else if (act === "plane") {
1291
+ this.#plane = target.dataset["plane"] ?? "";
1292
+ this.#afterFilter();
1293
+ }
1294
+ };
1295
+ #setView(view) {
1296
+ this.#view = clampView(view);
1297
+ this.#mapKey = "";
1298
+ this.#sync();
1299
+ this.#request();
1300
+ }
1301
+ // --- the pointer and the keyboard ------------------------------------------------------------------------------------------------------------
1302
+ #local(event) {
1303
+ const box = this.#dotCanvas.getBoundingClientRect();
1304
+ return { x: event.clientX - box.left, y: event.clientY - box.top };
1305
+ }
1306
+ /** The satellite drawn nearest to a point, within `reach` pixels. */
1307
+ #hit(x, y, reach) {
1308
+ let best = null;
1309
+ let gap = reach * reach;
1310
+ for (const g of this.#shownGroups()) {
1311
+ const { sx, sy, on } = g;
1312
+ for (let i = 0; i < g.n; i += 1) {
1313
+ if (on[i] !== 1)
1314
+ continue;
1315
+ const dx = sx[i] - x;
1316
+ const dy = sy[i] - y;
1317
+ const d = dx * dx + dy * dy;
1318
+ if (d <= gap) {
1319
+ gap = d;
1320
+ best = { g, i };
1321
+ }
1322
+ }
1323
+ }
1324
+ return best;
1325
+ }
1326
+ #pick(ref, via) {
1327
+ const state = ref ? this.#stateOf(ref) : null;
1328
+ const detail = ref
1329
+ ? { id: ref.g.sats.sets[ref.i].NORAD_CAT_ID, index: ref.i, group: ref.g.id, name: this.#nameOf(ref), plane: this.#planeOfRef(ref), altitudeKm: ref.g.alt[ref.i], sunlit: state?.sunlit ?? null, bearingDeg: state?.bearingDeg ?? null, ascending: state?.ascending ?? null, via }
1330
+ : { id: null, index: -1, group: null, name: null, plane: null, altitudeKm: null, sunlit: null, bearingDeg: null, ascending: null, via };
1331
+ this.dispatchEvent(new CustomEvent("chikyu-flat-pick", { detail, bubbles: true, composed: true }));
1332
+ }
1333
+ #choose(ref, via) {
1334
+ const same = sameRef(ref, this.#selected);
1335
+ if (ref === null && this.#selected === null)
1336
+ return;
1337
+ if (!same) {
1338
+ this.#selected = ref;
1339
+ this.#trackKey = "";
1340
+ if (this.#footprint || this.#track)
1341
+ this.#request();
1342
+ }
1343
+ this.#sync();
1344
+ this.#placeMarks();
1345
+ if (ref) {
1346
+ this.#announceLive(ref);
1347
+ this.#pick(ref, via);
1348
+ }
1349
+ else if (!same)
1350
+ this.#pick(null, via);
1351
+ }
1352
+ #announceLive(ref) {
1353
+ if (!this.#live)
1354
+ return;
1355
+ const state = this.#stateOf(ref);
1356
+ this.#live.textContent = this.#describe(ref) + (state ? say(this.language, state.sunlit ? "sunlitNow" : "shadowNow") : "");
1357
+ }
1358
+ /** Where one satellite is over the ground, which way it goes and whether the Sun lights it, at the moment shown (SGP4 placed exactly, one call); null when it cannot be placed then. */
1359
+ #stateOf(ref) {
1360
+ const out = new Float64Array(6);
1361
+ if (!ref.g.sats.exact(ref.i, this.time, out))
1362
+ return null;
1363
+ return trackStateOfScene([out[0], out[1], out[2]], [out[3], out[4], out[5]], this.time);
1364
+ }
1365
+ /**
1366
+ * Where a loaded satellite is over the ground at the moment shown, which way its ground track runs and whether the Sun lights it: `{ lat, lon, heightKm, bearingDeg, ascending, sunlit }` (see `GroundTrackState`), placed exactly by SGP4. Null when the number names no loaded satellite
1367
+ * or it cannot be placed at that moment. It is the same state that `chikyu-flat-pick` carries (`sunlit`, `bearingDeg`, `ascending`).
1368
+ *
1369
+ * @param id - The NORAD catalogue number.
1370
+ * @returns The state, or null.
1371
+ */
1372
+ stateOf(id) {
1373
+ const ref = this.#index.get(id);
1374
+ return ref ? this.#stateOf(ref) : null;
1375
+ }
1376
+ /** The state (`stateOf`) of the chosen satellite, or null when none is chosen. */
1377
+ get selectedState() {
1378
+ return this.#selected ? this.#stateOf(this.#selected) : null;
1379
+ }
1380
+ #onDown = (event) => {
1381
+ if (event.pointerType === "mouse" && event.button !== 0)
1382
+ return;
1383
+ const at = this.#local(event);
1384
+ this.#pointers.set(event.pointerId, at);
1385
+ try {
1386
+ this.#dotCanvas.setPointerCapture(event.pointerId);
1387
+ }
1388
+ catch {
1389
+ // a pointer that is already gone
1390
+ }
1391
+ const pinch = this.#pointers.size === 2 ? this.#spread() : 0;
1392
+ this.#drag = { x: at.x, y: at.y, moved: this.#pointers.size === 2, pinch };
1393
+ this.#dotCanvas.style.cursor = "grabbing";
1394
+ };
1395
+ #spread() {
1396
+ const [a, b] = [...this.#pointers.values()];
1397
+ return a && b ? Math.hypot(a.x - b.x, a.y - b.y) : 0;
1398
+ }
1399
+ #onMove = (event) => {
1400
+ const at = this.#local(event);
1401
+ if (!this.#pointers.has(event.pointerId)) {
1402
+ // a pointer going over the map with no button down: the one under it is named
1403
+ if (event.pointerType === "mouse")
1404
+ this.#hoverAt(at.x, at.y);
1405
+ return;
1406
+ }
1407
+ const before = this.#pointers.get(event.pointerId);
1408
+ this.#pointers.set(event.pointerId, at);
1409
+ const drag = this.#drag;
1410
+ if (!drag)
1411
+ return;
1412
+ if (this.#pointers.size >= 2) {
1413
+ const spread = this.#spread();
1414
+ const [a, b] = [...this.#pointers.values()];
1415
+ if (drag.pinch > 0 && spread > 0 && a && b) {
1416
+ const factor = spread / drag.pinch;
1417
+ this.#view = zoomAbout(this.#view, factor, (a.x + b.x) / 2, (a.y + b.y) / 2);
1418
+ drag.pinch = spread;
1419
+ drag.moved = true;
1420
+ this.#mapKey = "";
1421
+ this.#sync();
1422
+ this.#request();
1423
+ }
1424
+ return;
1425
+ }
1426
+ if (!drag.moved && Math.hypot(at.x - drag.x, at.y - drag.y) < TAP_SLOP)
1427
+ return;
1428
+ drag.moved = true;
1429
+ const k = pixelsPerDegree(this.#view);
1430
+ this.#view = clampView({ ...this.#view, centerLon: this.#view.centerLon - (at.x - before.x) / k, centerLat: this.#view.centerLat + (at.y - before.y) / k });
1431
+ this.#hover = null;
1432
+ this.#sync();
1433
+ this.#request();
1434
+ };
1435
+ #onUp = (event) => {
1436
+ const at = this.#local(event);
1437
+ const drag = this.#drag;
1438
+ this.#pointers.delete(event.pointerId);
1439
+ try {
1440
+ this.#dotCanvas.releasePointerCapture(event.pointerId);
1441
+ }
1442
+ catch {
1443
+ // already released
1444
+ }
1445
+ if (this.#pointers.size === 0) {
1446
+ this.#drag = null;
1447
+ this.#dotCanvas.style.cursor = "";
1448
+ if (drag && !drag.moved) {
1449
+ // a tap: a finger needs more room than a mouse
1450
+ const hit = this.#hit(at.x, at.y, event.pointerType === "touch" ? 22 : 9);
1451
+ if (event.pointerType !== "mouse")
1452
+ this.#hover = null;
1453
+ this.#choose(hit, "tap");
1454
+ }
1455
+ }
1456
+ else if (drag)
1457
+ drag.pinch = this.#spread();
1458
+ };
1459
+ #onCancel = (event) => {
1460
+ this.#pointers.delete(event.pointerId);
1461
+ if (this.#pointers.size === 0) {
1462
+ this.#drag = null;
1463
+ this.#dotCanvas.style.cursor = "";
1464
+ }
1465
+ };
1466
+ #onLeave = (event) => {
1467
+ if (event.pointerType !== "mouse" || this.#hover === null)
1468
+ return;
1469
+ this.#hover = null;
1470
+ this.#placeMarks();
1471
+ };
1472
+ #hoverAt(x, y) {
1473
+ const hit = this.#hit(x, y, 8);
1474
+ if (sameRef(hit, this.#hover))
1475
+ return;
1476
+ this.#hover = hit;
1477
+ this.#placeMarks();
1478
+ if (hit)
1479
+ this.#pick(hit, "hover");
1480
+ }
1481
+ #onWheel = (event) => {
1482
+ // a plain wheel scrolls the page; Control or Command with the wheel (and a trackpad's pinch, which arrives as one) zooms
1483
+ if (!event.ctrlKey && !event.metaKey)
1484
+ return;
1485
+ event.preventDefault();
1486
+ const at = this.#local(event);
1487
+ this.#setView(zoomAbout(this.#view, Math.exp(-event.deltaY * 0.01), at.x, at.y));
1488
+ };
1489
+ #onKey = (event) => {
1490
+ const key = event.key;
1491
+ if (key === "+" || key === "=") {
1492
+ event.preventDefault();
1493
+ this.#setView(zoomAbout(this.#view, 1.6));
1494
+ return;
1495
+ }
1496
+ if (key === "-" || key === "_") {
1497
+ event.preventDefault();
1498
+ this.#setView(zoomAbout(this.#view, 1 / 1.6));
1499
+ return;
1500
+ }
1501
+ if (key === "Escape") {
1502
+ if (this.#cursor || this.#selected) {
1503
+ this.#cursor = null;
1504
+ this.#choose(null, "key");
1505
+ }
1506
+ return;
1507
+ }
1508
+ if (key === "Enter" || key === " ") {
1509
+ event.preventDefault();
1510
+ const ref = this.#cursor ?? this.#selected;
1511
+ if (ref)
1512
+ this.#choose(ref, "key");
1513
+ return;
1514
+ }
1515
+ const step = key === "ArrowRight" || key === "ArrowDown" ? 1 : key === "ArrowLeft" || key === "ArrowUp" ? -1 : key === "PageDown" ? 10 : key === "PageUp" ? -10 : 0;
1516
+ if (step === 0 && key !== "Home" && key !== "End")
1517
+ return;
1518
+ event.preventDefault();
1519
+ // the satellites on show, from the left of the map to the right
1520
+ const list = [];
1521
+ for (const g of this.#shownGroups())
1522
+ for (let i = 0; i < g.n; i += 1)
1523
+ if (g.on[i] === 1)
1524
+ list.push({ g, i });
1525
+ if (list.length === 0)
1526
+ return;
1527
+ list.sort((a, b) => a.g.sx[a.i] - b.g.sx[b.i] || a.g.sy[a.i] - b.g.sy[b.i]);
1528
+ const current = this.#cursor ?? this.#selected;
1529
+ const at = current ? list.findIndex((one) => one.g === current.g && one.i === current.i) : -1;
1530
+ const next = key === "Home" ? 0 : key === "End" ? list.length - 1 : at < 0 ? (step > 0 ? 0 : list.length - 1) : Math.max(0, Math.min(list.length - 1, at + step));
1531
+ this.#cursor = list[next];
1532
+ this.#placeMarks();
1533
+ this.#announceLive(this.#cursor);
1534
+ this.#pick(this.#cursor, "key");
1535
+ };
1536
+ /** Choose a satellite from code, as a reader's tap would, without sending `chikyu-flat-pick`. A NORAD number the groups do not hold, or `null`, clears the choice. */
1537
+ pick(id) {
1538
+ this.selected = id;
1539
+ }
1540
+ }
1541
+ _a = ChikyuFlat;