astraeus 0.6.0 → 0.8.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 (288) hide show
  1. package/CHANGELOG.md +192 -0
  2. package/README.md +205 -34
  3. package/package.json +5 -4
  4. package/src/api/AstraeusScene.d.ts +24 -6
  5. package/src/api/AstraeusScene.js +46 -19
  6. package/src/api/AstraeusScene.node.js +46 -19
  7. package/src/api/assembleScene.d.ts +36 -0
  8. package/src/api/assembleScene.js +175 -0
  9. package/src/api/bodySetChecks.d.ts +10 -0
  10. package/src/api/bodySetChecks.js +117 -0
  11. package/src/api/bodySetInput.d.ts +81 -0
  12. package/src/api/bodySetInput.js +1 -0
  13. package/src/api/containingBlock.d.ts +6 -0
  14. package/src/api/containingBlock.js +16 -0
  15. package/src/api/data.d.ts +17 -5
  16. package/src/api/data.js +28 -10
  17. package/src/api/definitionOf.d.ts +16 -0
  18. package/src/api/definitionOf.js +20 -0
  19. package/src/api/errors.d.ts +61 -1
  20. package/src/api/frozenCopy.d.ts +6 -0
  21. package/src/api/frozenCopy.js +26 -0
  22. package/src/api/group.d.ts +8 -2
  23. package/src/api/group.js +24 -5
  24. package/src/api/index.d.ts +19 -7
  25. package/src/api/index.js +2 -2
  26. package/src/api/index.node.js +2 -2
  27. package/src/api/listeners.d.ts +5 -0
  28. package/src/api/listeners.js +25 -0
  29. package/src/api/look.d.ts +47 -0
  30. package/src/api/look.js +1 -0
  31. package/src/api/lookInput.d.ts +3 -0
  32. package/src/api/lookInput.js +41 -0
  33. package/src/api/moonPanelInput.d.ts +60 -0
  34. package/src/api/moonPanelInput.js +1 -0
  35. package/src/api/mount.d.ts +10 -16
  36. package/src/api/mount.js +27 -11
  37. package/src/api/mount.node.js +27 -11
  38. package/src/api/pathProvenance.d.ts +15 -6
  39. package/src/api/pathProvenance.js +23 -11
  40. package/src/api/pickerInput.d.ts +25 -0
  41. package/src/api/pickerInput.js +1 -0
  42. package/src/api/planBodies.d.ts +72 -0
  43. package/src/api/planBodies.js +300 -0
  44. package/src/api/planBodySets.d.ts +68 -0
  45. package/src/api/planBodySets.js +234 -0
  46. package/src/api/planCamera.d.ts +83 -0
  47. package/src/api/planCamera.js +184 -0
  48. package/src/api/planGroups.d.ts +36 -0
  49. package/src/api/planGroups.js +103 -0
  50. package/src/api/planMoonPanel.d.ts +19 -0
  51. package/src/api/planMoonPanel.js +104 -0
  52. package/src/api/planPaths.d.ts +40 -0
  53. package/src/api/planPaths.js +212 -0
  54. package/src/api/planPicker.d.ts +12 -0
  55. package/src/api/planPicker.js +40 -0
  56. package/src/api/planPlaces.d.ts +16 -0
  57. package/src/api/planPlaces.js +99 -0
  58. package/src/api/planStory.d.ts +26 -0
  59. package/src/api/planStory.js +66 -0
  60. package/src/api/planTimeline.d.ts +27 -0
  61. package/src/api/planTimeline.js +68 -0
  62. package/src/api/planViews.d.ts +25 -0
  63. package/src/api/planViews.js +35 -0
  64. package/src/api/prepared.js +4 -1
  65. package/src/api/renamedInputs.d.ts +15 -0
  66. package/src/api/renamedInputs.js +39 -0
  67. package/src/api/scene.d.ts +176 -65
  68. package/src/api/scene.js +257 -725
  69. package/src/api/sceneFreeze.d.ts +4 -0
  70. package/src/api/sceneFreeze.js +10 -0
  71. package/src/api/sceneReads.d.ts +171 -0
  72. package/src/api/sceneReads.js +6 -0
  73. package/src/api/sphereOfInfluence.d.ts +20 -0
  74. package/src/api/sphereOfInfluence.js +48 -0
  75. package/src/api/story.d.ts +49 -19
  76. package/src/api/story.js +54 -22
  77. package/src/api/sunOrbit.js +9 -11
  78. package/src/api/time.d.ts +2 -1
  79. package/src/api/time.js +2 -1
  80. package/src/api/viewerCamera.d.ts +22 -0
  81. package/src/api/viewerCamera.js +84 -0
  82. package/src/api/viewerClock.d.ts +30 -0
  83. package/src/api/viewerClock.js +85 -0
  84. package/src/api/viewerFirstDraw.d.ts +14 -0
  85. package/src/api/viewerFirstDraw.js +26 -0
  86. package/src/api/viewerHandle.d.ts +79 -0
  87. package/src/api/viewerHandle.js +31 -0
  88. package/src/api/viewerLink.d.ts +91 -13
  89. package/src/api/viewerLink.js +111 -64
  90. package/src/api/viewerLooks.d.ts +19 -0
  91. package/src/api/viewerLooks.js +37 -0
  92. package/src/api/viewerPicker.d.ts +22 -0
  93. package/src/api/viewerPicker.js +49 -0
  94. package/src/api/viewerSelection.d.ts +25 -0
  95. package/src/api/viewerSelection.js +31 -0
  96. package/src/api/viewerViews.d.ts +10 -0
  97. package/src/api/viewerViews.js +18 -0
  98. package/src/api/viewerZones.d.ts +20 -0
  99. package/src/api/viewerZones.js +47 -0
  100. package/src/api/views.d.ts +41 -0
  101. package/src/api/views.js +82 -0
  102. package/src/app/App.d.ts +5 -3
  103. package/src/app/App.js +211 -75
  104. package/src/app/App.node.js +211 -75
  105. package/src/app/AstraeusScene.d.ts +19 -2
  106. package/src/app/AstraeusScene.js +4 -4
  107. package/src/app/BodyView.d.ts +4 -1
  108. package/src/app/BodyView.js +2 -2
  109. package/src/app/CameraController.d.ts +12 -0
  110. package/src/app/CameraController.js +3 -1
  111. package/src/app/DeveloperSettings.d.ts +1 -4
  112. package/src/app/DeveloperSettings.js +6 -10
  113. package/src/app/FeatureMarkers.d.ts +4 -3
  114. package/src/app/FeatureMarkers.js +8 -13
  115. package/src/app/FrameRateSection.js +2 -1
  116. package/src/app/OrbitSetView.js +1 -1
  117. package/src/app/SettingControls.d.ts +11 -3
  118. package/src/app/SettingControls.js +10 -2
  119. package/src/app/SkyView.d.ts +3 -10
  120. package/src/app/SkyView.js +6 -28
  121. package/src/app/StoryMarkers.d.ts +4 -1
  122. package/src/app/StoryMarkers.js +3 -2
  123. package/src/app/TrackedBodyView.d.ts +1 -1
  124. package/src/app/TrackedBodyView.js +20 -11
  125. package/src/app/address.d.ts +16 -0
  126. package/src/app/address.js +31 -0
  127. package/src/app/bodyDraw.d.ts +10 -7
  128. package/src/app/bodyDraw.js +12 -32
  129. package/src/app/bodyMetrics.js +2 -2
  130. package/src/app/bodySet.d.ts +4 -20
  131. package/src/app/bodySet.js +5 -16
  132. package/src/app/debugReadout.js +1 -1
  133. package/src/app/displaySwitches.d.ts +4 -0
  134. package/src/app/displaySwitches.js +6 -0
  135. package/src/app/experienceDefinition.d.ts +14 -23
  136. package/src/app/listSwitch.d.ts +8 -14
  137. package/src/app/listSwitch.js +3 -10
  138. package/src/app/liveLook.d.ts +39 -0
  139. package/src/app/liveLook.js +66 -0
  140. package/src/app/look.d.ts +36 -0
  141. package/src/app/look.js +61 -0
  142. package/src/app/mission.d.ts +16 -3
  143. package/src/app/mission.js +16 -1
  144. package/src/app/openClock.d.ts +3 -2
  145. package/src/app/openClock.js +3 -3
  146. package/src/app/sceneCamera.d.ts +2 -0
  147. package/src/app/sceneCamera.js +23 -0
  148. package/src/app/sceneFrame.d.ts +6 -4
  149. package/src/app/sceneFrame.js +55 -14
  150. package/src/app/sceneHooks.js +3 -2
  151. package/src/app/style.css +114 -139
  152. package/src/app/trackedMetrics.d.ts +10 -3
  153. package/src/app/trackedMetrics.js +22 -11
  154. package/src/app/viewHiding.d.ts +13 -0
  155. package/src/app/viewHiding.js +37 -0
  156. package/src/app/viewLink.d.ts +10 -32
  157. package/src/app/viewLink.js +10 -49
  158. package/src/app/viewerPort.d.ts +56 -0
  159. package/src/app/views.d.ts +32 -0
  160. package/src/app/views.js +2 -0
  161. package/src/assets/bodies/galileanMoons.js +1 -2
  162. package/src/assets/bodies/io.js +2 -2
  163. package/src/assets/bodies/listedMoons.d.ts +1 -1
  164. package/src/assets/bodies/listedMoons.js +2 -3
  165. package/src/assets/bodies/planetSystemMaps.js +2 -3
  166. package/src/assets/bodies/venus.js +2 -6
  167. package/src/assets/catalogue.js +1 -2
  168. package/src/assets/licence.d.ts +3 -3
  169. package/src/assets/licence.js +3 -3
  170. package/src/assets/pictures.d.ts +15 -12
  171. package/src/assets/pictures.js +24 -20
  172. package/src/assets/sky.d.ts +6 -5
  173. package/src/assets/sky.js +6 -9
  174. package/src/assets/visual.d.ts +4 -0
  175. package/src/core/bodies/index.d.ts +0 -4
  176. package/src/core/bodies/index.js +1 -6
  177. package/src/core/bodies/jupiterData.d.ts +0 -1
  178. package/src/core/bodies/jupiterData.js +2 -5
  179. package/src/core/bodies/moonSystem.d.ts +1 -1
  180. package/src/core/bodies/moonSystem.js +102 -55
  181. package/src/core/bodies/outerPlanetRingData.js +2 -2
  182. package/src/core/bodies/planetTrajectory.js +1 -1
  183. package/src/core/bodySetFamilies.d.ts +20 -0
  184. package/src/core/bodySetFamilies.js +14 -0
  185. package/src/core/chebyshevEphemeris.js +1 -1
  186. package/src/core/elementsBody.d.ts +8 -4
  187. package/src/core/elementsBody.js +32 -11
  188. package/src/core/elementsGroup.d.ts +27 -0
  189. package/src/core/elementsGroup.js +85 -0
  190. package/src/core/events.d.ts +2 -0
  191. package/src/core/events.js +2 -0
  192. package/src/core/illumination.js +1 -1
  193. package/src/core/listedOrbitGroup.d.ts +2 -0
  194. package/src/core/listedOrbitGroup.js +11 -7
  195. package/src/core/moonListText.d.ts +6 -0
  196. package/src/core/moonListText.js +19 -0
  197. package/src/core/moonTrajectory.js +1 -1
  198. package/src/core/pacing.d.ts +38 -3
  199. package/src/core/pacing.js +55 -4
  200. package/src/core/planetModels.js +2 -2
  201. package/src/core/planetSeries.d.ts +8 -0
  202. package/src/core/planetSeries.js +16 -2
  203. package/src/core/pointGroup.js +1 -1
  204. package/src/core/provenance.d.ts +2 -1
  205. package/src/core/provenance.js +2 -2
  206. package/src/core/referenceCenters.js +5 -5
  207. package/src/core/sampledTrajectory.js +1 -1
  208. package/src/core/scalePolicy.d.ts +1 -0
  209. package/src/core/startView.d.ts +19 -0
  210. package/src/core/startView.js +28 -0
  211. package/src/core/state.d.ts +6 -2
  212. package/src/core/state.js +3 -3
  213. package/src/core/storyPanels.d.ts +63 -0
  214. package/src/core/storyPanels.js +111 -0
  215. package/src/core/sunCentredSources.d.ts +4 -0
  216. package/src/core/sunCentredSources.js +9 -2
  217. package/src/core/timeInput.d.ts +4 -0
  218. package/src/core/timeInput.js +4 -0
  219. package/src/shell/AstraeusShell.d.ts +17 -3
  220. package/src/shell/AstraeusShell.js +60 -13
  221. package/src/shell/AstraeusShell.node.js +60 -13
  222. package/src/shell/Collapsible.d.ts +4 -3
  223. package/src/shell/Collapsible.js +5 -5
  224. package/src/shell/ControlsDrawer.d.ts +1 -1
  225. package/src/shell/ControlsDrawer.js +3 -1
  226. package/src/shell/DisplaySwitches.d.ts +18 -1
  227. package/src/shell/DisplaySwitches.js +20 -6
  228. package/src/shell/InfoPanel.d.ts +3 -1
  229. package/src/shell/InfoPanel.js +5 -4
  230. package/src/shell/MoonFamilyPanel.js +1 -1
  231. package/src/shell/ObjectControls.d.ts +3 -1
  232. package/src/shell/ObjectControls.js +2 -2
  233. package/src/shell/Sources.d.ts +5 -3
  234. package/src/shell/Sources.js +5 -5
  235. package/src/shell/StoryPanelView.d.ts +4 -3
  236. package/src/shell/StoryPanelView.js +8 -6
  237. package/src/shell/SwitchControl.d.ts +5 -11
  238. package/src/shell/SwitchControl.js +2 -20
  239. package/src/shell/TimelineBar.css +84 -66
  240. package/src/shell/TimelineBar.d.ts +5 -2
  241. package/src/shell/TimelineBar.js +37 -11
  242. package/src/shell/TimelineBar.node.js +37 -11
  243. package/src/shell/TopBar.css +22 -22
  244. package/src/shell/TopBar.d.ts +9 -3
  245. package/src/shell/TopBar.js +5 -5
  246. package/src/shell/TopBar.node.js +5 -5
  247. package/src/shell/bootLoader.d.ts +4 -10
  248. package/src/shell/bootLoader.js +6 -52
  249. package/src/shell/embedded.css +18 -18
  250. package/src/shell/experience.d.ts +1 -1
  251. package/src/shell/moonFamilies.d.ts +2 -6
  252. package/src/shell/moonFamilies.js +2 -18
  253. package/src/shell/phone.css +58 -58
  254. package/src/shell/storyPanels.d.ts +2 -53
  255. package/src/shell/storyPanels.js +1 -106
  256. package/src/shell/style.css +153 -134
  257. package/src/shell/timelineModel.d.ts +13 -0
  258. package/src/shell/timelineModel.js +25 -0
  259. package/src/shell/useDrawers.d.ts +3 -2
  260. package/src/shell/useDrawers.js +4 -3
  261. package/src/shell/viewCamera.d.ts +4 -0
  262. package/src/shell/viewCamera.js +13 -0
  263. package/src/shell/viewerKeys.d.ts +8 -0
  264. package/src/shell/viewerKeys.js +16 -0
  265. package/src/synthetic/syntheticDefinition.js +20 -24
  266. package/src/synthetic/syntheticJourneyScene.js +14 -4
  267. package/src/synthetic/syntheticProbeDefinition.js +2 -1
  268. package/src/synthetic/syntheticViewsDefinition.d.ts +3 -0
  269. package/src/synthetic/syntheticViewsDefinition.js +38 -0
  270. package/data/moons/jupiter.json +0 -3333
  271. package/data/moons/neptune.json +0 -555
  272. package/data/moons/pluto.json +0 -205
  273. package/data/moons/saturn.json +0 -8267
  274. package/data/moons/uranus.json +0 -887
  275. package/src/app/addressNavigation.d.ts +0 -17
  276. package/src/app/addressNavigation.js +0 -16
  277. package/src/assets/bodies/jupiterMoonCatalogue.d.ts +0 -3
  278. package/src/assets/bodies/jupiterMoonCatalogue.js +0 -4
  279. package/src/assets/bodies/outerPlanetCatalogues.d.ts +0 -7
  280. package/src/assets/bodies/outerPlanetCatalogues.js +0 -8
  281. package/src/assets/bodies/swiftTuttle.d.ts +0 -12
  282. package/src/assets/bodies/swiftTuttle.js +0 -13
  283. package/src/assets/moonCatalogue.d.ts +0 -49
  284. package/src/assets/moonCatalogue.js +0 -80
  285. package/src/core/bodies/outerPlanetData.d.ts +0 -4
  286. package/src/core/bodies/outerPlanetData.js +0 -13
  287. package/src/core/bodies/swiftTuttle.d.ts +0 -46
  288. package/src/core/bodies/swiftTuttle.js +0 -106
