@johnmorrisdotca/wakusei-planets 0.28.0 → 0.30.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.
@@ -0,0 +1,782 @@
1
+ import { setThreeLoader, takeRenderer } from "../scene/shared.js";
2
+ import { texturePaths } from "../scene/textures.js";
3
+ import { starLook } from "../star.js";
4
+ import { lineupBodies, LINEUP_SETS } from "./data.js";
5
+ import { lineupFocus, lineupProject, lineupView, lineupZoomFor, lineupZoomOf, LINEUP_LAYOUTS, placeLineup } from "./layout.js";
6
+ import { lineupLabels, lineupLabelsSvg, lineupText } from "./labels.js";
7
+ import { createLineupItem } from "./scene3d.js";
8
+ export { setThreeLoader };
9
+ const TEMPLATE = `<style>
10
+ :host { display: block; width: var(--wakusei-size, 720px); max-width: 100%; aspect-ratio: var(--wakusei-ratio, 16 / 9); position: relative; overflow: hidden; contain: layout style; touch-action: pan-y; user-select: none; -webkit-user-select: none; background: radial-gradient(ellipse at 50% 40%, #0a1120, #04060b); color: #fff; border-radius: var(--wakusei-radius, 10px); }
11
+ :host(:focus-visible) { outline: 3px solid #6cd0ff; outline-offset: -3px; }
12
+ :host([data-hand]) { cursor: grab; }
13
+ :host([data-held]) { cursor: grabbing; }
14
+ #stage, #flat, #over { position: absolute; inset: 0; width: 100%; height: 100%; }
15
+ #flat, #over { pointer-events: none; overflow: visible; }
16
+ #bar { position: absolute; left: 50%; top: 10px; transform: translateX(-50%); width: min(440px, 78%); display: flex; align-items: center; gap: 8px; padding: 6px 12px; border-radius: 999px; background: rgba(5, 7, 13, 0.72); border: 1px solid rgba(255, 255, 255, 0.2); }
17
+ #bar[hidden] { display: none; }
18
+ input[type="range"] { flex: 1; min-width: 0; margin: 0; height: 28px; accent-color: #6cd0ff; background: transparent; touch-action: none; }
19
+ input[type="range"]:focus-visible { outline: 2px solid #6cd0ff; outline-offset: 2px; border-radius: 4px; }
20
+ </style><div id="stage"></div><svg id="flat" aria-hidden="true"></svg><svg id="over" aria-hidden="true"></svg><div id="bar"><input id="zoom" type="range" min="0" max="1000" step="1" value="0" /></div>`;
21
+ const num = (value, fallback) => {
22
+ const n = value === null || value.trim() === "" ? NaN : Number(value);
23
+ return Number.isFinite(n) ? n : fallback;
24
+ };
25
+ const on = (value) => value !== null && !["off", "0", "false", "no"].includes(value.trim().toLowerCase());
26
+ const clamp = (value, low, high) => Math.min(high, Math.max(low, value));
27
+ /** A device that should get the cheaper star: little memory or two cores or fewer. */
28
+ const weakDevice = () => {
29
+ const nav = typeof navigator === "undefined" ? undefined : navigator;
30
+ return nav !== undefined && ((nav.deviceMemory ?? 8) <= 2 || (nav.hardwareConcurrency ?? 8) <= 2);
31
+ };
32
+ /**
33
+ * The `<wakusei-lineup>` custom element: the size line-up of stars (and, with `planets`, the Earth and Jupiter) at true relative size.
34
+ *
35
+ * Attributes: `stars` (`all`, `bright` or `largest`, or ids from `LINEUP_STARS` separated by commas; `all` by default), `planets` (add the Earth and Jupiter), `layout` (`row` or `stack`), `zoom` (0 to 1, the framed size on a
36
+ * logarithmic scale of radius) or `at` (the id of a body to frame: the Sun by default), `turn` (`off` stops the bodies turning by themselves; they do not under reduced motion unless it is `on`), `look` (`realistic` or `painted`: the
37
+ * planets'), `labels` (`off` hides the words), `controls` (`none` hides the zoom slider), `size` (pixels across), `lang` (`en` or `ja`), `quality` (`full` or `low`), `live` (`always`, `hover` or `off`: when it takes the page's one WebGL
38
+ * context), `texture-base` and `texture-far-base`.
39
+ *
40
+ * A drag on a body turns it (a horizontal swipe on a touch screen); Ctrl, Command or Alt with the wheel zooms; with the element focused the arrow keys go to the next body, + and - zoom a little, Home and End go to the ends,
41
+ * and a double click puts every body back.
42
+ *
43
+ * @example
44
+ * ```ts no-run
45
+ * import { WakuseiLineup } from "@johnmorrisdotca/wakusei-planets/lineup";
46
+ *
47
+ * const lineup = document.createElement("wakusei-lineup") as WakuseiLineup;
48
+ * lineup.setAttribute("stars", "bright");
49
+ * lineup.setAttribute("planets", "");
50
+ * document.body.append(lineup);
51
+ * void lineup.zoomTo("betelgeuse");
52
+ * ```
53
+ */
54
+ export class WakuseiLineup extends HTMLElement {
55
+ static observedAttributes = ["stars", "planets", "layout", "zoom", "at", "turn", "look", "size", "lang", "live", "labels", "controls", "quality", "texture-base", "texture-far-base"];
56
+ #root;
57
+ #stage;
58
+ #over;
59
+ #flat;
60
+ #bar;
61
+ #input;
62
+ #bodies = [];
63
+ #places = [];
64
+ #looks = new Map();
65
+ #computed = "";
66
+ #zoom = 0;
67
+ #hands = new Map();
68
+ #held;
69
+ #state = "loading";
70
+ #renderer;
71
+ #release;
72
+ #view;
73
+ #viewKey = "";
74
+ #stilled = false;
75
+ #wantLive = false;
76
+ #visible = typeof IntersectionObserver !== "function";
77
+ #io;
78
+ #queued = false;
79
+ #reduce = false;
80
+ #anim;
81
+ #animDone;
82
+ #overKey = "";
83
+ #drag;
84
+ #hover = () => void this.goLive();
85
+ #onContext = (state) => {
86
+ if (state === "unavailable")
87
+ this.#set("unavailable");
88
+ else if (state === "lost")
89
+ this.#set("lost");
90
+ else if (this.#view?.live)
91
+ this.#set("live");
92
+ };
93
+ #onHidden = () => {
94
+ if (document.visibilityState !== "hidden")
95
+ this.#sync();
96
+ };
97
+ /** What the element is doing now. */
98
+ get state() {
99
+ return this.#state;
100
+ }
101
+ /** The zoom now, 0 to 1. Setting it moves the camera at once; `zoomTo` moves it smoothly. */
102
+ get zoom() {
103
+ return this.#zoom;
104
+ }
105
+ set zoom(value) {
106
+ this.#cancelAnimation();
107
+ this.#setZoom(value);
108
+ }
109
+ /** The body the camera frames now: its id. */
110
+ get focused() {
111
+ return lineupFocus(this.#places, this.#zoom)?.body.id;
112
+ }
113
+ /** The bodies drawn, smallest first. */
114
+ get bodies() {
115
+ return this.#bodies;
116
+ }
117
+ /** Numbers for a test or a status line. */
118
+ get stats() {
119
+ return { state: this.#state, bodies: this.#bodies.length, drawn: this.#view?.scene?.drawn ?? [], renderer: this.#renderer?.stats };
120
+ }
121
+ /** Where everything is on the page now: the picture's size in pixels, the camera, and the bodies' centres and radii in pixels. */
122
+ get metrics() {
123
+ const { width, height } = this.#size();
124
+ const view = this.#viewNow();
125
+ return { width, height, view, dots: lineupProject(this.#places, view, width, height).map((dot) => ({ id: dot.place.body.id, cx: dot.cx, cy: dot.cy, r: dot.r })) };
126
+ }
127
+ connectedCallback() {
128
+ this.#root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
129
+ this.#root.innerHTML = TEMPLATE;
130
+ this.#stage = this.#root.getElementById("stage");
131
+ this.#over = this.#root.getElementById("over");
132
+ this.#flat = this.#root.getElementById("flat");
133
+ this.#bar = this.#root.getElementById("bar");
134
+ this.#input = this.#root.getElementById("zoom");
135
+ this.#reduce = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
136
+ if (!this.hasAttribute("role"))
137
+ this.setAttribute("role", "group");
138
+ if (!this.hasAttribute("tabindex"))
139
+ this.tabIndex = 0;
140
+ if (!this.hasAttribute("data-state"))
141
+ this.setAttribute("data-state", this.#state);
142
+ if (typeof IntersectionObserver === "function") {
143
+ this.#io = new IntersectionObserver((entries) => {
144
+ const last = entries[entries.length - 1];
145
+ if (last === undefined)
146
+ return;
147
+ this.#visible = last.isIntersecting;
148
+ if (this.#visible) {
149
+ this.#still();
150
+ if (this.#view?.live !== true && this.#priority())
151
+ void this.goLive();
152
+ }
153
+ });
154
+ this.#io.observe(this);
155
+ }
156
+ document.addEventListener("visibilitychange", this.#onHidden);
157
+ this.#applyHover();
158
+ this.#input.addEventListener("input", this.#onSlider);
159
+ this.addEventListener("pointerdown", this.#onDown);
160
+ this.addEventListener("pointermove", this.#onMove);
161
+ this.addEventListener("pointerup", this.#onUp);
162
+ this.addEventListener("pointercancel", this.#onUp);
163
+ this.addEventListener("keydown", this.#onKey);
164
+ this.addEventListener("dblclick", this.#onDouble);
165
+ this.addEventListener("wheel", this.#onWheel, { passive: false });
166
+ this.#compute(true);
167
+ this.#queue();
168
+ }
169
+ disconnectedCallback() {
170
+ this.#cancelAnimation();
171
+ this.#io?.disconnect();
172
+ document.removeEventListener("visibilitychange", this.#onHidden);
173
+ this.#applyHover(false);
174
+ this.#input.removeEventListener("input", this.#onSlider);
175
+ this.removeEventListener("pointerdown", this.#onDown);
176
+ this.removeEventListener("pointermove", this.#onMove);
177
+ this.removeEventListener("pointerup", this.#onUp);
178
+ this.removeEventListener("pointercancel", this.#onUp);
179
+ this.removeEventListener("keydown", this.#onKey);
180
+ this.removeEventListener("dblclick", this.#onDouble);
181
+ this.removeEventListener("wheel", this.#onWheel);
182
+ this.#disposeView(true);
183
+ }
184
+ attributeChangedCallback(name, before, after) {
185
+ if (!this.isConnected || before === after)
186
+ return;
187
+ if (name === "live")
188
+ this.#applyHover();
189
+ if (name === "zoom") {
190
+ this.#cancelAnimation();
191
+ this.#setZoom(num(after, this.#zoom));
192
+ return;
193
+ }
194
+ if (name === "at") {
195
+ const at = after === null ? undefined : lineupZoomOf(this.#places, after);
196
+ if (at !== undefined) {
197
+ this.#cancelAnimation();
198
+ this.#setZoom(at);
199
+ }
200
+ return;
201
+ }
202
+ if (name === "stars" || name === "planets" || name === "layout" || name === "quality")
203
+ this.#compute(false);
204
+ if (name === "look" || name === "texture-base" || name === "texture-far-base")
205
+ this.#rebuild();
206
+ if (name === "turn") {
207
+ this.#sync();
208
+ this.#changed();
209
+ return;
210
+ }
211
+ this.#queue();
212
+ }
213
+ /**
214
+ * Zoom to a body (its id) or to a number from 0 to 1, smoothly: the camera glides there along the logarithmic scale of radius, as fast as a reader can follow, or at once under reduced motion or with `smooth: false`.
215
+ * Resolves when it has arrived (or been interrupted by a hand). An id that is not in the line-up resolves at once and moves nothing.
216
+ */
217
+ zoomTo(target, options = {}) {
218
+ const to = typeof target === "number" ? clamp(target, 0, 1) : lineupZoomOf(this.#places, target);
219
+ this.#cancelAnimation();
220
+ if (to === undefined)
221
+ return Promise.resolve();
222
+ if (options.smooth === false || this.#reduce || !this.isConnected || Math.abs(to - this.#zoom) < 1e-4) {
223
+ this.#setZoom(to);
224
+ return Promise.resolve();
225
+ }
226
+ const from = this.#zoom;
227
+ const started = performance.now();
228
+ const duration = 450 + 1100 * Math.abs(to - from);
229
+ return new Promise((resolve) => {
230
+ this.#animDone = resolve;
231
+ const step = (now) => {
232
+ const t = clamp((now - started) / duration, 0, 1);
233
+ const eased = t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2;
234
+ this.#setZoom(from + (to - from) * eased);
235
+ if (t < 1)
236
+ this.#anim = requestAnimationFrame(step);
237
+ else {
238
+ this.#anim = undefined;
239
+ this.#animDone = undefined;
240
+ resolve();
241
+ }
242
+ };
243
+ this.#anim = requestAnimationFrame(step);
244
+ });
245
+ }
246
+ /** Turn a body by hand, in degrees, as a drag would; both are added to what is there. `pitch` stays within 85 degrees. */
247
+ turnBy(id, yaw, pitch = 0) {
248
+ const hand = this.#hands.get(id) ?? { yaw: 0, pitch: 0 };
249
+ this.#hands.set(id, { yaw: (hand.yaw + yaw) % 360, pitch: clamp(hand.pitch + pitch, -85, 85) });
250
+ this.#changed();
251
+ }
252
+ /** Put every body back as it was turned. */
253
+ resetTurns() {
254
+ this.#hands.clear();
255
+ this.#changed();
256
+ }
257
+ /** Take the page's one WebGL context and draw the line-up on it. Resolves true when it is live. */
258
+ async goLive() {
259
+ if (this.getAttribute("live") === "off" && !this.#wantLive)
260
+ return this.#view?.live === true;
261
+ this.#wantLive = true;
262
+ await this.#ensureView();
263
+ const ok = (await this.#view?.focus()) === true;
264
+ if (ok) {
265
+ this.#set("live");
266
+ this.#sync();
267
+ }
268
+ else if (this.#state !== "unavailable" && this.#state !== "lost")
269
+ this.#set("still");
270
+ return ok;
271
+ }
272
+ /** Give the WebGL context back: the picture stays as a still. */
273
+ rest() {
274
+ this.#wantLive = false;
275
+ if (this.#view === undefined)
276
+ return;
277
+ this.#view.blur();
278
+ if (this.#state !== "unavailable") {
279
+ this.#set("still");
280
+ this.#rekey();
281
+ }
282
+ }
283
+ /**
284
+ * The picture as it is now, as an SVG element that stands alone: a dark background, the bodies as a picture (or flat discs when there is no WebGL) and the labels as vector text. It is the same picture that is saved and printed.
285
+ * The element is not in the page; put it in one (out of sight) before saving it, so its styles can be read.
286
+ */
287
+ async picture() {
288
+ const { width, height } = this.#size();
289
+ const view = this.#viewNow();
290
+ let body;
291
+ if (this.#state === "unavailable")
292
+ body = this.#flatMarkup(width, height);
293
+ else {
294
+ const href = await this.#pixels();
295
+ body = `<image x="0" y="0" width="${width}" height="${height}" preserveAspectRatio="none" href="${href}"/>`;
296
+ }
297
+ const dots = lineupProject(this.#places, view, width, height);
298
+ const labels = this.#labelsOn() ? lineupLabelsSvg(lineupLabels(dots, width, height, this.#lang(), { keep: this.focused, font: this.#font(width) }), this.#font(width)) : "";
299
+ const markup = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}" role="img" aria-label="${this.#label().replace(/&/g, "&amp;").replace(/"/g, "&quot;")}"><rect width="${width}" height="${height}" fill="#05070d"/>${body}${labels}</svg>`;
300
+ return new DOMParser().parseFromString(markup, "image/svg+xml").documentElement;
301
+ }
302
+ /** The picture as SVG text. */
303
+ async toSvg() {
304
+ return new XMLSerializer().serializeToString(await this.picture());
305
+ }
306
+ /** The picture as a PNG, `scale` times the size it is on the page (1 to 4). */
307
+ async toPng(scale = 2) {
308
+ const svg = await this.picture();
309
+ const width = Number(svg.getAttribute("width"));
310
+ const height = Number(svg.getAttribute("height"));
311
+ const ratio = clamp(scale, 1, 4);
312
+ const image = await new Promise((resolve, reject) => {
313
+ const made = new Image(width, height);
314
+ made.onload = () => resolve(made);
315
+ made.onerror = () => reject(new Error("the picture could not be drawn"));
316
+ made.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(svg))}`;
317
+ });
318
+ const canvas = document.createElement("canvas");
319
+ canvas.width = Math.round(width * ratio);
320
+ canvas.height = Math.round(height * ratio);
321
+ canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
322
+ return new Promise((resolve, reject) => canvas.toBlob((blob) => (blob === null ? reject(new Error("the picture could not be made")) : resolve(blob)), "image/png"));
323
+ }
324
+ // --- what is drawn --------------------------------------------------------------------------------------------------------------------------------------
325
+ #lang() {
326
+ return this.getAttribute("lang") === "ja" ? "ja" : "en";
327
+ }
328
+ #labelsOn() {
329
+ return on(this.getAttribute("labels") ?? "on");
330
+ }
331
+ /** The label text size: a little smaller on a narrow picture. */
332
+ #font(width) {
333
+ return width < 520 ? 10.5 : 12;
334
+ }
335
+ #spin() {
336
+ const turn = this.getAttribute("turn");
337
+ if (turn === null)
338
+ return !this.#reduce;
339
+ return on(turn === "" ? "on" : turn);
340
+ }
341
+ #size() {
342
+ const width = Math.max(1, Math.round(this.clientWidth || num(this.getAttribute("size"), 720)));
343
+ const height = Math.max(1, Math.round(this.clientHeight || (width * 9) / 16));
344
+ return { width, height };
345
+ }
346
+ #viewNow() {
347
+ const { width, height } = this.#size();
348
+ return lineupView(this.#places, this.#zoom, width / height);
349
+ }
350
+ /** The bodies, their places and their star looks for the attributes; a change of the set or the layout keeps the camera on the body it was framing. */
351
+ #compute(first) {
352
+ const stars = this.getAttribute("stars") ?? "all";
353
+ const planets = this.hasAttribute("planets") && on(this.getAttribute("planets") === "" ? "on" : this.getAttribute("planets"));
354
+ const layout = LINEUP_LAYOUTS.includes(this.getAttribute("layout") ?? "") ? this.getAttribute("layout") : "row";
355
+ const quality = this.getAttribute("quality") === "low" || (this.getAttribute("quality") !== "full" && weakDevice()) ? "low" : "full";
356
+ const key = JSON.stringify([stars, planets, layout, quality]);
357
+ if (key === this.#computed)
358
+ return;
359
+ const focus = lineupFocus(this.#places, this.#zoom);
360
+ const before = focus === undefined ? undefined : { id: focus.body.id, r: focus.r };
361
+ this.#computed = key;
362
+ this.removeAttribute("data-error");
363
+ try {
364
+ const set = LINEUP_SETS.includes(stars) ? stars : stars.split(",").map((one) => one.trim()).filter((one) => one !== "");
365
+ this.#bodies = lineupBodies({ set, planets });
366
+ }
367
+ catch (error) {
368
+ this.setAttribute("data-error", error instanceof Error ? error.message : String(error));
369
+ this.#bodies = [];
370
+ }
371
+ this.#places = placeLineup(this.#bodies, layout);
372
+ this.#looks = new Map();
373
+ for (const body of this.#bodies) {
374
+ if (body.row === undefined)
375
+ continue;
376
+ const estimated = body.row.basis === "luminosity" || body.row.basis === "weak-distance" ? ["radiusSun"] : [];
377
+ this.#looks.set(body.id, starLook({ ...body.row.look, name: body.row.name.en, radiusSun: body.row.radiusSun, estimated }, { quality }));
378
+ }
379
+ for (const id of [...this.#hands.keys()])
380
+ if (!this.#bodies.some((body) => body.id === id))
381
+ this.#hands.delete(id);
382
+ // the camera: the attribute's, on the first look; after a change the body it was on, or the Sun
383
+ const attribute = this.getAttribute("zoom");
384
+ const at = this.getAttribute("at");
385
+ const zoom = first
386
+ ? attribute !== null
387
+ ? num(attribute, 0)
388
+ : (lineupZoomOf(this.#places, at ?? "sun") ?? 0)
389
+ : before === undefined
390
+ ? (lineupZoomOf(this.#places, "sun") ?? 0)
391
+ : (lineupZoomOf(this.#places, before.id) ?? lineupZoomFor(this.#places, before.r));
392
+ this.#zoom = clamp(zoom, 0, 1);
393
+ this.#syncSlider();
394
+ if (!first) {
395
+ this.#rebuild();
396
+ this.dispatchEvent(new CustomEvent("wakusei-lineup-zoom", { detail: { zoom: this.#zoom, focus: this.focused } }));
397
+ }
398
+ this.#queue();
399
+ }
400
+ /** The scene is built for one set of bodies and one look: a new set or look makes a new view, and a view that was live takes the context again. */
401
+ #rebuild() {
402
+ if (this.#view === undefined)
403
+ return;
404
+ if (this.#view.live)
405
+ this.#wantLive = true;
406
+ this.#disposeView();
407
+ }
408
+ #setZoom(value) {
409
+ const next = clamp(Number.isFinite(value) ? value : 0, 0, 1);
410
+ if (next === this.#zoom)
411
+ return;
412
+ this.#zoom = next;
413
+ this.#syncSlider();
414
+ this.dispatchEvent(new CustomEvent("wakusei-lineup-zoom", { detail: { zoom: next, focus: this.focused } }));
415
+ this.#changed();
416
+ }
417
+ #syncSlider() {
418
+ if (this.#input === undefined)
419
+ return;
420
+ this.#input.value = String(Math.round(this.#zoom * 1000));
421
+ const lang = this.#lang();
422
+ const first = this.#bodies[0]?.name[lang] ?? "";
423
+ const last = this.#bodies[this.#bodies.length - 1]?.name[lang] ?? "";
424
+ this.#input.setAttribute("aria-label", lang === "ja" ? `ズーム: ${first}から${last}まで` : `Zoom: from ${first} up to ${last}`);
425
+ const near = this.#places.length === 0 ? undefined : lineupFocus(this.#places, this.#zoom)?.body;
426
+ if (near !== undefined) {
427
+ const text = lineupText(near, lang);
428
+ this.#input.setAttribute("aria-valuetext", `${text.name}: ${text.radius}`);
429
+ }
430
+ this.#bar.hidden = this.getAttribute("controls") === "none" || this.#places.length < 2;
431
+ }
432
+ #label() {
433
+ const lang = this.#lang();
434
+ const names = this.#bodies.map((body) => body.name[lang]);
435
+ return lang === "ja" ? `大きさくらべ: ${names.join("、")} (大きさの比は実際のとおり)` : `Size line-up: ${names.join(", ")}, at true relative size`;
436
+ }
437
+ // --- drawing ------------------------------------------------------------------------------------------------------------------------------------------
438
+ #draw() {
439
+ return { places: this.#places, view: this.#viewNow(), hands: this.#hands, spin: this.#spin(), ...(this.#held === undefined ? {} : { holding: this.#held }) };
440
+ }
441
+ #queue() {
442
+ if (this.#queued)
443
+ return;
444
+ this.#queued = true;
445
+ queueMicrotask(() => {
446
+ this.#queued = false;
447
+ if (this.isConnected)
448
+ void this.#refresh();
449
+ });
450
+ }
451
+ #changed() {
452
+ if (!this.isConnected)
453
+ return;
454
+ if (this.#view?.live === true && !this.#queued) {
455
+ this.#paintOver();
456
+ this.#sync();
457
+ this.#view.invalidate();
458
+ }
459
+ else
460
+ this.#queue();
461
+ }
462
+ async #refresh() {
463
+ if (!this.isConnected)
464
+ return;
465
+ this.#style();
466
+ this.#syncSlider();
467
+ this.setAttribute("aria-label", this.#label());
468
+ this.#paintOver();
469
+ if (this.#bodies.length === 0 || this.#state === "unavailable") {
470
+ if (this.#state === "unavailable")
471
+ this.#paintFlat();
472
+ return;
473
+ }
474
+ if (this.#view === undefined || this.#viewKey === "")
475
+ await this.#ensureView();
476
+ if (this.#view?.live !== true && this.#wantLive) {
477
+ void this.goLive();
478
+ return;
479
+ }
480
+ if (this.#view?.live === true) {
481
+ this.#sync();
482
+ this.#view.invalidate();
483
+ }
484
+ else {
485
+ this.#rekey();
486
+ if (this.#wantLive || this.#priority())
487
+ void this.goLive();
488
+ }
489
+ }
490
+ #style() {
491
+ if (this.hasAttribute("size"))
492
+ this.style.setProperty("--wakusei-size", `${num(this.getAttribute("size"), 720)}px`);
493
+ }
494
+ #priority() {
495
+ return (this.getAttribute("live") ?? "always") === "always" && this.#visible;
496
+ }
497
+ #applyHover(allow = true) {
498
+ const events = ["pointerenter", "focusin", "pointerdown"];
499
+ for (const name of events)
500
+ this.removeEventListener(name, this.#hover);
501
+ if (allow && (this.getAttribute("live") ?? "always") === "hover")
502
+ for (const name of events)
503
+ this.addEventListener(name, this.#hover);
504
+ }
505
+ #dots() {
506
+ const { width, height } = this.#size();
507
+ return lineupProject(this.#places, this.#viewNow(), width, height);
508
+ }
509
+ #paintOver() {
510
+ if (this.#over === undefined)
511
+ return;
512
+ const { width, height } = this.#size();
513
+ const dots = this.#dots();
514
+ const markup = this.#labelsOn() ? lineupLabelsSvg(lineupLabels(dots, width, height, this.#lang(), { keep: this.focused, font: this.#font(width) }), this.#font(width)) : "";
515
+ const key = `${width}x${height}|${markup}`;
516
+ if (key === this.#overKey)
517
+ return;
518
+ this.#overKey = key;
519
+ this.#over.setAttribute("viewBox", `0 0 ${width} ${height}`);
520
+ this.#over.innerHTML = markup;
521
+ }
522
+ /** Flat discs, for a page with no WebGL: each body a disc in the colour of its star (a planet in its own colour), shaded a little to the edge. */
523
+ #flatMarkup(width, height) {
524
+ const dots = this.#dots();
525
+ const defs = [];
526
+ const discs = [];
527
+ for (const dot of dots) {
528
+ if (dot.r < 0.4 || dot.cx + dot.r < 0 || dot.cx - dot.r > width || dot.cy + dot.r < 0 || dot.cy - dot.r > height)
529
+ continue;
530
+ const id = dot.place.body.id;
531
+ const look = this.#looks.get(id);
532
+ const centre = look?.tone ?? (id === "earth" ? "#5d9bd8" : "#e0c39a");
533
+ const edge = look?.colour ?? (id === "earth" ? "#2a5d96" : "#9b7a52");
534
+ defs.push(`<radialGradient id="flat-${id}" cx="50%" cy="50%" r="50%"><stop offset="0" stop-color="${centre}"/><stop offset="0.8" stop-color="${edge}"/><stop offset="1" stop-color="${edge}" stop-opacity="0.85"/></radialGradient>`);
535
+ discs.push(`<circle cx="${dot.cx.toFixed(2)}" cy="${dot.cy.toFixed(2)}" r="${Math.max(dot.r, 0.4).toFixed(2)}" fill="url(#flat-${id})"/>`);
536
+ }
537
+ return `<defs>${defs.join("")}</defs>${discs.join("")}`;
538
+ }
539
+ #paintFlat() {
540
+ const { width, height } = this.#size();
541
+ this.#flat.setAttribute("viewBox", `0 0 ${width} ${height}`);
542
+ this.#flat.innerHTML = this.#state === "unavailable" ? this.#flatMarkup(width, height) : "";
543
+ }
544
+ #key() {
545
+ const { width } = this.#size();
546
+ const hands = [...this.#hands].map(([id, hand]) => `${id}:${Math.round(hand.yaw)}/${Math.round(hand.pitch)}`).join(",");
547
+ return `${this.#computed}|${this.getAttribute("look") ?? ""}|${width}|${this.#zoom.toFixed(4)}|${hands}`;
548
+ }
549
+ // Replacing a view keeps the renderer lease; leaving 3D gives it back.
550
+ #disposeView(releaseRenderer = false) {
551
+ this.#view?.dispose();
552
+ this.#view = undefined;
553
+ this.#viewKey = "";
554
+ if (releaseRenderer) {
555
+ this.#release?.();
556
+ this.#release = undefined;
557
+ this.#renderer = undefined;
558
+ }
559
+ }
560
+ async #ensureView() {
561
+ if (this.#renderer === undefined) {
562
+ const taken = takeRenderer(this.#onContext);
563
+ this.#renderer = taken.renderer;
564
+ this.#release = taken.release;
565
+ }
566
+ if (this.#view === undefined)
567
+ this.#makeView();
568
+ }
569
+ #makeView() {
570
+ this.#viewKey = this.#key();
571
+ this.#stilled = false;
572
+ this.#stage.innerHTML = "";
573
+ const item = createLineupItem({
574
+ key: this.#viewKey,
575
+ bodies: this.#bodies,
576
+ stars: this.#looks,
577
+ look: this.getAttribute("look") === "painted" ? "painted" : "realistic",
578
+ state: () => this.#draw(),
579
+ ...texturePaths(this),
580
+ redraw: () => this.#view?.invalidate(),
581
+ });
582
+ this.#view = this.#renderer.view(this.#stage, item);
583
+ this.#set("loading");
584
+ if (this.#visible)
585
+ this.#still();
586
+ }
587
+ #still() {
588
+ if (this.#stilled || this.#view === undefined)
589
+ return;
590
+ this.#stilled = true;
591
+ void this.#view.showStill().then(() => {
592
+ if (this.#state === "loading")
593
+ this.#set("still");
594
+ });
595
+ }
596
+ #rekey() {
597
+ if (this.#renderer === undefined || this.#view === undefined || this.#view.live)
598
+ return;
599
+ if (this.#key() === this.#viewKey)
600
+ return;
601
+ this.#disposeView();
602
+ this.#makeView();
603
+ }
604
+ #sync() {
605
+ const scene = this.#view?.scene;
606
+ if (scene === undefined || typeof scene.apply !== "function")
607
+ return;
608
+ scene.apply(this.#draw());
609
+ }
610
+ #set(state) {
611
+ if (state === this.#state)
612
+ return;
613
+ this.#state = state;
614
+ this.setAttribute("data-state", state);
615
+ this.dispatchEvent(new CustomEvent("wakusei-state", { detail: { state } }));
616
+ if (state === "unavailable")
617
+ this.#paintFlat();
618
+ else if (this.#flat !== undefined)
619
+ this.#flat.innerHTML = "";
620
+ }
621
+ // --- reading the picture ------------------------------------------------------------------------------------------------------------------------------
622
+ /** The canvas as a PNG address, taken right after a draw, in the same task, while it still holds the picture. */
623
+ async #pixels() {
624
+ // the shared renderer draws nothing out of sight, so a picture asked for while the element is scrolled away brings it into view for the moment it takes, and puts the page back
625
+ const [x, y] = [window.scrollX, window.scrollY];
626
+ const away = !this.#visible;
627
+ if (away) {
628
+ this.scrollIntoView({ block: "center", behavior: "instant" });
629
+ for (let i = 0; i < 40 && !this.#visible; i += 1)
630
+ await new Promise((resolve) => setTimeout(resolve, 50));
631
+ }
632
+ try {
633
+ return await this.#readPixels();
634
+ }
635
+ finally {
636
+ if (away)
637
+ window.scrollTo(x, y);
638
+ }
639
+ }
640
+ async #readPixels() {
641
+ if (this.#view?.live !== true && !(await this.goLive()))
642
+ throw new Error("the 3D picture is not available here");
643
+ return new Promise((done, reject) => {
644
+ const view = this.#view;
645
+ const scene = view?.scene;
646
+ const canvas = this.#stage.querySelector("canvas");
647
+ if (view === undefined || scene?.afterDraw === undefined || canvas === null) {
648
+ reject(new Error("the 3D picture is not available here"));
649
+ return;
650
+ }
651
+ const timeout = setTimeout(() => reject(new Error("the picture was not drawn")), 8000);
652
+ scene.afterDraw(() => {
653
+ clearTimeout(timeout);
654
+ try {
655
+ done(canvas.toDataURL("image/png"));
656
+ }
657
+ catch (error) {
658
+ reject(error instanceof Error ? error : new Error("the picture could not be read"));
659
+ }
660
+ });
661
+ this.#sync();
662
+ view.invalidate();
663
+ });
664
+ }
665
+ // --- hands --------------------------------------------------------------------------------------------------------------------------------------------
666
+ #onSlider = () => {
667
+ this.#cancelAnimation();
668
+ this.#setZoom(Number(this.#input.value) / 1000);
669
+ };
670
+ #cancelAnimation() {
671
+ if (this.#anim !== undefined)
672
+ cancelAnimationFrame(this.#anim);
673
+ this.#anim = undefined;
674
+ const done = this.#animDone;
675
+ this.#animDone = undefined;
676
+ done?.();
677
+ }
678
+ /** The body under a point (client coordinates): the one the point is nearest the middle of, within a few pixels of its edge. */
679
+ #hit(clientX, clientY) {
680
+ const box = this.getBoundingClientRect();
681
+ const { width, height } = this.#size();
682
+ const x = ((clientX - box.left) / Math.max(1, box.width)) * width;
683
+ const y = ((clientY - box.top) / Math.max(1, box.height)) * height;
684
+ let best;
685
+ for (const dot of this.#dots()) {
686
+ if (dot.r < 0.2)
687
+ continue;
688
+ const slop = 6;
689
+ const d = Math.hypot(x - dot.cx, y - dot.cy);
690
+ if (d > dot.r + slop)
691
+ continue;
692
+ const score = d / Math.max(dot.r, 1);
693
+ if (best === undefined || score < best.score)
694
+ best = { id: dot.place.body.id, score };
695
+ }
696
+ return best?.id;
697
+ }
698
+ #onDown = (event) => {
699
+ if (event.composedPath().includes(this.#bar) || (event.pointerType === "mouse" && event.button !== 0))
700
+ return;
701
+ const id = this.#hit(event.clientX, event.clientY);
702
+ if (id === undefined)
703
+ return;
704
+ this.#drag = { id, x: event.clientX, y: event.clientY, pointer: event.pointerId };
705
+ this.#held = id;
706
+ this.setAttribute("data-held", "");
707
+ try {
708
+ this.setPointerCapture(event.pointerId);
709
+ }
710
+ catch {
711
+ /* a pointer that is already gone */
712
+ }
713
+ void this.goLive();
714
+ this.#changed();
715
+ };
716
+ #onMove = (event) => {
717
+ if (this.#drag === undefined) {
718
+ if (event.pointerType === "mouse")
719
+ this.toggleAttribute("data-hand", this.#hit(event.clientX, event.clientY) !== undefined);
720
+ return;
721
+ }
722
+ if (event.pointerId !== this.#drag.pointer)
723
+ return;
724
+ const dx = event.clientX - this.#drag.x;
725
+ const dy = event.clientY - this.#drag.y;
726
+ this.#drag.x = event.clientX;
727
+ this.#drag.y = event.clientY;
728
+ const hand = this.#hands.get(this.#drag.id) ?? { yaw: 0, pitch: 0 };
729
+ // the surface follows the hand: a drag right turns the front to the right, a drag down brings the pole toward you
730
+ this.#hands.set(this.#drag.id, { yaw: (hand.yaw + dx * 0.4) % 360, pitch: clamp(hand.pitch + dy * 0.4, -85, 85) });
731
+ this.#changed();
732
+ };
733
+ #onUp = (event) => {
734
+ if (this.#drag === undefined || event.pointerId !== this.#drag.pointer)
735
+ return;
736
+ this.#drag = undefined;
737
+ this.#held = undefined;
738
+ this.removeAttribute("data-held");
739
+ this.#changed();
740
+ };
741
+ #onDouble = (event) => {
742
+ if (event.composedPath().includes(this.#bar))
743
+ return;
744
+ this.resetTurns();
745
+ };
746
+ #onWheel = (event) => {
747
+ if (!(event.ctrlKey || event.metaKey || event.altKey))
748
+ return;
749
+ event.preventDefault();
750
+ this.#cancelAnimation();
751
+ this.#setZoom(this.#zoom - event.deltaY * 0.0006);
752
+ };
753
+ #onKey = (event) => {
754
+ if (event.ctrlKey || event.metaKey || event.altKey)
755
+ return;
756
+ const at = lineupFocus(this.#places, this.#zoom);
757
+ const index = at === undefined ? 0 : this.#places.indexOf(at);
758
+ const go = (i) => {
759
+ const to = this.#places[clamp(i, 0, this.#places.length - 1)];
760
+ if (to !== undefined)
761
+ void this.zoomTo(to.body.id);
762
+ };
763
+ const key = event.key;
764
+ if (key === "ArrowRight" || key === "ArrowUp")
765
+ go(index + 1);
766
+ else if (key === "ArrowLeft" || key === "ArrowDown")
767
+ go(index - 1);
768
+ else if (key === "+" || key === "=")
769
+ this.zoom = this.#zoom + 0.03;
770
+ else if (key === "-" || key === "_")
771
+ this.zoom = this.#zoom - 0.03;
772
+ else if (key === "Home")
773
+ go(0);
774
+ else if (key === "End")
775
+ go(this.#places.length - 1);
776
+ else
777
+ return;
778
+ event.preventDefault();
779
+ };
780
+ }
781
+ if (typeof customElements !== "undefined" && !customElements.get("wakusei-lineup"))
782
+ customElements.define("wakusei-lineup", WakuseiLineup);