@johnmorrisdotca/chikyu-earth 0.34.0 → 0.35.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.
package/dist/sky/host.js CHANGED
@@ -1,12 +1,27 @@
1
1
  import { canvasRatio } from "../markers/project.js";
2
+ import { boxCovered, pathOutside, touches } from "./cover.js";
3
+ import { createCultureLines } from "./culture-lines.js";
4
+ import { areaInHull, hullOf, nearestSegment, placeBox, visibleCentre } from "./figure-pick.js";
5
+ import { inKeep, keepBox, touchesKeep } from "./keep-clear.js";
2
6
  /** The styles of the layer, for an element to add to its own (`#sk-canvas`, `#sk-names` and the labels in its shadow root). */
3
7
  export const SKY_STYLE = "#sk-canvas{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}#sk-names{position:absolute;inset:0;overflow:hidden;pointer-events:none}" +
4
- ".sk-name,.sk-figure,.sk-designation{position:absolute;left:0;top:0;margin:0;white-space:nowrap;pointer-events:none;font-family:var(--hoshi-label-font,Michroma,system-ui,sans-serif);font-size:calc(var(--hoshi-label-size,11) * 1px);font-weight:var(--hoshi-label-weight,400);color:var(--hoshi-label-colour,#e9f1ff);letter-spacing:calc(var(--hoshi-label-letter-spacing,.14) * 1em);font-variant:var(--hoshi-label-case-variant,small-caps);text-transform:var(--hoshi-label-case-transform,none);text-shadow:0 0 calc(var(--hoshi-label-halo-width,3) * 1px) var(--hoshi-label-halo,#0a1230)}" +
8
+ ".sk-name,.sk-figure,.sk-constellation,.sk-designation{position:absolute;left:0;top:0;margin:0;white-space:nowrap;pointer-events:none;font-family:var(--hoshi-label-font,Michroma,system-ui,sans-serif);font-size:calc(var(--hoshi-label-size,11) * 1px);font-weight:var(--hoshi-label-weight,400);color:var(--hoshi-label-colour,#e9f1ff);letter-spacing:calc(var(--hoshi-label-letter-spacing,.14) * 1em);font-variant:var(--hoshi-label-case-variant,small-caps);text-transform:var(--hoshi-label-case-transform,none);text-shadow:0 0 calc(var(--hoshi-label-halo-width,3) * 1px) var(--hoshi-label-halo,#0a1230)}" +
5
9
  ".sk-designation{font-family:var(--hoshi-label-designation-font,ui-monospace,monospace);font-size:calc(var(--hoshi-label-designation-size,9) * 1px);color:var(--hoshi-label-designation-colour,#b8c6e0);letter-spacing:0;font-variant:normal;text-transform:none}" +
6
- ".sk-figure{color:var(--hoshi-label-colour,#e9f1ff)}[hidden]{display:none}";
10
+ ".sk-figure{color:var(--hoshi-label-colour,#e9f1ff);opacity:0;transition:opacity .15s ease-out}.sk-constellation{font-size:calc(var(--hoshi-label-size,11) * .9px);color:var(--hoshi-label-constellation-colour,#9db0d3);letter-spacing:.22em;opacity:.85}@media (prefers-reduced-motion:reduce){.sk-figure{transition:none}}.sk-ruler{visibility:hidden}.sk-live{position:absolute;left:0;top:0;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}[hidden]{display:none}";
11
+ /**
12
+ * The sky cultures besides the IAU's, each loaded by a dynamic import of its own, only when a page asks for it: a page that never sets `chinese` never downloads it. (The imports are written out, one for each, so that a bundler makes a file of each.)
13
+ */
14
+ const CULTURES = {
15
+ western: async () => (await import("@johnmorrisdotca/hoshi-stars/cultures/western")).western,
16
+ japanese: async () => (await import("@johnmorrisdotca/hoshi-stars/cultures/japanese")).japanese,
17
+ chinese: async () => (await import("@johnmorrisdotca/hoshi-stars/cultures/chinese")).chinese,
18
+ };
19
+ const warnedCultures = new Set();
7
20
  const NAME_POOL = 40;
21
+ /** What other layers of the element draw as labels over the sky (bodies, satellites, places, cities): a constellation's name keeps off them. */
22
+ const OTHER_LABELS = ".sp-label,.sp-sat,.cm-label,.pl-name:not(.pl-measure),.cn-name";
8
23
  /** The attributes this layer reads. */
9
- export const SKY_ATTRIBUTES = ["star-names", "star-names-magnitude", "constellation-lines"];
24
+ export const SKY_ATTRIBUTES = ["star-names", "star-names-magnitude", "constellation-lines", "constellation-names", "constellation-culture", "keep-clear"];
10
25
  /**
11
26
  * Makes the layer of one element, inside its shadow root. Nothing of hoshi-stars is loaded, and nothing is added to the root, until one of the three attributes is there.
12
27
  *
@@ -29,14 +44,132 @@ export function createSkyHost(options) {
29
44
  const pool = [];
30
45
  const designations = [];
31
46
  let figureName;
47
+ /** The figure the pointer rests on, and the one a click or tap picked (IAU abbreviations): the lines of either are lit and the name of one is shown. */
48
+ let hoverAbbr = null;
49
+ let pickAbbr = null;
50
+ /** The abbreviation the name now shown (the figure name's span) is of, and the timer that hides it after it has faded. */
51
+ let shownAbbr = null;
52
+ let fadeTimer;
53
+ /** The names of the constellations: the spans of the optional layer (`constellation-names`), and what is known of each figure from hoshi-stars. */
54
+ const figurePool = [];
55
+ let shownFigures = 0;
56
+ /** What is known of each figure of the IAU's 88 (from hoshi-stars' `constellations`), and of each culture that has been loaded; `culture` is the culture the lines are of now. */
57
+ let iauInfo;
58
+ const cultureData = new Map();
59
+ const cultureLoading = new Set();
60
+ const cultureFailed = new Set();
61
+ let culture = "iau";
62
+ const activeInfo = () => (culture === "iau" ? iauInfo : cultureData.get(culture)?.info);
63
+ /** Whether the lines are drawn (the attribute `constellation-lines`): the names alone use the figures but draw none. */
64
+ let drawStrokes = false;
65
+ /** A pick asked for before hoshi-stars was in. */
66
+ let pendingPick;
67
+ const middle = { x: 0, y: 0 };
68
+ const found = { x: 0, y: 0 };
69
+ /** The boxes of what is on the picture already, from its top left: the pool is reused, `takenN` of it is in use. */
70
+ const taken = [];
71
+ let takenN = 0;
72
+ /** The star names that stayed (their boxes, noted as they were measured), the other layers' labels (read again only when they have changed) and the size of each text as drawn (measured once). */
73
+ const starBoxes = [];
74
+ let starN = 0;
75
+ const otherBoxes = [];
76
+ let otherN = 0;
77
+ let otherStale = true;
78
+ let otherWatch;
79
+ const sizes = new Map();
80
+ let ruler;
81
+ /** The hull of each figure, made when a pointer first asks of it after a projection change. */
82
+ const hulls = [];
83
+ /** A visually hidden polite live region: a pick is read out with the figure's name. */
84
+ let live;
85
+ let queuedFrame = false;
32
86
  let attached = false;
