astraeus 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +76 -7
  3. package/package.json +10 -6
  4. package/src/api/AstraeusScene.d.ts +27 -0
  5. package/src/api/AstraeusScene.js +38 -0
  6. package/src/api/AstraeusScene.node.js +37 -0
  7. package/src/api/activity.d.ts +50 -0
  8. package/src/api/activity.js +62 -0
  9. package/src/api/bodies.d.ts +24 -0
  10. package/src/api/bodies.js +24 -0
  11. package/src/api/errors.d.ts +1 -1
  12. package/src/api/group.d.ts +89 -0
  13. package/src/api/group.js +121 -0
  14. package/src/api/index.d.ts +6 -1
  15. package/src/api/index.js +3 -1
  16. package/src/api/index.node.js +8 -0
  17. package/src/api/mount.d.ts +10 -1
  18. package/src/api/mount.js +15 -4
  19. package/src/api/mount.node.js +36 -0
  20. package/src/api/prepared.d.ts +10 -0
  21. package/src/api/prepared.js +5 -0
  22. package/src/api/scene.d.ts +148 -9
  23. package/src/api/scene.js +563 -59
  24. package/src/api/story.d.ts +69 -0
  25. package/src/api/story.js +63 -0
  26. package/src/api/sunOrbit.d.ts +20 -0
  27. package/src/api/sunOrbit.js +85 -0
  28. package/src/api/switches.d.ts +14 -0
  29. package/src/api/switches.js +19 -0
  30. package/src/api/time.d.ts +4 -0
  31. package/src/api/time.js +8 -0
  32. package/src/app/App.d.ts +6 -2
  33. package/src/app/App.js +43 -21
  34. package/src/app/App.node.js +401 -0
  35. package/src/app/AstraeusScene.d.ts +1 -1
  36. package/src/app/DebugOverlay.d.ts +3 -52
  37. package/src/app/DebugOverlay.js +2 -29
  38. package/src/app/PanelLoadBoundary.d.ts +19 -0
  39. package/src/app/PanelLoadBoundary.js +17 -0
  40. package/src/app/SkyView.d.ts +3 -3
  41. package/src/app/SkyView.js +19 -10
  42. package/src/app/debugReadout.d.ts +53 -0
  43. package/src/app/debugReadout.js +30 -0
  44. package/src/app/developerPanels.d.ts +6 -0
  45. package/src/app/developerPanels.js +11 -0
  46. package/src/app/displaySwitches.d.ts +54 -0
  47. package/src/app/displaySwitches.js +48 -0
  48. package/src/app/experienceDefinition.d.ts +13 -1
  49. package/src/app/listSwitch.d.ts +16 -0
  50. package/src/{experiences/showers/showerChoice.js → app/listSwitch.js} +1 -9
  51. package/src/app/metricReadouts.d.ts +1 -1
  52. package/src/app/metricReadouts.js +1 -1
  53. package/src/app/openClock.d.ts +7 -0
  54. package/src/app/openClock.js +14 -0
  55. package/src/app/sceneContentsHooks.d.ts +3 -3
  56. package/src/app/sceneContentsHooks.js +2 -2
  57. package/src/app/sceneDebug.d.ts +1 -1
  58. package/src/app/sceneDebug.js +1 -1
  59. package/src/app/sceneFrame.js +4 -3
  60. package/src/app/sceneFraming.d.ts +13 -0
  61. package/src/app/sceneFraming.js +22 -0
  62. package/src/app/skyModel.js +3 -1
  63. package/src/app/trackedMetrics.d.ts +53 -0
  64. package/src/{experiences/apollo11/spacecraftMetrics.js → app/trackedMetrics.js} +40 -56
  65. package/src/assets/licence.d.ts +1 -0
  66. package/src/assets/pictures.d.ts +1 -1
  67. package/src/assets/sky.d.ts +4 -4
  68. package/src/assets/sky.js +12 -13
  69. package/src/core/bodies/index.d.ts +3 -0
  70. package/src/core/bodies/index.js +3 -1
  71. package/src/core/bodies/io.js +1 -1
  72. package/src/core/bodies/jupiterData.js +2 -2
  73. package/src/core/bodies/jupiterMoons.js +8 -12
  74. package/src/core/bodies/moon.d.ts +8 -0
  75. package/src/core/bodies/moon.js +28 -5
  76. package/src/core/bodies/outerPlanetData.js +7 -7
  77. package/src/core/bodies/planetMoons.js +18 -27
  78. package/src/core/bodies/swiftTuttle.js +2 -0
  79. package/src/core/elementsBody.d.ts +2 -0
  80. package/src/core/elementsBody.js +3 -0
  81. package/src/core/moonTrajectory.js +3 -5
  82. package/src/core/planetModels.js +1 -1
  83. package/src/core/planetSeries.d.ts +2 -0
  84. package/src/core/planetSeries.js +4 -0
  85. package/src/core/provenance.d.ts +7 -2
  86. package/src/core/provenance.js +3 -1
  87. package/src/core/scalePolicy.d.ts +3 -0
  88. package/src/core/scalePolicy.js +2 -0
  89. package/src/core/state.d.ts +1 -0
  90. package/src/shell/AstraeusShell.d.ts +4 -1
  91. package/src/shell/AstraeusShell.js +12 -6
  92. package/src/shell/AstraeusShell.node.js +225 -0
  93. package/src/shell/DisplaySwitches.d.ts +16 -0
  94. package/src/shell/DisplaySwitches.js +31 -0
  95. package/src/shell/StoryPanelView.js +3 -1
  96. package/src/shell/TimelineBar.css +4 -0
  97. package/src/shell/TimelineBar.node.js +75 -0
  98. package/src/shell/TopBar.css +20 -0
  99. package/src/shell/TopBar.d.ts +4 -1
  100. package/src/shell/TopBar.js +3 -2
  101. package/src/shell/TopBar.node.js +14 -0
  102. package/src/shell/experience.d.ts +4 -0
  103. package/src/shell/infoModel.js +3 -1
  104. package/src/shell/phone.css +4 -1
  105. package/src/shell/topBarIcons.d.ts +1 -0
  106. package/src/shell/topBarIcons.js +1 -0
  107. package/src/shell/useDrawers.js +1 -1
  108. package/src/shell/useZoomThrough.d.ts +7 -0
  109. package/src/shell/useZoomThrough.js +51 -0
  110. package/src/synthetic/syntheticDefinition.js +3 -3
  111. package/src/experiences/apollo11/spacecraftMetrics.d.ts +0 -34
  112. package/src/experiences/showers/showerChoice.d.ts +0 -25
