ReviewOS

also looking at this

craft-native/craft

feat: finish native customization and platform seams

#401
Merged glennmichael123 wants to merge codex/issues-388-400-344 into main
21 files +707 -17
packages/ios/templates/CraftApp.swiftmodified+153-3
Changes to packages/ios/templates/CraftApp.swift
@@ -102,6 +102,96 @@ enum CraftPageAppearance {
102102 }
103103}
104104
105/// The app-wide UIKit appearance override. SwiftUI's `preferredColorScheme`
106/// only controls the SwiftUI environment; native screen controllers need the
107/// UIKit override as well so their trait collection, controls and navigation
108/// chrome resolve the same way. A runtime choice is kept here so screens
109/// created after the choice inherit it instead of reverting to the bundle
110/// config.
111enum CraftInterfaceStyleController {
112 /// The app's bundled choice is the default for newly-created screens.
113 /// A runtime choice is separate: it is the only value that should
114 /// override a screen's own generated config.
115 private static var configured: UIUserInterfaceStyle = .unspecified
116 private static var runtimeSelection: UIUserInterfaceStyle?
117
118 static func configuredStyle(for config: CraftConfig) -> UIUserInterfaceStyle {
119 switch config.appearance {
120 case "system": return .unspecified
121 case "light": return .light
122 case "dark": return .dark
123 default: return config.darkMode ? .dark : .light
124 }
125 }
126
127 static func configure(_ config: CraftConfig) {
128 configured = configuredStyle(for: config)
129 runtimeSelection = nil
130 applyToWindows()
131 }
132
133 static func style(for config: CraftConfig) -> UIUserInterfaceStyle {
134 runtimeSelection ?? configuredStyle(for: config)
135 }
136
137 static func colorScheme(for config: CraftConfig) -> ColorScheme? {
138 switch style(for: config) {
139 case .light: return .light
140 case .dark: return .dark
141 default: return nil
142 }
143 }
144
145 /// Returns false rather than silently accepting a typo from JavaScript.
146 @discardableResult
147 static func set(_ value: String) -> Bool {
148 let style: UIUserInterfaceStyle
149 switch value {
150 case "system": style = .unspecified
151 case "light": style = .light
152 case "dark": style = .dark
153 default: return false
154 }
155 runtimeSelection = style
156 applyToWindows()
157 NotificationCenter.default.post(name: .craftColorSchemeChanged, object: nil)
158 return true
159 }
160
161 static func currentName() -> String {
162 let requested = runtimeSelection ?? UIApplication.shared.connectedScenes
163 .compactMap { ($0 as? UIWindowScene)?.windows.first(where: { $0.isKeyWindow })?.traitCollection.userInterfaceStyle }
164 .first ?? .unspecified
165 let style = requested == .unspecified
166 ? (UIApplication.shared.connectedScenes
167 .compactMap { ($0 as? UIWindowScene)?.windows.first(where: { $0.isKeyWindow })?.traitCollection.userInterfaceStyle }
168 .first { $0 != .unspecified } ?? UITraitCollection.current.userInterfaceStyle)
169 : requested
170 return style == .dark ? "dark" : "light"
171 }
172
173 static func apply(to controller: UIViewController, config: CraftConfig) {
174 controller.overrideUserInterfaceStyle = style(for: config)
175 }
176
177 private static func applyToWindows() {
178 let style = runtimeSelection ?? configured
179 for scene in UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene }) {
180 for window in scene.windows {
181 window.overrideUserInterfaceStyle = style
182 apply(style, to: window.rootViewController)
183 }
184 }
185 }
186
187 private static func apply(_ style: UIUserInterfaceStyle, to controller: UIViewController?) {
188 guard let controller else { return }
189 controller.overrideUserInterfaceStyle = style
190 controller.children.forEach { apply(style, to: $0) }
191 if let presented = controller.presentedViewController { apply(style, to: presented) }
192 }
193}
194
105195/// Tells the shell when SwiftUI's colour scheme changes: the one appearance
106196/// setting with no notification of its own.
107197struct CraftColorSchemeObserver: View {
@@ -195,6 +285,7 @@ struct CraftRecoveryBudget {
195285final class CraftAppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
196286 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
197287 let config = CraftConfig.bundled()
288 CraftInterfaceStyleController.configure(config)
198289 // First, so a crash anywhere in the rest of launch is reported too.
199290 CraftCrashReporter.shared.start(config)
200291 UNUserNotificationCenter.current().delegate = self
@@ -606,7 +697,7 @@ struct CraftApp: App {
606697 .ignoresSafeArea(.keyboard, edges: .bottom)
607698 }
608699 }
609 .preferredColorScheme(appState.config.colorScheme)
700 .preferredColorScheme(appState.appearanceScheme)
610701 .environmentObject(appState)
611702 .onOpenURL { url in
612703 // Handle deep links and universal links
@@ -689,6 +780,10 @@ final class CraftChrome: ObservableObject {
689780 /// The selected tab highlight's corner radius. Nil preserves the default
690781 /// capsule, while a finite non-negative value opts into a rounded rect.
691782 private(set) var tabSelectionCornerRadius: CGFloat?
783 /// The configured static shape, retained when the page updates only its
784 /// tabs or selected item at runtime.
785 private var configuredTabSelectionCornerRadius: CGFloat?
786 private(set) var tabSelectionColor: UIColor?
692787
693788 weak var webView: WKWebView?
694789 /// What the tab bar covers at the bottom of the screen, in points.
@@ -723,9 +818,13 @@ final class CraftChrome: ObservableObject {
723818 /// The tab bar from `tabs` in craft.config.json, there before the page
724819 /// loads; the page's own `tabBar` message replaces it later. `splash`
725820 /// false when the first screen is native and draws itself.
726 func configure(tabs configured: [CraftConfig.Tab], selected: String?, splash: Bool) {
821 func configure(tabs configured: [CraftConfig.Tab], selected: String?, splash: Bool, appearance: CraftConfig.TabBar? = nil) {
727822 splashVisible = splash
728823 tabSwipeEnabled = true
824 configuredTabSelectionCornerRadius = appearance?.selection?.cornerRadius
825 .flatMap { $0.isFinite && $0 >= 0 ? CGFloat($0) : nil }
826 tabSelectionCornerRadius = configuredTabSelectionCornerRadius
827 tabSelectionColor = appearance?.selection?.color.flatMap { UIColor(hex: $0) }
729828 guard !configured.isEmpty else { return }
730829 tabs = configured.map { Tab(id: $0.id, title: $0.title, symbol: $0.symbol ?? "circle", badge: nil, selectedSymbol: Tab.normalizedSelectedSymbol($0.selectedSymbol), selectedIconTint: $0.selectedIconTint, selectedIconPulse: $0.selectedIconPulse) }
731830 self.selected = selected ?? configured.first?.id
@@ -856,6 +955,7 @@ final class CraftChrome: ObservableObject {
856955 tint = light.map { light in dark.map { dark in UIColor { $0.userInterfaceStyle == .dark ? dark : light } } ?? light }
857956 }
858957 if let swipeEnabled = body["swipeEnabled"] as? Bool { tabSwipeEnabled = swipeEnabled }
958 if !body.keys.contains("selection") { tabSelectionCornerRadius = configuredTabSelectionCornerRadius }
859959 withAnimation(Self.motion(.easeOut(duration: 0.2))) { tabBarVisible = !tabs.isEmpty && !hiddenByScreen }
860960 publishLayout()
861961 case "selectTab":
@@ -1312,6 +1412,7 @@ private struct CraftTabSelectionShape: Shape {
13121412}
13131413
13141414private struct CraftTabSelectionIndicator: View {
1415 @ObservedObject private var chrome = CraftChrome.shared
13151416 @ObservedObject private var progress = CraftChrome.shared.tabSwipeProgress
13161417 let selected: Int?
13171418 let count: Int
@@ -1323,7 +1424,7 @@ private struct CraftTabSelectionIndicator: View {
13231424 let width = geometry.size.width / CGFloat(max(1, count))
13241425 CraftTabSelectionShape(cornerRadius: cornerRadius)
13251426 .frame(width: width, height: geometry.size.height)
1326 .foregroundStyle(Color.primary.opacity(0.09))
1427 .foregroundStyle(chrome.tabSelectionColor.map { Color($0) } ?? Color.primary.opacity(0.09))
13271428 .offset(x: position * width)
13281429 }
13291430 }
@@ -1557,6 +1658,8 @@ class DeepLinkManager {
15571658// MARK: - App State
15581659class AppState: ObservableObject {
15591660 @Published var config: CraftConfig
1661 @Published private(set) var appearanceScheme: ColorScheme?
1662 private var appearanceObserver: NSObjectProtocol?
15601663
15611664 init() {
15621665 if let configURL = Bundle.main.url(forResource: "craft.config", withExtension: "json"),
@@ -1565,11 +1668,26 @@ class AppState: ObservableObject {
15651668 } else {
15661669 self.config = CraftConfig()
15671670 }
1671 self.appearanceScheme = CraftInterfaceStyleController.colorScheme(for: config)
1672 appearanceObserver = NotificationCenter.default.addObserver(
1673 forName: .craftColorSchemeChanged,
1674 object: nil,
1675 queue: .main,
1676 ) { [weak self] _ in
1677 guard let self else { return }
1678 self.appearanceScheme = CraftInterfaceStyleController.colorScheme(for: self.config)
1679 }
15681680 // Before the first frame: the hybrid start screen, and the tab bar
15691681 // from the config, are decided here, if the app delegate has not
15701682 // already (it does at launch; the first call decides).
15711683 CraftHybrid.shared.configure(config)
15721684 }
1685
1686 deinit {
1687 if let appearanceObserver {
1688 NotificationCenter.default.removeObserver(appearanceObserver)
1689 }
1690 }
15731691}
15741692
15751693extension CraftConfig {
@@ -1706,6 +1824,9 @@ struct CraftConfig: Codable {
17061824 var nativeScreens: [String: String]? = nil
17071825 /// The tab bar to show before the page describes its own.
17081826 var tabs: [Tab]? = nil
1827 /// Static styling for the selected tab indicator; the page may still
1828 /// override its shape through `tabBar.set({ selection })`.
1829 var tabBar: TabBar? = nil
17091830 /// Hybrid: web-storage keys the page's own code writes, mirrored into the
17101831 /// Keychain under another name for native screens (`{"auth_token": "auth.token"}`).
17111832 var shareStorage: [String: String]? = nil
@@ -1733,6 +1854,15 @@ struct CraftConfig: Codable {
17331854 var selectedIconPulse: Bool? = nil
17341855 }
17351856
1857 struct TabBar: Codable {
1858 var selection: TabSelection? = nil
1859 }
1860
1861 struct TabSelection: Codable {
1862 var cornerRadius: Double? = nil
1863 var color: String? = nil
1864 }
1865
17361866 struct BackgroundRefresh: Codable {
17371867 var enabled: Bool = false
17381868 /// The BGTaskScheduler identifier; `<bundleId>.refresh` if unset.
@@ -2535,6 +2665,18 @@ struct CraftWebView: UIViewRepresentable {
25352665 resolveCallback(callbackId, result: CraftSymbols.image(named: body["name"] as? String ?? "", options: body) ?? NSNull())
25362666 case "statusBarSetStyle":
25372667 resolveCallback(callbackId, result: CraftStatusBar.setStyle(body["style"] as? String ?? "default"))
2668 case "setAppearance":
2669 guard let appearance = body["appearance"] as? String else {
2670 rejectCallback(callbackId, error: "setAppearance needs light, dark or system", code: "INVALID_ARGUMENT")
2671 return
2672 }
2673 guard CraftInterfaceStyleController.set(appearance) else {
2674 rejectCallback(callbackId, error: "setAppearance needs light, dark or system", code: "INVALID_ARGUMENT")
2675 return
2676 }
2677 resolveCallback(callbackId, result: true)
2678 case "getAppearance":
2679 resolveCallback(callbackId, result: CraftInterfaceStyleController.currentName())
25382680 case "chromeSetUnderPageColor":
25392681 // What shows past the page's edges when it rubber-bands.
25402682 if #available(iOS 15.0, *), let webView, let css = body["color"] as? String, let color = UIColor(css: css) {
@@ -5596,6 +5738,14 @@ struct CraftWebView: UIViewRepresentable {
55965738 getInfo: function() { return craft.getDeviceInfo(); },
55975739 getCapabilities: function() { return Promise.resolve(Object.assign({}, craft.capabilities)); }
55985740 };
5741 craft.app = Object.assign(craft.app || {}, {
5742 setAppearance: function(appearance) {
5743 return craft._invoke('setAppearance', {appearance: appearance});
5744 },
5745 getAppearance: function() {
5746 return craft._invoke('getAppearance', {});
5747 }
5748 });
55995749 // Feedback, as on Android and the web, where there is no
56005750 // motor to fire: an app that left enableHaptics off gets
56015751 // nothing played and a settled promise, so `await