Skip to content

orbit ​

@c9up/orbit: aurora components as native views on a phone, laid out and diffed by a Rust host. Guide: Introduction.

Installation ​

bash
pnpm add @c9up/orbit

Peer dependencies: @c9up/aurora (required) and @c9up/photon (only for @c9up/orbit/pages). The app is built and run by ream android:*, which adds the native host and the app's style table; see Building the app.

Entry points ​

ImportContents
@c9up/orbitThe core, free of React Native: mounting a template on the native host, stacks of screens, the style table, motion values, the server connection, and the standard URL and TextDecoder.
@c9up/orbit/react-nativeThe app's entry on the phone: run(App) registers the app with React Native, gives orbit its host and style table, and wires the back button. Importing it installs the standard URL and TextDecoder.
@c9up/orbit/pagesPages driven by the ream server, shown as screens of a stack (needs @c9up/photon).

The package has no react-native export condition: the phone entry is the ./react-native subpath, imported by the app's entry file.

Exports ​

@c9up/orbit ​

ExportKindDescription
mountfunctionRenders an aurora template as native views through the host.
MountOptionsinterfaceOptions of mount.
RoottypeThe mounted root that mount returns.
OrbitReportinterfaceOne commit's report from the host.
afterCommitfunctionRuns a hook once the next commit has reached the host.
useHostfunctionGives orbit its native host, once, before mount.
OrbitHostinterfaceWhat orbit needs from the native side.
NATIVE_MODULE_NAMEconst"NativeOrbit", the TurboModule name the native side registers.
GestureEventtypeWhat a gesture handler (@click, @longpress, @pan, @swipe) receives.
createStackfunctionA stack of screens.
useScreenfunctionThe screen a component is part of.
goBackfunctionWhat the back button does: pops the innermost shown stack.
StacktypeA stack of screens (the class createStack returns).
StackOptionsinterfaceOptions of createStack.
Navigatorinterfacepush, pop, replace, canGoBack.
ScreeninterfaceA Navigator plus focused().
ScreenComponenttype(props: P) => TemplateResult.
useStylesfunctionGives orbit the app's style table.
colorSchemeconstSignal of the scheme dark: follows.
unknownClassesconstClasses elements asked for that the style table does not have.
StyleTableinterfaceThe table ream css:compile writes.
bindMotionfunctionWires a motion style to a committed view.
bindScrollYfunctionFeeds a motion value from a scroll view's offset.
MotionValue, MotionNodeclassRe-exported from @c9up/aurora/core; on the phone the host drives them on the UI thread once useHost ran.
MotionStyle, SpringOptions, TimingOptionstypeRe-exported from @c9up/aurora/core.
connectServerfunctionOne connection to the app's ream server, for pages, comet and relay.
ServerConnectioninterfaceWhat connectServer returns.
ConnectOptionsinterfaceOptions of connectServer.
TokenStoreinterfaceWhere authorize keeps the API token.
ServerEventStreamclassServer-sent events over React Native's streaming XHR.
ServerEventinterfaceOne server-sent event.
colorToArgbfunctionA CSS colour as a 32-bit ARGB integer.
installTextDecoderfunctionInstalls a standard UTF-8 TextDecoder where the engine has none (Hermes).
StandardTextDecoderclassThe UTF-8 TextDecoder it installs.
installStandardUrlfunctionInstalls a standard URL in place of the platform's when it is not one.
StandardURLclassThe URL it installs.
errorsnamespaceThe package's errors, one class per code, see Errors

Mounting ​

FunctionSignatureDescription
useHostuseHost(next: OrbitHost): voidGives orbit its native host, once, before mount. Motion values made from then on live in the host.
mountmount(result: TemplateResult, options: MountOptions): RootRenders the template; the root commits on its own after each change, batched to a microtask.
afterCommitafterCommit(hook: () => void): voidRuns hook once the next commit has reached the host.
colorToArgbcolorToArgb(css: string): numberReads #rgb, #rgba, #rrggbb, #rrggbbaa, rgb() / rgba() (comma or space syntax) and transparent.
MountOptions fieldTypeDescription
viewport{ width: number; height: number }The root's size in dp (React Native: Dimensions.get("window")).
hostOrbitHostDefaults to the host given to useHost.
onError(error: Error) => voidTold of what orbit recovered from instead of throwing: a commit the host refused while nothing waited on it (a scheduled one), an image address from data orbit will not load, a value of a drawing the host left out. Without it, a development build (__DEV__) logs them with console.warn and a production build says nothing.
Root memberSignatureDescription
flushflush(): OrbitReportCommits what changed now, instead of at the end of the turn.
reportsreadonly reports: OrbitReport[]Every commit's report, newest last (development and benchmarks).