@@ -1,11 +1,15 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { useEffect, useRef, useState } from "react";
2
+ import { useEffect, useImperativeHandle, useRef, useState } from "react";
3
3
  import "../app/style.css";
4
4
  import { App } from "../app/App.js";
5
+ import { makeContainingBlock } from "./containingBlock.js";
5
6
  import { prepareScene } from "./prepared.js";
7
+ import { viewerHandleOf } from "./viewerHandle.js";
6
8
  import { ViewerLink } from "./viewerLink.js";
7
9
  const FILL = { width: "100%", height: "100%" };
8
10
  const asError = (cause) => (cause instanceof Error ? cause : new Error(String(cause)));
11
+ /** A camera target as text by value: keys in sorted order, so the same pose with its keys in another order is the same key. */
12
+ const cameraValueKey = (camera) => JSON.stringify(Object.entries(camera).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
9
13
  /**
10
14
  * The full viewer `mount` draws, as a React component: `<AstraeusScene scene={scene} data={[...]} />`. Waits for the scene's data, then draws; cleans up on unmount.
11
15
  * @example
@@ -14,47 +18,70 @@ const asError = (cause) => (cause instanceof Error ? cause : new Error(String(ca
14
18
  * return <div style={{ height: "100vh" }}><AstraeusScene scene={scene} onError={console.error} /></div>;
15
19
  * }
16
20
  */
17
- export function AstraeusScene({ scene, data, onReady, onError, time, rate, onChange, className, style }) {
21
+ export function AstraeusScene({ ref, scene, data, onReady, onError, time, rate, view, camera, onChange, onEventZone, onPick, onFirstDraw, address, developerTools, className, style }) {
18
22
  const [definition, setDefinition] = useState();
19
23
  // The latest data and callbacks, read when the scene is built, so a new array or arrow function each render does not rebuild it.
20
- const latest = useRef({ data, onReady, onError, onChange });
21
- latest.current = { data, onReady, onError, onChange };
24
+ const latest = useRef({ data, onReady, onError, onChange, onEventZone, onPick, onFirstDraw });
25
+ latest.current = { data, onReady, onError, onChange, onEventZone, onPick, onFirstDraw };
22
26
  const [link] = useState(() => new ViewerLink());
27
+ const [handle] = useState(() => viewerHandleOf(link));
28
+ useImperativeHandle(ref, () => handle, [handle]);
23
29
  useEffect(() => {
30
+ link.reopen(); // StrictMode replays this effect after its cleanup closed the link: only a real unmount leaves it closed
24
31
  const stop = link.onChange((change) => latest.current.onChange?.(change));
25
- return () => { stop(); link.close(); };
32
+ const stopZones = link.onEventZone((change) => latest.current.onEventZone?.(change));
33
+ const stopPick = link.onPick((change) => latest.current.onPick?.(change));
34
+ const stopFrame = link.onFirstDraw(() => latest.current.onFirstDraw?.());
35
+ return () => { stop(); stopZones(); stopFrame(); stopPick(); link.close(); };
26
36
  }, [link]);
27
37
  // A Date made fresh each render must not seek again, so the moment is compared by value.
28
38
  const timeKey = time instanceof Date ? time.getTime() : time;
29
- // After the viewer is drawn (its own effects have attached the clock by now), the props take effect.
30
- useEffect(() => {
31
- if (definition === undefined)
32
- return;
39
+ // After the viewer is drawn (its own effects have attached the clock by now), each prop takes effect on its own: once when drawn,
40
+ // then only when that prop changes, so a host change to one never overrides a visitor's later choice of another control.
41
+ const apply = (set) => {
33
42
  try {
34
- if (timeKey !== undefined)
35
- link.setTime(timeKey);
36
- if (rate !== undefined)
37
- link.setRate(rate);
43
+ set();
38
44
  }
39
45
  catch (cause) {
40
46
  latest.current.onError?.(asError(cause));
41
47
  }
42
- }, [definition, link, timeKey, rate]);
48
+ };
49
+ const cameraKey = camera === undefined ? undefined : cameraValueKey(camera);
50
+ const cameraRef = useRef(camera);
51
+ cameraRef.current = camera;
52
+ const drawn = definition !== undefined;
53
+ useEffect(() => { if (drawn && timeKey !== undefined)
54
+ apply(() => link.setTime(timeKey)); }, [drawn, link, timeKey]); // eslint-disable-line react-hooks/exhaustive-deps
55
+ useEffect(() => { if (drawn && rate !== undefined)
56
+ apply(() => link.setRate(rate)); }, [drawn, link, rate]); // eslint-disable-line react-hooks/exhaustive-deps
57
+ useEffect(() => { if (drawn && view !== undefined)
58
+ apply(() => link.setView(view)); }, [drawn, link, view]); // eslint-disable-line react-hooks/exhaustive-deps
59
+ useEffect(() => { if (drawn && cameraRef.current !== undefined)
60
+ apply(() => link.setCamera(cameraRef.current)); }, [drawn, link, cameraKey]); // eslint-disable-line react-hooks/exhaustive-deps
43
61
  useEffect(() => {
44
62
  let open = true;
45
63
  setDefinition(undefined);
64
+ link.detach(); // a rebuild: the old viewer is going, so `onReady` below waits for the new one's attach
46
65
  try {
47
66
  const prepared = prepareScene(scene, latest.current.data);
48
- prepared.ready.then(() => { if (open) {
67
+ prepared.ready.then(() => {
68
+ if (!open)
69
+ return;
49
70
  setDefinition(prepared.definition);
50
- latest.current.onReady?.();
51
- } }, (cause) => { if (open)
71
+ // The viewer attaches its clock in an effect after this render; onReady waits for it, so the handle's reads and sets work inside it.
72
+ void link.whenAttached().then(() => { if (open)
73
+ latest.current.onReady?.(handle); }, () => undefined); // a closed link (unmounted) rejects the wait: onReady does not fire
74
+ }, (cause) => { if (open)
52
75
  latest.current.onError?.(asError(cause)); });
53
76
  }
54
77
  catch (cause) {
55
78
  latest.current.onError?.(asError(cause));
56
79
  }
57
80
  return () => { open = false; };
58
- }, [scene]);
59
- return _jsx("div", { className: className, style: { ...FILL, isolation: "isolate", ...style }, children: definition ? _jsx(App, { definition: definition, writeTitle: false, host: link }) : null });
81
+ }, [scene, link, handle]);
82
+ // The viewer's root fills this wrapper, so it is the containing block (unless the host's own class or style positions it already).
83
+ const wrapper = useRef(null);
84
+ useEffect(() => { if (wrapper.current !== null)
85
+ makeContainingBlock(wrapper.current); }, []);
86
+ return _jsx("div", { ref: wrapper, className: className, style: { ...FILL, isolation: "isolate", ...style }, children: definition ? _jsx(App, { definition: definition, writeTitle: false, address: address === true, developerTools: developerTools === true, host: link }) : null });
60
87
  }
@@ -1,10 +1,14 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { useEffect, useRef, useState } from "react";
2
+ import { useEffect, useImperativeHandle, useRef, useState } from "react";
3
3
  import { App } from "../app/App.node.js";
4
+ import { makeContainingBlock } from "./containingBlock.js";
4
5
  import { prepareScene } from "./prepared.js";
6
+ import { viewerHandleOf } from "./viewerHandle.js";
5
7
  import { ViewerLink } from "./viewerLink.js";
6
8
  const FILL = { width: "100%", height: "100%" };
7
9
  const asError = (cause) => (cause instanceof Error ? cause : new Error(String(cause)));
10
+ /** A camera target as text by value: keys in sorted order, so the same pose with its keys in another order is the same key. */
11
+ const cameraValueKey = (camera) => JSON.stringify(Object.entries(camera).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
8
12
  /**
9
13
  * The full viewer `mount` draws, as a React component: `<AstraeusScene scene={scene} data={[...]} />`. Waits for the scene's data, then draws; cleans up on unmount.
10
14
  * @example
@@ -13,47 +17,70 @@ const asError = (cause) => (cause instanceof Error ? cause : new Error(String(ca
13
17
  * return <div style={{ height: "100vh" }}><AstraeusScene scene={scene} onError={console.error} /></div>;
14
18
  * }
15
19
  */
16
- export function AstraeusScene({ scene, data, onReady, onError, time, rate, onChange, className, style }) {
20
+ export function AstraeusScene({ ref, scene, data, onReady, onError, time, rate, view, camera, onChange, onEventZone, onPick, onFirstDraw, address, developerTools, className, style }) {
17
21
  const [definition, setDefinition] = useState();
18
22
  // The latest data and callbacks, read when the scene is built, so a new array or arrow function each render does not rebuild it.
19
- const latest = useRef({ data, onReady, onError, onChange });
20
- latest.current = { data, onReady, onError, onChange };
23
+ const latest = useRef({ data, onReady, onError, onChange, onEventZone, onPick, onFirstDraw });
24
+ latest.current = { data, onReady, onError, onChange, onEventZone, onPick, onFirstDraw };
21
25
  const [link] = useState(() => new ViewerLink());
26
+ const [handle] = useState(() => viewerHandleOf(link));
27
+ useImperativeHandle(ref, () => handle, [handle]);
22
28
  useEffect(() => {
29
+ link.reopen(); // StrictMode replays this effect after its cleanup closed the link: only a real unmount leaves it closed
23
30
  const stop = link.onChange((change) => latest.current.onChange?.(change));
24
- return () => { stop(); link.close(); };
31
+ const stopZones = link.onEventZone((change) => latest.current.onEventZone?.(change));
32
+ const stopPick = link.onPick((change) => latest.current.onPick?.(change));
33
+ const stopFrame = link.onFirstDraw(() => latest.current.onFirstDraw?.());
34
+ return () => { stop(); stopZones(); stopFrame(); stopPick(); link.close(); };
25
35
  }, [link]);
26
36
  // A Date made fresh each render must not seek again, so the moment is compared by value.
27
37
  const timeKey = time instanceof Date ? time.getTime() : time;
28
- // After the viewer is drawn (its own effects have attached the clock by now), the props take effect.
29
- useEffect(() => {
30
- if (definition === undefined)
31
- return;
38
+ // After the viewer is drawn (its own effects have attached the clock by now), each prop takes effect on its own: once when drawn,
39
+ // then only when that prop changes, so a host change to one never overrides a visitor's later choice of another control.
40
+ const apply = (set) => {
32
41
  try {
33
- if (timeKey !== undefined)
34
- link.setTime(timeKey);
35
- if (rate !== undefined)
36
- link.setRate(rate);
42
+ set();
37
43
  }
38
44
  catch (cause) {
39
45
  latest.current.onError?.(asError(cause));
40
46
  }
41
- }, [definition, link, timeKey, rate]);
47
+ };
48
+ const cameraKey = camera === undefined ? undefined : cameraValueKey(camera);
49
+ const cameraRef = useRef(camera);
50
+ cameraRef.current = camera;
51
+ const drawn = definition !== undefined;
52
+ useEffect(() => { if (drawn && timeKey !== undefined)
53
+ apply(() => link.setTime(timeKey)); }, [drawn, link, timeKey]); // eslint-disable-line react-hooks/exhaustive-deps
54
+ useEffect(() => { if (drawn && rate !== undefined)
55
+ apply(() => link.setRate(rate)); }, [drawn, link, rate]); // eslint-disable-line react-hooks/exhaustive-deps
56
+ useEffect(() => { if (drawn && view !== undefined)
57
+ apply(() => link.setView(view)); }, [drawn, link, view]); // eslint-disable-line react-hooks/exhaustive-deps
58
+ useEffect(() => { if (drawn && cameraRef.current !== undefined)
59
+ apply(() => link.setCamera(cameraRef.current)); }, [drawn, link, cameraKey]); // eslint-disable-line react-hooks/exhaustive-deps
42
60
  useEffect(() => {
43
61
  let open = true;
44
62
  setDefinition(undefined);
63
+ link.detach(); // a rebuild: the old viewer is going, so `onReady` below waits for the new one's attach
45
64
  try {
46
65
  const prepared = prepareScene(scene, latest.current.data);
47
- prepared.ready.then(() => { if (open) {
66
+ prepared.ready.then(() => {
67
+ if (!open)
68
+ return;
48
69
  setDefinition(prepared.definition);
49
- latest.current.onReady?.();
50
- } }, (cause) => { if (open)
70
+ // The viewer attaches its clock in an effect after this render; onReady waits for it, so the handle's reads and sets work inside it.
71
+ void link.whenAttached().then(() => { if (open)
72
+ latest.current.onReady?.(handle); }, () => undefined); // a closed link (unmounted) rejects the wait: onReady does not fire
73
+ }, (cause) => { if (open)
51
74
  latest.current.onError?.(asError(cause)); });
52
75
  }
53
76
  catch (cause) {
54
77
  latest.current.onError?.(asError(cause));
55
78
  }
56
79
  return () => { open = false; };
57
- }, [scene]);
58
- return _jsx("div", { className: className, style: { ...FILL, isolation: "isolate", ...style }, children: definition ? _jsx(App, { definition: definition, writeTitle: false, host: link }) : null });
80
+ }, [scene, link, handle]);
81
+ // The viewer's root fills this wrapper, so it is the containing block (unless the host's own class or style positions it already).
82
+ const wrapper = useRef(null);
83
+ useEffect(() => { if (wrapper.current !== null)
84
+ makeContainingBlock(wrapper.current); }, []);
85
+ return _jsx("div", { ref: wrapper, className: className, style: { ...FILL, isolation: "isolate", ...style }, children: definition ? _jsx(App, { definition: definition, writeTitle: false, address: address === true, developerTools: developerTools === true, host: link }) : null });
59
86
  }
@@ -0,0 +1,36 @@
1
+ import type { ScalePolicy } from "../core/scalePolicy.js";
2
+ import { type BodyMetricKind } from "../app/bodyMetrics.js";
3
+ import type { ExperienceDefinition } from "../app/experienceDefinition.js";
4
+ import type { LookInput } from "./look.js";
5
+ import { type DataSource } from "./data.js";
6
+ import { type SceneCamera } from "./planCamera.js";
7
+ import type { BodyPlan } from "./planBodies.js";
8
+ import type { BodySetPlan } from "./planBodySets.js";
9
+ import type { MoonPanelPlan } from "./planMoonPanel.js";
10
+ import type { PickerPlan } from "./planPicker.js";
11
+ import type { PlacesPlan } from "./planPlaces.js";
12
+ import { type GroupPlan } from "./planGroups.js";
13
+ import { type Tracked } from "./planPaths.js";
14
+ import type { StoryPlan } from "./planStory.js";
15
+ import type { TimelinePlan } from "./planTimeline.js";
16
+ import type { ViewPlan } from "./planViews.js";
17
+ /** What a `Scene` hands the assembler: the planners it has filled, its camera and its scale choice. Internal; never exported from the package. */
18
+ export interface ScenePlanners {
19
+ readonly plan: BodyPlan;
20
+ readonly tracked: ReadonlyMap<string, Tracked>;
21
+ readonly groupPlan: GroupPlan;
22
+ readonly bodySets: BodySetPlan;
23
+ readonly moonPanel: MoonPanelPlan;
24
+ readonly picker: PickerPlan;
25
+ readonly places: PlacesPlan;
26
+ readonly story: StoryPlan;
27
+ readonly timeline: TimelinePlan;
28
+ readonly viewPlan: ViewPlan;
29
+ readonly camera: SceneCamera;
30
+ readonly scale: ScalePolicy;
31
+ readonly scaleOnly: boolean;
32
+ readonly look: LookInput | undefined;
33
+ readonly bodyReadouts: readonly BodyMetricKind[];
34
+ }
35
+ /** The app's plug-in contract for a scene's planners. Throws if the scene is empty or a body needs a data package not passed in `data`. */
36
+ export declare function assembleScene(parts: ScenePlanners, data: readonly DataSource[]): ExperienceDefinition;
@@ -0,0 +1,175 @@
1
+ import { isPlanetId, loadPlanetSeries, planetSeriesLoaded, planetSeriesSpan } from "../core/planetSeries.js";
2
+ import { TimeScaleOutOfRangeError } from "../core/timeScale.js";
3
+ import { catalogue as builtInCatalogue } from "../assets/catalogue.js";
4
+ import { createComposition } from "../assets/compositions.js";
5
+ import { mergePictures } from "../assets/pictures.js";
6
+ import { bodyMetrics } from "../app/bodyMetrics.js";
7
+ import { needsPlanetSeries } from "../app/planetNeeds.js";
8
+ import { createReadoutMetrics } from "../app/trackedMetrics.js";
9
+ import { checkDataSources, installData } from "./data.js";
10
+ import { SceneError } from "./errors.js";
11
+ import { cameraPresetsOf, fitFarthestKm, startPresetEntry, startViewEntry, viewEntries } from "./planCamera.js";
12
+ import { groupLayersEntry, lateGroups } from "./planGroups.js";
13
+ import { autoPaths, checkNamedReadouts, checkReadouts, pathCover } from "./planPaths.js";
14
+ /** The `out-of-span` error naming the planets when the scene's window reaches outside the years the planet series cover (the series are loaded); undefined otherwise. */
15
+ function planetSpanError(ids, window) {
16
+ const planets = ids.filter(isPlanetId);
17
+ if (planets.length === 0 || !planetSeriesLoaded())
18
+ return undefined;
19
+ const span = planetSeriesSpan();
20
+ if (window.startUtcMs >= span.startUtcMs && window.endUtcMs <= span.endUtcMs)
21
+ return undefined;
22
+ const iso = (ms) => new Date(ms).toISOString().slice(0, 10);
23
+ return new SceneError("out-of-span", `${planets.join(", ")} is outside the years the built-in planet series covers: it covers ${iso(span.startUtcMs)} to ${iso(span.endUtcMs)}, but the scene runs ${iso(window.startUtcMs)} to ${iso(window.endUtcMs)}; set the timeline inside that span`);
24
+ }
25
+ /** Throws `out-of-span` naming the planets when the scene's window reaches outside the years the planet series cover (the series are loaded). */
26
+ function checkPlanetSpan(ids, window) {
27
+ const error = planetSpanError(ids, window);
28
+ if (error !== undefined)
29
+ throw error;
30
+ }
31
+ /**
32
+ * The one choke point for planet-series reads during setup (orbit lines, the fit distance, clump groups): checks the span first, and turns a
33
+ * `TimeScaleOutOfRangeError` from the read into the named `out-of-span` error when the window is outside the series, so no setup read can leak the raw one.
34
+ */
35
+ function planetRead(ids, window, read) {
36
+ checkPlanetSpan(ids, window);
37
+ try {
38
+ return read();
39
+ }
40
+ catch (error) {
41
+ if (error instanceof TimeScaleOutOfRangeError)
42
+ throw planetSpanError(ids, window) ?? error;
43
+ throw error;
44
+ }
45
+ }
46
+ /**
47
+ * A setup read in `toDefinition`: an `out-of-span` failure is recorded in `fault` and the read gives `fallback`, so `toDefinition` (and so `mount`) never throws it;
48
+ * `prepare` rejects with the recorded error, which is how it always arrives (once, as `ready` rejecting).
49
+ */
50
+ function deferredRead(ids, window, fault, fallback, read) {
51
+ try {
52
+ return planetRead(ids, window, read);
53
+ }
54
+ catch (error) {
55
+ if (error instanceof SceneError && error.code === "out-of-span") {
56
+ fault.error ??= error;
57
+ return fallback;
58
+ }
59
+ throw error;
60
+ }
61
+ }
62
+ /** The app's plug-in contract for a scene's planners. Throws if the scene is empty or a body needs a data package not passed in `data`. */
63
+ export function assembleScene(parts, data) {
64
+ const { plan, groupPlan, bodySets, moonPanel, places, story, timeline: timelinePlan, viewPlan, camera, tracked: trackedMap } = parts;
65
+ if (plan.bodies.size === 0)
66
+ throw new SceneError("empty-scene", "the scene has no bodies; call addBody before mount");
67
+ checkDataSources(data);
68
+ plan.checkData(data);
69
+ bodySets.checkData(data);
70
+ groupPlan.checkReadouts();
71
+ const ids = [...plan.bodies.keys()];
72
+ const paths = plan.moonPaths();
73
+ const sunCentred = plan.checkSunCentred(ids);
74
+ plan.checkSolarSystemScale(parts.scale, sunCentred);
75
+ for (const entry of trackedMap.values())
76
+ checkReadouts(entry, ids);
77
+ for (const [id, readouts] of plan.readouts)
78
+ checkNamedReadouts(id, readouts, ids, "addBody");
79
+ const entries = [...trackedMap.values()];
80
+ const tracked = entries.map((entry) => entry.body);
81
+ const timeline = timelinePlan.setting;
82
+ const { window, startUtcMs } = timelinePlan.span([...tracked.map((body) => body.trajectory.bounds), ...[...groupPlan.activities.values()].map((activity) => activity.window)]);
83
+ const sunOrbitIds = plan.sunOrbitIds(ids);
84
+ // The farthest distance is worked out in setup, once: now when the planet series are in, else in `prepare` once they are; never in the frame loop.
85
+ const fault = {};
86
+ // `lineFixedTo: "auto"` paths read body states: now when the planet series are in, else in `prepare` once they are (the viewer draws only after it resolves); never per frame.
87
+ const auto = autoPaths(plan.catalogue, entries, tracked, ids);
88
+ auto.now((read) => deferredRead(ids, window, fault, undefined, read));
89
+ const fit = deferredRead(ids, window, fault, undefined, () => fitFarthestKm(camera, plan.catalogue, plan.own, startUtcMs));
90
+ // The lines read planet positions; when the planet series are not loaded yet (a consumer's mount), they are drawn in `prepare`, once the series are in. The viewer draws only after `prepare` resolves.
91
+ const sunPaths = deferredRead(ids, window, fault, [], () => plan.earlySunPaths(sunOrbitIds, startUtcMs, planetSeriesLoaded()));
92
+ const storyPanels = story.panels(window, trackedMap.values(), [...plan.bodies.keys(), ...trackedMap.keys(), ...groupPlan.groups.keys(), ...bodySets.memberIds()]);
93
+ groupPlan.check(ids);
94
+ bodySets.check({ ids, catalogue: plan.catalogue, orbits: plan.orbits });
95
+ // A clump near a body reads its position; with the planet series not loaded yet, those groups are built in `prepare` (the viewer draws only after it resolves).
96
+ const seriesIn = planetSeriesLoaded();
97
+ const late = lateGroups(seriesIn);
98
+ const layers = deferredRead(ids, window, fault, [], () => [...groupPlan.layers(ids, window, startUtcMs, (plan) => !late(plan))]);
99
+ const setLayers = bodySets.layers({ ids, catalogue: plan.catalogue, orbits: plan.orbits, window, startUtcMs });
100
+ const labelled = [...plan.bodies.values(), ...tracked, ...[...groupPlan.groups.values()]].map(({ id, label }) => ({ id, label }));
101
+ const catalogue = plan.catalogue;
102
+ if (camera.following && camera.target !== undefined && camera.followChoices !== undefined && !camera.followChoices.includes(camera.target))
103
+ throw new SceneError("bad-camera", `camera.follow("${camera.target}"): the opening view follows "${camera.target}", which camera.setFollowChoices does not list`);
104
+ story.checkObjects(new Set(labelled.map(({ id }) => id)));
105
+ const objects = [
106
+ ...[...plan.bodies.values()].map((body) => plan.bodyObject(body, ids, sunCentred, camera)),
107
+ ...[...trackedMap.values()].map(({ body, description, knownLimitations, provenanceSpans }) => ({ id: body.id, label: body.label, color: body.color, availability: body.trajectory.bounds, labelPriority: 80, ...plan.labelReach(body.id, sunCentred, camera), provenance: body.provenance, ...(provenanceSpans === undefined ? {} : { provenanceSpans }), ...(description === undefined ? {} : { description }), ...(knownLimitations === undefined ? {} : { knownLimitations }) })),
108
+ ...bodySets.objects({ ids, catalogue: plan.catalogue }),
109
+ ];
110
+ const pictures = mergePictures(data.map((source) => source.pictures));
111
+ const members = new Set(bodySets.memberIds());
112
+ const moonFamilies = moonPanel.list(new Map(objects.filter(({ id }) => plan.bodies.has(id) || members.has(id)).map(({ id, label }) => [id, label])), new Set(ids), plan.catalogue, (picture) => pictures[picture]?.url);
113
+ const bodyFeatures = places.featureSets(new Map(objects.map(({ id, label }) => [id, label])));
114
+ const definition = {
115
+ experience: {
116
+ objects,
117
+ cameraPresets: cameraPresetsOf(labelled, camera.followChoices),
118
+ ...startPresetEntry(camera),
119
+ ...(moonFamilies === undefined ? {} : { moonFamilies }),
120
+ ...(bodyFeatures.length === 0 ? {} : { bodyFeatures }),
121
+ events: story.events,
122
+ ...story.provenanceEntries(),
123
+ ...(storyPanels === undefined ? {} : { storyPanels }),
124
+ ...(timeline?.none === true ? { hideTimeline: true } : {}),
125
+ window,
126
+ ...groupPlan.windowsEntry(),
127
+ rates: timelinePlan.rates(),
128
+ },
129
+ clock: timelinePlan.clock(startUtcMs),
130
+ ...timelinePlan.pacing(story.events),
131
+ ...groupLayersEntry(layers, groupPlan.groups.size > 0, sunOrbitIds.length > 0),
132
+ ...(sunOrbitIds.length === 0 ? {} : { paths: sunPaths }),
133
+ ...(setLayers.length === 0 ? {} : { bodySets: setLayers }),
134
+ ...(plan.catalogue === builtInCatalogue ? {} : { catalogue: plan.catalogue }),
135
+ ...plan.visualOverrides(),
136
+ // The viewer draws only the pictures of the packages passed to it (T-252); nothing is shared between viewers.
137
+ ...picturesEntry(data),
138
+ composition: createComposition(plan.catalogue, { id: "scene", bodies: ids, defaultCenter: ids[0], ...(paths.length === 0 ? {} : { paths }) }),
139
+ scaleChoices: plan.scaleChoices(parts.scale, parts.scaleOnly),
140
+ ...viewPlan.switchesEntry(),
141
+ ...parts.picker.entry(),
142
+ ...(parts.look === undefined ? {} : { look: parts.look }),
143
+ ...viewPlan.viewsEntry({ objects: [...trackedMap.keys(), ...ids, ...groupPlan.groups.keys()], events: story.events.map(({ id }) => id) }, storyPanels),
144
+ ...viewEntries(timeline, camera, fit?.read, pathCover(trackedMap.values(), sunCentred, ids[0])),
145
+ ...startViewEntry(camera),
146
+ trackedBodies: tracked,
147
+ createMetrics: ({ resolver }) => {
148
+ const catalogued = bodyMetrics(resolver, ids, parts.bodyReadouts, catalogue);
149
+ const bodyReadouts = [...plan.readouts].map(([id, specs]) => ({ id, label: plan.bodies.get(id).label, center: ids[0], readouts: specs }));
150
+ const readouts = createReadoutMetrics([...trackedMap.values()].map(({ body, readouts: specs }) => ({ body, readouts: specs })), resolver, undefined, bodyReadouts);
151
+ return (objectId, timeUtcMs) => (groupPlan.groups.has(objectId) ? groupPlan.metrics(objectId, timeUtcMs) : trackedMap.has(objectId) || plan.readouts.has(objectId) ? readouts(objectId, timeUtcMs) : catalogued(objectId, timeUtcMs));
152
+ },
153
+ prepare: async () => {
154
+ if (fault.error !== undefined)
155
+ throw fault.error;
156
+ if (needsPlanetSeries(definition) || auto.later || sunPaths.length < sunOrbitIds.length || groupPlan.groups.size > layers.length)
157
+ await loadPlanetSeries();
158
+ checkPlanetSpan(ids, window);
159
+ auto.settle((read) => planetRead(ids, window, read));
160
+ if (groupPlan.groups.size > layers.length)
161
+ layers.push(...planetRead(ids, window, () => groupPlan.layers(ids, window, startUtcMs, late)));
162
+ if (sunPaths.length < sunOrbitIds.length)
163
+ sunPaths.push(...planetRead(ids, window, () => sunOrbitIds.map((id) => plan.sunPath(id, startUtcMs))));
164
+ if (fit !== undefined)
165
+ planetRead(ids, window, () => fit.settle());
166
+ await installData(data, ids, window, catalogue, bodySets.load());
167
+ },
168
+ };
169
+ return definition;
170
+ }
171
+ /** The viewer's own pictures (those of the packages passed to it); absent when no package brings any. */
172
+ function picturesEntry(data) {
173
+ const pictures = mergePictures(data.map((source) => source.pictures));
174
+ return Object.keys(pictures).length === 0 ? {} : { pictures };
175
+ }
@@ -0,0 +1,10 @@
1
+ import type { BodySetInput } from "./bodySetInput.js";
2
+ import { SceneError } from "./errors.js";
3
+ /** The `bad-body-set` error for a set, naming the call and the set. */
4
+ export declare const bad: (id: unknown, message: string) => SceneError;
5
+ /** The id of a body given as a reference or an id. */
6
+ export declare const idOf: (ref: string | {
7
+ readonly id: string;
8
+ }) => string;
9
+ /** Checks what can be checked before the scene is complete, and says whether the members are listed moons or made-up ones. */
10
+ export declare function checkInput(input: BodySetInput): "listed" | "elements";
@@ -0,0 +1,117 @@
1
+ import { MAX_BODY_SET_FAMILIES } from "../core/bodySetFamilies.js";
2
+ import { listedMoon } from "../core/bodies/listedMoons.js";
3
+ import { SceneError } from "./errors.js";
4
+ import { toUtcMs } from "./time.js";
5
+ const HEX = /^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/;
6
+ const ELEMENT_KEYS = ["semiMajorAxisKm", "eccentricity", "inclinationDeg", "raanDeg", "argumentOfPeriapsisDeg", "trueAnomalyDeg"];
7
+ /** The `bad-body-set` error for a set, naming the call and the set. */
8
+ export const bad = (id, message) => new SceneError("bad-body-set", `addBodySet("${String(id)}"): ${message}`);
9
+ /** The id of a body given as a reference or an id. */
10
+ export const idOf = (ref) => (typeof ref === "string" ? ref : ref?.id);
11
+ const isText = (value) => typeof value === "string" && value !== "";
12
+ const isPositive = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
13
+ const isTexts = (value) => Array.isArray(value) && value.every(isText);
14
+ /** Checks one family's id, label, colour and brightness. */
15
+ function checkFamily(id, family, seen) {
16
+ if (!isText(family?.id))
17
+ throw bad(id, "every family needs a non-empty id");
18
+ if (seen.has(family.id))
19
+ throw bad(id, `family "${family.id}" appears twice`);
20
+ seen.add(family.id);
21
+ if (!isText(family.label))
22
+ throw bad(id, `family "${family.id}" needs a label`);
23
+ if (family.color !== undefined && !(typeof family.color === "string" && HEX.test(family.color)))
24
+ throw bad(id, `family "${family.id}": color "${String(family.color)}" is not a hex colour such as "#9de3a8"`);
25
+ if (family.brightness !== undefined && !isPositive(family.brightness))
26
+ throw bad(id, `family "${family.id}": brightness must be above 0`);
27
+ }
28
+ /** Checks a member's card words: listed flag, facts, known limits, label and radius. */
29
+ function checkMemberCard(id, member) {
30
+ const at = `member "${member.id}"`;
31
+ if (member.listed !== undefined && typeof member.listed !== "boolean")
32
+ throw bad(id, `${at}: listed must be true or false`);
33
+ const facts = member.facts;
34
+ if (facts !== undefined && !(Array.isArray(facts) && facts.every((fact) => isText(fact?.label) && isText(fact.value))))
35
+ throw bad(id, `${at}: facts must be a list of { label, value } with both texts non-empty`);
36
+ if (member.knownLimitations !== undefined && !isTexts(member.knownLimitations))
37
+ throw bad(id, `${at}: knownLimitations must be a list of non-empty texts`);
38
+ if (member.label !== undefined && !isText(member.label))
39
+ throw bad(id, `${at}: label must be a non-empty text`);
40
+ if (member.radiusKm !== undefined && !isPositive(member.radiusKm))
41
+ throw bad(id, `${at}: radiusKm must be above 0`);
42
+ }
43
+ /** Checks the elements of a made-up member: finite numbers, a bound orbit, a known plane and a valid moment. */
44
+ function checkElements(id, member) {
45
+ const at = `member "${member.id}"`;
46
+ const elements = member.elements;
47
+ if (member.label === undefined || member.radiusKm === undefined)
48
+ throw bad(id, `${at} has elements, so it needs a label and a radiusKm`);
49
+ for (const key of ELEMENT_KEYS)
50
+ if (!(typeof elements[key] === "number" && Number.isFinite(elements[key])))
51
+ throw bad(id, `${at}: elements.${key} must be a finite number`);
52
+ if (!(elements.semiMajorAxisKm > 0))
53
+ throw bad(id, `${at}: elements.semiMajorAxisKm must be above 0`);
54
+ if (!(elements.eccentricity >= 0 && elements.eccentricity < 1))
55
+ throw bad(id, `${at}: elements.eccentricity must be at least 0 and below 1`);
56
+ if (!(elements.inclinationDeg >= 0 && elements.inclinationDeg <= 180))
57
+ throw bad(id, `${at}: elements.inclinationDeg must be from 0 to 180`);
58
+ if (elements.plane !== undefined && elements.plane !== "ecliptic-j2000" && elements.plane !== "EQJ")
59
+ throw bad(id, `${at}: elements.plane "${String(elements.plane)}" is not "ecliptic-j2000" or "EQJ"`);
60
+ if (elements.time !== undefined)
61
+ toUtcMs(elements.time, `addBodySet("${id}") member "${member.id}" elements.time`);
62
+ }
63
+ /** Checks one member and says which kind it is: a listed moon (no elements) or a made-up one. */
64
+ function checkMember(id, member, families) {
65
+ if (!isText(member?.id))
66
+ throw bad(id, "every member needs a non-empty id");
67
+ if (!families.has(member.family))
68
+ throw bad(id, `member "${member.id}" is in family "${String(member.family)}", which the set does not list`);
69
+ checkMemberCard(id, member);
70
+ if (member.elements === undefined) {
71
+ if (listedMoon(member.id) === undefined)
72
+ throw bad(id, `member "${member.id}" has no elements and is not a listed moon (listedMoons(planet) names them); give it \`elements\``);
73
+ return "listed";
74
+ }
75
+ checkElements(id, member);
76
+ return "elements";
77
+ }
78
+ /** Checks the bodies, centre gravity, history and balance point a set was given. */
79
+ function checkExtras(id, input, families) {
80
+ const bodies = input.bodies ?? [];
81
+ if (!Array.isArray(bodies) || bodies.some((body) => !isText(idOf(body?.id)) || !families.has(body.family)))
82
+ throw bad(id, "bodies must be a list of { id, family } with a family the set lists");
83
+ if (new Set(bodies.map((body) => idOf(body.id))).size !== bodies.length)
84
+ throw bad(id, "a body appears twice in bodies");
85
+ if (input.centerGmKm3S2 !== undefined && !isPositive(input.centerGmKm3S2))
86
+ throw bad(id, "centerGmKm3S2 must be above 0");
87
+ if (input.orbitHistoryMs !== undefined && !(Number.isFinite(input.orbitHistoryMs) && input.orbitHistoryMs >= 0))
88
+ throw bad(id, "orbitHistoryMs must be 0 or above");
89
+ const balance = input.balancePoint;
90
+ if (balance !== undefined && !(isText(idOf(balance?.body)) && isPositive(balance.gmKm3S2)))
91
+ throw bad(id, "balancePoint needs a body and a gmKm3S2 above 0");
92
+ }
93
+ /** Checks what can be checked before the scene is complete, and says whether the members are listed moons or made-up ones. */
94
+ export function checkInput(input) {
95
+ const id = input?.id;
96
+ if (!isText(id))
97
+ throw bad(id, "the set needs a non-empty id");
98
+ const { families, members } = input;
99
+ if (!Array.isArray(families) || families.length === 0 || families.length > MAX_BODY_SET_FAMILIES)
100
+ throw bad(id, `the set needs 1 to ${MAX_BODY_SET_FAMILIES} families`);
101
+ const familyIds = new Set();
102
+ for (const family of families)
103
+ checkFamily(id, family, familyIds);
104
+ if (!Array.isArray(members) || members.length === 0)
105
+ throw bad(id, "the set needs at least one member; the list is empty");
106
+ const kinds = new Set(members.map((member) => checkMember(id, member, familyIds)));
107
+ if (kinds.size > 1)
108
+ throw bad(id, "its members are a mix of listed moons and made-up ones with elements; a set is one kind or the other");
109
+ if (new Set(members.map((member) => member.id)).size !== members.length)
110
+ throw bad(id, "a member id appears twice");
111
+ if (members.some((member) => member.id === id))
112
+ throw bad(id, "a member cannot have the set's own id");
113
+ if (typeof input.provenance !== "object" || input.provenance === null)
114
+ throw bad(id, "the set needs a provenance");
115
+ checkExtras(id, input, familyIds);
116
+ return [...kinds][0];
117
+ }
@@ -0,0 +1,81 @@
1
+ import type { Provenance } from "../core/provenance.js";
2
+ import type { BodyRef } from "./bodies.js";
3
+ import type { CardFactInput } from "./scene.js";
4
+ import type { TimeInput } from "./time.js";
5
+ /** One family of a body set: members that share an orbit colour and a place in the moon panel. */
6
+ export interface BodySetFamilyInput {
7
+ /** The family's id; distinct within the set. */
8
+ readonly id: string;
9
+ readonly label: string;
10
+ /** Orbit colour as a CSS hex colour; default: the palette in family order. */
11
+ readonly color?: string;
12
+ /** Orbit brightness multiplier, above 0; default 1 (the Developer drawer's family gain). */
13
+ readonly brightness?: number;
14
+ }
15
+ /** The elements of a made-up member on two-body motion about the set's centre. Angles in degrees, length in km. */
16
+ export interface BodySetElementsInput {
17
+ readonly semiMajorAxisKm: number;
18
+ /** At least 0 and below 1: a bound orbit. */
19
+ readonly eccentricity: number;
20
+ readonly inclinationDeg: number;
21
+ readonly raanDeg: number;
22
+ readonly argumentOfPeriapsisDeg: number;
23
+ readonly trueAnomalyDeg: number;
24
+ /** The moment the elements hold; the scene's opening time when absent. */
25
+ readonly time?: TimeInput;
26
+ /** The plane the angles are given in: "ecliptic-j2000" or "EQJ" (default). */
27
+ readonly plane?: "ecliptic-j2000" | "EQJ";
28
+ }
29
+ /** One member of a body set: a dot that is selectable, with an info card. */
30
+ export interface BodySetMemberInput {
31
+ readonly id: string;
32
+ /** The id of one of the set's families. */
33
+ readonly family: string;
34
+ /** Required with `elements`; a listed moon defaults to its own. */
35
+ readonly label?: string;
36
+ /** Required with `elements`; a listed moon defaults to its own. */
37
+ readonly radiusKm?: number;
38
+ /** Absent: `id` is a listed moon of the centre (positions come through `data`); present: a made-up member on two-body motion. All members of a set are one kind or the other. */
39
+ readonly elements?: BodySetElementsInput;
40
+ /** Info card words, as on `addBody`. */
41
+ readonly description?: string;
42
+ readonly facts?: readonly CardFactInput[];
43
+ /** Where this member's position comes from; default: the set's. */
44
+ readonly provenance?: Provenance;
45
+ readonly knownLimitations?: readonly string[];
46
+ /** Whether the Object menu offers it; default false, so a long list does not bury the menu. */
47
+ readonly listed?: boolean;
48
+ }
49
+ /** A body added with `addBody` that belongs to one of the set's families. */
50
+ export interface BodySetBodyInput {
51
+ readonly id: BodyRef | string;
52
+ readonly family: string;
53
+ }
54
+ /** A member or body the centre circles with: orbit lines are drawn about the balance point. */
55
+ export interface BodySetBalanceInput {
56
+ readonly body: BodyRef | string;
57
+ readonly gmKm3S2: number;
58
+ }
59
+ /**
60
+ * Many small bodies about one centre, each selectable, drawn as one batch: dots with a pixel floor, a ball at true size close up, names on hover, tap or near zoom,
61
+ * and one batch of orbit lines coloured by family.
62
+ */
63
+ export interface BodySetInput {
64
+ /** The set's id; not shared with any body, path, group or member. */
65
+ readonly id: string;
66
+ /** The body the members circle; the scene's centre (its first body) when absent. It must be in the scene. */
67
+ readonly center?: BodyRef | string;
68
+ /** One to sixteen families, in order. */
69
+ readonly families: readonly BodySetFamilyInput[];
70
+ readonly members: readonly BodySetMemberInput[];
71
+ /** Bodies added with `addBody` that belong to a family: their orbit lines take its colour, and one with no `orbit` of its own gets its line in this batch. */
72
+ readonly bodies?: readonly BodySetBodyInput[];
73
+ /** Where the positions come from, shown for the set. */
74
+ readonly provenance: Provenance;
75
+ /** Gravity of the centre, km^3/s^2, sizing each orbit line to one lap. Default: the centre's moon system, else its catalogue record; neither throws `bad-body-set`. */
76
+ readonly centerGmKm3S2?: number;
77
+ /** A member or body the centre circles with. Default: the centre's moon system's own when that body is in the set, else none. */
78
+ readonly balancePoint?: BodySetBalanceInput;
79
+ /** How far before the window's start to load positions, ms, so an orbit line can reach back. Default 0. Passed to the moon loader for every moon of the centre the scene holds. */
80
+ readonly orbitHistoryMs?: number;
81
+ }
@@ -0,0 +1 @@
1
+ export {};