@c9up/orbit 0.0.0-stage → 0.1.1

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 (105) hide show
  1. package/Cargo.lock +139 -0
  2. package/Cargo.toml +20 -0
  3. package/LICENSE +21 -0
  4. package/README.md +320 -2
  5. package/android/orbit.cmake +31 -0
  6. package/android/src/main/cpp/NativeOrbit.cpp +309 -0
  7. package/android/src/main/cpp/NativeOrbit.h +35 -0
  8. package/android/src/main/cpp/orbit_host.h +34 -0
  9. package/android/src/main/java/com/c9up/orbit/OrbitEffects.kt +286 -0
  10. package/android/src/main/java/com/c9up/orbit/OrbitHost.kt +258 -0
  11. package/android/src/main/java/com/c9up/orbit/OrbitImage.kt +346 -0
  12. package/android/src/main/java/com/c9up/orbit/OrbitInput.kt +161 -0
  13. package/android/src/main/java/com/c9up/orbit/OrbitPress.kt +110 -0
  14. package/android/src/main/java/com/c9up/orbit/OrbitVector.kt +115 -0
  15. package/android/src/main/java/com/c9up/orbit/OrbitViews.kt +362 -0
  16. package/crates/orbit-host/Cargo.toml +14 -0
  17. package/crates/orbit-host/src/gesture.rs +561 -0
  18. package/crates/orbit-host/src/lib.rs +2042 -0
  19. package/crates/orbit-host/src/motion.rs +328 -0
  20. package/crates/orbit-host/src/vector.rs +1173 -0
  21. package/dist/color.d.ts +10 -0
  22. package/dist/color.d.ts.map +1 -0
  23. package/dist/color.js +62 -0
  24. package/dist/color.js.map +1 -0
  25. package/dist/commit.d.ts +77 -0
  26. package/dist/commit.d.ts.map +1 -0
  27. package/dist/commit.js +302 -0
  28. package/dist/commit.js.map +1 -0
  29. package/dist/errors.d.ts +76 -0
  30. package/dist/errors.d.ts.map +1 -0
  31. package/dist/errors.js +89 -0
  32. package/dist/errors.js.map +1 -0
  33. package/dist/host.d.ts +49 -0
  34. package/dist/host.d.ts.map +1 -0
  35. package/dist/host.js +20 -0
  36. package/dist/host.js.map +1 -0
  37. package/dist/index.d.ts +31 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.js +31 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/motion.d.ts +18 -0
  42. package/dist/motion.d.ts.map +1 -0
  43. package/dist/motion.js +67 -0
  44. package/dist/motion.js.map +1 -0
  45. package/dist/node.d.ts +46 -0
  46. package/dist/node.d.ts.map +1 -0
  47. package/dist/node.js +110 -0
  48. package/dist/node.js.map +1 -0
  49. package/dist/pages.d.ts +56 -0
  50. package/dist/pages.d.ts.map +1 -0
  51. package/dist/pages.js +157 -0
  52. package/dist/pages.js.map +1 -0
  53. package/dist/react-native/index.d.ts +33 -0
  54. package/dist/react-native/index.d.ts.map +1 -0
  55. package/dist/react-native/index.js +71 -0
  56. package/dist/react-native/index.js.map +1 -0
  57. package/dist/report.d.ts +13 -0
  58. package/dist/report.d.ts.map +1 -0
  59. package/dist/report.js +22 -0
  60. package/dist/report.js.map +1 -0
  61. package/dist/server.d.ts +109 -0
  62. package/dist/server.d.ts.map +1 -0
  63. package/dist/server.js +290 -0
  64. package/dist/server.js.map +1 -0
  65. package/dist/stack.d.ts +117 -0
  66. package/dist/stack.d.ts.map +1 -0
  67. package/dist/stack.js +299 -0
  68. package/dist/stack.js.map +1 -0
  69. package/dist/styles.d.ts +138 -0
  70. package/dist/styles.d.ts.map +1 -0
  71. package/dist/styles.js +920 -0
  72. package/dist/styles.js.map +1 -0
  73. package/dist/template.d.ts +27 -0
  74. package/dist/template.d.ts.map +1 -0
  75. package/dist/template.js +1436 -0
  76. package/dist/template.js.map +1 -0
  77. package/dist/textDecoder.d.ts +29 -0
  78. package/dist/textDecoder.d.ts.map +1 -0
  79. package/dist/textDecoder.js +149 -0
  80. package/dist/textDecoder.js.map +1 -0
  81. package/dist/url.d.ts +45 -0
  82. package/dist/url.d.ts.map +1 -0
  83. package/dist/url.js +303 -0
  84. package/dist/url.js.map +1 -0
  85. package/package.json +96 -3
  86. package/scripts/build-android.sh +27 -0
  87. package/scripts/test-styles.mjs +31 -0
  88. package/specs/NativeOrbit.ts +34 -0
  89. package/src/color.ts +68 -0
  90. package/src/commit.ts +373 -0
  91. package/src/errors.ts +178 -0
  92. package/src/host.ts +91 -0
  93. package/src/index.ts +64 -0
  94. package/src/motion.ts +88 -0
  95. package/src/node.ts +133 -0
  96. package/src/pages.ts +207 -0
  97. package/src/react-native/index.ts +115 -0
  98. package/src/react-native/react-native.d.ts +39 -0
  99. package/src/report.ts +25 -0
  100. package/src/server.ts +395 -0
  101. package/src/stack.ts +428 -0
  102. package/src/styles.ts +1021 -0
  103. package/src/template.ts +1681 -0
  104. package/src/textDecoder.ts +162 -0
  105. package/src/url.ts +333 -0