@@ -0,0 +1,69 @@
1
+ import { type TimelineEvent } from "../core/events.js";
2
+ import { type Provenance } from "../core/provenance.js";
3
+ import type { TimeBounds } from "../core/trajectory.js";
4
+ import { type PanelLookup, type StoryPanelSet } from "../shell/storyPanels.js";
5
+ import { type TimeInput } from "./time.js";
6
+ /** A timed event: a labelled moment on the timeline. The id is unique among the scene's events. */
7
+ export interface EventInput {
8
+ readonly id: string;
9
+ readonly label: string;
10
+ readonly time: TimeInput;
11
+ /** A free word the timeline may group by, such as "launch". */
12
+ readonly type?: string;
13
+ /** Where this event's time comes from. Shown with the event; an event without one shows the `provenance` of `addEvents`. Malformed: `addEvents` throws "bad-event" naming the event. */
14
+ readonly provenance?: Provenance;
15
+ }
16
+ /** Options of `addEvents`. */
17
+ export interface AddEventsOptions {
18
+ /** Where the event times come from; shown with every event. */
19
+ readonly provenance?: Provenance;
20
+ }
21
+ /**
22
+ * The timeline. With `start` and `end`: its span, the playback speeds offered (`rates`, simulated seconds per real second) and the speed it opens at
23
+ * (`rate`, default 60). With `none: true`: no timeline at all, so the viewer draws no timeline bar; the time is frozen at `at` (else the time of `setTime`),
24
+ * or, when `rate` is given, runs on from there at that rate.
25
+ */
26
+ export type TimelineInput = {
27
+ readonly start: TimeInput;
28
+ readonly end: TimeInput;
29
+ readonly rates?: readonly number[];
30
+ readonly rate?: number; /** True: while playing, reaching the end wraps to the start and plays on. The viewer can still seek and pause. Default false. Not available with `none: true`, where it is ignored. */
31
+ readonly loop?: boolean;
32
+ readonly none?: undefined;
33
+ } | {
34
+ readonly none: true;
35
+ readonly at?: TimeInput;
36
+ readonly rate?: number;
37
+ };
38
+ /** What `setTimeline` was given, checked and converted. */
39
+ export interface TimelineSetting {
40
+ readonly window?: TimeBounds;
41
+ readonly rates?: readonly number[];
42
+ readonly rate?: number;
43
+ /** Playback wraps from the end of the span to its start. */
44
+ readonly loop?: boolean;
45
+ /** No timeline bar. */
46
+ readonly none: boolean;
47
+ /** For no timeline: the moment time is frozen at, or runs on from. */
48
+ readonly atUtcMs?: number;
49
+ }
50
+ /**
51
+ * The raw settings of a scene's story panels: `{ pauseSeconds?, autoOpen?, panels: [{ id, at: { utc } | { event } | { anchor }, title, body, details?, badge, sources, object? }] }`.
52
+ * `badge` is "observed", "modelled" or "illustrative"; `sources` is never empty. A panel's time may name an event of `addEvents` or an anchor of a path, and `object` a
53
+ * body or path of the scene; these are checked when the scene is turned into a definition (mount), and a mistake throws `bad-panels` naming the panel and field.
54
+ */
55
+ export interface StoryPanelsInput {
56
+ /** Seconds playback holds when a panel opens by itself (0 to 20, default 6; 0 never pauses). Playback then restarts, unless the visitor pressed Play during the hold, which ends it at once. */
57
+ readonly pauseSeconds?: number;
58
+ /** Whether panels open by themselves as forward playback crosses them (default true). */
59
+ readonly autoOpen?: boolean;
60
+ readonly panels: readonly unknown[];
61
+ }
62
+ /** Checks a provenance given to `addEvents` (for the whole batch, or for the event `eventId`) and returns it frozen; throws "bad-event" when malformed. */
63
+ export declare function eventProvenanceOf(value: unknown, eventId?: string): Provenance;
64
+ /** The events merged with `inputs`, sorted by time; each needs a distinct non-empty id and label and a valid moment. */
65
+ export declare function eventsOf(inputs: readonly EventInput[], known: readonly TimelineEvent[]): readonly TimelineEvent[];
66
+ /** Checks a `setTimeline` argument and converts its moments. */
67
+ export declare function timelineOf(input: TimelineInput): TimelineSetting;
68
+ /** The story panels resolved against the scene's events, anchors, objects and window; a mistake becomes a `bad-panels` SceneError. */
69
+ export declare function panelsOf(raw: StoryPanelsInput, lookup: PanelLookup): StoryPanelSet;
@@ -0,0 +1,63 @@
1
+ import { createEvents } from "../core/events.js";
2
+ import { createProvenance } from "../core/provenance.js";
3
+ import { parseStoryPanels, StoryPanelError } from "../shell/storyPanels.js";
4
+ import { SceneError } from "./errors.js";
5
+ import { toUtcMs } from "./time.js";
6
+ /** Checks a provenance given to `addEvents` (for the whole batch, or for the event `eventId`) and returns it frozen; throws "bad-event" when malformed. */
7
+ export function eventProvenanceOf(value, eventId) {
8
+ const where = eventId === undefined ? "addEvents: provenance" : `addEvents: event "${eventId}" provenance`;
9
+ try {
10
+ return createProvenance(value);
11
+ }
12
+ catch (error) {
13
+ throw new SceneError("bad-event", `${where} is malformed (${error instanceof Error ? error.message : String(error)})`);
14
+ }
15
+ }
16
+ /** The events merged with `inputs`, sorted by time; each needs a distinct non-empty id and label and a valid moment. */
17
+ export function eventsOf(inputs, known) {
18
+ if (!Array.isArray(inputs))
19
+ throw new SceneError("bad-event", "addEvents: events must be a list");
20
+ const ids = new Set(known.map((event) => event.id));
21
+ const added = inputs.map((input) => {
22
+ if (typeof input?.id !== "string" || input.id === "")
23
+ throw new SceneError("bad-event", "addEvents: every event needs a non-empty id");
24
+ if (typeof input.label !== "string" || input.label === "")
25
+ throw new SceneError("bad-event", `addEvents: event "${input.id}" needs a non-empty label`);
26
+ if (ids.has(input.id))
27
+ throw new SceneError("bad-event", `addEvents: event "${input.id}" appears twice`);
28
+ ids.add(input.id);
29
+ const timeUtcMs = toUtcMs(input.time, `addEvents: event "${input.id}" time`);
30
+ return { id: input.id, label: input.label, timeUtcMs, ...(input.type === undefined ? {} : { type: input.type }) };
31
+ });
32
+ return createEvents([...known, ...added].sort((a, b) => a.timeUtcMs - b.timeUtcMs));
33
+ }
34
+ /** Checks a `setTimeline` argument and converts its moments. */
35
+ export function timelineOf(input) {
36
+ const bad = (message) => new SceneError("bad-timeline", `setTimeline: ${message}`);
37
+ if (typeof input !== "object" || input === null)
38
+ throw bad("give an object such as { start, end } or { none: true }");
39
+ if (input.rate !== undefined && !(Number.isFinite(input.rate) && input.rate !== 0))
40
+ throw bad(`rate must be a finite, non-zero number, got ${String(input.rate)}`);
41
+ if (input.loop !== undefined && typeof input.loop !== "boolean")
42
+ throw bad("loop must be true or false");
43
+ if (input.none === true)
44
+ return { none: true, ...(input.at === undefined ? {} : { atUtcMs: toUtcMs(input.at, "setTimeline at") }), ...(input.rate === undefined ? {} : { rate: input.rate }) };
45
+ const window = { startUtcMs: toUtcMs(input.start, "setTimeline start"), endUtcMs: toUtcMs(input.end, "setTimeline end") };
46
+ if (window.endUtcMs <= window.startUtcMs)
47
+ throw bad("end must be after start");
48
+ const rates = input.rates;
49
+ if (rates !== undefined && (!Array.isArray(rates) || rates.length === 0 || !rates.every((rate) => Number.isFinite(rate) && rate > 0)))
50
+ throw bad("rates must be a non-empty list of positive numbers");
51
+ return { none: false, window, ...(rates === undefined ? {} : { rates }), ...(input.rate === undefined ? {} : { rate: input.rate }), ...(input.loop === true ? { loop: true } : {}) };
52
+ }
53
+ /** The story panels resolved against the scene's events, anchors, objects and window; a mistake becomes a `bad-panels` SceneError. */
54
+ export function panelsOf(raw, lookup) {
55
+ try {
56
+ return parseStoryPanels(raw, lookup);
57
+ }
58
+ catch (error) {
59
+ if (error instanceof StoryPanelError)
60
+ throw new SceneError("bad-panels", `addStoryPanels: ${error.message}`);
61
+ throw error;
62
+ }
63
+ }
@@ -0,0 +1,20 @@
1
+ import type { BodyId } from "../core/body.js";
2
+ import { type EccentricSampling } from "../core/sunCentredSources.js";
3
+ import { type BodyCatalogue } from "../assets/catalogue.js";
4
+ import type { PathLayer } from "../app/experienceDefinition.js";
5
+ /** The id of a body's Sun-orbit line. */
6
+ export declare const sunOrbitIdOf: (id: BodyId) => string;
7
+ /** Whether the catalogue holds this body and it circles the Sun (the catalogue's root). */
8
+ export declare function circlesTheSun(catalogue: BodyCatalogue, id: BodyId): boolean;
9
+ /**
10
+ * The orbit line of a body that circles the Sun: one full turn from `startUtcMs`, from the body's own state source. A body given published elements
11
+ * (`sampling`) is drawn from its periapsis for one period with samples spaced by eccentric anomaly, so a sharp orbit is smooth. Returns undefined when
12
+ * the body completes no turn within the search (a comet's century-long orbit given without elements).
13
+ */
14
+ export declare function sunOrbitLayer(catalogue: BodyCatalogue, id: BodyId, startUtcMs: number, color: string, given?: EccentricSampling): PathLayer | undefined;
15
+ /**
16
+ * The farthest a body that circles the Sun gets from it, in km: a(1+e) when the period and eccentricity are known (published elements or the
17
+ * catalogue's comet sampling; a from Kepler's third law about the Sun), else the largest Sun distance over one full turn of its own state source.
18
+ * A planet's source reads the planet series, so those must be loaded. Throws `no-orbit` for a body that completes no turn in the search.
19
+ */
20
+ export declare function farthestSunDistanceKm(catalogue: BodyCatalogue, id: BodyId, startUtcMs: number, given?: EccentricSampling): number;
@@ -0,0 +1,85 @@
1
+ import { createOrbAstronomyAdapter } from "../core/astronomyAdapter.js";
2
+ import { BUILT_IN_SAMPLING, EARTH_EPHEMERIS } from "../core/bodies/index.js";
3
+ import { createEarthSunTrajectory, fullTurnSpanMs } from "../core/sunCentredSources.js";
4
+ import { rootBodyId } from "../assets/catalogue.js";
5
+ import { SceneError } from "./errors.js";
6
+ const DAY_MS = 86_400_000;
7
+ /** The turn search walks in two-day steps; the longest orbit among the planets is a dozen years. */
8
+ const TURN_STEP_MS = 2 * DAY_MS;
9
+ const TURN_MAX_STEPS = 3_000;
10
+ const TURN_SAMPLES = 361;
11
+ /** The id of a body's Sun-orbit line. */
12
+ export const sunOrbitIdOf = (id) => `${id}-orbit`;
13
+ /** Whether the catalogue holds this body and it circles the Sun (the catalogue's root). */
14
+ export function circlesTheSun(catalogue, id) {
15
+ return catalogue.has(id) && catalogue.get(id).definition.parentId === rootBodyId(catalogue);
16
+ }
17
+ function trajectoryOf(catalogue, id) {
18
+ const adapter = createOrbAstronomyAdapter();
19
+ return id === "earth" ? createEarthSunTrajectory(adapter) : catalogue.get(id).source.create(adapter);
20
+ }
21
+ /**
22
+ * The orbit line of a body that circles the Sun: one full turn from `startUtcMs`, from the body's own state source. A body given published elements
23
+ * (`sampling`) is drawn from its periapsis for one period with samples spaced by eccentric anomaly, so a sharp orbit is smooth. Returns undefined when
24
+ * the body completes no turn within the search (a comet's century-long orbit given without elements).
25
+ */
26
+ export function sunOrbitLayer(catalogue, id, startUtcMs, color, given) {
27
+ const sampling = given ?? BUILT_IN_SAMPLING[id];
28
+ const { definition, visual } = catalogue.get(id);
29
+ const source = trajectoryOf(catalogue, id);
30
+ const span = sampling === undefined ? turnSpan(source, startUtcMs) : { startUtcMs: sampling.periapsisUtcMs, endUtcMs: sampling.periapsisUtcMs + Math.round(sampling.periodMs) };
31
+ if (span === undefined)
32
+ return undefined;
33
+ const provenance = id === "earth" ? EARTH_EPHEMERIS.provenance : definition.accuracy.position;
34
+ return {
35
+ kind: "orbit",
36
+ color: color || visual.material.color,
37
+ source,
38
+ span,
39
+ ...(sampling === undefined ? { samples: TURN_SAMPLES } : { sampling }),
40
+ object: {
41
+ id: sunOrbitIdOf(id),
42
+ partOf: id,
43
+ label: `${definition.label}'s orbit`,
44
+ color: color || visual.material.color,
45
+ labelPriority: 50,
46
+ showLabel: false,
47
+ description: `${definition.label}'s path round the Sun for one full turn, drawn from the same position source that places ${definition.label}.`,
48
+ provenance,
49
+ knownLimitations: [sampling === undefined ? "A turn's samples joined by straight segments." : "One full turn of unperturbed two-body motion from periapsis; samples are spaced by eccentric anomaly and joined by straight segments."],
50
+ },
51
+ };
52
+ }
53
+ function turnSpan(source, startUtcMs) {
54
+ try {
55
+ return { startUtcMs, endUtcMs: startUtcMs + fullTurnSpanMs(source, startUtcMs, TURN_STEP_MS, TURN_MAX_STEPS) };
56
+ }
57
+ catch (error) {
58
+ if (error instanceof RangeError && /no full turn/.test(error.message))
59
+ return undefined;
60
+ throw error;
61
+ }
62
+ }
63
+ /**
64
+ * The farthest a body that circles the Sun gets from it, in km: a(1+e) when the period and eccentricity are known (published elements or the
65
+ * catalogue's comet sampling; a from Kepler's third law about the Sun), else the largest Sun distance over one full turn of its own state source.
66
+ * A planet's source reads the planet series, so those must be loaded. Throws `no-orbit` for a body that completes no turn in the search.
67
+ */
68
+ export function farthestSunDistanceKm(catalogue, id, startUtcMs, given) {
69
+ const sampling = given ?? BUILT_IN_SAMPLING[id];
70
+ if (sampling !== undefined) {
71
+ const gm = catalogue.get(rootBodyId(catalogue)).definition.gmKm3S2;
72
+ const semiMajorKm = Math.cbrt(gm * (sampling.periodMs / 1000 / (2 * Math.PI)) ** 2);
73
+ return semiMajorKm * (1 + sampling.eccentricity);
74
+ }
75
+ const source = trajectoryOf(catalogue, id);
76
+ const span = turnSpan(source, startUtcMs);
77
+ if (span === undefined)
78
+ throw new SceneError("no-orbit", `camera.fitOrbit("${id}"): "${id}" completes no turn within a dozen years and the catalogue does not know its period; add it with addBodyFromElements`);
79
+ let farthest = 0;
80
+ for (let k = 0; k < TURN_SAMPLES; k += 1) {
81
+ const [x, y, z] = source.stateAt(Math.round(span.startUtcMs + ((span.endUtcMs - span.startUtcMs) * k) / (TURN_SAMPLES - 1)), rootBodyId(catalogue)).positionKm;
82
+ farthest = Math.max(farthest, Math.hypot(x, y, z));
83
+ }
84
+ return farthest;
85
+ }
@@ -0,0 +1,14 @@
1
+ import { type DisplaySwitchId, type DisplaySwitchPlace, type DisplaySwitchSettings } from "../app/displaySwitches.js";
2
+ /**
3
+ * Where each display switch shows, and whether it starts on. `orbitLines` is the orbit ring, the trailing arc and the moon orbits as one switch; `labels` is body labels and
4
+ * anchor labels; `milkyWay` is the sky picture. `place` is `"top-bar"` (a button in the bar), `"panel"` (a row in one switch panel opened from the bar) or `"developer"`
5
+ * (only in the Developer drawer, where every switch stays). `on` is the starting state (default on).
6
+ */
7
+ export type SwitchesInput = {
8
+ readonly [id in DisplaySwitchId]?: {
9
+ readonly place: DisplaySwitchPlace;
10
+ readonly on?: boolean;
11
+ };
12
+ };
13
+ /** Checks a `setSwitches` argument against the switch names and places; returns the settings laid over the ones already set. */
14
+ export declare function switchesOf(input: SwitchesInput, known?: DisplaySwitchSettings): DisplaySwitchSettings;
@@ -0,0 +1,19 @@
1
+ import { DISPLAY_SWITCH_IDS, DISPLAY_SWITCH_PLACES } from "../app/displaySwitches.js";
2
+ import { SceneError } from "./errors.js";
3
+ /** Checks a `setSwitches` argument against the switch names and places; returns the settings laid over the ones already set. */
4
+ export function switchesOf(input, known = {}) {
5
+ const bad = (message) => new SceneError("bad-switch", `setSwitches: ${message}`);
6
+ if (typeof input !== "object" || input === null || Array.isArray(input))
7
+ throw bad(`give an object such as { orbitLines: { place: "top-bar" } } (switches: ${DISPLAY_SWITCH_IDS.join(", ")})`);
8
+ const settings = { ...known };
9
+ for (const [id, setting] of Object.entries(input)) {
10
+ if (!DISPLAY_SWITCH_IDS.includes(id))
11
+ throw bad(`"${id}" is not a switch (known: ${DISPLAY_SWITCH_IDS.join(", ")})`);
12
+ if (typeof setting !== "object" || setting === null || !DISPLAY_SWITCH_PLACES.includes(setting.place))
13
+ throw bad(`${id}.place must be one of ${DISPLAY_SWITCH_PLACES.join(", ")}, got ${JSON.stringify(setting?.place)}`);
14
+ if (setting.on !== undefined && typeof setting.on !== "boolean")
15
+ throw bad(`${id}.on must be true or false, got ${JSON.stringify(setting.on)}`);
16
+ settings[id] = { place: setting.place, ...(setting.on === undefined ? {} : { on: setting.on }) };
17
+ }
18
+ return settings;
19
+ }
@@ -0,0 +1,4 @@
1
+ /** A moment: ISO text, a Date, or Unix milliseconds. */
2
+ export type TimeInput = string | number | Date;
3
+ /** Converts a moment to Unix milliseconds, or throws a `bad-time` SceneError naming it. */
4
+ export declare function toUtcMs(time: TimeInput, what?: string): number;
@@ -0,0 +1,8 @@
1
+ import { SceneError } from "./errors.js";
2
+ /** Converts a moment to Unix milliseconds, or throws a `bad-time` SceneError naming it. */
3
+ export function toUtcMs(time, what = "time") {
4
+ const ms = time instanceof Date ? time.getTime() : typeof time === "number" ? time : Date.parse(time);
5
+ if (!Number.isFinite(ms))
6
+ throw new SceneError("bad-time", `${what} "${String(time)}" is not a valid moment; use an ISO text such as "1969-07-20T20:17:40Z", a Date or Unix milliseconds`);
7
+ return ms;
8
+ }
package/src/app/App.d.ts CHANGED
@@ -6,8 +6,12 @@ export declare function hiddenLabelsFrom(search: string, objects: readonly {
6
6
  }[]): Set<string>;
