@c9up/orbit 0.1.0 → 0.1.2

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 (81) hide show
  1. package/Cargo.lock +9 -16
  2. package/Cargo.toml +4 -0
  3. package/README.md +7 -1
  4. package/android/src/main/java/com/c9up/orbit/OrbitEffects.kt +74 -1
  5. package/android/src/main/java/com/c9up/orbit/OrbitHost.kt +67 -4
  6. package/android/src/main/java/com/c9up/orbit/OrbitInput.kt +90 -8
  7. package/android/src/main/java/com/c9up/orbit/OrbitViews.kt +23 -4
  8. package/crates/orbit-host/Cargo.toml +1 -1
  9. package/crates/orbit-host/src/lib.rs +580 -115
  10. package/crates/orbit-host/src/motion.rs +6 -0
  11. package/crates/orbit-host/src/vector.rs +312 -56
  12. package/dist/color.d.ts.map +1 -1
  13. package/dist/color.js +3 -3
  14. package/dist/color.js.map +1 -1
  15. package/dist/commit.d.ts +38 -0
  16. package/dist/commit.d.ts.map +1 -1
  17. package/dist/commit.js +154 -13
  18. package/dist/commit.js.map +1 -1
  19. package/dist/errors.d.ts +60 -26
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js +85 -11
  22. package/dist/errors.js.map +1 -1
  23. package/dist/host.d.ts.map +1 -1
  24. package/dist/host.js +4 -2
  25. package/dist/host.js.map +1 -1
  26. package/dist/index.d.ts +5 -2
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +6 -1
  29. package/dist/index.js.map +1 -1
  30. package/dist/motion.d.ts.map +1 -1
  31. package/dist/motion.js +7 -6
  32. package/dist/motion.js.map +1 -1
  33. package/dist/pages.d.ts.map +1 -1
  34. package/dist/pages.js +3 -3
  35. package/dist/pages.js.map +1 -1
  36. package/dist/react-native/index.d.ts +9 -1
  37. package/dist/react-native/index.d.ts.map +1 -1
  38. package/dist/react-native/index.js +55 -6
  39. package/dist/react-native/index.js.map +1 -1
  40. package/dist/report.d.ts +13 -0
  41. package/dist/report.d.ts.map +1 -0
  42. package/dist/report.js +22 -0
  43. package/dist/report.js.map +1 -0
  44. package/dist/server.d.ts +27 -3
  45. package/dist/server.d.ts.map +1 -1
  46. package/dist/server.js +15 -7
  47. package/dist/server.js.map +1 -1
  48. package/dist/stack.d.ts.map +1 -1
  49. package/dist/stack.js +3 -3
  50. package/dist/stack.js.map +1 -1
  51. package/dist/styles.d.ts.map +1 -1
  52. package/dist/styles.js +2 -2
  53. package/dist/styles.js.map +1 -1
  54. package/dist/template.d.ts.map +1 -1
  55. package/dist/template.js +56 -12
  56. package/dist/template.js.map +1 -1
  57. package/dist/textDecoder.d.ts +29 -0
  58. package/dist/textDecoder.d.ts.map +1 -0
  59. package/dist/textDecoder.js +149 -0
  60. package/dist/textDecoder.js.map +1 -0
  61. package/dist/url.d.ts.map +1 -1
  62. package/dist/url.js +4 -3
  63. package/dist/url.js.map +1 -1
  64. package/package.json +13 -7
  65. package/scripts/build-android.sh +0 -0
  66. package/src/color.ts +5 -10
  67. package/src/commit.ts +197 -18
  68. package/src/errors.ts +174 -44
  69. package/src/host.ts +4 -5
  70. package/src/index.ts +10 -1
  71. package/src/motion.ts +8 -6
  72. package/src/pages.ts +3 -6
  73. package/src/react-native/index.ts +70 -8
  74. package/src/react-native/react-native.d.ts +8 -0
  75. package/src/report.ts +25 -0
  76. package/src/server.ts +50 -14
  77. package/src/stack.ts +3 -9
  78. package/src/styles.ts +2 -5
  79. package/src/template.ts +65 -41
  80. package/src/textDecoder.ts +162 -0
  81. package/src/url.ts +10 -3
package/src/errors.ts CHANGED
@@ -1,48 +1,178 @@
1
1
  /**
2
- * Orbit's errors.
3
- *
4
- * Every failure carries a stable `code` (`E_ORBIT_<REASON>`), so a caller
5
- * branches on what went wrong rather than on a message.
2
+ * Orbit's errors, one per code. Every failure carries a stable
3
+ * `E_ORBIT_<REASON>` code, so a caller branches on `error.code` or on
4
+ * `instanceof errors.E_ORBIT_…` rather than on a message.
6
5
  */
