@johnmorrisdotca/wakusei-planets 0.30.0 → 0.31.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.
@@ -2,16 +2,28 @@ import { carryControls } from "@johnmorrisdotca/kazoku-ui/view-controls";
2
2
  import { BODIES, MOONS_OF } from "../facts.js";
3
3
  import { createGate, frameCap } from "../gate.js";
4
4
  import { createGameClock } from "./clock.js";
5
+ import { bodyKindOf, findBody, hopFrom, hostOf, HOP_ORDER } from "./bodies.js";
6
+ import { chooseLabels } from "./labels.js";
5
7
  import { createPainter } from "../scene/painter.js";
6
8
  import { setThreeLoader, takeRenderer } from "../scene/shared.js";
7
9
  import { texturePaths, tilesBase } from "../scene/textures.js";
8
- import { AU_IN_EARTH_RADII, EARTH_RADIUS_KM, frameAt, SPACE_PLANETS } from "./frame.js";
10
+ import { AU_IN_EARTH_RADII, EARTH_RADIUS_KM, frameAt, SPACE_DWARFS, SPACE_PLANETS } from "./frame.js";
11
+ import { moonOffset } from "../scene/orient.js";
9
12
  import { moonDistance, placeBodies, radiusIn } from "./scale.js";
10
13
  import { createSpaceItem, FIT_DISTANCE, newSpaceModel, SPACE_BODIES } from "./scene.js";
11
14
  export { setThreeLoader, SPACE_BODIES };
15
+ /** The words the view says on itself for the scale in use. A page in another language gives its own with `scaleNames`. */
16
+ const SCALE_WORDS = {
17
+ en: { true: "True distances", compressed: "Distances squeezed to fit" },
18
+ ja: { true: "本当の距離", compressed: "距離を縮めて表示" },
19
+ };
20
+ /** A body whose disc is smaller than this many CSS pixels across its radius is marked with a ring as well as its name. */
21
+ const RING_BELOW_PX = 4;
12
22
  const readLight = (value) => (value === "lit" ? "lit" : "sun");
13
23
  const RAD = Math.PI / 180;
14
24
  const REAL_TIME_TICK_MS = 60_000;
25
+ /** The plain wheel in an immersive view is passed on as a pinch of this share, so a notch (100) zooms about 1.2 times, as the family's mouse wheel does with Alt. */
26
+ const WHEEL_AS_PINCH = 0.2;
15
27
  /** The least time between two `wakusei-timechange` events while time runs: a few a second at most, however fast the picture is drawn. */
16
28
  const TIME_EVENT_MS = 250;