package/src/motion.ts ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Motion values on the phone: aurora's `MotionValue`, driven by the Rust host
3
+ * on the UI thread. JS declares values, curves and bindings once, and a
4
+ * blocked JS thread stops none of it. The same component file animates in the
5
+ * browser, where aurora's DOM renderer hands the curves to the Web Animations
6
+ * API.
7
+ */
8
+ import {
9
+ type MotionDriver,
10
+ type MotionStyle,
11
+ type MotionValue,
12
+ readMotionStyle,
13
+ setMotionDriver,
14
+ } from "@c9up/aurora/core";
15
+ import { E_ORBIT_INVALID_MOTION } from "./errors.js";
16
+ import { currentHost } from "./host.js";
17
+
18
+ export {
19
+ MotionNode,
20
+ type MotionStyle,
21
+ MotionValue,
22
+ type SpringOptions,
23
+ type TimingOptions,
24
+ } from "@c9up/aurora/core";
25
+
26
+ /** aurora's motion values, held and played by orbit's native host. */
27
+ const nativeDriver: MotionDriver = {
28
+ value: (tag, initial) => currentHost().motionValue(tag, initial),
29
+ set: (tag, value) => currentHost().motionSet(tag, value),
30
+ stop: (tag) => currentHost().motionStop(tag),
31
+ frames: (tag, frames, to, loop) =>
32
+ currentHost().motionFrames(tag, [...frames], to, loop),
33
+ spring: (tag, to, stiffness, damping, mass) =>
34
+ currentHost().motionSpring(tag, to, stiffness, damping, mass),
35
+ interpolate: (tag, input, from, to) =>
36
+ currentHost().motionInterpolate(tag, input, from, to),
37
+ dispose: (tag) => currentHost().motionDispose(tag),
38
+ };
39
+
40
+ /** @internal `useHost` installs it: motion values made from then on live in the host. */
41
+ export function useNativeMotion(): void {
42
+ setMotionDriver(nativeDriver);
43
+ }
44
+
45
+ const PROPS = {
46
+ opacity: 0,
47
+ translateX: 1,
48
+ translateY: 2,
49
+ scale: 3,
50
+ visible: 4,
51
+ } as const;
52
+ const KEYS = [
53
+ "opacity",
54
+ "translateX",
55
+ "translateY",
56
+ "scale",
57
+ "visible",
58
+ ] as const;
59
+
60
+ /** Wire `style` to the view `viewTag`; call once the view is committed. */
61
+ export function bindMotion(viewTag: number, style: MotionStyle): void {
62
+ for (const key of KEYS) {
63
+ const node = style[key];
64
+ if (node) currentHost().motionBind(viewTag, PROPS[key], node.tag);
65
+ }
66
+ }
67
+
68
+ /** Feed `value` from the scroll offset of the scroll view `scrollViewTag`. */
69
+ export function bindScrollY(scrollViewTag: number, value: MotionValue): void {
70
+ currentHost().motionBindScroll(scrollViewTag, value.tag);
71
+ }
72
+
73
+ /** Read a `motion=${…}` attribute value, as aurora reads it on the web. */
74
+ export function readMotion(value: unknown): MotionStyle {
75
+ try {
76
+ return readMotionStyle(value);
77
+ } catch (error) {
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 });
85
+ }
86
+ throw error;
87
+ }
88
+ }
package/src/node.ts ADDED
@@ -0,0 +1,133 @@
1
+ import { effect } from "@c9up/aurora/core";
2
+ import { colorToArgb } from "./color.js";
3
+
4
+ /**
5
+ * The tree orbit keeps in JS: one node per native element, with the props
6
+ * the host lays out and draws. Signals write props straight into it; a commit
7
+ * sends only what changed (see `commit.ts`).
8
+ */
9
+
10
+ export type Style = { [key: string]: string | number };
11
+ export type Props = { [key: string]: unknown };
12
+ export type Handler = (type: string, payload: unknown) => void;
13
+ type Value<T> = T | (() => T);
14
+
15
+ const COLOR_KEYS = new Set([
16
+ "backgroundColor",
17
+ "color",
18
+ "borderColor",
19
+ "shadowColor",
20
+ "placeholderColor",
21
+ ]);
22
+
23
+ // Tags the host keys its views by. Even numbers from 2^30, out of the way of
24
+ // anything else that might share a surface.
25
+ let nextTag = 1 << 30;
26
+
27
+ function allocateTag(): number {
28
+ nextTag += 2;
29
+ return nextTag;
30
+ }
31
+
32
+ /** Style as the host reads it: flattened, colours as ARGB integers. */
33
+ export function flatten(style: Style): Props {
34
+ const out: Props = {};
35
+ for (const [key, value] of Object.entries(style)) {
36
+ out[key] =
37
+ COLOR_KEYS.has(key) && typeof value === "string"
38
+ ? colorToArgb(value)
39
+ : value;
40
+ }
41
+ return out;
42
+ }
43
+
44
+ /** Called whenever a node below `from` changed: the commit walks this path. */
45
+ let onDirty: () => void = () => {};
46
+
47
+ export function setDirtyListener(listener: () => void): void {
48
+ onDirty = listener;
49
+ }
50
+
51
+ function markChildrenDirty(from: NativeNode | null): void {
52
+ for (let p = from; p && !p.childrenDirty; p = p.parent)
53
+ p.childrenDirty = true;
54
+ onDirty();
55
+ }
56
+
57
+ /** A run of children that a reactive slot replaces wholesale. */
58
+ export class Region {
59
+ parent: NativeNode | null = null;
60
+ items: Child[] = [];
61
+
62
+ set(items: Child[]): void {
63
+ this.items = items;
64
+ for (const item of items) adopt(item, this.parent);
65
+ markChildrenDirty(this.parent);
66
+ }
67
+ }
68
+
69
+ export type Child = NativeNode | Region;
70
+
71
+ function adopt(child: Child, parent: NativeNode | null): void {
72
+ child.parent = parent;
73
+ if (child instanceof Region)
74
+ for (const item of child.items) adopt(item, parent);
75
+ }
76
+
77
+ function flattenInto(
78
+ children: readonly Child[],
79
+ out: NativeNode[],
80
+ ): NativeNode[] {
81
+ for (const child of children) {
82
+ if (child instanceof Region) flattenInto(child.items, out);
83
+ else out.push(child);
84
+ }
85
+ return out;
86
+ }
87
+
88
+ export class NativeNode {
89
+ readonly tag = allocateTag();
90
+ parent: NativeNode | null = null;
91
+ /** Props changed since the last commit, or null. */
92
+ pendingProps: Props | null = null;
93
+ /** Something below this node changed since the last commit. */
94
+ childrenDirty = false;
95
+ onEvent: Handler | null = null;
96
+ /** An image's bytes, sent to the host's memory with the next commit. */
97
+ pendingBytes: Uint8Array | null = null;
98
+ /** A scroll view's offset readers (dp), told on each native scroll. */
99
+ readonly scrollListeners: Array<(y: number) => void> = [];
100
+
101
+ constructor(
102
+ readonly viewName: string,
103
+ public props: Props,
104
+ readonly children: Child[],
105
+ ) {
106
+ for (const child of children) adopt(child, this);
107
+ }
108
+
109
+ flatChildren(): NativeNode[] {
110
+ return flattenInto(this.children, []);
111
+ }
112
+
113
+ setProps(patch: Props): void {
114
+ Object.assign(this.props, patch);
115
+ this.pendingProps = this.pendingProps
116
+ ? Object.assign(this.pendingProps, patch)
117
+ : { ...patch };
118
+ markChildrenDirty(this.parent);
119
+ }
120
+ }
121
+
122
+ /** Raw text content, static or signal-backed: the effect patches only `text`. */
123
+ export function rawText(content: Value<string>): NativeNode {
124
+ const raw = new NativeNode("RCTRawText", { text: "" }, []);
125
+ if (typeof content === "function") {
126
+ effect(() => raw.setProps({ text: content() }));
127
+ // The first run is the initial content, not a change to send.
128
+ raw.pendingProps = null;
129
+ } else {
130
+ raw.props.text = content;
131
+ }
132
+ return raw;
133
+ }
package/src/pages.ts ADDED
@@ -0,0 +1,207 @@
1
+ /**
2
+ * `@c9up/orbit/pages` — pages the ream server drives, on the phone.
3
+ *
4
+ * The server stays the router: a link or a visit asks it for the next page
5
+ * object (photon's protocol, the one the browser speaks after `visits: true`)
6
+ * and the app shows the page it names — an aurora component bundled with the
7
+ * app — as a screen of a stack. The same controller answers the browser and
8
+ * the phone.
9
+ *
10
+ * run(() => html`${serverPages({
11
+ * server: 'https://app.example',
12
+ * pages: { Home, Orders, Order },
13
+ * })}`)
14
+ *
15
+ * photon's router does the protocol — visits, partial reloads, deferred
16
+ * props, the version check, history — and this is where it runs: requests to
17
+ * the server, a back stack in memory mirrored by the screens, the back button
18
+ * going through photon's history. A covered page keeps its state; going back
19
+ * shows it as it was, without a request.
20
+ */
21
+
22
+ import { html } from "@c9up/aurora/core";
23
+ import type { TemplateResult } from "@c9up/aurora/renderer";
24
+ import {
25
+ bootPage,
26
+ type PhotonAdapterHandle,
27
+ type PhotonHost,
28
+ router,
29
+ } from "@c9up/photon/client/core";
30
+ import { E_ORBIT_INTERNAL, E_ORBIT_UNKNOWN_PAGE } from "./errors.js";
31
+ import { connectServer, type ServerConnection } from "./server.js";
32
+ import { createStack, type Stack, type StackOptions } from "./stack.js";
33
+ import { setLinkHandler } from "./template.js";
34
+
35
+ /**
36
+ * A page: an aurora component taking the page object's props. Declared as a
37
+ * method so a page typed with its own props (`{ orders: Order[] }`) is one.
38
+ */
39
+ type PageFunction = {
40
+ page(props: Record<string, unknown>): TemplateResult;
41
+ }["page"];
42
+
43
+ export interface ServerPagesOptions {
44
+ /**
45
+ * The ream server: its origin (https, or http to this machine through
46
+ * `adb reverse` or to the emulator's host `10.0.2.2`), or the connection
47
+ * `connectServer` made — the one comet and relay go through too.
48
+ */
49
+ server: string | ServerConnection;
50
+ /** The pages the server may name, by the name it renders them under. */
51
+ pages: { [name: string]: PageFunction };
52
+ /** The first page's path. Default `/`. */
53
+ url?: string;
54
+ /** How screens change (`transition`, `duration`, `background`). */
55
+ stack?: Omit<StackOptions, "back">;
56
+ /** Shown until the first page has arrived. */
57
+ loading?: () => TemplateResult;
58
+ /** Shown when the server could not give a page; `retry` asks again. */
59
+ failed?: (error: unknown, retry: () => void) => TemplateResult;
60
+ /** A link off the server (another site, `mailto:`): the platform opens it. */
61
+ open?: (url: string) => void;
62
+ }
63
+
64
+ /** What photon hands back from `resolveComponent`: one of `pages`, a function. */
65
+ function isPage(value: unknown): value is PageFunction {
66
+ return typeof value === "function";
67
+ }
68
+
69
+ const Loading = (): TemplateResult => html`<div class="flex-1"></div>`;
70
+
71
+ const Failed = (error: unknown, retry: () => void): TemplateResult =>
72
+ html`<div class="flex-1 items-center justify-center gap-4 p-6">
73
+ <p class="text-center">${error instanceof Error ? error.message : String(error)}</p>
74
+ <button class="rounded-md border px-4 py-2" @click=${retry}>Retry</button>
75
+ </div>`;
76
+
77
+ interface Entry {
78
+ state: unknown;
79
+ url: string;
80
+ }
81
+
82
+ /** The stack the server's pages are shown in; put it in a template. */
83
+ export function serverPages(options: ServerPagesOptions): Stack {
84
+ const server =
85
+ typeof options.server === "string"
86
+ ? connectServer(options.server)
87
+ : options.server;
88
+ const origin = server.origin;
89
+ const first = server.url(options.url ?? "/");
90
+ const failed = options.failed ?? Failed;
91
+ let entries: Entry[] = [{ state: null, url: first }];
92
+ let restore: ((state: unknown) => void) | undefined;
93
+ /** The page a visit rendered, waiting for photon to say how it goes in history. */
94
+ let pending: { page: PageFunction; props: Record<string, unknown> } | null =
95
+ null;
96
+ /** The back button asked photon for the previous entry. */
97
+ let popping = false;
98
+
99
+ const current = (): Entry => {
100
+ const entry = entries.at(-1);
101
+ if (entry === undefined)
102
+ throw new E_ORBIT_INTERNAL(["server pages: empty history"]);
103
+ return entry;
104
+ };
105
+ const absolute = (url: string): string => new URL(url, current().url).href;
106
+
107
+ const stack = createStack(options.loading ?? Loading, {
108
+ ...options.stack,
109
+ back: () => {
110
+ if (entries.length < 2 || restore === undefined) return false;
111
+ entries.pop();
112
+ popping = true;
113
+ restore(current().state);
114
+ return true;
115
+ },
116
+ });
117
+
118
+ /** The visit's page goes in as photon wrote it in history. */
119
+ const place = (how: "push" | "replace"): void => {
120
+ const next = pending;
121
+ pending = null;
122
+ if (next === null) return;
123
+ if (how === "push") stack.push(next.page, next.props);
124
+ else stack.replaceInPlace(next.page, next.props);
125
+ };
126
+
127
+ const host: PhotonHost = {
128
+ href: () => current().url,
129
+ baseUri: () => current().url,
130
+ // The connection refuses another origin, sends the session cookie and
131
+ // keeps the XSRF token the server sets.
132
+ fetch: (url, init) => server.fetch(absolute(url), init),
133
+ state: () => current().state,
134
+ push: (state, url) => {
135
+ entries.push({ state, url: absolute(url) });
136
+ place("push");
137
+ },
138
+ replace: (state, url) => {
139
+ entries[entries.length - 1] = { state, url: absolute(url) };
140
+ place("replace");
141
+ },
142
+ load: (url) => start(absolute(url)),
143
+ reload: () => start(current().url),
144
+ emit: () => {},
145
+ cookie: (name) => (name === "XSRF-TOKEN" ? server.xsrf() : undefined),
146
+ memoryHistory: true,
147
+ listen: (wire) => {
148
+ restore = wire.restore;
149
+ },
150
+ };
151
+
152
+ const adapter: PhotonAdapterHandle = {
153
+ update(page, props) {
154
+ if (!isPage(page)) return;
155
+ if (popping) {
156
+ // The covered screen is the page coming back, as it was left.
157
+ popping = false;
158
+ stack.pop();
159
+ return;
160
+ }
161
+ pending = { page, props };
162
+ },
163
+ unmount() {},
164
+ };
165
+
166
+ const resolveComponent = async (
167
+ name: string,
168
+ ): Promise<{ default: unknown }> => {
169
+ const page = Object.hasOwn(options.pages, name)
170
+ ? options.pages[name]
171
+ : undefined;
172
+ if (page === undefined) {
173
+ throw new E_ORBIT_UNKNOWN_PAGE([name]);
174
+ }
175
+ return { default: page };
176
+ };
177
+
178
+ /** A first load of `url`: the history starts again from its page. */
179
+ function start(url: string): void {
180
+ entries = [{ state: null, url }];
181
+ pending = null;
182
+ popping = false;
183
+ bootPage({
184
+ host,
185
+ url,
186
+ resolveComponent,
187
+ mount: async (_target, page, data) => {
188
+ if (isPage(page)) stack.reset(page, data.props);
189
+ return adapter;
190
+ },
191
+ }).catch((error: unknown) => {
192
+ stack.reset(() => failed(error, () => start(url)), undefined);
193
+ });
194
+ }
195
+
196
+ setLinkHandler((href) => {
197
+ const url = absolute(href);
198
+ if (new URL(url).origin === origin) {
199
+ const target = new URL(url);
200
+ void router.visit(target.pathname + target.search + target.hash);
201
+ } else {
202
+ options.open?.(url);
203
+ }
204
+ });
205
+ start(first);
206
+ return stack;
207
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * `@c9up/orbit/react-native` — an app's entry on a phone.
3
+ *
4
+ * import { run } from "@c9up/orbit/react-native";
5
+ * import { App } from "./App.js";
6
+ * run(App);
7
+ *
8
+ * React Native supplies the JS engine, the JSI module registry and the
9
+ * activity; nothing of React is used. `run` registers the app under the name
10
+ * the activity `ream android:*` generates starts, gives orbit its native host
11
+ * and the app's style table, and mounts the root component with the launch
12
+ * props (intent extras). The
13
+ * back button and the back gesture pop the innermost shown stack; with none
14
+ * to pop, the app goes back as any Android app does. React Native's `URL` is
15
+ * replaced by a standard one when it is not one (see `url.ts`).
16
+ */
17
+ import type { TemplateResult } from "@c9up/aurora/renderer";
18
+ // The app's style table: `ream android:*` compiles the app's Tailwind build
19
+ // into it and Metro serves it under this name.
20
+ import styles from "@c9up/orbit-styles";
21
+ import {
22
+ Appearance,
23
+ AppRegistry,
24
+ BackHandler,
25
+ Dimensions,
26
+ TurboModuleRegistry,
27
+ } from "react-native";
28
+ import { E_ORBIT_NO_HOST } from "../errors.js";
29
+ import { NATIVE_MODULE_NAME, type OrbitHost, useHost } from "../host.js";
30
+ import { goBack } from "../stack.js";
31
+ import { colorScheme, useStyles } from "../styles.js";
32
+ import { mount } from "../template.js";
33
+ import { installTextDecoder } from "../textDecoder.js";
34
+ import { installStandardUrl } from "../url.js";
35
+
36
+ // Before the app's own modules run: React Native's URL resolves a relative
37
+ // reference by appending it to the base, and photon's router (and any code
38
+ // shared with the browser) needs the standard one.
39
+ installStandardUrl();
40
+ // Hermes has TextEncoder but no TextDecoder: libraries shared with the web
41
+ // (msgpack, protobuf…) would die at load.
42
+ installTextDecoder();
43
+
44
+ /** The name the generated activity starts the app by. */
45
+ export const APP_NAME = "main";
46
+
47
+ export type LaunchProps = { [key: string]: unknown };
48
+
49
+ const METHODS: ReadonlyArray<keyof OrbitHost> = [
50
+ "setViewport",
51
+ "commit",
52
+ "imageBytes",
53
+ "layout",
54
+ "scroll",
55
+ "setEventHandler",
56
+ ];
57
+
58
+ function isOrbitHost(value: unknown): value is OrbitHost {
59
+ return (
60
+ typeof value === "object" &&
61
+ value !== null &&
62
+ METHODS.every((name) => typeof Reflect.get(value, name) === "function")
63
+ );
64
+ }
65
+
66
+ export interface RunOptions {
67
+ /**
68
+ * `system` (default): `dark:` follows the phone's setting, as a browser's
69
+ * `prefers-color-scheme` — until the app sets `colorScheme(…)` itself.
70
+ * `light` / `dark`: that one, whatever the phone says.
71
+ */
72
+ colorScheme?: "system" | "light" | "dark";
73
+ }
74
+
75
+ /**
76
+ * Follow the phone's light / dark setting into `colorScheme`, as long as the
77
+ * app has not chosen one itself (a value set by anything else stops it).
78
+ */
79
+ function followSystemScheme(): void {
80
+ const read = (
81
+ value: "light" | "dark" | null | undefined,
82
+ ): "light" | "dark" => (value === "dark" ? "dark" : "light");
83
+ let set = read(Appearance.getColorScheme());
84
+ colorScheme(set);
85
+ const subscription = Appearance.addChangeListener(({ colorScheme: next }) => {
86
+ if (colorScheme() !== set) {
87
+ subscription.remove();
88
+ return;
89
+ }
90
+ set = read(next);
91
+ colorScheme(set);
92
+ });
93
+ }
94
+
95
+ /** Register `root` as the app and mount it when the activity starts. */
96
+ export function run(
97
+ root: (props: LaunchProps) => TemplateResult,
98
+ options: RunOptions = {},
99
+ ): void {
100
+ AppRegistry.registerRunnable(APP_NAME, ({ initialProps }) => {
101
+ const host = TurboModuleRegistry.getEnforcing(NATIVE_MODULE_NAME);
102
+ if (!isOrbitHost(host)) {
103
+ throw new E_ORBIT_NO_HOST([
104
+ `the ${NATIVE_MODULE_NAME} module is not orbit's native host: is the app built by ream android:build?`,
105
+ ]);
106
+ }
107
+ useHost(host);
108
+ useStyles(styles);
109
+ const scheme = options.colorScheme ?? "system";
110
+ if (scheme === "system") followSystemScheme();
111
+ else colorScheme(scheme);
112
+ BackHandler.addEventListener("hardwareBackPress", goBack);
113
+ mount(root(initialProps ?? {}), { viewport: Dimensions.get("window") });
114
+ });
115
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The part of React Native's JS API orbit's app entry uses — declared here so
3
+ * orbit builds without React Native installed. An app has the real package;
4
+ * this file is not part of what orbit's declarations reference.
5
+ */
6
+ /** The app's style table, which `ream android:*`'s Metro config provides. */
7
+ declare module "@c9up/orbit-styles" {
8
+ const table: unknown;
9
+ export default table;
10
+ }
11
+
12
+ declare module "react-native" {
13
+ export const AppRegistry: {
14
+ registerRunnable(
15
+ name: string,
16
+ run: (params: { initialProps?: { [key: string]: unknown } }) => void,
17
+ ): void;
18
+ };
19
+ export const BackHandler: {
20
+ addEventListener(
21
+ event: "hardwareBackPress",
22
+ handler: () => boolean,
23
+ ): { remove(): void };
24
+ };
25
+ export const Dimensions: {
26
+ get(dimension: "window"): { width: number; height: number };
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
+ };
36
+ export const TurboModuleRegistry: {
37
+ getEnforcing(name: string): unknown;
38
+ };
39
+ }
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
+ }