6
+ import { createError } from "@c9up/flare";
7
7
 
8
- export type OrbitErrorCode =
9
- /** `mount` ran before `useHost` gave orbit a native host. */
10
- | "E_ORBIT_NO_HOST"
11
- /** The native host refused a commit; the message carries its report. */
12
- | "E_ORBIT_COMMIT_FAILED"
13
- /** An element with no native mapping yet (`<select>`, `<canvas>`, or `<text>` / a gradient inside an `<svg>`). */
14
- | "E_ORBIT_UNSUPPORTED_ELEMENT"
15
- /** A block element inside text: native text holds only inline runs. */
16
- | "E_ORBIT_BLOCK_IN_TEXT"
17
- /** `motion=${…}` was not an object of motion values. */
18
- | "E_ORBIT_INVALID_MOTION"
19
- /** `scroll-y=${…}` was not a motion value. */
20
- | "E_ORBIT_INVALID_SCROLL_BINDING"
21
- /** A colour orbit cannot read (named colours other than `transparent`, `hsl()`…). */
22
- | "E_ORBIT_INVALID_COLOR"
23
- /** `<img src>` over plain http: images are fetched over https only. */
24
- | "E_ORBIT_INSECURE_IMAGE_URL"
25
- /** `<img src>` with a scheme that is not an image source (`data:`, `javascript:`…). */
26
- | "E_ORBIT_IMAGE_SOURCE"
27
- /** Two elements of an `each` list share a key: a key names one row. */
28
- | "E_ORBIT_DUPLICATE_KEY"
29
- /** `useScreen()` in a component no screen of a stack built. */
30
- | "E_ORBIT_NO_SCREEN"
31
- /** One stack put in two places: a stack is shown once. */
32
- | "E_ORBIT_STACK_SHOWN"
33
- /** `useStyles` got something other than a table `ream css:compile` wrote. */
34
- | "E_ORBIT_STYLE_TABLE"
35
- /** `serverPages({ server })` over plain http to a host that is not this machine or the emulator's. */
36
- | "E_ORBIT_INSECURE_SERVER"
37
- /** The server named a page the app does not have (`serverPages({ pages })`). */
38
- | "E_ORBIT_UNKNOWN_PAGE";
39
-
40
- export class OrbitError extends Error {
41
- readonly code: OrbitErrorCode;
42
-
43
- constructor(code: OrbitErrorCode, message: string, options?: ErrorOptions) {
44
- super(message, options);
45
- this.name = new.target.name;
46
- this.code = code;
47
- }
8
+ /** `mount` ran before `useHost` gave orbit a native host, or the module is not orbit's host. */
9
+ export const E_ORBIT_NO_HOST = createError<[string]>(
10
+ "[orbit] %s",
11
+ "E_ORBIT_NO_HOST",
12
+ );
13
+
14
+ /** The native host refused a commit; the message carries its report. */
15
+ export const E_ORBIT_COMMIT_FAILED = createError<[unknown]>(
16
+ "[orbit] the host refused a commit: %j",
17
+ "E_ORBIT_COMMIT_FAILED",
18
+ );
19
+
20
+ /**
21
+ * The views of a screen nest deeper than the host lays out (100 levels): the
22
+ * layout recurses once per level on the JS thread's stack, so the host refuses
23
+ * the commit instead of overflowing it.
24
+ */
25
+ export const E_ORBIT_TREE_TOO_DEEP = createError<[string]>(
26
+ "[orbit] %s",
27
+ "E_ORBIT_TREE_TOO_DEEP",
28
+ );
29
+
30
+ /**
31
+ * A value of an `<svg>` the host cannot read (a `NaN` length, unreadable path
32
+ * data, `points` or `transform`): that part of the drawing is left out and the
33
+ * rest drawn. Reported to `mount`'s `onError`, never thrown.
34
+ */
35
+ export const E_ORBIT_SVG_VALUE = createError<[string]>(
36
+ "[orbit] %s",
37
+ "E_ORBIT_SVG_VALUE",
38
+ );
39
+
40
+ /** An element with no native mapping yet (`<select>`, `<canvas>`, or `<text>` / a gradient inside an `<svg>`). */
41
+ export const E_ORBIT_UNSUPPORTED_ELEMENT = createError<[string, string]>(
42
+ "[orbit] <%s> %s",
43
+ "E_ORBIT_UNSUPPORTED_ELEMENT",
44
+ );
45
+
46
+ /** A block element inside text: native text holds only inline runs. */
47
+ export const E_ORBIT_BLOCK_IN_TEXT = createError<[string]>(
48
+ "[orbit] <%s> cannot sit inside text on native",
49
+ "E_ORBIT_BLOCK_IN_TEXT",
50
+ );
51
+
52
+ /** `motion=${…}` was not an object of motion values. The message is aurora's. */
53
+ export const E_ORBIT_INVALID_MOTION = createError<[string]>(
54
+ "%s",
55
+ "E_ORBIT_INVALID_MOTION",
56
+ );
57
+
58
+ /** `scroll-y=${…}` was not a motion value. */
59
+ export const E_ORBIT_INVALID_SCROLL_BINDING = createError(
60
+ "[orbit] scroll-y expects a motion value",
61
+ "E_ORBIT_INVALID_SCROLL_BINDING",
62
+ );
63
+
64
+ /** A colour orbit cannot read (named colours other than `transparent`, `hsl()`…). */
65
+ export const E_ORBIT_INVALID_COLOR = createError<[string]>(
66
+ '[orbit] cannot read the colour "%s"',
67
+ "E_ORBIT_INVALID_COLOR",
68
+ );
69
+
70
+ /** `<img src>` over plain http: images are fetched over https only. */
71
+ export const E_ORBIT_INSECURE_IMAGE_URL = createError<[string]>(
72
+ '[orbit] <img src="%s">: an image is fetched over https only',
73
+ "E_ORBIT_INSECURE_IMAGE_URL",
74
+ );
75
+
76
+ /** `<img src>` with a scheme that is not an image source (`data:`, `javascript:`…). */
77
+ export const E_ORBIT_IMAGE_SOURCE = createError<[string, string]>(
78
+ '[orbit] <img src="%s">: %s',
79
+ "E_ORBIT_IMAGE_SOURCE",
80
+ );
81
+
82
+ /** Two elements of an `each` list share a key: a key names one row. */
83
+ export const E_ORBIT_DUPLICATE_KEY = createError<[string]>(
84
+ "[orbit] each(): two elements share the key %s — a key names one row",
85
+ "E_ORBIT_DUPLICATE_KEY",
86
+ );
87
+
88
+ /** `useScreen()` in a component no screen of a stack built. */
89
+ export const E_ORBIT_NO_SCREEN = createError(
90
+ "[orbit] useScreen() outside a screen: it reads the screen a stack shows, from a component that screen built",
91
+ "E_ORBIT_NO_SCREEN",
92
+ );
93
+
94
+ /** One stack put in two places: a stack is shown once. */
95
+ export const E_ORBIT_STACK_SHOWN = createError(
96
+ "[orbit] a stack is shown in one place: this one is already in a template",
97
+ "E_ORBIT_STACK_SHOWN",
98
+ );
99
+
100
+ /** `useStyles` got something other than a table `ream css:compile` wrote. */
101
+ export const E_ORBIT_STYLE_TABLE = createError(
102
+ "[orbit] not a style table orbit reads (version 1, from ream css:compile)",
103
+ "E_ORBIT_STYLE_TABLE",
104
+ );
105
+
106
+ /** `serverPages({ server })` over plain http to a host that is not this machine or the emulator's. */
107
+ export const E_ORBIT_INSECURE_SERVER = createError<[string]>(
108
+ "[orbit] the server %s is not https (plain http only reaches this machine or the emulator's host)",
109
+ "E_ORBIT_INSECURE_SERVER",
110
+ );
111
+
112
+ /** The server named a page the app does not have (`serverPages({ pages })`). */
113
+ export const E_ORBIT_UNKNOWN_PAGE = createError<[string]>(
114
+ '[orbit] the server named the page "%s", which this app does not have',
115
+ "E_ORBIT_UNKNOWN_PAGE",
116
+ );
117
+
118
+ /** A server connection was asked for a path that resolves to another origin. */
119
+ export const E_ORBIT_FOREIGN_ORIGIN = createError<[string, string]>(
120
+ "[orbit] the connection to %s does not reach %s",
121
+ "E_ORBIT_FOREIGN_ORIGIN",
122
+ );
123
+
124
+ /** The server answered a JSON request with an empty non-2xx response. */
125
+ export const E_ORBIT_SERVER_REQUEST_FAILED = createError<[string, number]>(
126
+ "[orbit] %s answered HTTP %d",
127
+ "E_ORBIT_SERVER_REQUEST_FAILED",
128
+ );
129
+
130
+ /** Server events need an `XMLHttpRequest`, and the platform has none. */
131
+ export const E_ORBIT_NO_XHR = createError(
132
+ "[orbit] server events need XMLHttpRequest",
133
+ "E_ORBIT_NO_XHR",
134
+ );
135
+
136
+ /** An invariant inside orbit broke: a bug in orbit. The site says which one. */
137
+ export const E_ORBIT_INTERNAL = createError<[string]>(
138
+ "[orbit] %s",
139
+ "E_ORBIT_INTERNAL",
140
+ );
141
+
142
+ // The errors below are raised by orbit's stand-ins for the platform's `URL`
143
+ // and `TextDecoder`, which Hermes lacks. Code written against those APIs
144
+ // expects what the WHATWG specs raise — `new URL("bad")` throws a `TypeError`,
145
+ // an unknown encoding label a `RangeError` — so these stay native error
146
+ // classes, named like the platform's own (`name` is `TypeError` /
147
+ // `RangeError`), with the code added. They are not flare exceptions on
148
+ // purpose: a polyfill must not change what the API it replaces throws.
149
+
150
+ /** `URL.createObjectURL` with no platform `URL` to make blob URLs. */
151
+ export class E_ORBIT_OBJECT_URL_UNAVAILABLE extends TypeError {
152
+ static readonly code = "E_ORBIT_OBJECT_URL_UNAVAILABLE";
153
+ readonly code = "E_ORBIT_OBJECT_URL_UNAVAILABLE";
154
+ }
155
+
156
+ /** A URL (or its base) that does not parse. */
157
+ export class E_ORBIT_INVALID_URL extends TypeError {
158
+ static readonly code = "E_ORBIT_INVALID_URL";
159
+ readonly code = "E_ORBIT_INVALID_URL";
160
+ }
161
+
162
+ /** `TextDecoder` given an encoding label other than UTF-8's. */
163
+ export class E_ORBIT_UNSUPPORTED_ENCODING extends RangeError {
164
+ static readonly code = "E_ORBIT_UNSUPPORTED_ENCODING";
165
+ readonly code = "E_ORBIT_UNSUPPORTED_ENCODING";
166
+ }
167
+
168
+ /** `TextDecoder.decode` given something that is not an `ArrayBuffer` or a view on one. */
169
+ export class E_ORBIT_INVALID_DECODER_INPUT extends TypeError {
170
+ static readonly code = "E_ORBIT_INVALID_DECODER_INPUT";
171
+ readonly code = "E_ORBIT_INVALID_DECODER_INPUT";
172
+ }
173
+
174
+ /** A `fatal` `TextDecoder` met bytes that are not valid UTF-8. */
175
+ export class E_ORBIT_INVALID_ENCODED_DATA extends TypeError {
176
+ static readonly code = "E_ORBIT_INVALID_ENCODED_DATA";
177
+ readonly code = "E_ORBIT_INVALID_ENCODED_DATA";
48
178
  }
package/src/host.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { OrbitError } from "./errors.js";
1
+ import { E_ORBIT_NO_HOST } from "./errors.js";
2
2
  import { useNativeMotion } from "./motion.js";
3
3
 
4
4
  /**
@@ -83,10 +83,9 @@ export function useHost(next: OrbitHost): void {
83
83
 
84
84
  export function currentHost(): OrbitHost {
85
85
  if (host === null) {
86
- throw new OrbitError(
87
- "E_ORBIT_NO_HOST",
88
- `[orbit] no native host: call useHost(TurboModuleRegistry.getEnforcing("${NATIVE_MODULE_NAME}")) before mount()`,
89
- );
86
+ throw new E_ORBIT_NO_HOST([
87
+ `no native host: call useHost(TurboModuleRegistry.getEnforcing("${NATIVE_MODULE_NAME}")) before mount()`,
88
+ ]);
90
89
  }
91
90
  return host;
92
91
  }
package/src/index.ts CHANGED
@@ -20,7 +20,11 @@ export {
20
20
  type OrbitReport,
21
21
  type Root,
22
22
  } from "./commit.js";
23
- export { OrbitError, type OrbitErrorCode } from "./errors.js";
23
+
24
+ // Not `export * as errors from`: React Native's Babel preset (what Metro runs
25
+ // over node_modules) does not transform an export namespace, and the bundle fails.
26
+ import * as errors from "./errors.js";
27
+
24
28
  export { NATIVE_MODULE_NAME, type OrbitHost, useHost } from "./host.js";
25
29
  export {
26
30
  bindMotion,
@@ -33,10 +37,12 @@ export {
33
37
  } from "./motion.js";
34
38
  /** The app's ream server, one connection for pages, comet and relay. */
35
39
  export {
40
+ type ConnectOptions,
36
41
  connectServer,
37
42
  type ServerConnection,
38
43
  type ServerEvent,
39
44
  ServerEventStream,
45
+ type TokenStore,
40
46
  } from "./server.js";
41
47
  export {
42
48
  createStack,
@@ -56,5 +62,8 @@ export {
56
62
  useStyles,
57
63
  } from "./styles.js";
58
64
  export { type GestureEvent, mount } from "./template.js";
65
+ /** A standard UTF-8 `TextDecoder` where the engine has none (Hermes). */
66
+ export { installTextDecoder, StandardTextDecoder } from "./textDecoder.js";
59
67
  /** A standard `URL` in place of the platform's, when it is not one (React Native's). */
60
68
  export { installStandardUrl, StandardURL } from "./url.js";
69
+ export { errors };
package/src/motion.ts CHANGED
@@ -6,14 +6,13 @@
6
6
  * API.
7
7
  */
8
8
  import {
9
- AuroraError,
10
9
  type MotionDriver,
11
10
  type MotionStyle,
12
11
  type MotionValue,
13
12
  readMotionStyle,
14
13
  setMotionDriver,
15
14
  } from "@c9up/aurora/core";
16
- import { OrbitError } from "./errors.js";
15
+ import { E_ORBIT_INVALID_MOTION } from "./errors.js";
17
16
  import { currentHost } from "./host.js";
18
17
 
19
18
  export {
@@ -76,10 +75,13 @@ export function readMotion(value: unknown): MotionStyle {
76
75
  try {
77
76
  return readMotionStyle(value);
78
77
  } catch (error) {
79
- if (error instanceof AuroraError) {
80
- throw new OrbitError("E_ORBIT_INVALID_MOTION", error.message, {
81
- cause: error,
82
- });
78
+ // Matched by code, not by class: the code is aurora's contract, and it
79
+ // holds whichever aurora release the app resolves.
80
+ if (
81
+ error instanceof Error &&
82
+ Reflect.get(error, "code") === "E_AURORA_INVALID_MOTION"
83
+ ) {
84
+ throw new E_ORBIT_INVALID_MOTION([error.message], { cause: error });
83
85
  }
84
86
  throw error;
85
87
  }
package/src/pages.ts CHANGED
@@ -27,7 +27,7 @@ import {
27
27
  type PhotonHost,
28
28
  router,
29
29
  } from "@c9up/photon/client/core";
30
- import { OrbitError } from "./errors.js";
30
+ import { E_ORBIT_INTERNAL, E_ORBIT_UNKNOWN_PAGE } from "./errors.js";
31
31
  import { connectServer, type ServerConnection } from "./server.js";
32
32
  import { createStack, type Stack, type StackOptions } from "./stack.js";
33
33
  import { setLinkHandler } from "./template.js";
@@ -99,7 +99,7 @@ export function serverPages(options: ServerPagesOptions): Stack {
99
99
  const current = (): Entry => {
100
100
  const entry = entries.at(-1);
101
101
  if (entry === undefined)
102
- throw new Error("[orbit] server pages: empty history");
102
+ throw new E_ORBIT_INTERNAL(["server pages: empty history"]);
103
103
  return entry;
104
104
  };
105
105
  const absolute = (url: string): string => new URL(url, current().url).href;
@@ -170,10 +170,7 @@ export function serverPages(options: ServerPagesOptions): Stack {
170
170
  ? options.pages[name]
171
171
  : undefined;
172
172
  if (page === undefined) {
173
- throw new OrbitError(
174
- "E_ORBIT_UNKNOWN_PAGE",
175
- `[orbit] the server named the page "${name}", which this app does not have`,
176
- );
173
+ throw new E_ORBIT_UNKNOWN_PAGE([name]);
177
174
  }
178
175
  return { default: page };
179
176
  };
@@ -19,22 +19,28 @@ import type { TemplateResult } from "@c9up/aurora/renderer";
19
19
  // into it and Metro serves it under this name.
20
20
  import styles from "@c9up/orbit-styles";
21
21
  import {
22
+ Appearance,
22
23
  AppRegistry,
23
24
  BackHandler,
24
25
  Dimensions,
25
26
  TurboModuleRegistry,
26
27
  } from "react-native";
27
- import { OrbitError } from "../errors.js";
28
+ import type { Root } from "../commit.js";
29
+ import { E_ORBIT_NO_HOST } from "../errors.js";
28
30
  import { NATIVE_MODULE_NAME, type OrbitHost, useHost } from "../host.js";
29
31
  import { goBack } from "../stack.js";
30
- import { useStyles } from "../styles.js";
32
+ import { colorScheme, useStyles } from "../styles.js";
31
33
  import { mount } from "../template.js";
34
+ import { installTextDecoder } from "../textDecoder.js";
32
35
  import { installStandardUrl } from "../url.js";
33
36
 
34
37
  // Before the app's own modules run: React Native's URL resolves a relative
35
38
  // reference by appending it to the base, and photon's router (and any code
36
39
  // shared with the browser) needs the standard one.
37
40
  installStandardUrl();
41
+ // Hermes has TextEncoder but no TextDecoder: libraries shared with the web
42
+ // (msgpack, protobuf…) would die at load.
43
+ installTextDecoder();
38
44
 
39
45
  /** The name the generated activity starts the app by. */
40
46
  export const APP_NAME = "main";
@@ -58,19 +64,75 @@ function isOrbitHost(value: unknown): value is OrbitHost {
58
64
  );
59
65
  }
60
66
 
67
+ export interface RunOptions {
68
+ /**
69
+ * `system` (default): `dark:` follows the phone's setting, as a browser's
70
+ * `prefers-color-scheme` — until the app sets `colorScheme(…)` itself.
71
+ * `light` / `dark`: that one, whatever the phone says.
72
+ */
73
+ colorScheme?: "system" | "light" | "dark";
74
+ }
75
+
76
+ /**
77
+ * Follow the phone's light / dark setting into `colorScheme`, as long as the
78
+ * app has not chosen one itself (a value set by anything else stops it).
79
+ */
80
+ function followSystemScheme(): void {
81
+ const read = (
82
+ value: "light" | "dark" | null | undefined,
83
+ ): "light" | "dark" => (value === "dark" ? "dark" : "light");
84
+ let set = read(Appearance.getColorScheme());
85
+ colorScheme(set);
86
+ const subscription = Appearance.addChangeListener(({ colorScheme: next }) => {
87
+ if (colorScheme() !== set) {
88
+ subscription.remove();
89
+ return;
90
+ }
91
+ set = read(next);
92
+ colorScheme(set);
93
+ });
94
+ }
95
+
96
+ /**
97
+ * React Native stops the activity's surface when the activity goes — recreated
98
+ * for a change it does not handle (font size, language, display size), or
99
+ * finished by the back button — through a global only React's renderer
100
+ * installs: without it the call throws and the app dies. orbit's tree outlives
101
+ * the activity, so there is nothing to stop: the next activity shows it again.
102
+ */
103
+ function installStopSurface(): void {
104
+ const global = globalThis as { RN$stopSurface?: (surfaceId: number) => void };
105
+ global.RN$stopSurface ??= () => {};
106
+ }
107
+
61
108
  /** Register `root` as the app and mount it when the activity starts. */
62
- export function run(root: (props: LaunchProps) => TemplateResult): void {
109
+ export function run(
110
+ root: (props: LaunchProps) => TemplateResult,
111
+ options: RunOptions = {},
112
+ ): void {
113
+ installStopSurface();
114
+ let mounted: Root | null = null;
63
115
  AppRegistry.registerRunnable(APP_NAME, ({ initialProps }) => {
116
+ // A new activity (the last one was recreated or closed): the app, its
117
+ // state and its listeners are still here, only its views are new.
118
+ if (mounted) {
119
+ mounted.remount();
120
+ return;
121
+ }
64
122
  const host = TurboModuleRegistry.getEnforcing(NATIVE_MODULE_NAME);
65
123
  if (!isOrbitHost(host)) {
66
- throw new OrbitError(
67
- "E_ORBIT_NO_HOST",
68
- `[orbit] the ${NATIVE_MODULE_NAME} module is not orbit's native host: is the app built by ream android:build?`,
69
- );
124
+ throw new E_ORBIT_NO_HOST([
125
+ `the ${NATIVE_MODULE_NAME} module is not orbit's native host: is the app built by ream android:build?`,
126
+ ]);
70
127
  }
71
128
  useHost(host);
72
129
  useStyles(styles);
130
+ const scheme = options.colorScheme ?? "system";
131
+ if (scheme === "system") followSystemScheme();
132
+ else colorScheme(scheme);
73
133
  BackHandler.addEventListener("hardwareBackPress", goBack);
74
- mount(root(initialProps ?? {}), { viewport: Dimensions.get("window") });
134
+ mounted = mount(root(initialProps ?? {}), {
135
+ viewport: Dimensions.get("window"),
136
+ });
75
137
  });
76
138
  }
@@ -25,6 +25,14 @@ declare module "react-native" {
25
25
  export const Dimensions: {
26
26
  get(dimension: "window"): { width: number; height: number };
27
27
  };
28
+ export const Appearance: {
29
+ getColorScheme(): "light" | "dark" | null | undefined;
30
+ addChangeListener(
31
+ listener: (preferences: {
32
+ colorScheme: "light" | "dark" | null | undefined;
33
+ }) => void,
34
+ ): { remove(): void };
35
+ };
28
36
  export const TurboModuleRegistry: {
29
37
  getEnforcing(name: string): unknown;
30
38
  };
package/src/report.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Where orbit tells the app about a failure it recovered from instead of
3
+ * throwing: a commit the host refused while nobody was waiting on it (a
4
+ * scheduled commit), an image address from data orbit will not load, a value
5
+ * in a drawing the host left out. `mount({ onError })` sets the listener; with
6
+ * none, a development build (React Native's `__DEV__`) logs it with
7
+ * `console.warn` and a production build says nothing.
8
+ */
9
+
10
+ export type ErrorListener = (error: Error) => void;
11
+
12
+ let listener: ErrorListener | null = null;
13
+
14
+ /** The listener `mount` was given (null: the default described above). */
15
+ export function setErrorListener(next: ErrorListener | null): void {
16
+ listener = next;
17
+ }
18
+
19
+ export function report(error: Error): void {
20
+ if (listener) {
21
+ listener(error);
22
+ return;
23
+ }
24
+ if (Reflect.get(globalThis, "__DEV__") === true) console.warn(error);
25
+ }
package/src/server.ts CHANGED
@@ -21,7 +21,12 @@
21
21
  * mutation, and server-sent events read from React Native's streaming XHR.
22
22
  */
23
23
 
24
- import { OrbitError } from "./errors.js";
24
+ import {
25
+ E_ORBIT_FOREIGN_ORIGIN,
26
+ E_ORBIT_INSECURE_SERVER,
27
+ E_ORBIT_NO_XHR,
28
+ E_ORBIT_SERVER_REQUEST_FAILED,
29
+ } from "./errors.js";
25
30
 
26
31
  export interface ServerConnection {
27
32
  /** The server's origin (`https://app.example`). */
@@ -50,9 +55,35 @@ export interface ServerConnection {
50
55
  /**
51
56
  * Send `Authorization: Bearer <token>` with every request and stream from
52
57
  * now on (`null` stops): an API's token, which — unlike a browser's
53
- * `EventSource` — the phone can send on server-sent events too.
58
+ * `EventSource` — the phone can send on server-sent events too. With a
59
+ * `tokenStore`, the token is kept there too (and forgotten on `null`);
60
+ * the promise settles once it is.
54
61
  */
55
- authorize(token: string | null): void;
62
+ authorize(token: string | null): Promise<void>;
63
+ /**
64
+ * Authorize again with the token the `tokenStore` kept, as when the app
65
+ * starts: true when there was one. Without a store, false.
66
+ */
67
+ restore(): Promise<boolean>;
68
+ }
69
+
70
+ /**
71
+ * Where a connection keeps its API token between launches — on a phone,
72
+ * `@c9up/orbit-secure-store`'s getItem / setItem / deleteItem under a key:
73
+ *
74
+ * connectServer(origin, { tokenStore: {
75
+ * get: () => getItem('session'),
76
+ * set: (token) => token === null ? deleteItem('session') : setItem('session', token),
77
+ * } })
78
+ */
79
+ export interface TokenStore {
80
+ get(): Promise<string | null>;
81
+ set(token: string | null): Promise<void>;
82
+ }
83
+
84
+ export interface ConnectOptions {
85
+ /** Keeps the token `authorize` sets, so `restore` finds it at the next launch. */
86
+ tokenStore?: TokenStore;
56
87
  }
57
88
 
58
89
  const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "10.0.2.2"]);
@@ -67,14 +98,14 @@ function xsrfFrom(response: Response): string | undefined {
67
98
  }
68
99
 
69
100
  /** Connect to the app's ream server: https, or http to this machine or the emulator's host. */
70
- export function connectServer(server: string): ServerConnection {
101
+ export function connectServer(
102
+ server: string,
103
+ options: ConnectOptions = {},
104
+ ): ServerConnection {
71
105
  const base = new URL(server);
72
106
  const local = LOCAL_HOSTS.has(base.hostname);
73
107
  if (base.protocol !== "https:" && !(base.protocol === "http:" && local)) {
74
- throw new OrbitError(
75
- "E_ORBIT_INSECURE_SERVER",
76
- `[orbit] the server ${base.origin} is not https (plain http only reaches this machine or the emulator's host)`,
77
- );
108
+ throw new E_ORBIT_INSECURE_SERVER([base.origin]);
78
109
  }
79
110
  const origin = base.origin;
80
111
  let token: string | undefined;
@@ -83,9 +114,7 @@ export function connectServer(server: string): ServerConnection {
83
114
  const url = (path: string): string => {
84
115
  const target = new URL(path, `${origin}/`).href;
85
116
  if (new URL(target).origin !== origin) {
86
- throw new TypeError(
87
- `[orbit] the connection to ${origin} does not reach ${target}`,
88
- );
117
+ throw new E_ORBIT_FOREIGN_ORIGIN([origin, target]);
89
118
  }
90
119
  return target;
91
120
  };
@@ -133,7 +162,7 @@ export function connectServer(server: string): ServerConnection {
133
162
  const text = await response.text();
134
163
  if (text !== "") return JSON.parse(text);
135
164
  if (response.ok) return undefined;
136
- throw new Error(`[orbit] ${target} answered HTTP ${response.status}`);
165
+ throw new E_ORBIT_SERVER_REQUEST_FAILED([target, response.status]);
137
166
  },
138
167
  stream: (target) =>
139
168
  new ServerEventStream(url(target), () => ({
@@ -141,8 +170,15 @@ export function connectServer(server: string): ServerConnection {
141
170
  ...(bearer === null ? {} : { authorization: `Bearer ${bearer}` }),
142
171
  })),
143
172
  xsrf: () => token,
144
- authorize: (next) => {
173
+ authorize: async (next) => {
145
174
  bearer = next;
175
+ await options.tokenStore?.set(next);
176
+ },
177
+ restore: async () => {
178
+ const kept = await options.tokenStore?.get();
179
+ if (typeof kept !== "string" || kept === "") return false;
180
+ bearer = kept;
181
+ return true;
146
182
  },
147
183
  };
148
184
  }
@@ -187,7 +223,7 @@ function createRequest(): StreamingRequest {
187
223
  const request: unknown =
188
224
  typeof Xhr === "function" ? Reflect.construct(Xhr, []) : undefined;
189
225
  if (!isStreamingRequest(request)) {
190
- throw new TypeError("[orbit] server events need XMLHttpRequest");
226
+ throw new E_ORBIT_NO_XHR();
191
227
  }
192
228
  return request;
193
229
  }
package/src/stack.ts CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  } from "@c9up/aurora/core";
10
10
  import { captureContext, type TemplateResult } from "@c9up/aurora/renderer";
11
11
  import { afterCommit, treeHost } from "./commit.js";
12
- import { OrbitError } from "./errors.js";
12
+ import { E_ORBIT_NO_SCREEN, E_ORBIT_STACK_SHOWN } from "./errors.js";
13
13
  import { bindMotion, MotionValue } from "./motion.js";
14
14
  import { type Child, flatten, NativeNode, Region } from "./node.js";
15
15
 
@@ -87,10 +87,7 @@ const ScreenContext = createContext<Screen | undefined>(
87
87
  export function useScreen(): Screen {
88
88
  const screen = inject(ScreenContext);
89
89
  if (screen === undefined) {
90
- throw new OrbitError(
91
- "E_ORBIT_NO_SCREEN",
92
- "[orbit] useScreen() outside a screen: it reads the screen a stack shows, from a component that screen built",
93
- );
90
+ throw new E_ORBIT_NO_SCREEN();
94
91
  }
95
92
  return screen;
96
93
  }
@@ -239,10 +236,7 @@ export class Stack implements Navigator {
239
236
  */
240
237
  attach(build: ScreenBuilder, ended: (end: () => void) => void): NativeNode {
241
238
  if (this.#container) {
242
- throw new OrbitError(
243
- "E_ORBIT_STACK_SHOWN",
244
- "[orbit] a stack is shown in one place: this one is already in a template",
245
- );
239
+ throw new E_ORBIT_STACK_SHOWN();
246
240
  }
247
241
  this.#build = build;
248
242
  this.#container = new NativeNode(
package/src/styles.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type Signal, signal } from "@c9up/aurora/core";
2
- import { OrbitError } from "./errors.js";
2
+ import { E_ORBIT_STYLE_TABLE } from "./errors.js";
3
3
  import type { Style } from "./node.js";
4
4
 
5
5
  /**
@@ -149,10 +149,7 @@ export function isStyleTable(v: unknown): v is StyleTable {
149
149
  /** Give orbit the app's style table (`ream android:*` does it before the app runs). */
150
150
  export function useStyles(table: unknown): void {
151
151
  if (!isStyleTable(table)) {
152
- throw new OrbitError(
153
- "E_ORBIT_STYLE_TABLE",
154
- "[orbit] not a style table orbit reads (version 1, from ream css:compile)",
155
- );
152
+ throw new E_ORBIT_STYLE_TABLE();
156
153
  }
157
154
  selfRules = new Map();
158
155
  relatedRules = new Map();