OrbitReport is { deleted: number[]; parseUs: number; layoutUs: number; diffUs: number; measures: number; nodes: number; opsBytes: number; warnings?: string[] }. warnings lists the values of drawings the host left out, each starting with its code (E_ORBIT_SVG_VALUE: …); orbit also hands each one to onError.

A commit the host refuses is not lost: orbit sends what it carried again with the next commit. mount and flush() throw the refusal; a scheduled commit hands it to onError. Text reaches the host well formed: half of an emoji ("Ana😀".slice(0, 4)) is shown as U+FFFD, as a browser shows it.

Views may nest at most 100 levels deep under the root. The host lays the tree out on the JS thread, one level of its stack at a time, and refuses a deeper tree with E_ORBIT_TREE_TOO_DEEP before it lays it out. Data nested as deep as it likes (replies to replies) needs a limit of its own in the template.

OrbitHost is structural, so a test can pass a fake. Its methods: setViewport(width, height), commit(ops: string): string, imageBytes(tag, bytes: Uint8Array), layout(tags: string): string, scroll(tag, by, toEnd), setEventHandler(handler), and the motion methods motionValue, motionInterpolate, motionSet, motionStop, motionFrames, motionSpring, motionDispose, motionBind, motionBindScroll.

GestureEvent is { type: string } & { [key: string]: unknown }: the shape a DOM handler reads, plus the gesture's numbers.

Stacks and screens ​

FunctionSignatureDescription
createStackcreateStack(initial: () => TemplateResult, options?: StackOptions): Stack
createStack<P>(initial: ScreenComponent<P>, options: StackOptions & { props: P }): Stack
A stack with initial at the bottom; show it with html`${stack}`. A stack is shown in one place only.
useScreenuseScreen(): ScreenThe screen this component is part of, in its setup or in a slot it built.
goBackgoBack(): booleanPops the innermost shown stack that can; false when none can and the platform's own back applies.
Stack memberSignatureDescription
pushpush(screen: () => TemplateResult): void
push<P>(screen: ScreenComponent<P>, props: P): void
Shows screen on top; the one below keeps its state, covered.
poppop(): booleanEnds the top screen and shows the one below; false when only one is left.
replacereplace(screen: () => TemplateResult): void
replace<P>(screen: ScreenComponent<P>, props: P): void
Swaps the top screen for screen; the replaced one ends.
replaceInPlacereplaceInPlace<P>(screen: ScreenComponent<P>, props: P): voidSwaps the top screen at once, with no transition.
resetreset<P>(screen: ScreenComponent<P>, props: P): voidEnds every screen and starts again from screen, at once.
backback(): booleanWhat the back button does here: the back option, or pop().
canGoBackcanGoBack(): booleanWhether pop has a screen to go back to (reactive).
isShownisShown(): booleanWhether the stack is on screen, not inside a covered screen.

Screen adds focused(): boolean to Navigator: true while this screen is the one shown (reactive). A covered screen's effects keep running.

StackOptions fieldTypeDefaultDescription
transition'slide' | 'none''slide'slide: in from the right edge, the covered screen drifting left; none: at once.
durationnumber300The transition's length in ms.
backgroundstringnonePainted behind each screen.
back() => booleanpop()What the back button does when it reaches this stack; true when it went back.

Styles and motion ​

FunctionSignatureDescription
useStylesuseStyles(table: unknown): voidGives orbit the app's style table; run does it on the phone. Anything other than a version 1 table from ream css:compile throws E_ORBIT_STYLE_TABLE.
colorSchemeSignal<'light' | 'dark'>The scheme dark: and the theme's dark values follow; starts at 'light'.
unknownClassesSet<string>Classes an element asked for that the stylesheet does not have.
bindMotionbindMotion(viewTag: number, style: MotionStyle): voidWires style (opacity, translateX, translateY, scale, visible) to the view; call once the view is committed.
bindScrollYbindScrollY(scrollViewTag: number, value: MotionValue): voidFeeds value from the scroll offset of the scroll view.

Server connection ​