7
7
  /** `?loop=on` or `?loop=off` overrides the experience's own looping setting. */
8
8
  export declare function loopFromSearch(search: string, fallback: boolean): boolean;
9
- /** `onOpenAddress`: the entry's way to open a switch's address in place; without it a switch navigates the page. */
10
- export declare function App({ definition, onOpenAddress }: {
9
+ /**
10
+ * `onOpenAddress`: the entry's way to open a switch's address in place; without it a switch navigates the page.
11
+ * `writeTitle`: whether the page heading is set to the experience's name (default true); `mount` and `AstraeusScene` pass false so a host page keeps its own title.
12
+ */
13
+ export declare function App({ definition, onOpenAddress, writeTitle }: {
11
14
  readonly definition: ExperienceDefinition;
12
15
  readonly onOpenAddress?: (address: string) => void;
16
+ readonly writeTitle?: boolean;
13
17
  }): import("react").JSX.Element;
package/src/app/App.js CHANGED
@@ -1,16 +1,17 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
3
3
  import { createOrbAstronomyAdapter } from "../core/astronomyAdapter.js";
4
4
  import { viewUpFromSearch, viewUpVector } from "./viewUp.js";
5
- import { SimulationClock } from "../core/clock.js";
5
+ import { openClock } from "./openClock.js";
6
6
  import { createSolarSystemScale } from "../core/scalePolicy.js";
7
7
  import { bodySetsOf, cameraReachOf, catalogueOf, compositionOf, experienceWithGroups, groupsOf, initialObjectIdOf, mountedBodiesOf, pageTitleOf, scaleChoiceIdsOf, sceneCenterOf, sunCentredOf, trackedBodiesOf, visualOverridesOf } from "./experienceDefinition.js";
8
8
  import { AstraeusShell } from "../shell/AstraeusShell.js";
9
9
  import { scaleChoicesFor, scalePolicyFor, startScaleFor } from "../shell/scaleModel.js";
10
10
  import { scaleFromSearch, timeFromSearch, viewFromSearch, shareViewLink } from "./viewLink.js";
11
11
  import { Collapsible } from "../shell/Collapsible.js";
12
+ import { PanelLoadBoundary } from "./PanelLoadBoundary.js";
12
13
  import { BOOT_FADE_LIMITS, bootFadeSeconds, saveBootFadeSeconds } from "../shell/bootLoader.js";
13
- import { LabelSettings, UnderTheHoodSettings, ViewLinkReadout, MoonsAndRingsSettings, SkyAndSunSettings, StoryPanelSettings } from "./DeveloperSettings.js";
14
+ import { LabelSettings, UnderTheHoodSettings, ViewLinkReadout, MoonsAndRingsSettings, SkyAndSunSettings, StoryPanelSettings } from "./developerPanels.js";
14
15
  import { DEFAULT_ILLUMINATE_ALL } from "./lighting.js";
15
16
  import { SettingButtons, SettingColor, SettingGroup, SettingSlider } from "./SettingControls.js";
16
17
  import { DEFAULT_TIMELINE_GLOW } from "../shell/timelineGlow.js";
@@ -24,6 +25,7 @@ import { loadStarCatalogue } from "../assets/sky.js";
24
25
  import { resolveSkySettings, withSkyObject } from "./skyModel.js";
25
26
  import { ORBIT_LOOK_LIMITS, resolveOrbitLook } from "../assets/orbitLook.js";
26
27
  import { DEFAULT_BODY_SET_LOOK } from "./bodySet.js";
28
+ import { displaySwitchItems, orbitStart } from "./displaySwitches.js";
27
29
  import { baseGlowOf, glowLookFromSearch, markerSettingsFromSearch } from "./bodyDraw.js";
28
30
  import { brightnessFromSearch, milkyWayFromSearch, skyHiddenBySearch } from "./SkyView.js";
29
31
  /** Frames-per-second readings kept for the graph: one per 250 ms poll, so about 15 seconds. */
@@ -31,7 +33,7 @@ const FPS_HISTORY = 60;
31
33
  /** The sky settings in force: the experience's own, hidden when the address says `?sky=off`. */
32
34
  function skySettingsOf(definition) {
33
35
  const settings = resolveSkySettings(definition.sky);
34
- const milkyWay = milkyWayFromSearch(window.location.search) ?? settings.milkyWay;
36
+ const milkyWay = milkyWayFromSearch(window.location.search) ?? definition.displaySwitches?.milkyWay?.on ?? settings.milkyWay;
35
37
  const starBrightness = brightnessFromSearch(window.location.search, "stars") ?? settings.starBrightness;
36
38
  const milkyWayBrightness = brightnessFromSearch(window.location.search, "milkywaybrightness") ?? settings.milkyWayBrightness;
37
39
  return { ...settings, milkyWay, starBrightness, milkyWayBrightness, visible: settings.visible && !skyHiddenBySearch(window.location.search) };
@@ -55,6 +57,15 @@ export function loopFromSearch(search, fallback) {
55
57
  const value = new URLSearchParams(search).get("loop");
56
58
  return value === "on" ? true : value === "off" ? false : fallback;
57
59
  }
60
+ /** The labels switch's starting state, if the story gave one. */
61
+ function labelStart(definition) {
62
+ return definition.displaySwitches?.labels?.on;
63
+ }
64
+ /** The orbit lines a story starts off: the ring and arc, and the moon orbits. */
65
+ function startOrbitControls(definition) {
66
+ const start = orbitStart(definition.displaySwitches?.orbitLines);
67
+ return start === undefined ? {} : { orbitLook: start.look, bodySetLook: { ...DEFAULT_BODY_SET_LOOK, orbitsOn: false } };
68
+ }
58
69
  function copyOfGlow(look) {
59
70
  return look === undefined ? null : { ...look };
60
71
  }
@@ -74,13 +85,8 @@ function switcherOf(definition, runtime, open) {
74
85
  /** Everything one mounted experience shares: clock, resolver, catalogue and the settings read from its definition and the address. */
75
86
  function buildRuntime(definition) {
76
87
  const adapter = createOrbAstronomyAdapter();
77
- const clock = new SimulationClock(definition.clock.startUtcMs);
78
- clock.setRate(definition.clock.rate);
79
88
  // A copied view link carries the time it was copied at.
80
- const linkedTime = timeFromSearch(window.location.search);
81
- if (linkedTime !== undefined)
82
- clock.seek(linkedTime);
83
- clock.play();
89
+ const clock = openClock(definition, timeFromSearch(window.location.search));
84
90
  // One resolver per mount: every position in the scene comes from it, whatever the scene centre.
85
91
  const resolver = createSceneResolver(adapter, catalogueOf(definition));
86
92
  return {
@@ -115,7 +121,7 @@ function initialSceneControls(definition, runtime, experience, startScale, glowB
115
121
  return {
116
122
  policy: scalePolicyFor(startScale, suppliedPolicies),
117
123
  cameraRequest: null,
118
- showAnchorLabels: false,
124
+ showAnchorLabels: labelStart(definition) === true && runtime.trackedBodies.length > 0,
119
125
  loop: loopFromSearch(search, definition.loop === true),
120
126
  up: viewUpVector(startViewUp(definition)),
121
127
  showMilkyWay: runtime.sky.milkyWay,
@@ -124,7 +130,8 @@ function initialSceneControls(definition, runtime, experience, startScale, glowB
124
130
  starBrightness: runtime.sky.starBrightness,
125
131
  milkyWayBrightness: runtime.sky.milkyWayBrightness,
126
132
  illuminateAll: DEFAULT_ILLUMINATE_ALL,
127
- hiddenLabels: hiddenLabelsFrom(search, experience.objects),
133
+ hiddenLabels: hiddenLabelsFrom(search, labelStart(definition) === undefined ? experience.objects : experience.objects.map(({ id }) => ({ id, showLabel: labelStart(definition) }))),
134
+ ...startOrbitControls(definition),
128
135
  labelObjects: experience.objects,
129
136
  storyMarkers,
130
137
  featureMarkers: featureMarkerSpecs(definition.experience.bodyFeatures),
@@ -135,12 +142,16 @@ function initialSceneControls(definition, runtime, experience, startScale, glowB
135
142
  ...(startView === undefined ? {} : { startView }),
136
143
  };
137
144
  }
138
- /** `onOpenAddress`: the entry's way to open a switch's address in place; without it a switch navigates the page. */
139
- export function App({ definition, onOpenAddress }) {
145
+ /**
146
+ * `onOpenAddress`: the entry's way to open a switch's address in place; without it a switch navigates the page.
147
+ * `writeTitle`: whether the page heading is set to the experience's name (default true); `mount` and `AstraeusScene` pass false so a host page keeps its own title.
148
+ */
149
+ export function App({ definition, onOpenAddress, writeTitle = true }) {
140
150
  // The page heading names the experience once it is open; app.html says only "Astraeus" until then.
141
151
  useEffect(() => {
142
- document.title = pageTitleOf(definition);
143
- }, [definition]);
152
+ if (writeTitle)
153
+ document.title = pageTitleOf(definition);
154
+ }, [definition, writeTitle]);
144
155
  const runtime = useMemo(() => buildRuntime(definition), [definition]);
145
156
  const experienceRuntime = useMemo(() => ({ clock: runtime.clock, resolver: runtime.resolver, catalogue: runtime.catalogue }), [runtime]);
146
157
  // The choices offered, in the experience's order; the solar-system policy enlarges only the bodies the experience names.
@@ -178,18 +189,18 @@ export function App({ definition, onOpenAddress }) {
178
189
  const [developerMode, setDeveloperMode] = useState(false);
179
190
  const [timelineGlow, setTimelineGlow] = useState(DEFAULT_TIMELINE_GLOW);
180
191
  const [phoneLayout, setPhoneLayout] = useState(DEFAULT_PHONE_LAYOUT);
181
- const [anchorLabels, setAnchorLabels] = useState(false);
192
+ const [anchorLabels, setAnchorLabels] = useState(controls.current.showAnchorLabels);
182
193
  const [glowShown, setGlowShown] = useState(copyOfGlow(controls.current.glowLook));
183
194
  const orbitPaths = orbitPathsOf(runtime);
184
195
  const orbitDefault = useMemo(() => resolveOrbitLook(orbitPaths[0]?.look), [orbitPaths]);
185
- const [orbitShown, setOrbitShown] = useState(orbitDefault);
196
+ const [orbitShown, setOrbitShown] = useState({ ...orbitDefault, ...controls.current.orbitLook });
186
197
  const setOrbit = (change) => {
187
198
  controls.current.orbitLook = { ...controls.current.orbitLook, ...change };
188
199
  setOrbitShown({ ...orbitDefault, ...controls.current.orbitLook });
189
200
  };
190
201
  const resetOrbit = () => { delete controls.current.orbitLook; setOrbitShown(orbitDefault); };
191
202
  const bodySets = runtime.bodySets;
192
- const [setLook, setSetLook] = useState(DEFAULT_BODY_SET_LOOK);
203
+ const [setLook, setSetLook] = useState(controls.current.bodySetLook ?? DEFAULT_BODY_SET_LOOK);
193
204
  const changeSetLook = (change) => {
194
205
  const next = { ...(controls.current.bodySetLook ?? DEFAULT_BODY_SET_LOOK), ...change };
195
206
  controls.current.bodySetLook = next;
@@ -287,6 +298,17 @@ export function App({ definition, onOpenAddress }) {
287
298
  return;
288
299
  setViewLink(await shareViewLink({ view, scaleId: scale, up: upChoice, timeUtcMs: runtime.clock.snapshot().timeUtcMs }));
289
300
  };
301
+ const displaySwitches = displaySwitchItems({
302
+ settings: definition.displaySwitches,
303
+ orbit: { present: orbitPaths.length > 0, look: orbitShown, set: setOrbit },
304
+ moons: { present: bodySets.length > 0, look: setLook, set: changeSetLook },
305
+ sky: { present: runtime.sky.visible, on: milkyWayOn, set: (on) => { controls.current.showMilkyWay = on; setMilkyWayOn(on); } },
306
+ labels: {
307
+ objectIds: experience.objects.map((object) => object.id), hidden: hiddenLabels,
308
+ setHidden: (hidden) => { controls.current.hiddenLabels = new Set(hidden); setHiddenLabels(new Set(hidden)); },
309
+ anchorsPresent: runtime.trackedBodies.length > 0, anchors: anchorLabels, setAnchors: (on) => { controls.current.showAnchorLabels = on; setAnchorLabels(on); },
310
+ },
311
+ });
290
312
  const sections = definition.developerSections ?? [];
291
313
  const renderSection = (section) => (_jsxs("section", { className: section.id === "clock" ? "hud-section hud-section-clock" : "hud-section", "aria-labelledby": `developer-${section.id}-heading`, children: [_jsx("h3", { id: `developer-${section.id}-heading`, children: section.heading }), section.render(experienceRuntime)] }, section.id));
292
314
  const hasStoryPanels = (storySet?.panels.length ?? 0) > 0;
@@ -362,7 +384,7 @@ export function App({ definition, onOpenAddress }) {
362
384
  },
363
385
  ];
364
386
  const presentGroups = groups.filter((group) => group !== null);
365
- const developerTools = (_jsxs("div", { className: "hud", children: [_jsxs("header", { className: "developer-heading", children: [_jsx("h2", { children: "Developer tools" }), _jsx("p", { children: "Live readouts, controls and diagnostics for this scene." })] }), presentGroups.map((group, index) => (_jsx(Collapsible, { id: group.id, title: group.title, defaultOpen: index === 0, className: `dev-group${group.className === undefined ? "" : ` ${group.className}`}`, children: group.body }, group.id)))] }));
387
+ const developerTools = (_jsx(PanelLoadBoundary, { children: _jsx(Suspense, { fallback: _jsx("p", { className: "developer-loading", role: "status", children: "Loading developer tools..." }), children: _jsxs("div", { className: "hud", children: [_jsxs("header", { className: "developer-heading", children: [_jsx("h2", { children: "Developer tools" }), _jsx("p", { children: "Live readouts, controls and diagnostics for this scene." })] }), presentGroups.map((group, index) => (_jsx(Collapsible, { id: group.id, title: group.title, defaultOpen: index === 0, className: `dev-group${group.className === undefined ? "" : ` ${group.className}`}`, children: group.body }, group.id)))] }) }) }));
366
388
  return (_jsx(AstraeusShell, { experience: shellExperience, snapshot: clockSnapshot, developerMode: developerMode, onDeveloperModeChange: setDeveloperMode, onTogglePlayback: () => {
367
389
  if (runtime.clock.playing)
368
390
  runtime.clock.pause();
@@ -375,5 +397,5 @@ export function App({ definition, onOpenAddress }) {
375
397
  }, onSeek: (timeUtcMs) => {
376
398
  runtime.clock.seek(timeUtcMs);
377
399
  setClockSnapshot(runtime.clock.snapshot());
378
- }, onCameraRequest: updateCameraRequest, onSelectionChange: updateSelectedObject, scaleId: scale, onScaleChange: updateScale, scaleChoices: scaleChoices, switcher: switcherOf(definition, runtime, onOpenAddress), metricsFor: metricsFor, developerTools: developerTools, storyPanelSettings: { autoOpen: storyAutoOpen, pauseSeconds: storyPauseSeconds }, timelineGlow: timelineGlow, phoneLayout: phoneLayout, highlightedFamily: setLook.highlightFamily, onHighlightFamily: highlightFamily, onSetPlaying: setPlaying, panelRequest: panelRequest, onOpenPanelChange: markOpenPanel, featureRequest: featureRequest, pickRequest: pickRequest, onOpenFeatureChange: markOpenFeature, children: _jsx("div", { className: "canvas-host", children: _jsx(AstraeusScene, { runtime: runtime, controls: controls.current, readout: readout, scaleId: scale }) }) }));
400
+ }, onCameraRequest: updateCameraRequest, onSelectionChange: updateSelectedObject, scaleId: scale, onScaleChange: updateScale, scaleChoices: scaleChoices, switcher: switcherOf(definition, runtime, onOpenAddress), displaySwitches: displaySwitches, metricsFor: metricsFor, developerTools: developerTools, storyPanelSettings: { autoOpen: storyAutoOpen, pauseSeconds: storyPauseSeconds }, timelineGlow: timelineGlow, phoneLayout: phoneLayout, highlightedFamily: setLook.highlightFamily, onHighlightFamily: highlightFamily, onSetPlaying: setPlaying, panelRequest: panelRequest, onOpenPanelChange: markOpenPanel, featureRequest: featureRequest, pickRequest: pickRequest, onOpenFeatureChange: markOpenFeature, children: _jsx("div", { className: "canvas-host", children: _jsx(AstraeusScene, { runtime: runtime, controls: controls.current, readout: readout, scaleId: scale }) }) }));
379
401
  }