An open source design system that's fully customizable and agent ready
TypeScript
feat(native): AstryxLogicHost runs a logic core and drives native views (#7989)
Cindy Zhange769940915af
diff --git a/packages/native/README.md b/packages/native/README.mdindex ba9441e090..9db2ad5816 100644--- a/packages/native/README.md+++ b/packages/native/README.md@@ -21,6 +21,7 @@ rests on evidence.| Icons | `NATIVE_ICON_DEFAULTS` | Astryx's built-in icon names mapped to SF Symbols on Apple platforms and Material Symbols on Android. || Wire | `AstryxNode`, `AstryxAction` | Each component as JSON a TypeScript core sends a native host (arm C), and the action a host sends back when a view calls a callback. Swift decodes `<Name>Node` and turns it into `<Name>Props` with `viewProps(send:)`. || Logic core | `@astryxdesign/native/logic` | `createLogicCore` holds a screen's state, builds its node tree, and reduces actions; `connectBridge` carries it to a native host as JSON. ECMAScript built-ins only, so it runs in Hermes. Shaped after EJ Campbell's astryx-swift spike. |+| Logic host | `AstryxLogicHost` (Swift) | Runs a logic core bundle in JavaScriptCore, decodes each tree into `AstryxNode`, and sends views' actions back. A Hermes host speaks the same bridge. |Contracts cover Badge, Button, Card, Divider, Heading, HStack, ProgressBar,Selector, Switch, Text, TextInput, and VStack. React Native and Android@@ -90,14 +91,17 @@ const action: AstryxAction = {``````swift-let node = try JSONDecoder().decode(AstryxNode.self, from: snapshot)-if case .switch(let wifi) = node {- let props = wifi.viewProps { action in core.dispatch(action.json) }+let host = AstryxLogicHost(bundle: bundleSource) // calls the bundle's global astryxStart(host)+if case .switch(let wifi) = host.root {+ let props = wifi.viewProps(send: host.send)}``````ts+// tsconfig: "customConditions": ["ios"]+import type {AstryxAction, AstryxNode} from '@astryxdesign/native/components';import {connectBridge, createLogicCore} from '@astryxdesign/native/logic';+import type {Bridge, BridgeHost} from '@astryxdesign/native/logic';const core = createLogicCore<{wifi: boolean}, AstryxNode, AstryxAction>({initial: {wifi: true},@@ -112,13 +116,10 @@ const core = createLogicCore<{wifi: boolean}, AstryxNode, AstryxAction>({? {wifi: action.args[0]}: state,});-// In the app's JavaScript engine: the host reads snapshots and dispatches actions.-const bridge = connectBridge(core, {- connected() {},- changed(json) {- /* to Swift */- },-});+// The bundle's entry: the native host calls it with its two calls in and+// gets back the bridge it reads snapshots from and dispatches actions to.+(globalThis as {astryxStart?: (host: BridgeHost) => Bridge}).astryxStart =+ host => connectBridge(core, host);```## Working on itdiff --git a/packages/native/apple/Sources/AstryxNative/Logic/AstryxLogicHost.swift b/packages/native/apple/Sources/AstryxNative/Logic/AstryxLogicHost.swiftnew file mode 100644index 0000000000..4a66739a9a--- /dev/null+++ b/packages/native/apple/Sources/AstryxNative/Logic/AstryxLogicHost.swift@@ -0,0 +1,102 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+//+// The host side of arm C (AST-082 FR12): a TypeScript logic core runs in a+// JavaScript engine inside the app and native views draw its tree. Its shape+// follows the ClientHost of EJ Campbell's astryx-swift spike+// (github.com/ejc3/astryx-swift, MIT), which runs the core in Hermes. This host+// uses JavaScriptCore, part of the platform SDK, so the package needs nothing+// else; a Hermes host speaks the same bridge.++#if os(iOS) || os(macOS)+import Foundation+import JavaScriptCore+import Observation++/// Runs a logic core bundle and carries its tree to native views and their+/// actions back, as the JSON `@astryxdesign/native/logic`'s `connectBridge`+/// speaks.+///+/// The bundle defines a global function, `astryxStart` by default, that takes+/// the host (`connected(version)` and `changed(json)`) and returns the bridge+/// (`getSnapshot()` and `dispatch(json)`).+@MainActor+@Observable+public final class AstryxLogicHost {+ /// The bridge version this host speaks (`BRIDGE_VERSION` in TypeScript).+ public static let bridgeVersion = 1++ /// The current tree; nil before the first snapshot and once the host fails.+ public private(set) var root: AstryxNode?+ /// Why the core stopped or a snapshot could not be read.+ public private(set) var failure: String?++ @ObservationIgnored private let context: JSContext+ @ObservationIgnored private var bridge: JSValue?++ public init(bundle source: String, entry: String = "astryxStart") {+ context = JSContext()+ context.exceptionHandler = { [weak self] _, exception in+ let message = exception?.toString() ?? "An unknown JavaScript error"+ MainActor.assumeIsolated { self?.fail(message) }+ }+ context.evaluateScript(source)+ guard failure == nil else { return }+ guard let start = context.objectForKeyedSubscript(entry), start.isObject else {+ fail("The bundle defines no \(entry) function")+ return+ }+ let host = JSValue(newObjectIn: context)+ let connected: @convention(block) (Int) -> Void = { [weak self] version in+ MainActor.assumeIsolated {+ if version != Self.bridgeVersion {+ self?.fail("The core speaks bridge \(version); this host speaks \(Self.bridgeVersion)")+ }+ }+ }+ let changed: @convention(block) (String) -> Void = { [weak self] json in+ MainActor.assumeIsolated { self?.receive(json) }+ }+ host?.setObject(connected, forKeyedSubscript: "connected" as NSString)+ host?.setObject(changed, forKeyedSubscript: "changed" as NSString)+ bridge = start.call(withArguments: [host as Any])+ guard failure == nil, let snapshot = bridge?.invokeMethod("getSnapshot", withArguments: []),+ snapshot.isString, let json = snapshot.toString() else {+ if failure == nil { fail("The bridge returned no snapshot") }+ return+ }+ receive(json)+ }++ /// Sends a view's action to the core: `node.viewProps(send: host.send)`.+ /// Views call it on the main thread, where it dispatches at once; from any+ /// other thread it dispatches on the main actor.+ public nonisolated func send(_ action: AstryxAction) {+ if Thread.isMainThread {+ MainActor.assumeIsolated { dispatch(action) }+ } else {+ Task { @MainActor in self.dispatch(action) }+ }+ }++ private func dispatch(_ action: AstryxAction) {+ guard failure == nil, let bridge else { return }+ bridge.invokeMethod("dispatch", withArguments: [action.json])+ }++ private func receive(_ json: String) {+ // A failed host stays failed: a later tree does not bring it back.+ guard failure == nil else { return }+ do {+ root = try JSONDecoder().decode(AstryxNode.self, from: Data(json.utf8))+ } catch {+ fail("The core sent a tree this binding cannot read: \(error)")+ }+ }++ /// Stops the host: no tree to draw and no actions sent.+ private func fail(_ message: String) {+ failure = message+ root = nil+ }+}+#endifdiff --git a/packages/native/apple/Tests/AstryxNativeTests/LogicHostTests.swift b/packages/native/apple/Tests/AstryxNativeTests/LogicHostTests.swiftnew file mode 100644index 0000000000..cca95ea394--- /dev/null+++ b/packages/native/apple/Tests/AstryxNativeTests/LogicHostTests.swift@@ -0,0 +1,85 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import Testing+@testable import AstryxNative++/// A logic core with the bridge `@astryxdesign/native/logic` exposes, written+/// out by hand so the Swift tests need no build step.+private let settingsBundle = """+function astryxStart(host) {+ var state = {wifi: true};+ function view() {+ return {component: 'VStack', key: 'root', props: {children: [+ {component: 'Switch', key: 'wifi', props: {label: 'Wi-Fi', value: state.wifi}, events: ['onChange']},+ {component: 'Text', key: 'status', props: {children: state.wifi ? 'Connected' : 'Off'}}+ ]}};+ }+ host.connected(1);+ return {+ getSnapshot: function () { return JSON.stringify(view()); },+ dispatch: function (json) {+ var action = JSON.parse(json);+ if (action.key === 'wifi' && action.event === 'onChange') {+ state = {wifi: action.args[0]};+ host.changed(JSON.stringify(view()));+ }+ }+ };+}+"""++@MainActor+@Test func aViewsActionReachesTheCoreAndTheNewTreeComesBack() throws {+ let host = AstryxLogicHost(bundle: settingsBundle)+ #expect(host.failure == nil)+ guard case .vStack(let stack) = host.root, case .switch(let wifi) = stack.props.children?[0] else {+ Issue.record("unexpected first tree")+ return+ }+ #expect(wifi.props.value == true)++ // The view calls its onChange; the action goes to the core.+ let props = wifi.viewProps(send: host.send)+ props.onChange?(false)++ guard case .vStack(let next) = host.root, case .text(let status) = next.props.children?[1] else {+ Issue.record("unexpected next tree")+ return+ }+ #expect(status.props.children == "Off")+}++@MainActor+@Test func aLaterErrorClearsTheTreeAndStopsActions() throws {+ let bundle = settingsBundle + "\nvar fragile = astryxStart; astryxStart = function (h) { var b = fragile(h); var d = b.dispatch; b.dispatch = function (j) { if (JSON.parse(j).args[0] === false) throw new Error('core broke'); d(j); }; return b; };"+ let host = AstryxLogicHost(bundle: bundle)+ guard case .vStack(let stack) = host.root, case .switch(let wifi) = stack.props.children?[0] else {+ Issue.record("unexpected first tree")+ return+ }+ wifi.viewProps(send: host.send).onChange?(false)+ #expect(host.failure?.contains("core broke") == true)+ #expect(host.root == nil)+}++@MainActor+@Test func aTreeAfterAFailureIsIgnored() {+ let bundle = """+ function astryxStart(h) {+ h.connected(2);+ h.changed(JSON.stringify({component: 'Text', key: 'late', props: {children: 'Too late'}}));+ return {getSnapshot: function () { return '{}'; }, dispatch: function () {}};+ }+ """+ let host = AstryxLogicHost(bundle: bundle)+ #expect(host.failure?.contains("bridge 2") == true)+ #expect(host.root == nil)+}++@MainActor+@Test func aBundleWithoutTheEntryOrWithAnErrorFails() {+ #expect(AstryxLogicHost(bundle: "var x = 1;").failure == "The bundle defines no astryxStart function")+ #expect(AstryxLogicHost(bundle: "throw new Error('boom');").failure?.contains("boom") == true)+ let wrongVersion = AstryxLogicHost(bundle: "function astryxStart(h) { h.connected(2); return {getSnapshot: function () { return '{}'; }}; }")+ #expect(wrongVersion.failure?.contains("bridge 2") == true)+}