FunctionSignatureDescription
connectServerconnectServer(server: string, options?: ConnectOptions): ServerConnectionConnects to the app's ream server: https, or http to localhost, 127.0.0.1, [::1] or the emulator's host 10.0.2.2. Any other plain http throws E_ORBIT_INSECURE_SERVER.
ServerConnection memberSignatureDescription
originreadonly origin: stringThe server's origin.
urlurl(path: string): stringpath on the server, absolute.
fetchfetch(url: string, init?: RequestInit): Promise<Response>A request to the server: refused for another origin, carrying the session cookie and, on a mutation, the X-XSRF-TOKEN the server's XSRF-TOKEN cookie set.
jsonjson(url: string, body: unknown, options?: { signal?: AbortSignal }): Promise<unknown>POSTs body as JSON and resolves the JSON answer (nothing for a 204): the shape of comet's RpcTransport.
streamstream(url: string): ServerEventStreamA server-sent event stream: what relay's stream option takes.
xsrfxsrf(): string | undefinedThe XSRF-TOKEN the server set last.
authorizeauthorize(token: string | null): Promise<void>Sends Authorization: Bearer <token> with every request and stream from now on; null stops. With a tokenStore, the token is kept there too.
restorerestore(): Promise<boolean>Authorizes again with the token the tokenStore kept; false when there was none or no store.
TypeShape
ConnectOptions{ tokenStore?: TokenStore }
TokenStore{ get(): Promise<string | null>; set(token: string | null): Promise<void> }
ServerEvent{ readonly type: string; readonly data?: string; readonly lastEventId?: string }
ServerEventStream memberSignatureDescription
constructornew ServerEventStream(url: string, headers?: () => Record<string, string>, options?: { credentials?: boolean })Opens the stream; credentials defaults to true.
CONNECTING, OPEN, CLOSEDstatic readonly 0, 1, 2The readyState values.
urlreadonly url: stringThe stream's URL.
readyStatenumberThe current state.
addEventListeneraddEventListener(type: string, listener: (event: ServerEvent) => void): voidListens to events of type.
removeEventListenerremoveEventListener(type: string, listener: (event: ServerEvent) => void): voidStops listening.
closeclose(): voidCloses the stream for good.

A dropped connection dispatches error and reconnects after the server's retry: (3000 ms when unset) with Last-Event-ID. An answer that is not a 200 text/event-stream fails the stream for good.

Platform shims ​

ExportSignatureDescription
installTextDecoderinstallTextDecoder(): booleanPuts StandardTextDecoder in place when the engine has no TextDecoder; true when it did.
StandardTextDecodernew StandardTextDecoder(label?: string, options?: { fatal?: boolean; ignoreBOM?: boolean })UTF-8 only; decode(input?: ArrayBuffer | ArrayBufferView, options?: { stream?: boolean }): string.
installStandardUrlinstallStandardUrl(): booleanPuts StandardURL in place of the platform's URL when that one is not standard; true when it did. The platform's createObjectURL stays reachable.
StandardURLnew StandardURL(url: string | StandardURL, base?: string | StandardURL)A standard URL: canParse, createObjectURL, revokeObjectURL, the URL parts, searchParams, href, toString(), toJSON().

@c9up/orbit/react-native ​