33
87
  let covered;
88
+ /** The places the page asked to keep clear, and as boxes from the picture's top left: measured when something has changed (a resize, a new list), never at each frame. */
89
+ let keepList = [];
90
+ const keep = [];
91
+ let keepStale = true;
92
+ let keepWatch;
93
+ let keepEvents = false;
94
+ /** Whether a point of the picture is on a body or in a place kept clear: what the names are laid out against (the lines are cut at the bodies only). */
95
+ const blockedAt = (x, y) => (covered ? covered(x, y) : false) || inKeep(keep, x, y);
34
96
  /** The language the names were last laid out in: the page may change its language after the element was made, so it is read again at each draw. */
35
97
  let usedLang;
36
98
  /** The names drawn at the last frame that were left out because they ran over another as the browser draws them (by label), and how many names are shown. */
37
99
  const culled = [];
38
100
  let drawnNames = 0;
39
- const wanted = () => options.attribute("star-names") !== null || options.attribute("constellation-lines") !== null;
101
+ /** Lays the layer out once more at the next frame (one for any number of calls), where something it avoids has moved without the picture drawing: a place the page keeps clear that was scrolled, another layer's label. */
102
+ const later = () => {
103
+ if (queuedFrame)
104
+ return;
105
+ queuedFrame = true;
106
+ const run = () => {
107
+ queuedFrame = false;
108
+ if (module && last && (keep.length > 0 || options.attribute("constellation-names") !== null || shownAbbr !== null))
109
+ compute();
110
+ };
111
+ if (typeof globalThis.requestAnimationFrame === "function")
112
+ globalThis.requestAnimationFrame(run);
113
+ else
114
+ setTimeout(run, 16);
115
+ };
116
+ const wanted = () => options.attribute("star-names") !== null || options.attribute("constellation-lines") !== null || options.attribute("constellation-names") !== null;
117
+ /** The places to keep clear now: the property's and the elements the attribute's selector matches. */
118
+ const keepItems = () => {
119
+ const items = [...keepList];
120
+ const selector = options.attribute("keep-clear");
121
+ if (selector) {
122
+ try {
123
+ items.push(...Array.from(doc.querySelectorAll(selector)));
124
+ }
125
+ catch {
126
+ // not a selector: nothing is kept clear by it
127
+ }
128
+ }
129
+ return items;
130
+ };
131
+ /** Reads the boxes of the places to keep clear: when the list, the selector or a box has changed, and not at each frame. */
132
+ const measureKeep = (rewatch) => {
133
+ keepStale = false;
134
+ const items = keepItems();
135
+ keep.length = 0;
136
+ if (items.length === 0) {
137
+ keepWatch?.disconnect();
138
+ return;
139
+ }
140
+ const host = root.host;
141
+ const own = host.getBoundingClientRect();
142
+ for (const item of items)
143
+ keep.push(keepBox(item, own));
144
+ if (!rewatch)
145
+ return;
146
+ // a box that grows or shrinks is read again and the layer laid out again; the observer is set again only when the list has changed
147
+ if (typeof ResizeObserver === "undefined")
148
+ return;
149
+ keepWatch ??= new ResizeObserver(() => {
150
+ keepStale = true;
151
+ if (module && last)
152
+ compute();
153
+ });
154
+ keepWatch.disconnect();
155
+ for (const item of items)
156
+ if ("getBoundingClientRect" in item && item instanceof Element)
157
+ keepWatch.observe(item);
158
+ keepWatch.observe(host);
159
+ const view = doc.defaultView;
160
+ if (!keepEvents && view && items.length > 0) {
161
+ keepEvents = true;
162
+ view.addEventListener("resize", markStale);
163
+ view.addEventListener("scroll", markStale, { capture: true, passive: true });
164
+ }
165
+ };
166
+ function markStale() {
167
+ keepStale = true;
168
+ // scrolled or resized while something is kept clear: the names are laid out again at the next frame, once however many events
169
+ if (keep.length > 0)
170
+ later();
171
+ }
172
+ let keepRewatch = true;
40
173
  const attach = () => {
41
174
  if (attached)
42
175
  return;
@@ -51,32 +184,75 @@ export function createSkyHost(options) {
51
184
  figureName.className = "sk-figure";
52
185
  figureName.hidden = true;
53
186
  box.append(figureName);
54
- root.append(canvas, box);
187
+ ruler = doc.createElement("span");
188
+ ruler.className = "sk-ruler";
189
+ ruler.setAttribute("aria-hidden", "true");
190
+ ruler.hidden = false;
191
+ box.append(ruler);
192
+ live = doc.createElement("div");
193
+ live.id = "sk-live";
194
+ live.className = "sk-live";
195
+ live.setAttribute("role", "status");
196
+ live.setAttribute("aria-live", "polite");
197
+ root.append(canvas, box, live);
55
198
  const host = root.host;
199
+ const at = { x: 0, y: 0 };
56
200
  const place = (event) => {
57
201
  const rect = host.getBoundingClientRect();
58
- return { x: event.clientX - rect.left, y: event.clientY - rect.top };
202
+ at.x = event.clientX - rect.left;
203
+ at.y = event.clientY - rect.top;
204
+ return at;
59
205
  };
60
- // a mouse lights the figure it rests on and lets go when it leaves; a finger lights what it touches and the pick stays until the next touch
206
+ // a mouse lights the figure it rests on, shows its name and lets go when it leaves (the hit test runs once a frame at most, and only when the pointer has moved); a click or a tap picks the figure it is on, or lets the pick go on empty sky
207
+ const rest = { x: 0, y: 0 };
208
+ let queued = false;
209
+ let down;
61
210
  host.addEventListener("pointermove", (event) => {
62
- if (!lines || event.pointerType === "touch")
211
+ // a button held is a drag, a turn of the view: nothing is hit then
212
+ if (!lines || !drawStrokes || event.pointerType === "touch" || event.buttons !== 0)
63
213
  return;
64
- const at = place(event);
65
- if (lines.point(at.x, at.y))
66
- drawLines();
214
+ const here = place(event);
215
+ rest.x = here.x;
216
+ rest.y = here.y;
217
+ if (queued)
218
+ return;
219
+ queued = true;
220
+ const run = () => {
221
+ queued = false;
222
+ setHover(figureAt(rest.x, rest.y));
223
+ };
224
+ if (typeof globalThis.requestAnimationFrame === "function")
225
+ globalThis.requestAnimationFrame(run);
226
+ else
227
+ setTimeout(run, 16);
67
228
  });
68
229
  host.addEventListener("pointerleave", (event) => {
69
- if (!lines || event.pointerType === "touch")
230
+ if (event.pointerType === "touch")
70
231
  return;
71
- if (lines.point())
72
- drawLines();
232
+ setHover(null);
73
233
  });
74
234
  host.addEventListener("pointerdown", (event) => {
75
- if (!lines || event.pointerType !== "touch")
235
+ const here = place(event);
236
+ down = { id: event.pointerId, x: here.x, y: here.y, at: event.timeStamp };
237
+ });
238
+ host.addEventListener("pointerup", (event) => {
239
+ const start = down;
240
+ down = undefined;
241
+ if (!start || start.id !== event.pointerId || !lines || !drawStrokes)
242
+ return;
243
+ const here = place(event);
244
+ // a press that did not move, and was not held: a click or a tap, not the start of a turn
245
+ if (Math.hypot(here.x - start.x, here.y - start.y) > 6 || event.timeStamp - start.at > 600)
76
246
  return;
77
- const at = place(event);
78
- if (lines.point(at.x, at.y))
79
- drawLines();
247
+ setPick(figureAt(here.x, here.y), true);
248
+ });
249
+ host.addEventListener("keydown", (event) => {
250
+ if (!lines || !drawStrokes || event.altKey || event.ctrlKey || event.metaKey)
251
+ return;
252
+ if (event.key === "Escape" && pickAbbr !== null)
253
+ setPick(null, true);
254
+ else if (event.key === "c" || event.key === "C")
255
+ cycle(event.shiftKey ? -1 : 1);
80
256
  });
81
257
  };
82
258
  const sizeCanvas = (frame) => {
@@ -91,6 +267,259 @@ export function createSkyHost(options) {
91
267
  context?.setTransform(ratio, 0, 0, ratio, 0, 0);
92
268
  return context;
93
269
  };
270
+ /** What the page can be told of a constellation: its names from hoshi-stars, with the culture. */
271
+ const detailOf = (abbreviation) => {
272
+ const info = activeInfo()?.get(abbreviation);
273
+ return { abbreviation, id: abbreviation, name: info?.name ?? abbreviation, english: info?.english ?? abbreviation, japanese: info?.japanese ?? abbreviation, kind: info?.kind ?? "constellation", culture };
274
+ };
275
+ const emit = (type, detail) => {
276
+ root.host.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true }));
277
+ };
278
+ /** The text of a figure's name in the page's language, in the case the style asks for: for the IAU's 88 the Latin or Japanese name; for a culture's own figures its name in the page's language (a Japanese asterism by its reading in kana: すばる). */
279
+ const figureText = (abbreviation) => {
280
+ const info = activeInfo()?.get(abbreviation);
281
+ const ja = options.language() === "ja";
282
+ let text = abbreviation;
283
+ if (info && culture === "iau")
284
+ text = ja ? info.japanese : info.name;
285
+ else if (info) {
286
+ const names = info.names ?? {};
287
+ text = ja ? (info.kind === "asterism" && info.reading ? info.reading : (names["ja"] ?? info.name)) : info.kind === "constellation" ? (names["la"] ?? info.name) : (names["en"] ?? info.name);
288
+ }
289
+ return module && lines ? module.labelText(text, lines.style) : text;
290
+ };
291
+ /** The figure under a point of the picture: one with a line within reach of it, else the smallest one it is inside of (a pointer in a figure picks it, not only on its lines). `null` where a body covers the point, or none is there. */
292
+ function figureAt(x, y) {
293
+ if (!lines || !drawStrokes || covered?.(x, y))
294
+ return null;
295
+ const reach = lines.settings.reach ?? 14;
296
+ let best = reach * reach;
297
+ let nearest = null;
298
+ for (const figure of lines.figures) {
299
+ if (figure.end <= figure.start)
300
+ continue;
301
+ const d = nearestSegment(lines.segments, figure.start, figure.end, x, y);
302
+ if (d < best) {
303
+ best = d;
304
+ nearest = figure.abbreviation;
305
+ }
306
+ }
307
+ if (nearest)
308
+ return nearest;
309
+ let smallest = Number.POSITIVE_INFINITY;
310
+ for (const figure of lines.figures) {
311
+ if (figure.end <= figure.start || x < figure.left || x > figure.right || y < figure.top || y > figure.bottom)
312
+ continue;
313
+ const index = lines.figures.indexOf(figure);
314
+ const area = areaInHull((hulls[index] ??= hullOf(lines.segments, figure.start, figure.end)), x, y);
315
+ if (area >= 0 && area < smallest) {
316
+ smallest = area;
317
+ nearest = figure.abbreviation;
318
+ }
319
+ }
320
+ return nearest;
321
+ }
322
+ function setHover(abbreviation) {
323
+ if (abbreviation === hoverAbbr)
324
+ return;
325
+ hoverAbbr = abbreviation;
326
+ emit("chikyu-constellation-hover", abbreviation === null ? null : detailOf(abbreviation));
327
+ drawLines();
328
+ }
329
+ function setPick(abbreviation, send) {
330
+ if (abbreviation === pickAbbr)
331
+ return;
332
+ pickAbbr = abbreviation;
333
+ if (send) {
334
+ emit("chikyu-constellation-pick", abbreviation === null ? null : detailOf(abbreviation));
335
+ // a pick is read out, with the figure's name in the page's language; a hover is not (it would be too much to hear)
336
+ if (live)
337
+ live.textContent = abbreviation === null ? "" : options.language() === "ja" ? `${figureText(abbreviation)}を選択` : `${figureText(abbreviation)} selected`;
338
+ }
339
+ drawLines();
340
+ }
341
+ /** Picks the next (or the previous) figure in view, from the left: the keyboard's way to pick. */
342
+ function cycle(step) {
343
+ if (!lines)
344
+ return;
345
+ const inView = lines.figures.filter((f) => f.end > f.start).sort((a, b) => a.left + a.right - (b.left + b.right));
346
+ if (inView.length === 0)
347
+ return;
348
+ const at = inView.findIndex((f) => f.abbreviation === pickAbbr);
349
+ const next = inView[(at < 0 ? (step > 0 ? 0 : inView.length - 1) : (at + step + inView.length) % inView.length)];
350
+ setPick(next.abbreviation, true);
351
+ }
352
+ const takenAbbr = [];
353
+ /** Whether a box may stand: clear of bodies and kept-clear areas, and clear of the names already placed (those of `ignore` aside). */
354
+ const freeFor = (ignore, useTaken) => (l, t, r, b) => {
355
+ const blocked = keep.length > 0 ? blockedAt : covered;
356
+ if (blocked && boxCovered(blocked, l, t, r, b))
357
+ return false;
358
+ if (touchesKeep(keep, l, t, r, b))
359
+ return false;
360
+ if (!useTaken)
361
+ return true;
362
+ for (let i = 0; i < takenN; i += 1) {
363
+ const a = taken[i];
364
+ if ((ignore === undefined || takenAbbr[i] !== ignore) && l < a.r + 1 && r > a.l - 1 && t < a.b + 1 && b > a.t - 1)
365
+ return false;
366
+ }
367
+ return true;
368
+ };
369
+ let takenStale = true;
370
+ /** Notes a box among those taken, reusing the objects of the pool. */
371
+ const take = (l, t, r, b, abbreviation) => {
372
+ const one = (taken[takenN] ??= { l: 0, t: 0, r: 0, b: 0 });
373
+ one.l = l;
374
+ one.t = t;
375
+ one.r = r;
376
+ one.b = b;
377
+ takenAbbr[takenN] = abbreviation;
378
+ takenN += 1;
379
+ };
380
+ /** The other layers' labels (bodies, places, satellites, cities) are read again only after one of them has changed (a mutation of the shadow root outside this layer), never at each frame. */
381
+ const readOthers = () => {
382
+ otherStale = false;
383
+ otherN = 0;
384
+ if (typeof MutationObserver !== "undefined" && !otherWatch) {
385
+ otherWatch = new MutationObserver((records) => {
386
+ for (const record of records) {
387
+ if (record.target === canvas || record.target === live || (box && box.contains(record.target)))
388
+ continue;
389
+ otherStale = true;
390
+ later();
391
+ return;
392
+ }
393
+ });
394
+ otherWatch.observe(root, { childList: true, subtree: true, attributes: true, attributeFilter: ["style", "hidden"] });
395
+ }
396
+ const own = root.host.getBoundingClientRect();
397
+ for (const el of Array.from(root.querySelectorAll?.(OTHER_LABELS) ?? [])) {
398
+ if (el.hidden)
399
+ continue;
400
+ const rect = el.getBoundingClientRect();
401
+ if (rect.width <= 0 && rect.height <= 0)
402
+ continue;
403
+ const one = (otherBoxes[otherN] ??= { l: 0, t: 0, r: 0, b: 0 });
404
+ one.l = rect.left - own.left;
405
+ one.t = rect.top - own.top;
406
+ one.r = rect.right - own.left;
407
+ one.b = rect.bottom - own.top;
408
+ otherN += 1;
409
+ }
410
+ };
411
+ /** The boxes of what is already on the picture: the star names that stayed (noted when they were measured), the other layers' labels and, as they are placed, the constellation names. No layout is asked for here but when another layer has changed. */
412
+ function gatherTaken() {
413
+ takenN = 0;
414
+ takenStale = false;
415
+ if (otherStale)
416
+ readOthers();
417
+ for (let i = 0; i < starN; i += 1)
418
+ take(starBoxes[i].l, starBoxes[i].t, starBoxes[i].r, starBoxes[i].b, null);
419
+ for (let i = 0; i < otherN; i += 1)
420
+ take(otherBoxes[i].l, otherBoxes[i].t, otherBoxes[i].r, otherBoxes[i].b, null);
421
+ }
422
+ /**
423
+ * The size of a text as drawn with a class of the layer, measured once (on a hidden ruler) and kept until the style, the language or a font changes: the layout never has to be asked again to place a name.
424
+ */
425
+ const textBox = (className, text) => {
426
+ const key = `${className}|${text}`;
427
+ let known = sizes.get(key);
428
+ if (!known) {
429
+ const rect = ruler && typeof ruler.getBoundingClientRect === "function" ? (() => {
430
+ ruler.className = `${className} sk-ruler`;
431
+ ruler.textContent = text;
432
+ return ruler.getBoundingClientRect();
433
+ })() : undefined;
434
+ known = { w: rect && rect.width > 0 ? rect.width : 90, h: rect && rect.height > 0 ? rect.height : 14 };
435
+ sizes.set(key, known);
436
+ }
437
+ return known;
438
+ };
439
+ const reduced = () => doc.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true;
440
+ /** The name of the lit figure (the one the pointer is on, else the picked one) at the middle of the part of it that is in view, clear of the star names, the Earth and the places kept clear; it fades in and out. */
441
+ function updateFigureName(frame) {
442
+ const el = figureName;
443
+ if (!el)
444
+ return;
445
+ const abbreviation = hoverAbbr ?? pickAbbr;
446
+ const figure = abbreviation && lines ? lines.figures.find((f) => f.abbreviation === abbreviation) : undefined;
447
+ const blocked = keep.length > 0 ? blockedAt : covered;
448
+ if (!abbreviation || !lines || !figure || figure.end <= figure.start || !visibleCentre(lines.segments, figure.start, figure.end, frame.width, frame.height, blocked, middle)) {
449
+ fadeName();
450
+ return;
451
+ }
452
+ if (takenStale)
453
+ gatherTaken();
454
+ const text = figureText(abbreviation);
455
+ if (el.hidden) {
456
+ el.style.opacity = "0";
457
+ el.hidden = false;
458
+ }
459
+ if (el.textContent !== text)
460
+ el.textContent = text;
461
+ const { w, h } = textBox("sk-figure", text);
462
+ // the middle of the figure, or the nearest place that is clear: of the other names first, and where there is none, over them
463
+ if (!placeBox(middle.x, middle.y, w, h, frame.width, frame.height, freeFor(abbreviation, true), found) && !placeBox(middle.x, middle.y, w, h, frame.width, frame.height, freeFor(abbreviation, false), found)) {
464
+ fadeName();
465
+ return;
466
+ }
467
+ el.style.transform = `translate(${Math.round(found.x)}px,${Math.round(found.y)}px) translate(-50%,-50%)`;
468
+ if (shownAbbr !== abbreviation || el.style.opacity !== "1") {
469
+ clearTimeout(fadeTimer);
470
+ if (typeof el.getBoundingClientRect === "function")
471
+ void el.offsetWidth;
472
+ el.style.opacity = "1";
473
+ }
474
+ shownAbbr = abbreviation;
475
+ }
476
+ function fadeName() {
477
+ const el = figureName;
478
+ shownAbbr = null;
479
+ if (!el || el.hidden || el.style.opacity === "0")
480
+ return;
481
+ el.style.opacity = "0";
482
+ clearTimeout(fadeTimer);
483
+ fadeTimer = setTimeout(() => {
484
+ el.hidden = true;
485
+ }, reduced() ? 0 : 180);
486
+ }
487
+ /** The optional layer of the constellations' names (`constellation-names`): each figure's name at the middle of the part of it in view, quieter than the star names, and clear of them, of the bodies, of the places kept clear and of each other. */
488
+ function placeConstellationNames(frame) {
489
+ const on = options.attribute("constellation-names") !== null && lines !== undefined && module !== undefined && box !== undefined;
490
+ shownFigures = 0;
491
+ if (on) {
492
+ gatherTaken();
493
+ const inView = lines.figures.filter((f) => f.end > f.start).sort((a, b) => (b.right - b.left) * (b.bottom - b.top) - (a.right - a.left) * (a.bottom - a.top));
494
+ const blocked = keep.length > 0 ? blockedAt : covered;
495
+ for (const figure of inView) {
496
+ if (figure.abbreviation === shownAbbr || !visibleCentre(lines.segments, figure.start, figure.end, frame.width, frame.height, blocked, middle))
497
+ continue;
498
+ while (figurePool.length <= shownFigures) {
499
+ const span = doc.createElement("span");
500
+ span.className = "sk-constellation";
501
+ box.append(span);
502
+ figurePool.push(span);
503
+ }
504
+ const el = figurePool[shownFigures];
505
+ const text = figureText(figure.abbreviation);
506
+ if (el.textContent !== text)
507
+ el.textContent = text;
508
+ el.hidden = false;
509
+ const { w, h } = textBox("sk-constellation", text);
510
+ // not far from the middle: a name set off to the far side of a figure names nothing
511
+ if (!placeBox(middle.x, middle.y, w, h, frame.width, frame.height, freeFor(undefined, true), found) || Math.abs(found.x - middle.x) > 1.6 * w || Math.abs(found.y - middle.y) > 5 * h) {
512
+ el.hidden = true;
513
+ continue;
514
+ }
515
+ el.style.transform = `translate(${Math.round(found.x)}px,${Math.round(found.y)}px) translate(-50%,-50%)`;
516
+ take(found.x - w / 2, found.y - h / 2, found.x + w / 2, found.y + h / 2, figure.abbreviation);
517
+ shownFigures += 1;
518
+ }
519
+ }
520
+ for (let i = shownFigures; i < figurePool.length; i += 1)
521
+ figurePool[i].hidden = true;
522
+ }
94
523
  /** The lines and the rings, and the names: drawn again from what `update` laid out. */