17
29
  const readCentre = (value) => {
@@ -28,22 +40,26 @@ const readTime = (value) => {
28
40
  const ms = Date.parse(value);
29
41
  return Number.isFinite(ms) ? ms : "now";
30
42
  };
43
+ /** A body the view can put at its middle: the eleven of `SPACE_BODIES` and the moons of the planets in them. */
44
+ const canCentre = (id) => SPACE_BODIES.includes(id) || (BODIES[id].kind === "moon" && SPACE_BODIES.includes(hostOf(id) ?? ""));
31
45
  const readBody = (value) => {
32
- const id = value.toLowerCase();
33
- return SPACE_BODIES.includes(id) ? id : undefined;
46
+ const id = findBody(value);
47
+ return id !== undefined && canCentre(id) ? id : undefined;
34
48
  };
35
49
  /**
36
50
  * The zoom range of the space view when it carries its own controls. The floor, a millionth, takes the camera out past Neptune in the true scale. The ceiling is where the camera reaches the body: it is held at
37
- * 1.05 radii from the surface (`FIT_DISTANCE` over the zoom), so past a zoom of about 3.2 nothing moves; 3 is where the finest map tiles of the Earth, Mars and the Moon (16384 pixels round) run out of detail too, so it is the same ceiling for both.
51
+ * 1.05 radii from the surface (`FIT_DISTANCE` over the zoom), so past a zoom of about 3.9 nothing moves; 3.6 is where the finest map tiles of the Earth, Mars and the Moon (16384 pixels round) run out of detail too, so it is the same ceiling for both.
38
52
  */
39
- const CARRIED_LIMITS = { zoomMin: 1e-6, zoomMax: 3, tiltMax: 90 };
40
- const STYLE = `<style>:host{display:block;aspect-ratio:1/1;position:relative;overflow:hidden}#stage,#labels{position:absolute;inset:0}#labels{pointer-events:none;overflow:hidden}.sp-label{position:absolute;left:0;top:0;margin:0;padding:0;border:0;background:none;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;white-space:nowrap;text-shadow:0 0 3px #000,0 0 3px #000;will-change:transform;pointer-events:none}.sp-label:focus-visible{outline:2px solid #6cd0ff;outline-offset:2px;border-radius:4px}.sp-label::before{content:"";display:inline-block;width:5px;height:5px;margin:0 5px 1px -2px;border-radius:50%;background:#fff}.sp-label[hidden]{display:none}</style><div id="stage"></div><div id="labels"></div>`;
53
+ const CARRIED_LIMITS = { zoomMin: 1e-6, zoomMax: 3.6, tiltMax: 90 };
54
+ const STYLE = `<style>:host{display:block;aspect-ratio:1/1;position:relative;overflow:hidden}:host([immersive]){aspect-ratio:auto;width:100%;height:100%;touch-action:none!important;user-select:none;-webkit-user-select:none;-webkit-tap-highlight-color:transparent}#stage,#labels{position:absolute;inset:0}#labels{pointer-events:none;overflow:hidden}.sp-label{position:absolute;left:0;top:0;margin:0;padding:0;border:0;background:none;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;white-space:nowrap;text-shadow:0 0 3px #000,0 0 3px #000;will-change:transform;pointer-events:none}.sp-label:focus-visible{outline:2px solid #6cd0ff;outline-offset:2px;border-radius:4px}.sp-label::before{content:"";display:inline-block;width:5px;height:5px;margin:0 5px 1px -2px;border-radius:50%;background:#fff}.sp-label[hidden]{display:none}.sp-ring{position:absolute;left:0;top:0;width:16px;height:16px;margin:-8px 0 0 -8px;box-sizing:border-box;border:1.5px solid rgba(255,255,255,.85);border-radius:50%;box-shadow:0 0 3px #000;pointer-events:none;will-change:transform}.sp-ring[hidden]{display:none}.sp-scale{position:absolute;left:10px;top:8px;margin:0;padding:0;font:12px/16px system-ui,-apple-system,sans-serif;color:#fff;opacity:.9;text-shadow:0 0 3px #000,0 0 3px #000;pointer-events:none}</style><div id="stage"></div><div id="labels"></div><p class="sp-scale" part="scale" role="status"></p>`;
41
55
  /**
42
56
  * The `<wakusei-space>` custom element: the Earth, the Moon, the Sun and the planets where they are at a date and time, drawn with three.js through the shared renderer. It takes `center`
43
57
  * (`"lon,lat"`), `time` (`now` or an ISO date), `speed` (1 is real time, 0 holds, 86400 is a day a second, negative runs backwards), `scale` (`compressed` or `true`), `look` (`realistic` or `painted`),
44
58
  * `light` (`sun` or `lit`), `lang` (`en` or `ja`: the names), `labels` and `orbits` (`off` hides them), and `texture-base`, `texture-far-base`, `max-texture` and `tiles` (where the finer map tiles are, for a close zoom; `off` for none). Positions come from this package's own models. It draws
45
59
  * only when something changes, and nothing while it is out of sight.
46
60
  *
61
+ * `immersive` makes it a full-screen view: it fills the box it is in, whatever the shape (the body looked at is framed by the shorter side), the plain wheel zooms and a drag anywhere on it turns it. Without it Ctrl, Command or Alt with the wheel zooms and the plain wheel scrolls the page.
62
+ *
47
63
  * It carries the shared view controls itself: a drag turns the camera round the body, two fingers pinch, Ctrl, Command or Alt with the wheel zooms (the plain wheel scrolls the page), and the arrow keys, + and - and 0 work once it is
48
64
  * focused. `controls="none"` turns them off; `zoom-min` and `zoom-max` set the range (a millionth to 3 by default); a `<kazoku-view-controls for="...">` takes over and reads it.
49
65
  *
@@ -65,7 +81,7 @@ const STYLE = `<style>:host{display:block;aspect-ratio:1/1;position:relative;ove
65
81
  * ```
66
82
  */
67
83
  export class WakuseiSpace extends HTMLElement {
68
- static observedAttributes = ["center", "time", "speed", "scale", "labels", "orbits", "look", "light", "lang"];
84
+ static observedAttributes = ["center", "time", "speed", "scale", "labels", "orbits", "help", "look", "light", "lang"];
69
85
  #model = newSpaceModel();
70
86
  #clock = createGameClock("now", 1);
71
87
  #view;
@@ -79,6 +95,10 @@ export class WakuseiSpace extends HTMLElement {
79
95
  #pool = new Map();
80
96
  #places;
81
97
  #names = {};
98
+ #selected = null;
99
+ #scaleNames = {};
100
+ #rings = new Map();
101
+ #scaleLine;
82
102
  #hint = "choose to look at it";
83
103
  #painter;
84
104
  #focusBeforeRide = "earth";
@@ -92,9 +112,10 @@ export class WakuseiSpace extends HTMLElement {
92
112
  this.#model.centre = readCentre(this.getAttribute("center")) ?? this.#model.centre;
93
113
  this.#clock = createGameClock(readTime(this.getAttribute("time")), this.#readSpeed());
94
114
  this.#model.time = this.#clock.time;
95
- this.#model.mode = this.getAttribute("scale") === "true" ? "true" : "compressed";
115
+ this.#model.mode = this.getAttribute("scale") === "compressed" ? "compressed" : "true";
96
116
  this.#model.labels = this.getAttribute("labels") !== "off";
97
117
  this.#model.orbits = this.getAttribute("orbits") !== "off";
118
+ this.#model.help = this.hasAttribute("help") && this.getAttribute("help") !== "off";
98
119
  this.#model.look = this.getAttribute("look") === "painted" ? "painted" : "realistic";
99
120
  this.#model.light = readLight(this.getAttribute("light"));
100
121
  this.#model.stepMs = Math.max(1000, Math.abs(this.#clock.speed) * 1000);
@@ -108,7 +129,10 @@ export class WakuseiSpace extends HTMLElement {
108
129
  root.innerHTML = STYLE;
109
130
  this.#stage = root.getElementById("stage");
110
131
  this.#labelBox = root.getElementById("labels");
132
+ this.#scaleLine = root.querySelector(".sp-scale");
133
+ this.#nameScale();
111
134
  this.#pool.clear();
135
+ this.#rings.clear();
112
136
  const nav = navigator;
113
137
  this.#gate = createGate(1000 / frameCap(30, { deviceMemory: nav.deviceMemory, hardwareConcurrency: nav.hardwareConcurrency }), () => this.#view?.invalidate());
114
138
  this.#stage.addEventListener("webglcontextlost", this.#lost, true);
@@ -140,6 +164,8 @@ export class WakuseiSpace extends HTMLElement {
140
164
  });
141
165
  this.#schedule();
142
166
  this.addEventListener("pointerdown", this.#down);
167
+ // before the shared hands (which hear it after this): a plain wheel in an immersive view zooms
168
+ this.addEventListener("wheel", this.#wheel, { capture: true, passive: false });
143
169
  this.#hands = carryControls(this, { limits: CARRIED_LIMITS, onChange: (view, info) => this.setView(view, info.final) });
144
170
  this.#labelBox.addEventListener("click", this.#labelClick);
145
171
  this.#labelBox.addEventListener("focusin", this.#labelFocus);
@@ -148,6 +174,7 @@ export class WakuseiSpace extends HTMLElement {
148
174
  this.#hands?.unbind();
149
175
  this.#hands = undefined;
150
176
  this.removeEventListener("pointerdown", this.#down);
177
+ this.removeEventListener("wheel", this.#wheel, { capture: true });
151
178
  window.removeEventListener("pointerup", this.#up, true);
152
179
  clearTimeout(this.#timer);
153
180
  this.#timer = undefined;
@@ -165,18 +192,22 @@ export class WakuseiSpace extends HTMLElement {
165
192
  else if (name === "speed")
166
193
  this.speed = this.#readSpeed();
167
194
  else if (name === "scale")
168
- this.scale = value === "true" ? "true" : "compressed";
195
+ this.scale = value === "compressed" ? "compressed" : "true";
169
196
  else if (name === "labels")
170
197
  this.labels = value !== "off";
171
198
  else if (name === "orbits")
172
199
  this.orbits = value !== "off";
200
+ else if (name === "help")
201
+ this.help = value !== null && value !== "off";
173
202
  else if (name === "look")
174
203
  this.look = value === "painted" ? "painted" : "realistic";
175
204
  else if (name === "light")
176
205
  this.light = readLight(value);
177
- else if (name === "lang")
206
+ else if (name === "lang") {
178
207
  for (const [id, button] of this.#pool)
179
208
  this.#nameLabel(button, id);
209
+ this.#nameScale();
210
+ }
180
211
  }
181
212
  /** The home place the camera starts above, as longitude and latitude in degrees. */
182
213
  get centre() {
@@ -214,21 +245,30 @@ export class WakuseiSpace extends HTMLElement {
214
245
  if (this.#clock.speed === 0 && was !== 0)
215
246
  this.#announce(false);
216
247
  }
217
- /** `compressed` (the default: every direction real, the distances squeezed) or `true` (real distances and sizes). */
248
+ /** `true` (the default: real distances and sizes; a body too small to see is marked with a ring and its name) or `compressed` (every direction real, the distances squeezed). The scale in use is always named on the view. */
218
249
  get scale() {
219
250
  return this.#model.mode;
220
251
  }
221
252
  set scale(value) {
222
253
  this.#model.mode = value;
254
+ this.#nameScale();
223
255
  this.#gate?.request();
224
256
  }
257
+ /** The words naming the scale on the view, for a page in another language (`{ true: "距離はそのまま" }`). A scale left out keeps its words in the element's `lang`. */
258
+ get scaleNames() {
259
+ return { ...this.#scaleNames };
260
+ }
261
+ set scaleNames(value) {
262
+ this.#scaleNames = { ...value };
263
+ this.#nameScale();
264
+ }
225
265
  get labels() {
226
266
  return this.#model.labels;
227
267
  }
228
268
  set labels(value) {
229
269
  this.#model.labels = value;
230
270
  if (!value)
231
- for (const label of this.#pool.values())
271
+ for (const label of [...this.#pool.values(), ...this.#rings.values()])
232
272
  label.hidden = true;
233
273
  this.#gate?.request();
234
274
  }
@@ -239,6 +279,17 @@ export class WakuseiSpace extends HTMLElement {
239
279
  this.#model.orbits = value;
240
280
  this.#gate?.request();
241
281
  }
282
+ /**
283
+ * Help mode (the `help` attribute; off by default): on the body looked at, a line along its axis and a curved arrow round it showing which way it spins, by the right-hand rule about the axis it really turns about, so it is
284
+ * right for Venus and Uranus, which turn backwards, and for Uranus on its side. It is about learning, so the arrow is drawn over the body.
285
+ */
286
+ get help() {
287
+ return this.#model.help;
288
+ }
289
+ set help(value) {
290
+ this.#model.help = value;
291
+ this.#gate?.request();
292
+ }
242
293
  /** How the bodies are drawn: `realistic` (shaded from the body's real colours and features) or `painted` (public-domain surface maps). */
243
294
  get look() {
244
295
  return this.#model.look === "painted" ? "painted" : "realistic";
@@ -277,7 +328,7 @@ export class WakuseiSpace extends HTMLElement {
277
328
  }
278
329
  this.#gate?.request();
279
330
  }
280
- /** The body the camera looks at (`earth`, `sun`, `moon`, `mercury` to `neptune`, `pluto`): at zoom 1 it fills the view; the yaw and tilt turn the camera round it. */
331
+ /** The body the camera looks at: any body the view places, by name in any case (`earth`, `sun`, `moon`, `mercury` to `neptune`, `pluto`, and the moons of the planets such as `titan`). At zoom 1 it fills the view; the yaw and tilt turn the camera round it. Setting it moves the camera there at once and keeps the zoom; `goTo` glides and brings the body into view. */
281
332
  get body() {
282
333
  return this.#model.focus;
283
334
  }
@@ -285,8 +336,75 @@ export class WakuseiSpace extends HTMLElement {
285
336
  const id = readBody(name);
286
337
  if (!id)
287
338
  return;
339
+ this.#centre(id);
340
+ }
341
+ /** Move the camera to `id` (not yet drawn) and tell the page. */
342
+ #centre(id) {
343
+ const was = this.#model.focus;
344
+ this.#model.focus = id;
345
+ this.#gate?.request();
346
+ if (was !== id)
347
+ this.#announceHop();
348
+ }
349
+ /** What the hopper can do from where it is: the body at the middle, and the bodies the previous and next hop lead to. */
350
+ get hopper() {
351
+ const here = this.#model.focus;
352
+ return { current: this.bodyInfo(here), previous: this.bodyInfo(hopFrom(here, -1, canCentre)), next: this.bodyInfo(hopFrom(here, 1, canCentre)) };
353
+ }
354
+ /**
355
+ * Go to a body: it becomes the middle of the view and the zoom brings it whole into view (`zoom`, 1 by default; a planet's `-moons` preset for its system), gliding there from where the camera is unless `smooth` is
356
+ * false or the reader asked for reduced motion. `wakusei-hop` tells the page where it went and where the next and previous hops lead. A name in any case, in English or Japanese, works.
357
+ *
358
+ * @param target - A body's name (`"saturn"`, `"Saturn"`, `"土星"`).
359
+ * @param options - `smooth` (true by default) and `zoom` (1 by default).
360
+ * @returns Whether the view can go there.
361
+ */
362
+ goTo(target, options = {}) {
363
+ const id = readBody(target);
364
+ if (!id)
365
+ return false;
366
+ const model = this.#model;
367
+ const reduced = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
368
+ const pose = model.pose;
369
+ const glide = (options.smooth ?? true) && !reduced && pose.valid && model.ride === null;
370
+ if (model.ride !== null)
371
+ this.ride(null, { smooth: false });
372
+ model.transition = glide ? { start: performance.now(), duration: 1200, from: { p: [pose.p[0], pose.p[1], pose.p[2]], q: [pose.q[0], pose.q[1], pose.q[2], pose.q[3]], fov: pose.fov } } : null;
373
+ this.#selected = id;
288
374
  this.#model.focus = id;
375
+ const zoom = options.zoom ?? 1;
376
+ // a bar bound to the element holds the view's state: it applies the zoom the page hears in the event; without one the element's own hands do
377
+ if (!this.hasAttribute("data-kazoku-bar"))
378
+ this.#hands?.controller.set({ zoom }, true, "jump");
379
+ this.#schedule();
289
380
  this.#gate?.request();
381
+ this.#announceHop(zoom);
382
+ return true;
383
+ }
384
+ /** Go to the next body in the order of `bodyList()` (the Sun, Mercury, Venus, the Earth, the Moon, Mars, Phobos, Deimos, Ceres, Jupiter, its moons, and on), round to the Sun after the last. */
385
+ next(options = {}) {
386
+ this.goTo(hopFrom(this.#model.focus, 1, canCentre), options);
387
+ return this.bodyInfo(this.#model.focus);
388
+ }
389
+ /** Go to the previous body in the same order. */
390
+ previous(options = {}) {
391
+ this.goTo(hopFrom(this.#model.focus, -1, canCentre), options);
392
+ return this.bodyInfo(this.#model.focus);
393
+ }
394
+ /** Every body the view can go to, in the hopper's order, with its kind and, for a moon, its planet: a page's jump list. */
395
+ bodyList() {
396
+ return HOP_ORDER.filter(canCentre).map((id) => this.bodyInfo(id));
397
+ }
398
+ /** The body a press has chosen and the page may be showing a card for, or null. A second press on it, or `goTo`, makes it the middle of the view. */
399
+ get selected() {
400
+ return this.#selected;
401
+ }
402
+ set selected(id) {
403
+ this.#selected = id;
404
+ }
405
+ /** `zoom` is the zoom the page should bring the view to: given by `goTo`, left out when the body was only set (the zoom stays). */
406
+ #announceHop(zoom) {
407
+ this.dispatchEvent(new CustomEvent("wakusei-hop", { detail: { ...this.hopper, zoom }, bubbles: true, composed: true }));
290
408
  }
291
409
  /** The words shown beside each body, for a page in another language (`{ mars: "火星" }`). A body left out keeps its name in the element's `lang`. */
292
410
  get bodyNames() {
@@ -309,8 +427,30 @@ export class WakuseiSpace extends HTMLElement {
309
427
  /** The name, radius and distance from the Earth of a body now, for a page's own caption. */
310
428
  bodyInfo(id) {
311
429
  const frame = this.#model.drawn?.frame ?? frameAt(this.#model.time);
312
- const geo = id === "earth" ? [0, 0, 0] : id === "sun" ? frame.sun : id === "moon" ? frame.moon : frame.planets[id];
313
- return { id, name: this.#nameOf(id), radiusKm: BODIES[id].radiusKm, distanceKm: Math.hypot(geo[0], geo[1], geo[2]) * AU_IN_EARTH_RADII * EARTH_RADIUS_KM };
430
+ const km = AU_IN_EARTH_RADII * EARTH_RADIUS_KM;
431
+ let geo = [Number.NaN, Number.NaN, Number.NaN];
432
+ const host = hostOf(id);
433
+ if (id === "earth")
434
+ geo = [0, 0, 0];
435
+ else if (id === "sun")
436
+ geo = frame.sun;
437
+ else if (id === "moon")
438
+ geo = frame.moon;
439
+ else if (SPACE_PLANETS.includes(id))
440
+ geo = frame.planets[id];
441
+ else if (SPACE_DWARFS.includes(id))
442
+ geo = frame.dwarfs[id];
443
+ else if (host !== undefined && (SPACE_PLANETS.includes(host) || SPACE_DWARFS.includes(host))) {
444
+ // a moon: its planet's place and its offset in the planet's radii
445
+ const at = SPACE_DWARFS.includes(host) ? frame.dwarfs[host] : frame.planets[host];
446
+ const offset = moonOffset(id, this.#model.time);
447
+ const radius = BODIES[host].radiusKm / km;
448
+ geo = [at[0] + offset[0] * radius, at[1] + offset[1] * radius, at[2] + offset[2] * radius];
449
+ }
450
+ const info = { id, name: this.#nameOf(id), kind: bodyKindOf(id), radiusKm: BODIES[id].radiusKm, distanceKm: Math.hypot(geo[0], geo[1], geo[2]) * km };
451
+ if (host !== undefined)
452
+ info.host = host;
453
+ return info;
314
454
  }
315
455
  // --- riding along -------------------------------------------------------------------------------------------------------------------------------
316
456
  /**
@@ -354,11 +494,17 @@ export class WakuseiSpace extends HTMLElement {
354
494
  const distanceKm = Math.max(100, options.distanceKm ?? 3000);
355
495
  if (typeof target !== "string") {
356
496
  const around = options.around && SPACE_BODIES.includes(options.around) ? options.around : "earth";
497
+ if (options.view === "beside")
498
+ return undefined;
357
499
  return { target, around, view: options.view ?? "from", look, distanceKm };
358
500
  }
359
501
  const id = target.toLowerCase();
360
- if (SPACE_BODIES.includes(id))
502
+ if (SPACE_BODIES.includes(id)) {
503
+ // the view from beside a moon is for a moon: of the bodies of the view only the Moon is one
504
+ if (options.view === "beside" && id !== "moon")
505
+ return undefined;
361
506
  return { target: id, around: "earth", view: id === "earth" ? "follow" : (options.view ?? "from"), look, distanceKm };
507
+ }
362
508
  for (const [planet, moons] of Object.entries(MOONS_OF)) {
363
509
  if (!moons.includes(id) || !SPACE_BODIES.includes(planet) || planet === "earth")
364
510
  continue;
@@ -377,12 +523,19 @@ export class WakuseiSpace extends HTMLElement {
377
523
  this.dispatchEvent(new CustomEvent("wakusei-ride-lost", { detail: this.riding }));
378
524
  }
379
525
  /** The zoom that shows a part of the sky: the Earth alone, the Moon's orbit, the Sun, the planets out to Mars, all of them, or a planet's nearer moons, at this scale and moment. */
380
- zoomFor(preset) {
526
+ zoomFor(named) {
381
527
  const mode = this.#model.mode;
528
+ // a name in any case; one that is no preset gives 1, the zoom that fills the view with the body looked at, not NaN
529
+ const preset = String(named).toLowerCase();
530
+ if (!["earth", "moon", "sun", "inner", "solar-system"].includes(preset) && !(preset.endsWith("-moons") && findBody(preset.slice(0, -6)) !== undefined))
531
+ return 1;
382
532
  if (preset.endsWith("-moons")) {
383
533
  const id = preset.slice(0, -6);
384
534
  const sites = this.#painterNow().moons(id, this.#model.time);
385
- const reach = Math.max(1, ...sites.map((site) => moonDistance(mode, id, Math.hypot(...site.offset))).filter((r) => r <= 22));
535
+ const distances = sites.map((site) => moonDistance(mode, id, Math.hypot(...site.offset)));
536
+ // the moons within 22 radii; a system whose moons are all farther (a dwarf planet's) is framed by them all
537
+ const near = distances.filter((r) => r <= 22);
538
+ const reach = Math.max(1, ...(near.length > 0 ? near : distances));
386
539
  const radius = radiusIn(id, mode);
387
540
  return Math.min(1, (FIT_DISTANCE * radius) / ((reach * radius * 1.15) / Math.tan(17.5 * RAD)));
388
541
  }
@@ -396,7 +549,11 @@ export class WakuseiSpace extends HTMLElement {
396
549
  inner: Math.max(away("mercury"), away("venus"), away("mars"), away("sun")),
397
550
  "solar-system": Math.max(...SPACE_PLANETS.map(away), away("sun")),
398
551
  }[preset];
399
- return preset === "earth" ? 1 : FIT_DISTANCE / Math.max(FIT_DISTANCE, reach * 3.4);
552
+ if (preset === "earth")
553
+ return 1;
554
+ const zoom = FIT_DISTANCE / Math.max(FIT_DISTANCE, reach * 3.4);
555
+ // the Moon's own picture is a quarter of the Earth's in the compressed scale (it was drawn as 0.9 of it): the view of its orbit is still the one that holds the Earth too, three Moon-distances out
556
+ return preset === "moon" && mode === "compressed" ? zoom * (radiusIn("moon", mode) / 0.9) : zoom;
400
557
  }
401
558
  /** What the element is doing, for a page or a test. */
402
559
  get stats() {
@@ -414,6 +571,10 @@ export class WakuseiSpace extends HTMLElement {
414
571
  bodies: { look: this.#model.look, painted: this.#model.painted.bodies, moons: this.#model.painted.moons, held: this.#model.painted.held },
415
572
  tiles: { ...this.#model.tiles },
416
573
  ride: { riding: this.#model.ride !== null, lost: this.#model.rideLost, gliding: this.#model.transition !== null },
574
+ orbits: { drawn: [...this.#model.rings.drawn], miss: { ...this.#model.rings.miss }, hidden: [...this.#model.rings.hidden] },
575
+ arrows: Object.fromEntries(Object.entries(this.#model.arrows).map(([id, list]) => [id, list.map((a) => ({ position: [...a.position], direction: [...a.direction] }))])),
576
+ arrowPx: this.#model.arrowPx,
577
+ help: this.#model.helpDrawn ? { body: this.#model.helpDrawn.body, axis: [...this.#model.helpDrawn.axis], pole: [...this.#model.helpDrawn.pole], retrograde: this.#model.helpDrawn.retrograde, arcTurn: [...this.#model.helpDrawn.arcTurn] } : null,
417
578
  };
418
579
  }
419
580
  // --- the game clock ----------------------------------------------------------------------------------------------------------------------------
@@ -465,7 +626,10 @@ export class WakuseiSpace extends HTMLElement {
465
626
  const box = this.#labelBox;
466
627
  if (!box)
467
628
  return;
468
- for (const id of SPACE_BODIES) {
629
+ const wanted = [];
630
+ const spots = new Map();
631
+ const ids = [...new Set([...SPACE_BODIES, ...this.#pool.keys(), ...Object.keys(places)])];
632
+ for (const id of ids) {
469
633
  let label = this.#pool.get(id);
470
634
  const at = places[id];
471
635
  if (!label) {
@@ -480,21 +644,107 @@ export class WakuseiSpace extends HTMLElement {
480
644
  this.#pool.set(id, button);
481
645
  label = button;
482
646
  }
483
- if (!at) {
647
+ let ring = this.#rings.get(id);
648
+ if (!ring) {
649
+ ring = box.ownerDocument.createElement("div");
650
+ ring.className = "sp-ring";
651
+ ring.dataset["ring"] = id;
652
+ ring.hidden = true;
653
+ box.append(ring);
654
+ this.#rings.set(id, ring);
655
+ }
656
+ if (!at)
657
+ continue;
658
+ const x = Math.round(at.x + Math.max(4, Math.min(at.r, 40)));
659
+ const y = Math.round(at.y - 8);
660
+ spots.set(id, { x, y, small: at.r < RING_BELOW_PX });
661
+ wanted.push({ id, x, y, width: this.#widthOf(label), height: 16, rank: this.#rank(id), size: at.r });
662
+ }
663
+ // no two names overlap: a moon gives way to its planet and a planet to the Sun
664
+ const shown = chooseLabels(wanted);
665
+ for (const id of ids) {
666
+ const label = this.#pool.get(id);
667
+ const ring = this.#rings.get(id);
668
+ if (!label || !ring)
669
+ continue;
670
+ const spot = spots.get(id);
671
+ if (!spot || !shown.has(id)) {
484
672
  if (!label.hidden)
485
673
  label.hidden = true;
674
+ if (!ring.hidden)
675
+ ring.hidden = true;
486
676
  continue;
487
677
  }
488
678
  if (label.hidden)
489
679
  label.hidden = false;
490
- label.style.transform = `translate(${Math.round(at.x + Math.max(4, Math.min(at.r, 40)))}px,${Math.round(at.y - 8)}px)`;
680
+ label.style.transform = `translate(${spot.x}px,${spot.y}px)`;
681
+ // a body too small to see is marked: a ring round the place it is, as well as its name
682
+ if (ring.hidden === spot.small)
683
+ ring.hidden = !spot.small;
684
+ if (spot.small)
685
+ ring.style.transform = `translate(${Math.round(places[id].x)}px,${Math.round(places[id].y)}px)`;
686
+ }
687
+ }
688
+ /** How sure a body's name is of its place: the body looked at first, then the Sun, the planets, the dwarf planets and the moons. */
689
+ #rank(id) {
690
+ if (id === this.#model.focus)
691
+ return 0;
692
+ if (id === "sun")
693
+ return 1;
694
+ const kind = bodyKindOf(id);
695
+ return kind === "moon" ? 4 : kind === "dwarf-planet" ? 3 : 2;
696
+ }
697
+ #widths = new WeakMap();
698
+ /** The width of a name's box on the screen, measured when its words change and not at every frame. */
699
+ #widthOf(label) {
700
+ let width = this.#widths.get(label);
701
+ if (width === undefined) {
702
+ const hidden = label.hidden;
703
+ if (hidden)
704
+ label.hidden = false;
705
+ width = label.offsetWidth;
706
+ if (hidden)
707
+ label.hidden = true;
708
+ if (width > 0)
709
+ this.#widths.set(label, width);
491
710
  }
711
+ return width;
712
+ }
713
+ /** Say which scale is on, on the view itself. */
714
+ #nameScale() {
715
+ if (!this.#scaleLine)
716
+ return;
717
+ const words = SCALE_WORDS[this.getAttribute("lang") === "ja" ? "ja" : "en"];
718
+ this.#scaleLine.textContent = this.#scaleNames[this.#model.mode] ?? words[this.#model.mode];
719
+ }
720
+ /** Where a body is on the screen now: its centre and radius in CSS pixels in the element, or `null` when it is behind the camera or not drawn. */
721
+ placeOf(id) {
722
+ const at = this.#places?.[id];
723
+ return at ? { ...at } : null;
492
724
  }
493
725
  #nameLabel(button, id) {
494
726
  const text = this.#nameOf(id);
495
727
  button.textContent = text;
728
+ this.#widths.delete(button);
496
729
  button.setAttribute("aria-label", `${text}: ${this.#hint}`);
497
730
  }
731
+ /** True for the full-screen mode (the `immersive` attribute): the element fills its box in any shape, a plain wheel zooms instead of scrolling the page, and a touch drag turns the view instead of scrolling it. */
732
+ get immersive() {
733
+ return this.hasAttribute("immersive");
734
+ }
735
+ set immersive(value) {
736
+ this.toggleAttribute("immersive", value);
737
+ }
738
+ // In an immersive view a plain wheel zooms. It is passed on to the shared hands as the wheel's own pinch (Ctrl and a small step), so whichever hands hold the view (the element's, or a bar bound to it) apply it with their limits;
739
+ // Ctrl, Command, Alt and Shift with the wheel are the family's own and are left alone.
740
+ #wheel = (event) => {
741
+ if (!this.hasAttribute("immersive") || event.ctrlKey || event.metaKey || event.altKey || event.shiftKey)
742
+ return;
743
+ event.preventDefault();
744
+ event.stopImmediatePropagation();
745
+ const pixels = event.deltaMode === 1 ? event.deltaY * 33 : event.deltaMode === 2 ? event.deltaY * 800 : event.deltaY;
746
+ this.dispatchEvent(new WheelEvent("wheel", { deltaY: Math.max(-250, Math.min(250, pixels)) * WHEEL_AS_PINCH, deltaMode: 0, clientX: event.clientX, clientY: event.clientY, ctrlKey: true, bubbles: true, cancelable: true, composed: true }));
747
+ };
498
748
  // A body is chosen by pressing on it or on its name (and by Tab and Enter on the name); a drag that turns the view is not a choice.
499
749
  #downX = 0;
500
750
  #downY = 0;
@@ -515,8 +765,7 @@ export class WakuseiSpace extends HTMLElement {
515
765
  const y = event.clientY - rect.top;
516
766
  let best;
517
767
  let bestD = Infinity;
518
- for (const id of SPACE_BODIES) {
519
- const at = this.#places[id];
768
+ for (const [id, at] of Object.entries(this.#places)) {
520
769
  if (!at)
521
770
  continue;
522
771
  const d = Math.hypot(x - at.x, y - at.y);
@@ -526,13 +775,27 @@ export class WakuseiSpace extends HTMLElement {
526
775
  }
527
776
  }
528
777
  if (best)
529
- this.dispatchEvent(new CustomEvent("wakusei-body-click", { detail: this.bodyInfo(best), bubbles: true, composed: true }));
778
+ this.#press(best);
530
779
  };
531
780
  #labelClick = (event) => {
532
781
  const id = event.target?.dataset?.["body"];
533
782
  if (id)
534
- this.dispatchEvent(new CustomEvent("wakusei-body-click", { detail: this.bodyInfo(id), bubbles: true, composed: true }));
783
+ this.#press(id);
535
784
  };
785
+ /**
786
+ * A press on a body or its name. `wakusei-body-click` tells the page every time. The first press on a body selects it (`wakusei-body-select`, for the page's card); a second press on the body that is selected makes it
787
+ * the middle of the view (`goTo`), unless it already is, so a press never sends the view anywhere else.
788
+ */
789
+ #press(id) {
790
+ this.dispatchEvent(new CustomEvent("wakusei-body-click", { detail: this.bodyInfo(id), bubbles: true, composed: true }));
791
+ if (this.#selected === id) {
792
+ if (canCentre(id) && this.#model.focus !== id)
793
+ this.goTo(id);
794
+ return;
795
+ }
796
+ this.#selected = id;
797
+ this.dispatchEvent(new CustomEvent("wakusei-body-select", { detail: this.bodyInfo(id), bubbles: true, composed: true }));
798
+ }
536
799
  #labelFocus = (event) => {
537
800
  const id = event.target?.dataset?.["body"];
538
801
  if (id)
@@ -1,3 +1,4 @@
1
+ import { type DwarfId } from "../facts.ts";
1
2
  import { type Vec3 } from "../vec.ts";
2
3
  /**
3
4
  * A position or direction as `[x, y, z]` in the scene's axes: J2000 equatorial, x to the vernal equinox, y north.
@@ -44,6 +45,29 @@ export declare const AU_IN_EARTH_RADII: number;
44
45
  * ```
45
46
  */
46
47
  export declare const SPACE_PLANETS: readonly ["mercury", "venus", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto"];
48
+ /**
49
+ * The dwarf planets besides Pluto that the space view places: Ceres, Orcus, Haumea, Quaoar, Makemake, Gonggong, Eris and Sedna.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * import { SPACE_DWARFS } from "@johnmorrisdotca/wakusei-planets/space";
54
+ *
55
+ * console.log(SPACE_DWARFS.join(", "));
56
+ * ```
57
+ */
58
+ export declare const SPACE_DWARFS: readonly ["ceres", "orcus", "haumea", "quaoar", "makemake", "gonggong", "eris", "sedna"];
59
+ /**
60
+ * One of the dwarf planets in `SPACE_DWARFS`.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * import { planetOrbit, type SpaceDwarf } from "@johnmorrisdotca/wakusei-planets/space";
65
+ *
66
+ * const dwarf: SpaceDwarf = "eris";
67
+ * console.log(planetOrbit(dwarf, Date.UTC(2026, 10, 2), 8).length);
68
+ * ```
69
+ */
70
+ export type SpaceDwarf = DwarfId;
47
71
  /**
48
72
  * One of the planets in `SPACE_PLANETS`.
49
73
  *
@@ -72,6 +96,8 @@ export interface SpaceFrame {
72
96
  sun: Vec3;
73
97
  moon: Vec3;
74
98
  planets: Record<SpacePlanet, Vec3>;
99
+ /** The dwarf planets besides Pluto, from their osculating elements (good for a few years either side of 2026). */
100
+ dwarfs: Record<SpaceDwarf, Vec3>;
75
101
  }
76
102
  /**
77
103
  * The state of the sky at `ms`: the Sun, the Moon and eight planets as seen from the Earth's centre, worked out by this package's own models in a fraction of a millisecond.
@@ -136,7 +162,7 @@ export declare function createTrack(initialStepMs?: number): {
136
162
  /**
137
163
  * The path a planet or the Earth takes round the Sun, as `count + 1` points round one trip from where the planet is at `ms`, from the Sun, in astronomical units and the scene's axes.
138
164
  *
139
- * @param id - The planet or `earth`.
165
+ * @param id - The planet, the dwarf planet or `earth`.
140
166
  * @param ms - The moment the path starts at, in milliseconds since the Unix epoch.
141
167
  * @param count - How many segments to cut the trip into.
142
168
  * @returns `count + 1` points; the last is near the first.
@@ -149,4 +175,21 @@ export declare function createTrack(initialStepMs?: number): {
149
175
  * console.log(points.length);
150
176
  * ```
151
177
  */
152
- export declare function planetOrbit(id: SpacePlanet | "earth", ms: number, count?: number): Vec3[];
178
+ export declare function planetOrbit(id: SpacePlanet | SpaceDwarf | "earth", ms: number, count?: number): Vec3[];
179
+ /**
180
+ * The path the Moon takes round the Earth, as `count + 1` points round one sidereal month from where the Moon is at `ms`, from the Earth's centre, in astronomical units and the scene's axes. The first
181
+ * point is the Moon's own place at `ms` and the last is the first again, so the line is closed and passes through the Moon.
182
+ *
183
+ * @param ms - The moment the path starts at, in milliseconds since the Unix epoch.
184
+ * @param count - How many segments to cut the month into.
185
+ * @returns `count + 1` points; the last is the first.
186
+ *
187
+ * @example
188
+ * ```ts
189
+ * import { moonOrbit } from "@johnmorrisdotca/wakusei-planets/space";
190
+ *
191
+ * const ring = moonOrbit(Date.UTC(2026, 10, 2), 48);
192
+ * console.log(ring.length, Math.hypot(...ring[0]!).toFixed(4));
193
+ * ```
194
+ */
195
+ export declare function moonOrbit(ms: number, count?: number): Vec3[];