ExportKindDescription
runfunctionRegisters the root component as the app and mounts it when the activity starts.
RunOptionsinterfaceOptions of run.
LaunchPropstype{ [key: string]: unknown }: the props the app is started with. The activity ream android:* generates passes none, so root receives {}; the launch intent's extras are not read (another app can put anything in them).
APP_NAMEconst"main", the name the generated activity starts the app by.
FunctionSignatureDescription
runrun(root: (props: LaunchProps) => TemplateResult, options?: RunOptions): voidGives orbit the NativeOrbit host (throws E_ORBIT_NO_HOST when the module is not orbit's) and the style table, sets the colour scheme, sends the back button to goBack, and mounts root at the window's size with the launch props ({} from the generated activity).
RunOptions fieldTypeDefaultDescription
colorScheme'system' | 'light' | 'dark''system'system: dark: follows the phone's setting until the app sets colorScheme(…) itself; light / dark: that one, whatever the phone says.

@c9up/orbit/pages ​

ExportKindDescription
serverPagesfunctionThe stack the server's pages are shown in; put it in a template.
ServerPagesOptionsinterfaceOptions of serverPages.
FunctionSignatureDescription
serverPagesserverPages(options: ServerPagesOptions): StackA link or a visit asks the server for the next page object and shows the page it names as a screen; the back button goes through the router's history, and a covered page comes back as it was, without a request.
ServerPagesOptions fieldTypeDefaultDescription
serverstring | ServerConnectionrequiredThe server's origin (same rule as connectServer), or the connection connectServer made.
pages{ [name: string]: (props) => TemplateResult }requiredThe pages the server may name, by the name it renders them under. A name not listed throws E_ORBIT_UNKNOWN_PAGE.
urlstring'/'The first page's path.
stackOmit<StackOptions, 'back'>How screens change (transition, duration, background).
loading() => TemplateResultan empty viewShown until the first page has arrived.
failed(error: unknown, retry: () => void) => TemplateResultthe message and a Retry buttonShown when the server could not give a page; retry asks again.
open(url: string) => voidOpens a link off the server (another site, mailto:).

Errors ​

CodeRaised when
E_ORBIT_NO_HOSTmount ran before useHost, or the NativeOrbit module is not orbit's host.
E_ORBIT_COMMIT_FAILEDThe native host refused a commit; the message carries its report. What the commit carried is sent again with the next one.
E_ORBIT_TREE_TOO_DEEPThe views nest more than 100 levels deep: the host refuses the commit before it lays it out.
E_ORBIT_SVG_VALUEA value of an <svg> the host cannot read (a NaN length, unreadable path data, points or transform). That shape is left out (path data and points are drawn up to the error) and the rest drawn. Reported to onError, never thrown.
E_ORBIT_UNSUPPORTED_ELEMENTAn element has no native mapping (select, canvas, or text or a gradient inside an svg).
E_ORBIT_BLOCK_IN_TEXTA block element sits inside text.
E_ORBIT_INVALID_MOTIONmotion=${…} is not an object of motion values.
E_ORBIT_INVALID_SCROLL_BINDINGscroll-y=${…} is not a motion value.
E_ORBIT_INVALID_COLORA colour orbit cannot read.
E_ORBIT_INSECURE_IMAGE_URL<img src> uses plain http. Thrown for an address written in the template; for one from data (src=${…}) the image shows nothing and the error goes to onError.
E_ORBIT_IMAGE_SOURCE<img src> uses a scheme that is not an image source (data:, javascript:…), a scheme-relative address (//host/a.png) or a file: URL that does not decode. Thrown or reported as E_ORBIT_INSECURE_IMAGE_URL is.
E_ORBIT_DUPLICATE_KEYTwo elements of an each list share a key.
E_ORBIT_NO_SCREENuseScreen() runs in a component no screen built.
E_ORBIT_STACK_SHOWNOne stack is put in two places.
E_ORBIT_STYLE_TABLEuseStyles got something other than a table ream css:compile wrote.
E_ORBIT_INSECURE_SERVERconnectServer or serverPages is given plain http to a host that is neither this machine nor the emulator's.
E_ORBIT_UNKNOWN_PAGEThe server named a page that serverPages({ pages }) does not list.
E_ORBIT_FOREIGN_ORIGINA server connection was asked for a path that resolves to another origin.
E_ORBIT_SERVER_REQUEST_FAILEDThe server answered a json request with an empty non-2xx response.
E_ORBIT_NO_XHRServer events need an XMLHttpRequest, and the platform has none.
E_ORBIT_OBJECT_URL_UNAVAILABLEURL.createObjectURL was called with no platform URL to make blob URLs. A TypeError, as the standard URL raises.
E_ORBIT_INVALID_URLThe standard URL was given a URL, or a base, that does not parse. A TypeError, as the standard URL raises.
E_ORBIT_UNSUPPORTED_ENCODINGThe standard TextDecoder was given an encoding label other than UTF-8's. A RangeError, as the standard TextDecoder raises.
E_ORBIT_INVALID_DECODER_INPUTTextDecoder.decode was given something that is not an ArrayBuffer or a view on one. A TypeError, as the standard TextDecoder raises.
E_ORBIT_INVALID_ENCODED_DATAA fatal TextDecoder met bytes that are not valid UTF-8. A TypeError, as the standard TextDecoder raises.
E_ORBIT_INTERNALAn invariant inside orbit broke: a bug in orbit.

Every error is a class of the errors export, named by its code. The five raised by the standard URL and TextDecoder orbit installs stay a TypeError or a RangeError (name included), as those APIs raise, with the code added; the others are ream exceptions with a status.

Migration ​

  • OrbitError is gone: test error.code, or error instanceof errors.E_ORBIT_* with import { errors } from '@c9up/orbit'.
  • OrbitTypeError and OrbitRangeError are gone: the URL and TextDecoder refusals are still a TypeError / RangeError, now errors.E_ORBIT_INVALID_URL and the like. E_ORBIT_FOREIGN_ORIGIN and E_ORBIT_NO_XHR are no longer a TypeError: catch them by their code.
  • The OrbitErrorCode type is gone: error.code is a string.
  • An <img src=${…}> whose address comes from data no longer throws E_ORBIT_INSECURE_IMAGE_URL or E_ORBIT_IMAGE_SOURCE: that image shows nothing and the error goes to mount's onError. To act on it, pass onError. An address written in the template still throws.
  • <img src="//host/a.png"> is now refused with E_ORBIT_IMAGE_SOURCE; it used to load nothing from a local path. Write https://.
  • A scheduled commit the host refuses no longer rejects a microtask unseen: it goes to onError, and what it carried is sent with the next commit.
  • A view tree more than 100 levels deep is refused with E_ORBIT_TREE_TOO_DEEP (it used to crash the app past about 170). Limit how deep a template nests data that nests (replies to replies).
  • A value of an <svg> the host cannot read no longer fails the commit: that shape is left out and reported as E_ORBIT_SVG_VALUE.
  • <input maxlength> given a longer value keeps the value whole, as HTML does; maxlength limits typing only. It used to crash the app on Android.

See also ​