95
524
  function drawLines() {
96
525
  const frame = last;
@@ -101,20 +530,18 @@ export function createSkyHost(options) {
101
530
  return;
102
531
  renders += 1;
103
532
  context.clearRect(0, 0, frame.width, frame.height);
104
- if (lines && lines.count > 0) {
533
+ if (lines && drawStrokes && lines.count > 0) {
105
534
  context.lineWidth = 1;
106
535
  context.lineCap = "round";
107
536
  context.strokeStyle = "#cfe0ff";
108
537
  for (const figure of lines.figures) {
109
- const opacity = lines.opacityOf(figure);
538
+ const opacity = figure.abbreviation === hoverAbbr || figure.abbreviation === pickAbbr ? 1 : lines.opacityOf(figure);
110
539
  if (opacity <= 0)
111
540
  continue;
112
541
  context.globalAlpha = opacity;
113
542
  context.beginPath();
114
- for (let i = figure.start; i < figure.end; i += 1) {
115
- context.moveTo(lines.segments[i * 4], lines.segments[i * 4 + 1]);
116
- context.lineTo(lines.segments[i * 4 + 2], lines.segments[i * 4 + 3]);
117
- }
543
+ for (let i = figure.start; i < figure.end; i += 1)
544
+ pathOutside(context, lines.segments[i * 4], lines.segments[i * 4 + 1], lines.segments[i * 4 + 2], lines.segments[i * 4 + 3], covered, 0.75);
118
545
  context.stroke();
119
546
  }
120
547
  context.globalAlpha = 1;
@@ -141,18 +568,8 @@ export function createSkyHost(options) {
141
568
  }
142
569
  }
143
570
  }
144
- // the picked figure's name
145
- if (figureName) {
146
- const name = lines?.name;
147
- if (name) {
148
- figureName.hidden = false;
149
- if (figureName.textContent !== name.text)
150
- figureName.textContent = name.text;
151
- figureName.style.transform = `translate(${Math.round(name.x)}px,${Math.round(name.y)}px) translate(-50%,-100%)`;
152
- }
153
- else
154
- figureName.hidden = true;
155
- }
571
+ // the lit figure's name
572
+ updateFigureName(frame);
156
573
  }
157
574
  function placeNames() {
158
575
  if (!box || !names) {
@@ -203,7 +620,9 @@ export function createSkyHost(options) {
203
620
  */
204
621
  function cullOverlaps(shown) {
205
622
  culled.length = 0;
623
+ starN = 0;
206
624
  let visible = 0;
625
+ const own = shown > 0 ? root.host.getBoundingClientRect() : undefined;
207
626
  const kept = [];
208
627
  for (let i = 0; i < shown; i += 1) {
209
628
  const name = pool[i];
@@ -217,18 +636,16 @@ export function createSkyHost(options) {
217
636
  continue;
218
637
  }
219
638
  const rect = name.getBoundingClientRect();
220
- // a name whose whole top edge is over a body (the Earth, the Moon, the Sun) lies on it: hoshi-stars tests the star's point only, so a name set below a star at the Earth's edge can be left entirely on the Earth, and is left out
221
- const own = covered ? root.host.getBoundingClientRect() : undefined;
222
- if (covered && own) {
223
- const top = rect.top - own.top;
224
- const left = rect.left - own.left;
225
- const right = rect.right - own.left;
226
- if (covered(left, top) && covered((left + right) / 2, top) && covered(right, top)) {
227
- name.hidden = true;
228
- designations[i].hidden = true;
229
- culled.push(true);
230
- continue;
231
- }
639
+ // no part of a name or of its ring is drawn over a body (the Earth, the Moon, the Sun): the sky is behind them. hoshi-stars tests the star's own point only, so a name set beside a star at the Earth's edge can run onto it, and the label (name, ring and all) is left out
640
+ const blocked = keep.length > 0 ? blockedAt : covered;
641
+ // the catalogue letter set under the name is part of the label
642
+ const under = designations[i].hidden || typeof designations[i].getBoundingClientRect !== "function" ? undefined : designations[i].getBoundingClientRect();
643
+ const bottom = under ? Math.max(rect.bottom, under.bottom) : rect.bottom;
644
+ if (blocked && own && (touches(blocked, rect.left - own.left, rect.top - own.top, rect.right - own.left, bottom - own.top, names.labels[i]) || touchesKeep(keep, rect.left - own.left, rect.top - own.top, rect.right - own.left, bottom - own.top))) {
645
+ name.hidden = true;
646
+ designations[i].hidden = true;
647
+ culled.push(true);
648
+ continue;
232
649
  }
233
650
  const over = kept.some((one) => rect.left < one.r && rect.right > one.l && rect.top < one.b && rect.bottom > one.t);
234
651
  if (over) {
@@ -238,11 +655,38 @@ export function createSkyHost(options) {
238
655
  continue;
239
656
  }
240
657
  kept.push({ l: rect.left, t: rect.top, r: rect.right, b: rect.bottom });
658
+ // the boxes of the names that stayed, from the picture's top left, for the constellations' names to keep off
659
+ if (own) {
660
+ const one = (starBoxes[starN] ??= { l: 0, t: 0, r: 0, b: 0 });
661
+ one.l = rect.left - own.left;
662
+ one.t = rect.top - own.top;
663
+ one.r = rect.right - own.left;
664
+ one.b = bottom - own.top;
665
+ starN += 1;
666
+ }
241
667
  culled.push(false);
242
668
  visible += 1;
243
669
  }
244
670
  drawnNames = visible;
245
671
  }
672
+ /** Hides the lit figure's name and the constellations' names. */
673
+ function hideFigures() {
674
+ clearTimeout(fadeTimer);
675
+ if (figureName)
676
+ figureName.hidden = true;
677
+ shownAbbr = null;
678
+ for (const el of figurePool)
679
+ el.hidden = true;
680
+ shownFigures = 0;
681
+ }
682
+ /** The settings no longer ask for the lines: a figure that was picked is let go, and the page is told. */
683
+ function letGo() {
684
+ hoverAbbr = null;
685
+ if (pickAbbr !== null) {
686
+ pickAbbr = null;
687
+ emit("chikyu-constellation-pick", null);
688
+ }
689
+ }
246
690
  const vars = () => {
247
691
  if (!box || !module)
248
692
  return;
@@ -252,13 +696,70 @@ export function createSkyHost(options) {
252
696
  // the case is drawn by the labels' own CSS (small capitals, or the text itself written in capitals or lower case by `labelText`)
253
697
  box.style.setProperty("--hoshi-label-case-variant", (style.case ?? "small-caps") === "small-caps" ? "small-caps" : "normal");
254
698
  };
699
+ /** The sky culture the page asks for, exactly as it sets it: `iau` where it sets none. A value that is not a culture is `iau`, with one warning in the console. */
700
+ const readCulture = () => {
701
+ const raw = options.attribute("constellation-culture");
702
+ const id = raw === null || raw.trim() === "" ? "iau" : raw.trim().toLowerCase();
703
+ if (id === "iau")
704
+ return id;
705
+ if (Object.hasOwn(CULTURES, id) && !cultureFailed.has(id))
706
+ return id;
707
+ if (!warnedCultures.has(id)) {
708
+ warnedCultures.add(id);
709
+ console.warn(`chikyu-earth: constellation-culture="${id}" is not a sky culture here (iau, ${Object.keys(CULTURES).join(", ")}): the IAU's constellations are used.`);
710
+ }
711
+ return "iau";
712
+ };
713
+ const requestCulture = (id) => {
714
+ if (cultureLoading.has(id))
715
+ return;
716
+ cultureLoading.add(id);
717
+ void Promise.all([(options.cultures ?? ((name) => CULTURES[name]()))(id), import("@johnmorrisdotca/hoshi-stars/lines")])
718
+ .then(([loaded, library]) => {
719
+ const info = new Map();
720
+ const figures = [];
721
+ for (const figure of library.figures(loaded)) {
722
+ const a = figure.asterism;
723
+ figures.push({ id: a.id, segments: figure.segments });
724
+ info.set(a.id, { abbreviation: a.id, name: a.name, english: a.names.en ?? a.name, japanese: a.names.ja ?? a.readings.ja ?? a.name, kind: a.kind, names: a.names, ...(a.readings.ja ? { reading: a.readings.ja } : {}) });
725
+ }
726
+ cultureData.set(id, { figures, info });
727
+ cultureLoading.delete(id);
728
+ if (module) {
729
+ configure();
730
+ // a figure the page picked while the culture was on its way
731
+ if (pendingPick !== undefined && lines?.figures.some((f) => f.abbreviation === pendingPick)) {
732
+ setPick(pendingPick, false);
733
+ pendingPick = undefined;
734
+ }
735
+ compute();
736
+ }
737
+ })
738
+ .catch((error) => {
739
+ cultureLoading.delete(id);
740
+ cultureFailed.add(id);
741
+ // not "not a culture": it is one, and could not be had; the IAU's figures are shown in its place
742
+ warnedCultures.add(id);
743
+ console.warn(`chikyu-earth: the sky culture "${id}" could not be loaded, so the IAU's constellations are shown.`);
744
+ options.onError(error);
745
+ if (module) {
746
+ configure();
747
+ compute();
748
+ }
749
+ });
750
+ };
255
751
  const configure = () => {
256
752
  if (!module)
257
753
  return;
754
+ // the texts may be written in another language or look: their sizes are measured again
755
+ sizes.clear();
258
756
  const count = options.attribute("star-names");
259
757
  const magnitude = options.attribute("star-names-magnitude");
260
758
  const settings = module.starNamesFromAttributes(count, magnitude);
261
- const strength = module.lineStrengthFromAttribute(options.attribute("constellation-lines"));
759
+ const linesAttribute = module.lineStrengthFromAttribute(options.attribute("constellation-lines"));
760
+ // the names alone need the figures' places but draw no line: a strength that draws nothing visible, never drawn
761
+ const strength = linesAttribute ?? (options.attribute("constellation-names") !== null ? 0.01 : undefined);
762
+ drawStrokes = linesAttribute !== undefined;
262
763
  const lang = options.language();
263
764
  usedLang = lang;
264
765
  if (settings) {
@@ -269,14 +770,31 @@ export function createSkyHost(options) {
269
770
  }
270
771
  else
271
772
  names = undefined;
272
- if (strength !== undefined) {
773
+ const wantedCulture = readCulture();
774
+ if (strength === undefined)
775
+ lines = undefined;
776
+ else if (wantedCulture !== "iau" && !cultureData.has(wantedCulture)) {
777
+ // the culture's figures are brought in when asked for; until they are here none are drawn, never the IAU's in their place
778
+ requestCulture(wantedCulture);
779
+ if (lines) {
780
+ lines = undefined;
781
+ letGo();
782
+ }
783
+ }
784
+ else {
785
+ if (lines && culture !== wantedCulture) {
786
+ lines = undefined;
787
+ letGo();
788
+ }
789
+ culture = wantedCulture;
790
+ const loaded = module;
273
791
  if (!lines)
274
- lines = module.createFigureLines({ strength, lang, style });
792
+ lines = wantedCulture === "iau" ? loaded.createFigureLines({ strength, lang, style }) : createCultureLines(cultureData.get(wantedCulture).figures, strength, (partial) => loaded.labelStyle(partial), style);
275
793
  else
276
794
  lines.set({ strength, lang, style });
277
795
  }
278
- else
279
- lines = undefined;
796
+ if (!lines || !drawStrokes)
797
+ letGo();
280
798
  vars();
281
799
  };
282
800
  const load = () => {
@@ -289,8 +807,22 @@ export function createSkyHost(options) {
289
807
  module = loaded;
290
808
  if (!style.font)
291
809
  await options.loadFont().catch(() => undefined);
810
+ // the constellations' names (hoshi-stars' own): for the layer of names and for what a pick tells the page
811
+ try {
812
+ const all = await (options.constellations ?? (() => import("@johnmorrisdotca/hoshi-stars/constellations")))();
813
+ iauInfo = new Map(all.constellations().map((c) => [c.abbreviation, { abbreviation: c.abbreviation, name: c.name, english: c.english, japanese: c.japanese, kind: "constellation" }]));
814
+ }
815
+ catch {
816
+ iauInfo = undefined;
817
+ }
292
818
  configure();
293
819
  loading = false;
820
+ // a pick asked for before hoshi-stars was in (kept while the figures of a culture are still on their way)
821
+ if (pendingPick !== undefined && lines) {
822
+ if (lines.figures.some((f) => f.abbreviation === pendingPick))
823
+ setPick(pendingPick, false);
824
+ pendingPick = undefined;
825
+ }
294
826
  compute();
295
827
  })
296
828
  .catch((error) => {
@@ -304,6 +836,8 @@ export function createSkyHost(options) {
304
836
  attached = false;
305
837
  pool.length = 0;
306
838
  designations.length = 0;
839
+ figurePool.length = 0;
840
+ figureName = undefined;
307
841
  options.onError(error);
308
842
  });
309
843
  };
@@ -317,11 +851,18 @@ export function createSkyHost(options) {
317
851
  const discs = frame.discs;
318
852
  covered = frame.covered ?? (discs.length === 0 ? undefined : (x, y) => discs.some((d) => (x - d.x) * (x - d.x) + (y - d.y) * (y - d.y) <= d.radius * d.radius));
319
853
  const view = { width: frame.width, height: frame.height };
854
+ if (keepStale || keepRewatch) {
855
+ measureKeep(keepRewatch);
856
+ keepRewatch = false;
857
+ }
858
+ takenStale = true;
859
+ hulls.length = 0;
320
860
  if (names)
321
- names.update(frame.project, view, covered);
861
+ names.update(frame.project, view, keep.length > 0 ? blockedAt : covered);
322
862
  if (lines)
323
863
  lines.update(frame.project, view, names ? names.labels : undefined);
324
864
  placeNames();
865
+ placeConstellationNames(frame);
325
866
  drawLines();
326
867
  }
327
868
  /** The stars that are named at the last frame: each one's own point on the screen (the label's anchor) and its name, from the picture's top left, without the names the browser's measure left out. */
@@ -344,6 +885,7 @@ export function createSkyHost(options) {
344
885
  doc.addEventListener("kazoku-languagechange", onLanguage);
345
886
  // a font arrives (Michroma, or the one a Japanese name falls back to): the names are measured as they are drawn, so they are laid out again
346
887
  const onFonts = () => {
888
+ sizes.clear();
347
889
  if (module && wanted() && last)
348
890
  compute();
349
891
  };
@@ -364,13 +906,13 @@ export function createSkyHost(options) {
364
906
  name.hidden = true;
365
907
  for (const designation of designations)
366
908
  designation.hidden = true;
367
- if (figureName)
368
- figureName.hidden = true;
909
+ hideFigures();
369
910
  return;
370
911
  }
371
912
  compute();
372
913
  },
373
914
  refresh() {
915
+ keepRewatch = true;
374
916
  if (!wanted()) {
375
917
  names = undefined;
376
918
  lines = undefined;
@@ -380,8 +922,8 @@ export function createSkyHost(options) {
380
922
  name.hidden = true;
381
923
  for (const designation of designations)
382
924
  designation.hidden = true;
383
- if (figureName)
384
- figureName.hidden = true;
925
+ hideFigures();
926
+ letGo();
385
927
  return;
386
928
  }
387
929
  if (!module) {
@@ -391,23 +933,55 @@ export function createSkyHost(options) {
391
933
  configure();
392
934
  compute();
393
935
  },
936
+ setKeepClear(areas) {
937
+ keepList = areas ? [...areas] : [];
938
+ keepRewatch = true;
939
+ keepStale = true;
940
+ if (module && wanted() && last)
941
+ compute();
942
+ },
943
+ pick(abbreviation) {
944
+ if (!lines) {
945
+ pendingPick = abbreviation;
946
+ return;
947
+ }
948
+ const known = abbreviation === null || lines?.figures.some((f) => f.abbreviation === abbreviation);
949
+ if (known)
950
+ setPick(abbreviation, false);
951
+ },
952
+ get picked() {
953
+ return pickAbbr;
954
+ },
394
955
  setStyle(next) {
395
956
  style = next;
957
+ sizes.clear();
396
958
  if (module) {
397
959
  configure();
398
960
  compute();
399
961
  }
400
962
  },
401
963
  get stats() {
402
- return { on: wanted(), loaded: module !== undefined, names: names ? drawnNames : 0, figures: lines?.count ?? 0, picked: lines?.picked?.abbreviation ?? null, renders, lang: usedLang ?? "", stars: starPoints() };
964
+ return { on: wanted(), loaded: module !== undefined, names: names ? drawnNames : 0, figures: lines?.count ?? 0, picked: hoverAbbr ?? pickAbbr, pick: pickAbbr, hover: hoverAbbr, constellations: shownFigures, culture, renders, lang: usedLang ?? "", stars: starPoints() };
403
965
  },
404
966
  dispose() {
967
+ clearTimeout(fadeTimer);
968
+ otherWatch?.disconnect();
969
+ otherWatch = undefined;
970
+ live?.remove();
971
+ keepWatch?.disconnect();
972
+ keepWatch = undefined;
973
+ if (keepEvents) {
974
+ doc.defaultView?.removeEventListener("resize", markStale);
975
+ doc.defaultView?.removeEventListener("scroll", markStale, { capture: true });
976
+ keepEvents = false;
977
+ }
405
978
  doc.removeEventListener("kazoku-languagechange", onLanguage);
406
979
  doc.fonts?.removeEventListener?.("loadingdone", onFonts);
407
980
  canvas?.remove();
408
981
  box?.remove();
409
982
  pool.length = 0;
410
983
  designations.length = 0;
984
+ figurePool.length = 0;
411
985
  },
412
986
  };
413
987
  }