peachsim 0.1.2674 → 0.1.2676

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 (142) hide show
  1. package/dist-lib/agent-daemon-client.cjs +1 -1
  2. package/dist-lib/agent-events.cjs +1 -1
  3. package/dist-lib/attached-projects.cjs +1 -1
  4. package/dist-lib/auth/shared-session.cjs +1 -1
  5. package/dist-lib/backend-origin.cjs +1 -1
  6. package/dist-lib/beta.cjs +1 -1
  7. package/dist-lib/beta.mjs +2 -2
  8. package/dist-lib/bridge-constants.cjs +1 -1
  9. package/dist-lib/bridge-contract-input.cjs +1 -1
  10. package/dist-lib/bridge-contract-input.mjs +5 -5
  11. package/dist-lib/bridge-contract.cjs +1 -1
  12. package/dist-lib/bridge-contract.mjs +3 -3
  13. package/dist-lib/bundle-channel.cjs +105 -67
  14. package/dist-lib/capture-contract.cjs +1 -1
  15. package/dist-lib/capture-contract.mjs +3 -3
  16. package/dist-lib/cloud-contract.cjs +1 -1
  17. package/dist-lib/cloud-contract.mjs +3 -3
  18. package/dist-lib/cloud-test-args.cjs +1 -1
  19. package/dist-lib/cloud-test-args.mjs +2 -2
  20. package/dist-lib/cloud.cjs +1 -1
  21. package/dist-lib/cloud.mjs +7 -7
  22. package/dist-lib/config.cjs +1 -1
  23. package/dist-lib/config.mjs +5 -5
  24. package/dist-lib/detox/index.cjs +1 -1
  25. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  26. package/dist-lib/esm-chunks/{acorn-7UZN4VYK.mjs → acorn-YQ2Y333V.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-BVXC4YET.mjs → chunk-25EMRCS4.mjs} +1 -1
  28. package/dist-lib/esm-chunks/{chunk-ASL76C2M.mjs → chunk-3TL2TT2H.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-Y3Y67ML7.mjs → chunk-4Q6YODSW.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-6MQE6NHP.mjs → chunk-5EH6JZZK.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-5HLALTZU.mjs → chunk-626GTL22.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-UR4364IC.mjs → chunk-A35OFKUL.mjs} +15 -15
  33. package/dist-lib/esm-chunks/{chunk-JN5AITFW.mjs → chunk-B3U6FXEV.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-K6YX77B2.mjs → chunk-D575CGCI.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-TCJINVW7.mjs → chunk-DG6QGBQR.mjs} +6 -6
  36. package/dist-lib/esm-chunks/{chunk-PGWO5WJS.mjs → chunk-FVUPL6XV.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-DDKNMOMP.mjs → chunk-FWXP663K.mjs} +5 -5
  38. package/dist-lib/esm-chunks/{chunk-64GNURGG.mjs → chunk-HKPMHGF2.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-OICCOALD.mjs → chunk-JSIHMPMM.mjs} +4 -4
  40. package/dist-lib/esm-chunks/{chunk-S6FAF3O6.mjs → chunk-KLFBECKK.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-YTLETAHS.mjs → chunk-LF6SZQV5.mjs} +2 -2
  42. package/dist-lib/esm-chunks/{chunk-UQLURJW5.mjs → chunk-MPFHNHE7.mjs} +6 -6
  43. package/dist-lib/esm-chunks/{chunk-7LVYKI6B.mjs → chunk-QGE6LXQT.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-GY2LAJOJ.mjs → chunk-QRFI6Y4S.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-JGCL2DFM.mjs → chunk-RADKK7SO.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-GR6LZLL3.mjs → chunk-S6J4D2JN.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-UYNBXPDJ.mjs → chunk-UANRG6RG.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-OSSY6ZNV.mjs → chunk-VBRL6FF3.mjs} +3 -3
  49. package/dist-lib/esm-chunks/{chunk-YTVAFL2C.mjs → chunk-VUPCH2NW.mjs} +1 -1
  50. package/dist-lib/esm-chunks/{chunk-54JOIACB.mjs → chunk-ZK5FTTPS.mjs} +1 -1
  51. package/dist-lib/esm-chunks/{metro-layout-parser-SIV4DJUF.mjs → metro-layout-parser-AVSCGHIP.mjs} +3 -3
  52. package/dist-lib/esm-chunks/{swift-package-prebuilt-U4TO4A5N.mjs → swift-package-prebuilt-WAUVHTJ6.mjs} +12 -12
  53. package/dist-lib/esm-chunks/{swift-sdk-app-module-J5OL6AQS.mjs → swift-sdk-app-module-SMITHJSE.mjs} +16 -16
  54. package/dist-lib/esm-chunks/{swift-sdk-image-CV5NS7AQ.mjs → swift-sdk-image-A3PUVC5O.mjs} +16 -16
  55. package/dist-lib/esm-chunks/{swift-sdk-image-producer-I4HX7YZO.mjs → swift-sdk-image-producer-5OLYXCL2.mjs} +5 -5
  56. package/dist-lib/expo-swift-bundle.cjs +75 -42
  57. package/dist-lib/expo-swift-metadata.cjs +1 -1
  58. package/dist-lib/expo-swift-metadata.mjs +7 -7
  59. package/dist-lib/home-paths.cjs +1 -1
  60. package/dist-lib/host/bridge-host.cjs +3181 -865
  61. package/dist-lib/host/fetch-proxy-handler.cjs +12 -11
  62. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  63. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  64. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  65. package/dist-lib/host/websocket-proxy.cjs +1 -1
  66. package/dist-lib/index.cjs +1 -1
  67. package/dist-lib/kotlin-host.cjs +1 -1
  68. package/dist-lib/menu.cjs +1 -1
  69. package/dist-lib/menu.mjs +3 -3
  70. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  71. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  72. package/dist-lib/metro-production-bundle.cjs +1 -1
  73. package/dist-lib/metro-production-bundle.mjs +4 -4
  74. package/dist-lib/native-app-identity-project.cjs +20 -4
  75. package/dist-lib/native-app-identity-project.mjs +34 -18
  76. package/dist-lib/native-app-identity.cjs +1 -1
  77. package/dist-lib/native-app-identity.mjs +6 -6
  78. package/dist-lib/native-firebase-metadata.cjs +1 -1
  79. package/dist-lib/native-firebase-metadata.mjs +3 -3
  80. package/dist-lib/pdfium-raster.cjs +1 -1
  81. package/dist-lib/pdfium-raster.mjs +2 -2
  82. package/dist-lib/plist.cjs +1 -1
  83. package/dist-lib/plist.mjs +3 -3
  84. package/dist-lib/profiles.cjs +1 -1
  85. package/dist-lib/public-brand.cjs +1 -1
  86. package/dist-lib/public-origins-lib-esm.json +85 -85
  87. package/dist-lib/public-origins-lib.json +68 -64
  88. package/dist-lib/react-native-host-modules.cjs +1 -1
  89. package/dist-lib/react-native-host-modules.mjs +2 -2
  90. package/dist-lib/reap-browser.cjs +1 -1
  91. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  92. package/dist-lib/sdk.cjs +1 -1
  93. package/dist-lib/sdk.mjs +8 -8
  94. package/dist-lib/skills.cjs +3569 -1253
  95. package/dist-lib/swift-compile.cjs +2 -2
  96. package/dist-lib/swift-compile.mjs +12 -12
  97. package/dist-lib/swift-package.cjs +1 -1
  98. package/dist-lib/swift-package.mjs +3 -3
  99. package/dist-lib/swift-submit.cjs +1 -1
  100. package/dist-lib/swift-submit.mjs +6 -6
  101. package/dist-lib/swift-svg-raster.cjs +1 -1
  102. package/dist-lib/swift-svg-raster.mjs +2 -2
  103. package/dist-lib/swift-toolchain.cjs +1 -1
  104. package/dist-lib/swift.cjs +1 -1
  105. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  106. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  107. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  108. package/dist-lib/vendor/acorn.cjs +1 -1
  109. package/dist-lib/vendor/magic-string.cjs +1 -1
  110. package/dist-lib/vendor/stream-json.cjs +1 -1
  111. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  112. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  113. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase.cjs +1 -1
  116. package/dist-lib/vendor/terser.cjs +1 -1
  117. package/dist-lib/vendor/valibot.cjs +1 -1
  118. package/dist-lib/vendor/ws.cjs +1 -1
  119. package/dist-lib/vendor/zod.cjs +1 -1
  120. package/dist-lib/worklet-executable.cjs +1 -1
  121. package/dist-lib/worklet-executable.mjs +3 -3
  122. package/dist-types/packages/peach-engine/src/remote-stream/client-config.d.ts +4 -0
  123. package/package.json +1 -1
  124. package/sdk/ios/System/Library/Frameworks/AssetsLibrary.framework/Headers/ALAsset.h +14 -0
  125. package/sdk/ios/System/Library/Frameworks/AssetsLibrary.framework/Headers/ALAssetRepresentation.h +20 -0
  126. package/sdk/ios/System/Library/Frameworks/AssetsLibrary.framework/Headers/ALAssetsLibrary.h +71 -0
  127. package/sdk/ios/System/Library/Frameworks/AssetsLibrary.framework/Headers/AssetsLibrary.h +5 -0
  128. package/sdk/ios/System/Library/Frameworks/AssetsLibrary.framework/Modules/module.modulemap +5 -0
  129. package/sdk/ios/System/Library/Frameworks/BackgroundTasks.framework/Headers/BGTask.h +21 -0
  130. package/sdk/ios/System/Library/Frameworks/BackgroundTasks.framework/Headers/BGTaskRequest.h +24 -0
  131. package/sdk/ios/System/Library/Frameworks/BackgroundTasks.framework/Headers/BGTaskScheduler.h +32 -0
  132. package/sdk/ios/System/Library/Frameworks/BackgroundTasks.framework/Headers/BackgroundTasks.h +5 -0
  133. package/sdk/ios/System/Library/Frameworks/BackgroundTasks.framework/Modules/module.modulemap +5 -0
  134. package/sdk/ios/System/Library/Frameworks/LinkPresentation.framework/Headers/LPLinkMetadata.h +17 -0
  135. package/sdk/ios/System/Library/Frameworks/LinkPresentation.framework/Headers/LPMetadataProvider.h +18 -0
  136. package/sdk/ios/System/Library/Frameworks/LinkPresentation.framework/Headers/LinkPresentation.h +4 -0
  137. package/sdk/ios/System/Library/Frameworks/LinkPresentation.framework/Modules/module.modulemap +5 -0
  138. package/src/expo-native-workspace.ts +3 -4
  139. package/src/one-direct-host-source.ts +1934 -0
  140. package/src/one-native-controls-package.ts +157 -21
  141. package/src/turbo-source.ts +60 -23
  142. package/src/xcode-project.ts +30 -2
@@ -0,0 +1,1934 @@
1
+ // guest-side sources for direct core-to-Swift container hosting inside OneNativeControls.
2
+ // compiles iOS's PeachSwiftUI.mm, PeachSheet.mm, PeachMenu.mm and PeachPopover.mm directly
3
+ // against Peach's Swift SDK and exposes the 8-slot container host Wasm ABI.
4
+
5
+ export const ONE_DIRECT_STAGE_SWIFT = `import Foundation
6
+ @_spi(Peach) import SwiftUI
7
+ @_spi(Peach) import UIKit
8
+
9
+ @MainActor
10
+ private final class PeachOneStageContainerView: UIView {
11
+ var onWindowAttached: (() -> Void)?
12
+
13
+ override func didMoveToWindow() {
14
+ super.didMoveToWindow()
15
+ if window != nil {
16
+ onWindowAttached?()
17
+ }
18
+ }
19
+
20
+ override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
21
+ let hit = super.hitTest(point, with: event)
22
+ return hit === self ? nil : hit
23
+ }
24
+ }
25
+
26
+ @MainActor
27
+ @objc(PeachOneDirectStage)
28
+ public final class PeachOneDirectStage: NSObject {
29
+ @objc public static let shared = PeachOneDirectStage()
30
+ @objc public let stageView: UIView
31
+ private var generation: UInt64 = 0
32
+ var onStageDirty: (() -> Void)?
33
+ @objc public var onWindowAttached: (() -> Void)? {
34
+ didSet {
35
+ (stageView as? PeachOneStageContainerView)?.onWindowAttached = onWindowAttached
36
+ }
37
+ }
38
+
39
+ private override init() {
40
+ let view = PeachOneStageContainerView(frame: .zero)
41
+ view.backgroundColor = .clear
42
+ self.stageView = view
43
+ _ = OneNativeAsyncActionModule.self
44
+ super.init()
45
+ }
46
+
47
+ @objc public func tagHostView(_ view: UIView, node: UInt64, hostContentNode: UInt64) {
48
+ if node == 0 {
49
+ view._peachReactContentHost = nil
50
+ } else {
51
+ view._peachReactContentHost = "__peach_one_host:\\(node):\\(hostContentNode)"
52
+ }
53
+ }
54
+
55
+ @objc public func tagContentView(_ view: UIView, node: UInt64) {
56
+ if node == 0 {
57
+ view._peachReactContentHost = nil
58
+ } else {
59
+ view._peachReactContentHost = "__peach_one_content:\\(node)"
60
+ }
61
+ }
62
+
63
+ @objc public func attachHostView(_ view: UIView, frame: CGRect) {
64
+ if view.superview !== stageView {
65
+ view.removeFromSuperview()
66
+ stageView.addSubview(view)
67
+ }
68
+ if view.frame != frame {
69
+ view.frame = frame
70
+ }
71
+ }
72
+
73
+ @objc public func detachHostView(_ view: UIView) {
74
+ view._peachReactContentHost = nil
75
+ if view.superview === stageView {
76
+ view.removeFromSuperview()
77
+ }
78
+ }
79
+
80
+ @objc public func markDirty() {
81
+ generation &+= 1
82
+ onStageDirty?()
83
+ }
84
+ }
85
+
86
+ @MainActor
87
+ private final class PeachDirectTableView: UITableView {
88
+ var onLayoutBounds: ((CGSize) -> Void)?
89
+ var onWindowChanged: ((Bool) -> Void)?
90
+ private var lastReportedSize: CGSize = .zero
91
+
92
+ override func didMoveToWindow() {
93
+ super.didMoveToWindow()
94
+ onWindowChanged?(window != nil)
95
+ }
96
+
97
+ override func layoutSubviews() {
98
+ super.layoutSubviews()
99
+ let size = bounds.size
100
+ if size != lastReportedSize {
101
+ lastReportedSize = size
102
+ onLayoutBounds?(size)
103
+ }
104
+ }
105
+ }
106
+
107
+ @MainActor
108
+ private final class PeachDirectTableCell: UITableViewCell {
109
+ var rowIndex: Int = NSNotFound
110
+ weak var hostedView: UIView?
111
+ var hostedNode: UInt64 = 0
112
+
113
+ override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
114
+ super.init(style: style, reuseIdentifier: reuseIdentifier)
115
+ backgroundColor = .clear
116
+ contentView.backgroundColor = .clear
117
+ contentView.clipsToBounds = true
118
+ }
119
+
120
+ required init?(coder: NSCoder) {
121
+ fatalError("init(coder:) has not been implemented")
122
+ }
123
+
124
+ override func prepareForReuse() {
125
+ let hosted = hostedView
126
+ hostedView = nil
127
+ hostedNode = 0
128
+ rowIndex = NSNotFound
129
+ if let hosted, hosted.superview === contentView {
130
+ hosted.removeFromSuperview()
131
+ }
132
+ super.prepareForReuse()
133
+ }
134
+
135
+ override func layoutSubviews() {
136
+ super.layoutSubviews()
137
+ if let hosted = hostedView, hosted.superview === contentView {
138
+ let target = contentView.bounds
139
+ if hosted.frame != target {
140
+ hosted.frame = target
141
+ }
142
+ }
143
+ }
144
+ }
145
+
146
+ @MainActor
147
+ private struct PeachDirectMountedRow {
148
+ let node: UInt64
149
+ weak var view: UIView?
150
+ }
151
+
152
+ @MainActor
153
+ private struct PeachWeakViewBox {
154
+ weak var view: UIView?
155
+ }
156
+
157
+ @MainActor
158
+ @objc(PeachDirectTableList)
159
+ public final class PeachDirectTableList: NSObject, UITableViewDataSource, UITableViewDelegate {
160
+ private static let cellIdentifier = "PeachDirectTableCell"
161
+
162
+ private var table: PeachDirectTableView?
163
+ private var headerHost: UIView?
164
+ private var footerHost: UIView?
165
+ private var emptyHost: UIView?
166
+ private weak var headerView: UIView?
167
+ private weak var footerView: UIView?
168
+ private weak var emptyView: UIView?
169
+ private var headerNode: UInt64 = 0
170
+ private var footerNode: UInt64 = 0
171
+ private var emptyNode: UInt64 = 0
172
+
173
+ private var ownedViews: [ObjectIdentifier: PeachWeakViewBox] = [:]
174
+ private var mountedRows: [Int: PeachDirectMountedRow] = [:]
175
+
176
+ private var keys: [String] = []
177
+ private var keyToIndex: [String: Int] = [:]
178
+ private var selectableFlags: [Bool]?
179
+ private var allowsSelection: Bool = true
180
+ private var selectedControlled: Bool = false
181
+ private var selectedKey: String?
182
+
183
+ private var estimatedRowHeight: CGFloat = 56.0
184
+ private var lead: Double = 2.0
185
+ private var hasHeader: Bool = false
186
+ private var hasFooter: Bool = false
187
+ private var hasEmpty: Bool = false
188
+ private var paddingTop: CGFloat = 0.0
189
+ private var paddingBottom: CGFloat = 0.0
190
+ private var rowIndices: [Int] = []
191
+
192
+ private var observeScroll: Bool = false
193
+ private var observeRange: Bool = false
194
+ private var observeRowFrame: Bool = false
195
+ private var scrollEventThrottleMs: Double = 16.0
196
+ private var lastScrollEmitTime: TimeInterval = 0
197
+ private var lastOffset: CGPoint = .zero
198
+ private var lastOffsetTime: TimeInterval = 0
199
+ private var dragging: Bool = false
200
+ private var userDecelerating: Bool = false
201
+ private var mounting: Bool = false
202
+ private var commandScrolling: Bool = false
203
+ private var scrollingBack: Bool = false
204
+ private var lastContentSize: CGSize = .zero
205
+ private var lastViewportSize: CGSize = .zero
206
+
207
+ private var spec: NSDictionary?
208
+ private var contentInsetValue: UIEdgeInsets = .zero
209
+ private var appliedContentInset: UIEdgeInsets = .zero
210
+ private var adjustedTopInset: CGFloat = 0
211
+ private var hasMountedTable: Bool = false
212
+ private var keysDirty: Bool = false
213
+ private var selectionDirty: Bool = false
214
+ private var rowHeightsDirty: Bool = false
215
+ private var inTableUpdate: Bool = false
216
+
217
+ private var lastEmittedFirst: Int = -1
218
+ private var lastEmittedEnd: Int = -1
219
+ private var lastEmittedVisibleFirst: Int = -1
220
+ private var lastEmittedVisibleEnd: Int = -1
221
+
222
+ private var heightsByKey: [String: CGFloat] = [:]
223
+ private var emit: ((String, NSDictionary) -> Void)?
224
+
225
+ @objc public var nativeTableView: UITableView? { table }
226
+
227
+ @objc public override init() {
228
+ super.init()
229
+ }
230
+
231
+ private func ensureTable() -> PeachDirectTableView {
232
+ if let existing = table { return existing }
233
+ let tv = PeachDirectTableView(frame: .zero, style: .plain)
234
+ tv.dataSource = self
235
+ tv.delegate = self
236
+ tv.separatorStyle = .none
237
+ tv.backgroundColor = .clear
238
+ tv.cellLayoutMarginsFollowReadableWidth = false
239
+ tv.sectionHeaderTopPadding = 0
240
+ tv.estimatedSectionHeaderHeight = 0
241
+ tv.estimatedSectionFooterHeight = 0
242
+ tv.delaysContentTouches = true
243
+ tv.canCancelContentTouches = true
244
+ tv.contentInsetAdjustmentBehavior = .never
245
+ tv.register(PeachDirectTableCell.self, forCellReuseIdentifier: Self.cellIdentifier)
246
+ tv.onWindowChanged = { [weak self] attached in
247
+ guard let self else { return }
248
+ if attached {
249
+ self.flushRowHeights()
250
+ } else {
251
+ self.endInterruptedScroll()
252
+ }
253
+ }
254
+ tv.onLayoutBounds = { [weak self] size in
255
+ guard let self, let tv = self.table else { return }
256
+ if size != self.lastViewportSize {
257
+ self.lastViewportSize = size
258
+ self.emit?("viewportLayout", ["width": Double(size.width), "height": Double(size.height)] as NSDictionary)
259
+ self.emitRange(admitting: self.rangeBudget(scrollFrame: false))
260
+ }
261
+ let content = tv.contentSize
262
+ if content != self.lastContentSize {
263
+ self.lastContentSize = content
264
+ self.emit?("contentLayout", ["width": Double(content.width), "height": Double(content.height)] as NSDictionary)
265
+ }
266
+ }
267
+ table = tv
268
+ return tv
269
+ }
270
+
271
+ private func isRowSelectable(_ row: Int) -> Bool {
272
+ guard allowsSelection, row >= 0, row < keys.count else { return false }
273
+ guard let flags = selectableFlags, row < flags.count else { return true }
274
+ return flags[row]
275
+ }
276
+
277
+ private func heightForRow(_ row: Int) -> CGFloat {
278
+ if row >= 0, row < keys.count, let cached = heightsByKey[keys[row]] {
279
+ return max(1.0, cached)
280
+ }
281
+ return max(1.0, estimatedRowHeight)
282
+ }
283
+
284
+ private func isRestingAtTop(inset topInset: CGFloat) -> Bool {
285
+ guard let table else { return true }
286
+ return !commandScrolling && !dragging && !userDecelerating && !table.isTracking &&
287
+ abs(table.contentOffset.y + topInset) < 1.0
288
+ }
289
+
290
+ private func flushRowHeights() {
291
+ guard rowHeightsDirty, !keysDirty, !inTableUpdate, let table else { return }
292
+ guard table.bounds.width > 0 else { return }
293
+ rowHeightsDirty = false
294
+ inTableUpdate = true
295
+ if hasMountedTable && table.numberOfSections == 1 && table.numberOfRows(inSection: 0) == keys.count {
296
+ table.beginUpdates()
297
+ table.endUpdates()
298
+ table.layoutIfNeeded()
299
+ } else {
300
+ table.reloadData()
301
+ table.layoutIfNeeded()
302
+ }
303
+ inTableUpdate = false
304
+ attachVisibleCells()
305
+ PeachOneDirectStage.shared.markDirty()
306
+ }
307
+
308
+ @objc(configure:emit:)
309
+ public func configure(_ spec: NSDictionary, emit: @escaping (String, NSDictionary) -> Void) {
310
+ self.emit = emit
311
+ self.spec = spec
312
+
313
+ // the client sends keys and selectable flags only when they change, so a window shift carries neither
314
+ if let rawKeys = spec["keys"] as? [Any] {
315
+ let nextKeys = rawKeys.compactMap { $0 as? String }
316
+ if let rawSelectable = spec["selectable"] as? [Any] {
317
+ selectableFlags = rawSelectable.map { ($0 as? NSNumber)?.boolValue ?? true }
318
+ } else {
319
+ selectableFlags = nil
320
+ }
321
+ if nextKeys != keys {
322
+ keys = nextKeys
323
+ keyToIndex.removeAll(keepingCapacity: true)
324
+ for (idx, key) in keys.enumerated() {
325
+ keyToIndex[key] = idx
326
+ }
327
+ if heightsByKey.count > 4096 {
328
+ var pruned: [String: CGFloat] = [:]
329
+ pruned.reserveCapacity(keys.count)
330
+ for key in keys {
331
+ if let h = heightsByKey[key] { pruned[key] = h }
332
+ }
333
+ heightsByKey = pruned
334
+ }
335
+ keysDirty = true
336
+ lastEmittedFirst = -1
337
+ lastEmittedEnd = -1
338
+ }
339
+ }
340
+
341
+ if let rawAllows = spec["allowsSelection"] as? NSNumber {
342
+ allowsSelection = rawAllows.boolValue
343
+ } else {
344
+ allowsSelection = true
345
+ }
346
+
347
+ let nextControlled = (spec["selectedControlled"] as? NSNumber)?.boolValue ?? false
348
+ let nextSelectedKey = spec["selectedKey"] as? String
349
+ if nextControlled != selectedControlled || nextSelectedKey != selectedKey {
350
+ selectedControlled = nextControlled
351
+ selectedKey = nextSelectedKey
352
+ selectionDirty = true
353
+ }
354
+
355
+ if let rawEst = spec["estimatedRowHeight"] as? NSNumber {
356
+ estimatedRowHeight = max(1.0, CGFloat(rawEst.doubleValue))
357
+ } else {
358
+ estimatedRowHeight = 56.0
359
+ }
360
+ if let rawLead = spec["lead"] as? NSNumber {
361
+ lead = max(0.5, rawLead.doubleValue)
362
+ } else {
363
+ lead = 2.0
364
+ }
365
+ hasHeader = (spec["hasHeader"] as? NSNumber)?.boolValue ?? false
366
+ hasFooter = (spec["hasFooter"] as? NSNumber)?.boolValue ?? false
367
+ hasEmpty = (spec["hasEmpty"] as? NSNumber)?.boolValue ?? false
368
+ paddingTop = max(0.0, CGFloat((spec["paddingTop"] as? NSNumber)?.doubleValue ?? 0.0))
369
+ paddingBottom = max(0.0, CGFloat((spec["paddingBottom"] as? NSNumber)?.doubleValue ?? 0.0))
370
+ if let rawIndices = spec["rowIndices"] as? [NSNumber] {
371
+ rowIndices = rawIndices.map { $0.intValue }
372
+ } else {
373
+ rowIndices = []
374
+ }
375
+
376
+ observeScroll = (spec["observeScroll"] as? NSNumber)?.boolValue ?? false
377
+ observeRange = (spec["observeRange"] as? NSNumber)?.boolValue ?? false
378
+ observeRowFrame = (spec["observeRowFrame"] as? NSNumber)?.boolValue ?? false
379
+ scrollEventThrottleMs = (spec["scrollEventThrottle"] as? NSNumber)?.doubleValue ?? 16.0
380
+
381
+ if let inset = spec["contentInset"] as? NSDictionary {
382
+ contentInsetValue = UIEdgeInsets(
383
+ top: CGFloat((inset["top"] as? NSNumber)?.doubleValue ?? 0),
384
+ left: CGFloat((inset["left"] as? NSNumber)?.doubleValue ?? 0),
385
+ bottom: CGFloat((inset["bottom"] as? NSNumber)?.doubleValue ?? 0),
386
+ right: CGFloat((inset["right"] as? NSNumber)?.doubleValue ?? 0)
387
+ )
388
+ } else {
389
+ contentInsetValue = .zero
390
+ }
391
+ }
392
+
393
+ private func applyTableOptions() {
394
+ guard let table, let spec else { return }
395
+ if table.allowsSelection != allowsSelection { table.allowsSelection = allowsSelection }
396
+ let showsIndicator = (spec["showsVerticalScrollIndicator"] as? NSNumber)?.boolValue ?? true
397
+ if table.showsVerticalScrollIndicator != showsIndicator { table.showsVerticalScrollIndicator = showsIndicator }
398
+ if table.showsHorizontalScrollIndicator { table.showsHorizontalScrollIndicator = false }
399
+ let bounces = (spec["bounces"] as? NSNumber)?.boolValue ?? true
400
+ if table.bounces != bounces { table.bounces = bounces }
401
+ if table.alwaysBounceVertical != bounces { table.alwaysBounceVertical = bounces }
402
+ let directionalLock = (spec["directionalLockEnabled"] as? NSNumber)?.boolValue ?? false
403
+ if table.isDirectionalLockEnabled != directionalLock { table.isDirectionalLockEnabled = directionalLock }
404
+ let scrollEnabled = (spec["scrollEnabled"] as? NSNumber)?.boolValue ?? true
405
+ if table.isScrollEnabled != scrollEnabled { table.isScrollEnabled = scrollEnabled }
406
+ let scrollsToTop = (spec["scrollsToTop"] as? NSNumber)?.boolValue ?? true
407
+ if table.scrollsToTop != scrollsToTop { table.scrollsToTop = scrollsToTop }
408
+ if let rawDismiss = (spec["keyboardDismissMode"] as? NSNumber)?.intValue,
409
+ let dismiss = UIScrollView.KeyboardDismissMode(rawValue: rawDismiss),
410
+ table.keyboardDismissMode != dismiss {
411
+ table.keyboardDismissMode = dismiss
412
+ }
413
+ if let rawInsetAdj = (spec["insetAdjustment"] as? NSNumber)?.intValue,
414
+ let insetAdj = UIScrollView.ContentInsetAdjustmentBehavior(rawValue: rawInsetAdj),
415
+ table.contentInsetAdjustmentBehavior != insetAdj {
416
+ table.contentInsetAdjustmentBehavior = insetAdj
417
+ }
418
+ let testID = spec["testID"] as? String
419
+ if table.accessibilityIdentifier != testID {
420
+ table.accessibilityIdentifier = testID
421
+ }
422
+ if appliedContentInset != contentInsetValue {
423
+ let current = table.contentInset
424
+ let prev = appliedContentInset
425
+ appliedContentInset = contentInsetValue
426
+ table.contentInset = UIEdgeInsets(
427
+ top: current.top + (contentInsetValue.top - prev.top),
428
+ left: current.left + (contentInsetValue.left - prev.left),
429
+ bottom: current.bottom + (contentInsetValue.bottom - prev.bottom),
430
+ right: current.right + (contentInsetValue.right - prev.right)
431
+ )
432
+ }
433
+ }
434
+
435
+ private func syncControlledSelection(animated: Bool) {
436
+ guard let table, selectedControlled else { return }
437
+ let current = table.indexPathForSelectedRow
438
+ guard let selectedKey, !selectedKey.isEmpty, let idx = keyToIndex[selectedKey] else {
439
+ if let current { table.deselectRow(at: current, animated: animated) }
440
+ return
441
+ }
442
+ let target = IndexPath(row: idx, section: 0)
443
+ if current != target {
444
+ table.selectRow(at: target, animated: false, scrollPosition: .none)
445
+ }
446
+ }
447
+
448
+ private func attachRow(_ rowIndex: Int, to cell: PeachDirectTableCell) {
449
+ guard let row = mountedRows[rowIndex], let view = row.view else {
450
+ if let existing = cell.hostedView, existing.superview === cell.contentView {
451
+ existing.removeFromSuperview()
452
+ }
453
+ cell.hostedView = nil
454
+ cell.hostedNode = 0
455
+ return
456
+ }
457
+ let bounds = cell.contentView.bounds
458
+ if cell.hostedView === view && cell.hostedNode == row.node && view.superview === cell.contentView {
459
+ if view.frame != bounds { view.frame = bounds }
460
+ return
461
+ }
462
+ if let existing = cell.hostedView, existing !== view, existing.superview === cell.contentView {
463
+ existing.removeFromSuperview()
464
+ }
465
+ if view.superview !== cell.contentView {
466
+ if let prevContent = view.superview, let prevCell = prevContent.superview as? PeachDirectTableCell,
467
+ prevCell !== cell, prevCell.hostedView === view {
468
+ prevCell.hostedView = nil
469
+ prevCell.hostedNode = 0
470
+ }
471
+ view.removeFromSuperview()
472
+ view.frame = bounds
473
+ cell.contentView.addSubview(view)
474
+ } else if view.frame != bounds {
475
+ view.frame = bounds
476
+ }
477
+ cell.hostedView = view
478
+ cell.hostedNode = row.node
479
+ }
480
+
481
+ private func attachVisibleCells() {
482
+ guard let table else { return }
483
+ for raw in table.visibleCells {
484
+ guard let cell = raw as? PeachDirectTableCell else { continue }
485
+ var row = cell.rowIndex
486
+ if row == NSNotFound {
487
+ guard let path = table.indexPath(for: cell) else { continue }
488
+ row = path.row
489
+ cell.rowIndex = row
490
+ }
491
+ let style: UITableViewCell.SelectionStyle = isRowSelectable(row) ? .default : .none
492
+ if cell.selectionStyle != style { cell.selectionStyle = style }
493
+ attachRow(row, to: cell)
494
+ }
495
+ }
496
+
497
+ private func updateHeaderAndFooter(
498
+ table: PeachDirectTableView,
499
+ nextHeaderNode: UInt64,
500
+ nextHeaderView: UIView?,
501
+ headerSize: CGSize,
502
+ nextFooterNode: UInt64,
503
+ nextFooterView: UIView?,
504
+ footerSize: CGSize
505
+ ) -> Bool {
506
+ var changed = false
507
+
508
+ let headerContentH = nextHeaderView != nil ? max(0.0, headerSize.height) : 0.0
509
+ let headerTotalH = paddingTop + headerContentH
510
+ if nextHeaderView != nil || headerTotalH > 0.5 {
511
+ if let nextHeaderView {
512
+ ownedViews[ObjectIdentifier(nextHeaderView)] = PeachWeakViewBox(view: nextHeaderView)
513
+ }
514
+ let w = max(table.bounds.width, headerSize.width)
515
+ let host = headerHost ?? {
516
+ let v = UIView(frame: CGRect(x: 0, y: 0, width: w, height: headerTotalH))
517
+ v.backgroundColor = .clear
518
+ headerHost = v
519
+ return v
520
+ }()
521
+ if let prev = headerView, prev !== nextHeaderView, prev.superview === host {
522
+ prev.removeFromSuperview()
523
+ }
524
+ if let nextHeaderView, nextHeaderView.superview !== host {
525
+ nextHeaderView.removeFromSuperview()
526
+ host.addSubview(nextHeaderView)
527
+ }
528
+ let childFrame = CGRect(x: 0, y: paddingTop, width: w, height: headerContentH)
529
+ let sizeChanged = abs(host.frame.height - headerTotalH) > 0.5 || abs(host.frame.width - w) > 0.5
530
+ if sizeChanged || table.tableHeaderView !== host {
531
+ host.frame = CGRect(x: 0, y: 0, width: w, height: headerTotalH)
532
+ nextHeaderView?.frame = childFrame
533
+ table.tableHeaderView = host
534
+ changed = true
535
+ } else if let nextHeaderView, nextHeaderView.frame != childFrame {
536
+ nextHeaderView.frame = childFrame
537
+ }
538
+ headerView = nextHeaderView
539
+ headerNode = nextHeaderNode
540
+ } else {
541
+ if table.tableHeaderView != nil {
542
+ table.tableHeaderView = nil
543
+ changed = true
544
+ }
545
+ if let prev = headerView, prev.superview === headerHost { prev.removeFromSuperview() }
546
+ headerView = nil
547
+ headerNode = 0
548
+ }
549
+
550
+ let footerContentH = nextFooterView != nil ? max(0.0, footerSize.height) : 0.0
551
+ let footerTotalH = footerContentH + paddingBottom
552
+ if nextFooterView != nil || footerTotalH > 0.5 {
553
+ if let nextFooterView {
554
+ ownedViews[ObjectIdentifier(nextFooterView)] = PeachWeakViewBox(view: nextFooterView)
555
+ }
556
+ let w = max(table.bounds.width, footerSize.width)
557
+ let host = footerHost ?? {
558
+ let v = UIView(frame: CGRect(x: 0, y: 0, width: w, height: footerTotalH))
559
+ v.backgroundColor = .clear
560
+ footerHost = v
561
+ return v
562
+ }()
563
+ if let prev = footerView, prev !== nextFooterView, prev.superview === host {
564
+ prev.removeFromSuperview()
565
+ }
566
+ if let nextFooterView, nextFooterView.superview !== host {
567
+ nextFooterView.removeFromSuperview()
568
+ host.addSubview(nextFooterView)
569
+ }
570
+ let childFrame = CGRect(x: 0, y: 0, width: w, height: footerContentH)
571
+ let sizeChanged = abs(host.frame.height - footerTotalH) > 0.5 || abs(host.frame.width - w) > 0.5
572
+ if sizeChanged || table.tableFooterView !== host {
573
+ host.frame = CGRect(x: 0, y: 0, width: w, height: footerTotalH)
574
+ nextFooterView?.frame = childFrame
575
+ table.tableFooterView = host
576
+ changed = true
577
+ } else if let nextFooterView, nextFooterView.frame != childFrame {
578
+ nextFooterView.frame = childFrame
579
+ }
580
+ footerView = nextFooterView
581
+ footerNode = nextFooterNode
582
+ } else {
583
+ if table.tableFooterView != nil {
584
+ table.tableFooterView = nil
585
+ changed = true
586
+ }
587
+ if let prev = footerView, prev.superview === footerHost { prev.removeFromSuperview() }
588
+ footerView = nil
589
+ footerNode = 0
590
+ }
591
+
592
+ return changed
593
+ }
594
+
595
+ @objc(mountIn:children:viewForNode:sizeForNode:)
596
+ public func mount(
597
+ in container: UIView,
598
+ children: [NSNumber],
599
+ viewForNode: @escaping (UInt64) -> UIView?,
600
+ sizeForNode: @escaping (UInt64) -> CGSize
601
+ ) {
602
+ mounting = true
603
+ let table = ensureTable()
604
+ let previousViewport = table.bounds
605
+ let previousTopInset = table.adjustedContentInset.top
606
+ let followTop = !hasMountedTable || isRestingAtTop(inset: previousTopInset)
607
+
608
+ if table.superview !== container {
609
+ table.removeFromSuperview()
610
+ container.addSubview(table)
611
+ }
612
+ if table.frame != container.bounds {
613
+ table.frame = container.bounds
614
+ }
615
+ applyTableOptions()
616
+
617
+ let childNodes = children.map { $0.uint64Value }
618
+ var cursor = 0
619
+ var nextHeaderNode: UInt64 = 0
620
+ var nextFooterNode: UInt64 = 0
621
+ var nextEmptyNode: UInt64 = 0
622
+ if hasHeader && cursor < childNodes.count {
623
+ nextHeaderNode = childNodes[cursor]
624
+ cursor += 1
625
+ }
626
+ if hasFooter && cursor < childNodes.count {
627
+ nextFooterNode = childNodes[cursor]
628
+ cursor += 1
629
+ }
630
+ if hasEmpty && cursor < childNodes.count {
631
+ nextEmptyNode = childNodes[cursor]
632
+ cursor += 1
633
+ }
634
+
635
+ ownedViews.removeAll(keepingCapacity: true)
636
+
637
+ let nextHeaderView = nextHeaderNode != 0 ? viewForNode(nextHeaderNode) : nil
638
+ let headerSize = nextHeaderNode != 0 ? sizeForNode(nextHeaderNode) : .zero
639
+ let nextFooterView = nextFooterNode != 0 ? viewForNode(nextFooterNode) : nil
640
+ let footerSize = nextFooterNode != 0 ? sizeForNode(nextFooterNode) : .zero
641
+ let edgeChanged = updateHeaderAndFooter(
642
+ table: table,
643
+ nextHeaderNode: nextHeaderNode,
644
+ nextHeaderView: nextHeaderView,
645
+ headerSize: headerSize,
646
+ nextFooterNode: nextFooterNode,
647
+ nextFooterView: nextFooterView,
648
+ footerSize: footerSize
649
+ )
650
+
651
+ let nextEmptyView = (nextEmptyNode != 0 && keys.isEmpty) ? viewForNode(nextEmptyNode) : nil
652
+ if let nextEmptyView {
653
+ ownedViews[ObjectIdentifier(nextEmptyView)] = PeachWeakViewBox(view: nextEmptyView)
654
+ let host = emptyHost ?? {
655
+ let v = UIView(frame: table.bounds)
656
+ v.backgroundColor = .clear
657
+ v.autoresizingMask = [.flexibleWidth, .flexibleHeight]
658
+ emptyHost = v
659
+ return v
660
+ }()
661
+ if let prev = emptyView, prev !== nextEmptyView, prev.superview === host {
662
+ prev.removeFromSuperview()
663
+ }
664
+ if nextEmptyView.superview !== host {
665
+ nextEmptyView.removeFromSuperview()
666
+ host.addSubview(nextEmptyView)
667
+ }
668
+ if table.backgroundView !== host { table.backgroundView = host }
669
+ nextEmptyView.frame = host.bounds
670
+ emptyView = nextEmptyView
671
+ emptyNode = nextEmptyNode
672
+ } else {
673
+ if table.backgroundView != nil { table.backgroundView = nil }
674
+ if let prev = emptyView, prev.superview === emptyHost { prev.removeFromSuperview() }
675
+ emptyView = nil
676
+ emptyNode = 0
677
+ }
678
+
679
+ var nextRows: [Int: PeachDirectMountedRow] = [:]
680
+ nextRows.reserveCapacity(rowIndices.count)
681
+ var anyHeightChanged = false
682
+ let fallbackHeight = max(1.0, estimatedRowHeight)
683
+ var rowIdxCursor = 0
684
+ while cursor < childNodes.count && rowIdxCursor < rowIndices.count {
685
+ let rowNode = childNodes[cursor]
686
+ cursor += 1
687
+ let itemIndex = rowIndices[rowIdxCursor]
688
+ rowIdxCursor += 1
689
+ guard itemIndex >= 0, itemIndex < keys.count, let rowView = viewForNode(rowNode) else { continue }
690
+ nextRows[itemIndex] = PeachDirectMountedRow(node: rowNode, view: rowView)
691
+ ownedViews[ObjectIdentifier(rowView)] = PeachWeakViewBox(view: rowView)
692
+
693
+ let measured = sizeForNode(rowNode)
694
+ if measured.height > 0.5 {
695
+ let key = keys[itemIndex]
696
+ let prev = heightsByKey[key]
697
+ let prior = prev.map { max(1.0, $0) } ?? fallbackHeight
698
+ let clamped = max(1.0, measured.height)
699
+ if prev == nil || abs((prev ?? 0) - measured.height) > 0.5 {
700
+ heightsByKey[key] = measured.height
701
+ if abs(prior - clamped) > 0.5 { anyHeightChanged = true }
702
+ }
703
+ }
704
+ }
705
+
706
+ // Detach row views that left the mounted window.
707
+ for (oldIndex, oldRow) in mountedRows {
708
+ if let current = nextRows[oldIndex], current.node == oldRow.node { continue }
709
+ if let oldView = oldRow.view {
710
+ if let cell = oldView.superview?.superview as? PeachDirectTableCell, cell.hostedView === oldView {
711
+ cell.hostedView = nil
712
+ cell.hostedNode = 0
713
+ }
714
+ oldView.removeFromSuperview()
715
+ }
716
+ }
717
+ mountedRows = nextRows
718
+ rowHeightsDirty = rowHeightsDirty || anyHeightChanged
719
+
720
+ let keysChanged = keysDirty
721
+ if !hasMountedTable || keysChanged {
722
+ var priorSelectedKey: String? = nil
723
+ if selectedControlled {
724
+ priorSelectedKey = selectedKey
725
+ } else if hasMountedTable, let sel = table.indexPathForSelectedRow, sel.row >= 0, sel.row < keys.count {
726
+ priorSelectedKey = keys[sel.row]
727
+ }
728
+ hasMountedTable = true
729
+ keysDirty = false
730
+ selectionDirty = false
731
+ rowHeightsDirty = false
732
+ inTableUpdate = true
733
+ table.reloadData()
734
+ if table.bounds.width > 0 { table.layoutIfNeeded() }
735
+ if let priorSelectedKey, !priorSelectedKey.isEmpty, let idx = keyToIndex[priorSelectedKey], isRowSelectable(idx) {
736
+ table.selectRow(at: IndexPath(row: idx, section: 0), animated: false, scrollPosition: .none)
737
+ }
738
+ inTableUpdate = false
739
+ attachVisibleCells()
740
+ } else {
741
+ attachVisibleCells()
742
+ flushRowHeights()
743
+ if selectionDirty {
744
+ selectionDirty = false
745
+ syncControlledSelection(animated: true)
746
+ }
747
+ }
748
+
749
+ if (keysChanged || anyHeightChanged || edgeChanged), table.bounds.width > 0 {
750
+ table.layoutIfNeeded()
751
+ attachVisibleCells()
752
+ }
753
+ if followTop {
754
+ let inset = table.adjustedContentInset
755
+ let minimum = -inset.top
756
+ let maximum = max(minimum, table.contentSize.height + inset.bottom - table.bounds.height)
757
+ let y = min(max(minimum, minimum), maximum)
758
+ if abs(table.contentOffset.y - y) > 0.5 {
759
+ table.contentOffset = CGPoint(x: table.contentOffset.x, y: y)
760
+ }
761
+ }
762
+
763
+ let content = table.contentSize
764
+ if content != lastContentSize {
765
+ lastContentSize = content
766
+ emit?("contentLayout", ["width": Double(content.width), "height": Double(content.height)] as NSDictionary)
767
+ }
768
+ let viewport = table.bounds.size
769
+ if viewport != lastViewportSize {
770
+ lastViewportSize = viewport
771
+ emit?("viewportLayout", ["width": Double(viewport.width), "height": Double(viewport.height)] as NSDictionary)
772
+ }
773
+ let offset = table.contentOffset
774
+ if previousViewport.origin != offset {
775
+ lastOffset = offset
776
+ lastOffsetTime = 0
777
+ emitScroll(phase: "scroll", velocity: .zero, throttle: false, userInitiated: false)
778
+ }
779
+ mounting = false
780
+ emitRange(admitting: rangeBudget(scrollFrame: false))
781
+ PeachOneDirectStage.shared.markDirty()
782
+ }
783
+
784
+ @objc(refreshLayoutIn:viewForNode:sizeForNode:)
785
+ public func refreshLayout(
786
+ in container: UIView,
787
+ viewForNode: @escaping (UInt64) -> UIView?,
788
+ sizeForNode: @escaping (UInt64) -> CGSize
789
+ ) {
790
+ guard let table else { return }
791
+ mounting = true
792
+ if table.superview !== container {
793
+ table.removeFromSuperview()
794
+ container.addSubview(table)
795
+ }
796
+ var frameChanged = false
797
+ if table.frame != container.bounds {
798
+ table.frame = container.bounds
799
+ frameChanged = true
800
+ }
801
+
802
+ let nextHeaderView = headerNode != 0 ? (headerView ?? viewForNode(headerNode)) : nil
803
+ let headerSize = headerNode != 0 ? sizeForNode(headerNode) : .zero
804
+ let nextFooterView = footerNode != 0 ? (footerView ?? viewForNode(footerNode)) : nil
805
+ let footerSize = footerNode != 0 ? sizeForNode(footerNode) : .zero
806
+ let edgeChanged = updateHeaderAndFooter(
807
+ table: table,
808
+ nextHeaderNode: headerNode,
809
+ nextHeaderView: nextHeaderView,
810
+ headerSize: headerSize,
811
+ nextFooterNode: footerNode,
812
+ nextFooterView: nextFooterView,
813
+ footerSize: footerSize
814
+ )
815
+
816
+ var anyHeightChanged = false
817
+ let fallbackHeight = max(1.0, estimatedRowHeight)
818
+ for (itemIndex, row) in mountedRows {
819
+ guard itemIndex >= 0, itemIndex < keys.count else { continue }
820
+ let measured = sizeForNode(row.node)
821
+ if measured.height > 0.5 {
822
+ let key = keys[itemIndex]
823
+ let prev = heightsByKey[key]
824
+ let prior = prev.map { max(1.0, $0) } ?? fallbackHeight
825
+ let clamped = max(1.0, measured.height)
826
+ if prev == nil || abs((prev ?? 0) - measured.height) > 0.5 {
827
+ heightsByKey[key] = measured.height
828
+ if abs(prior - clamped) > 0.5 { anyHeightChanged = true }
829
+ }
830
+ }
831
+ }
832
+ if anyHeightChanged { rowHeightsDirty = true }
833
+
834
+ if rowHeightsDirty {
835
+ flushRowHeights()
836
+ } else if (frameChanged || edgeChanged), table.bounds.width > 0 {
837
+ table.layoutIfNeeded()
838
+ attachVisibleCells()
839
+ }
840
+
841
+ let content = table.contentSize
842
+ if content != lastContentSize {
843
+ lastContentSize = content
844
+ emit?("contentLayout", ["width": Double(content.width), "height": Double(content.height)] as NSDictionary)
845
+ }
846
+ let viewport = table.bounds.size
847
+ if viewport != lastViewportSize {
848
+ lastViewportSize = viewport
849
+ emit?("viewportLayout", ["width": Double(viewport.width), "height": Double(viewport.height)] as NSDictionary)
850
+ }
851
+ mounting = false
852
+ emitRange(admitting: rangeBudget(scrollFrame: false))
853
+ if frameChanged || edgeChanged || anyHeightChanged {
854
+ PeachOneDirectStage.shared.markDirty()
855
+ }
856
+ }
857
+
858
+ @objc(ownsView:)
859
+ public func ownsView(_ view: UIView) -> Bool {
860
+ ownedViews[ObjectIdentifier(view)]?.view === view
861
+ }
862
+
863
+ private func scrollToOffset(_ y: CGFloat, animated: Bool) {
864
+ guard let table else { return }
865
+ if table.contentOffset.y == y { return }
866
+ commandScrolling = true
867
+ userDecelerating = false
868
+ table.setContentOffset(CGPoint(x: table.contentOffset.x, y: y), animated: animated)
869
+ if !animated { commandScrolling = false }
870
+ PeachOneDirectStage.shared.markDirty()
871
+ }
872
+
873
+ @objc(command:payload:)
874
+ public func command(_ name: String, payload: NSDictionary) {
875
+ guard let table else { return }
876
+ if name == "scrollTo" {
877
+ let y = CGFloat((payload["y"] as? NSNumber)?.doubleValue ?? 0)
878
+ let animated = (payload["animated"] as? NSNumber)?.boolValue ?? false
879
+ scrollToOffset(y, animated: animated)
880
+ } else if name == "scrollToEnd" {
881
+ let animated = (payload["animated"] as? NSNumber)?.boolValue ?? false
882
+ let maxOffset = max(
883
+ -table.adjustedContentInset.top,
884
+ table.contentSize.height + table.adjustedContentInset.bottom - table.bounds.height
885
+ )
886
+ scrollToOffset(maxOffset, animated: animated)
887
+ } else if name == "scrollToIndex" {
888
+ let index = (payload["index"] as? NSNumber)?.intValue ?? -1
889
+ guard index >= 0, index < keys.count else { return }
890
+ let animated = (payload["animated"] as? NSNumber)?.boolValue ?? false
891
+ let viewPosition = CGFloat((payload["viewPosition"] as? NSNumber)?.doubleValue ?? 0)
892
+ let viewOffset = CGFloat((payload["viewOffset"] as? NSNumber)?.doubleValue ?? 0)
893
+ let rect = table.rectForRow(at: IndexPath(row: index, section: 0))
894
+ let viewportH = table.bounds.height
895
+ let minOffset = -table.adjustedContentInset.top
896
+ let maxOffset = max(minOffset, table.contentSize.height + table.adjustedContentInset.bottom - viewportH)
897
+ let target = rect.origin.y - viewPosition * (viewportH - rect.height) - viewOffset
898
+ scrollToOffset(max(minOffset, min(target, maxOffset)), animated: animated)
899
+ } else if name == "clearSelection" {
900
+ if let selected = table.indexPathForSelectedRow {
901
+ let animated = (payload["animated"] as? NSNumber)?.boolValue ?? false
902
+ table.deselectRow(at: selected, animated: animated)
903
+ PeachOneDirectStage.shared.markDirty()
904
+ }
905
+ }
906
+ }
907
+
908
+ private func rangeBudget(scrollFrame: Bool) -> Int {
909
+ if !dragging && !userDecelerating && !commandScrolling { return 2 }
910
+ if !scrollFrame { return 0 }
911
+ return 2
912
+ }
913
+
914
+ private func emitRange(admitting initialBudget: Int) {
915
+ guard let table, observeRange, let emit else { return }
916
+ let total = keys.count
917
+ guard total > 0 else { return }
918
+
919
+ var visFirst = 0
920
+ var visEnd = 0
921
+ if let visible = table.indexPathsForVisibleRows, !visible.isEmpty {
922
+ visFirst = visible.first!.row
923
+ visEnd = visible.last!.row + 1
924
+ for p in visible {
925
+ if p.row < visFirst { visFirst = p.row }
926
+ if p.row + 1 > visEnd { visEnd = p.row + 1 }
927
+ }
928
+ } else {
929
+ let h = max(1.0, estimatedRowHeight)
930
+ let top = max(0.0, table.contentOffset.y + table.adjustedContentInset.top)
931
+ let viewH = max(h, table.bounds.height)
932
+ visFirst = min(max(Int(floor(top / h)), 0), total)
933
+ visEnd = min(max(Int(ceil((top + viewH) / h)), visFirst), total)
934
+ }
935
+
936
+ let avgRow = max(1.0, estimatedRowHeight)
937
+ let viewH = max(avgRow, table.bounds.height)
938
+ let aheadRows = Int(ceil((Double(viewH) * lead) / Double(avgRow)))
939
+ let behindRows = Int(ceil((Double(viewH) * (lead * 0.5)) / Double(avgRow)))
940
+ let wantFirst = max(0, visFirst - (scrollingBack ? aheadRows : behindRows))
941
+ let wantEnd = min(total, visEnd + (scrollingBack ? behindRows : aheadRows))
942
+
943
+ var covered = true
944
+ for index in wantFirst..<wantEnd where mountedRows[index] == nil {
945
+ covered = false
946
+ break
947
+ }
948
+ if covered { return }
949
+
950
+ var budget = initialBudget
951
+ let requested = lastEmittedFirst >= 0
952
+ let jumped = requested && (visEnd <= lastEmittedFirst || visFirst >= lastEmittedEnd)
953
+ let release = 2 * max(1, budget)
954
+ if !requested {
955
+ budget = total
956
+ } else if jumped {
957
+ budget = 0
958
+ } else {
959
+ var inFlight = 0
960
+ if lastEmittedFirst < lastEmittedEnd {
961
+ for index in lastEmittedFirst..<lastEmittedEnd where mountedRows[index] == nil {
962
+ inFlight += 1
963
+ }
964
+ }
965
+ budget = min(budget, 2 * budget - inFlight)
966
+ }
967
+
968
+ func admit(_ index: Int) -> Bool {
969
+ if mountedRows[index] != nil || (requested && index >= lastEmittedFirst && index < lastEmittedEnd) {
970
+ return true
971
+ }
972
+ if budget <= 0 { return false }
973
+ budget -= 1
974
+ return true
975
+ }
976
+
977
+ var first = visFirst
978
+ var end = visEnd
979
+ var grew = true
980
+ while grew {
981
+ grew = false
982
+ if end < wantEnd && admit(end) {
983
+ end += 1
984
+ grew = true
985
+ }
986
+ if first > wantFirst && admit(first - 1) {
987
+ first -= 1
988
+ grew = true
989
+ }
990
+ }
991
+ if requested && !jumped {
992
+ first = min(first, lastEmittedFirst + release)
993
+ end = max(end, lastEmittedEnd - release)
994
+ }
995
+ if requested && first >= lastEmittedFirst && end <= lastEmittedEnd {
996
+ if visFirst == lastEmittedVisibleFirst && visEnd == lastEmittedVisibleEnd { return }
997
+ var visibleCovered = true
998
+ for index in visFirst..<visEnd where mountedRows[index] == nil {
999
+ visibleCovered = false
1000
+ break
1001
+ }
1002
+ if visibleCovered { return }
1003
+ }
1004
+
1005
+ lastEmittedFirst = first
1006
+ lastEmittedEnd = end
1007
+ lastEmittedVisibleFirst = visFirst
1008
+ lastEmittedVisibleEnd = visEnd
1009
+ emit("range", [
1010
+ "first": first,
1011
+ "end": end,
1012
+ "visibleFirst": visFirst,
1013
+ "visibleEnd": visEnd,
1014
+ ] as NSDictionary)
1015
+ }
1016
+
1017
+ private func emitScroll(phase: String, velocity: CGPoint, throttle: Bool, userInitiated: Bool) {
1018
+ guard let table, observeScroll, let emit else { return }
1019
+ let now = Date().timeIntervalSinceReferenceDate
1020
+ if throttle && scrollEventThrottleMs > 0 && (now - lastScrollEmitTime) * 1000.0 < scrollEventThrottleMs {
1021
+ return
1022
+ }
1023
+ lastScrollEmitTime = now
1024
+ let offset = table.contentOffset
1025
+ let viewport = table.bounds.size
1026
+ let content = table.contentSize
1027
+ emit("scroll", [
1028
+ "phase": phase,
1029
+ "userInitiated": userInitiated,
1030
+ "offset": ["x": Double(offset.x), "y": Double(offset.y)],
1031
+ "velocity": ["x": Double(velocity.x), "y": Double(velocity.y)],
1032
+ "viewport": ["width": Double(viewport.width), "height": Double(viewport.height)],
1033
+ "content": ["width": Double(content.width), "height": Double(content.height)],
1034
+ ] as NSDictionary)
1035
+ }
1036
+
1037
+ private func endInterruptedScroll() {
1038
+ if dragging {
1039
+ dragging = false
1040
+ emitScroll(phase: "drag-end", velocity: .zero, throttle: false, userInitiated: true)
1041
+ }
1042
+ if userDecelerating {
1043
+ userDecelerating = false
1044
+ emitScroll(phase: "momentum-end", velocity: .zero, throttle: false, userInitiated: true)
1045
+ }
1046
+ commandScrolling = false
1047
+ }
1048
+
1049
+ // MARK: - UITableViewDataSource
1050
+
1051
+ public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
1052
+ keys.count
1053
+ }
1054
+
1055
+ public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
1056
+ let cell = tableView.dequeueReusableCell(withIdentifier: Self.cellIdentifier, for: indexPath) as! PeachDirectTableCell
1057
+ cell.rowIndex = indexPath.row
1058
+ let style: UITableViewCell.SelectionStyle = isRowSelectable(indexPath.row) ? .default : .none
1059
+ if cell.selectionStyle != style { cell.selectionStyle = style }
1060
+ attachRow(indexPath.row, to: cell)
1061
+ return cell
1062
+ }
1063
+
1064
+ // MARK: - UITableViewDelegate
1065
+
1066
+ public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
1067
+ heightForRow(indexPath.row)
1068
+ }
1069
+
1070
+ public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
1071
+ heightForRow(indexPath.row)
1072
+ }
1073
+
1074
+ public func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
1075
+ isRowSelectable(indexPath.row)
1076
+ }
1077
+
1078
+ public func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
1079
+ isRowSelectable(indexPath.row) ? indexPath : nil
1080
+ }
1081
+
1082
+ public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
1083
+ guard indexPath.row >= 0, indexPath.row < keys.count else { return }
1084
+ let key = keys[indexPath.row]
1085
+ emit?("select", ["index": indexPath.row, "key": key] as NSDictionary)
1086
+ PeachOneDirectStage.shared.markDirty()
1087
+ }
1088
+
1089
+ public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
1090
+ guard observeRowFrame, let emit else { return }
1091
+ let rect = tableView.rectForRow(at: indexPath)
1092
+ emit("rowFrame", [
1093
+ "index": indexPath.row,
1094
+ "frame": [
1095
+ "x": Double(rect.origin.x),
1096
+ "y": Double(rect.origin.y),
1097
+ "width": Double(rect.size.width),
1098
+ "height": Double(rect.size.height),
1099
+ ],
1100
+ ] as NSDictionary)
1101
+ }
1102
+
1103
+ // MARK: - UIScrollViewDelegate
1104
+
1105
+ public func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) {
1106
+ let previous = adjustedTopInset
1107
+ adjustedTopInset = scrollView.adjustedContentInset.top
1108
+ if !mounting && previous != adjustedTopInset && isRestingAtTop(inset: previous) {
1109
+ scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: -adjustedTopInset)
1110
+ }
1111
+ }
1112
+
1113
+ public func scrollViewDidScroll(_ scrollView: UIScrollView) {
1114
+ if mounting { return }
1115
+ let offset = scrollView.contentOffset
1116
+ let now = Date().timeIntervalSinceReferenceDate
1117
+ var velocity = CGPoint.zero
1118
+ if lastOffsetTime > 0 && now > lastOffsetTime {
1119
+ let dt = max(now - lastOffsetTime, 1.0 / 120.0)
1120
+ velocity = CGPoint(
1121
+ x: CGFloat(Double(offset.x - lastOffset.x) / dt),
1122
+ y: CGFloat(Double(offset.y - lastOffset.y) / dt)
1123
+ )
1124
+ }
1125
+ if offset.y != lastOffset.y { scrollingBack = offset.y < lastOffset.y }
1126
+ lastOffset = offset
1127
+ lastOffsetTime = now
1128
+ emitScroll(
1129
+ phase: "scroll",
1130
+ velocity: velocity,
1131
+ throttle: true,
1132
+ userInitiated: !commandScrolling && (scrollView.isTracking || dragging || userDecelerating)
1133
+ )
1134
+ emitRange(admitting: rangeBudget(scrollFrame: true))
1135
+ PeachOneDirectStage.shared.markDirty()
1136
+ }
1137
+
1138
+ public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
1139
+ guard scrollView.window != nil else { return }
1140
+ if userDecelerating {
1141
+ userDecelerating = false
1142
+ emitScroll(phase: "momentum-end", velocity: .zero, throttle: false, userInitiated: true)
1143
+ }
1144
+ dragging = true
1145
+ commandScrolling = false
1146
+ emitScroll(phase: "drag-start", velocity: .zero, throttle: false, userInitiated: true)
1147
+ }
1148
+
1149
+ public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
1150
+ guard dragging else { return }
1151
+ dragging = false
1152
+ emitScroll(phase: "drag-end", velocity: .zero, throttle: false, userInitiated: true)
1153
+ if !decelerate { emitRange(admitting: rangeBudget(scrollFrame: false)) }
1154
+ }
1155
+
1156
+ public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
1157
+ guard scrollView.window != nil else { return }
1158
+ userDecelerating = true
1159
+ emitScroll(phase: "momentum-start", velocity: .zero, throttle: false, userInitiated: true)
1160
+ }
1161
+
1162
+ public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
1163
+ guard userDecelerating else { return }
1164
+ userDecelerating = false
1165
+ emitScroll(phase: "momentum-end", velocity: .zero, throttle: false, userInitiated: true)
1166
+ emitRange(admitting: rangeBudget(scrollFrame: false))
1167
+ }
1168
+
1169
+ public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
1170
+ commandScrolling = false
1171
+ emitRange(admitting: rangeBudget(scrollFrame: false))
1172
+ }
1173
+
1174
+ public func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
1175
+ emitScroll(phase: "scroll-to-top", velocity: .zero, throttle: false, userInitiated: false)
1176
+ }
1177
+
1178
+ @objc(unmount)
1179
+ public func unmount() {
1180
+ endInterruptedScroll()
1181
+ table?.removeFromSuperview()
1182
+ PeachOneDirectStage.shared.markDirty()
1183
+ }
1184
+
1185
+ @objc(detach)
1186
+ public func detach() {
1187
+ endInterruptedScroll()
1188
+ table?.dataSource = nil
1189
+ table?.delegate = nil
1190
+ table?.onLayoutBounds = nil
1191
+ table?.onWindowChanged = nil
1192
+ table?.tableHeaderView = nil
1193
+ table?.tableFooterView = nil
1194
+ table?.backgroundView = nil
1195
+ table?.removeFromSuperview()
1196
+ table = nil
1197
+ headerView?.removeFromSuperview()
1198
+ footerView?.removeFromSuperview()
1199
+ emptyView?.removeFromSuperview()
1200
+ headerView = nil
1201
+ footerView = nil
1202
+ emptyView = nil
1203
+ headerHost = nil
1204
+ footerHost = nil
1205
+ emptyHost = nil
1206
+ mountedRows.removeAll()
1207
+ ownedViews.removeAll()
1208
+ emit = nil
1209
+ PeachOneDirectStage.shared.markDirty()
1210
+ }
1211
+ }
1212
+
1213
+ public struct OneDirectStageView: View {
1214
+ @State private var tick: UInt64 = 0
1215
+
1216
+ public init() {}
1217
+
1218
+ public var body: some View {
1219
+ OneDirectStageRepresentable(tick: tick)
1220
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
1221
+ .onAppear {
1222
+ PeachOneDirectStage.shared.onStageDirty = {
1223
+ tick &+= 1
1224
+ }
1225
+ }
1226
+ }
1227
+ }
1228
+
1229
+ private struct OneDirectStageRepresentable: UIViewRepresentable {
1230
+ let tick: UInt64
1231
+
1232
+ func makeUIView(context: Context) -> UIView {
1233
+ PeachOneDirectStage.shared.stageView
1234
+ }
1235
+
1236
+ func updateUIView(_ uiView: UIView, context: Context) {
1237
+ _ = tick
1238
+ }
1239
+ }
1240
+ `
1241
+
1242
+ export const PEACH_ONE_HOST_SHIMS: Record<string, string> = {
1243
+ 'include/OneNativeControlsHost.h': `#pragma once
1244
+ #ifdef __cplusplus
1245
+ extern "C" {
1246
+ #endif
1247
+ void PeachOneDirectHostInit(void);
1248
+ #ifdef __cplusplus
1249
+ }
1250
+ #endif
1251
+ `,
1252
+ 'keep.c': `int peach_one_host_anchor(void) { return 0; }\n`,
1253
+ 'peach_core_mount.h': `#pragma once
1254
+ #include <stddef.h>
1255
+ #include <stdint.h>
1256
+ typedef uint64_t peach_node;
1257
+ struct peach_core;
1258
+ `,
1259
+ 'peach_core_css.h': `#pragma once
1260
+ #include <stddef.h>
1261
+ #include <stdint.h>
1262
+ #include "peach_core_mount.h"
1263
+ #ifdef __cplusplus
1264
+ extern "C" {
1265
+ #endif
1266
+ uint32_t peach_node_css_color(peach_core* core, peach_node node, const char* source, size_t size, double rgba[4]);
1267
+ #ifdef __cplusplus
1268
+ }
1269
+ #endif
1270
+ `,
1271
+ 'ios/PeachOneControlsSwift.h': `#pragma once
1272
+ #include "OneNativeControlsCore-Swift.h"
1273
+ @interface OneNativeAsyncActionModule : NSObject
1274
+ - (void)complete:(NSString*)identifier;
1275
+ - (void)completeString:(NSString*)identifier value:(NSString*)value error:(NSString*)error;
1276
+ @end
1277
+ `,
1278
+ 'ios/OneNativeSyncBridge.h': `#pragma once
1279
+ #include <stdint.h>
1280
+ #ifdef __cplusplus
1281
+ extern "C" {
1282
+ #endif
1283
+ void OneNativeSyncDidSetExternally(int32_t stateId);
1284
+ #ifdef __cplusplus
1285
+ }
1286
+ #endif
1287
+ `,
1288
+ 'ios/PeachPlatform.h': `#pragma once
1289
+ #import <UIKit/UIKit.h>
1290
+ UIColor* PeachPlatformColor(NSString* keyword);
1291
+ `,
1292
+ 'ios/PeachGestures.h': `#pragma once
1293
+ #import <UIKit/UIKit.h>
1294
+ #import "PeachContainer.h"
1295
+
1296
+ @interface PeachInputView : UIView
1297
+ @end
1298
+
1299
+ @interface PeachProjectedInputView : PeachInputView <PeachInputProjection>
1300
+ @property(nonatomic) peach_node inputOriginNode;
1301
+ @end
1302
+
1303
+ static inline void PeachHighlightControl(UIControl* control, BOOL highlighted) {
1304
+ (void)control;
1305
+ (void)highlighted;
1306
+ }
1307
+ static inline void PeachCancelAllTouchesContainingView(UIView* view) { (void)view; }
1308
+ `,
1309
+ 'ios/PeachProfiler.h': `#pragma once
1310
+ #include "../peach_core_mount.h"
1311
+ static const BOOL PeachProfilerActive = NO;
1312
+ static inline void PeachProfilerSheet(peach_node node) { (void)node; }
1313
+ `,
1314
+ 'ios/PeachSafeArea.h': `#pragma once
1315
+ #import "PeachGestures.h"
1316
+ @interface PeachSafeAreaView : PeachInputView
1317
+ @end
1318
+ `,
1319
+ }
1320
+
1321
+ export const PEACH_ONE_DIRECT_HOST_MM = `#import <Foundation/Foundation.h>
1322
+ #import <UIKit/UIKit.h>
1323
+ #import "PeachContainer.h"
1324
+ #import "PeachGestures.h"
1325
+ #import "PeachMenu.h"
1326
+ #import "PeachPlatform.h"
1327
+ #import "PeachPopover.h"
1328
+ #import "PeachSafeArea.h"
1329
+ #import "PeachSheet.h"
1330
+ #import "PeachSwiftUI.h"
1331
+ #include "PeachOneControlsSwift.h"
1332
+ #include "OneNativeSyncBridge.h"
1333
+ #include "../peach_core_css.h"
1334
+ #include "../include/OneNativeControlsHost.h"
1335
+
1336
+ #include <cmath>
1337
+ #include <cstdint>
1338
+ #include <cstring>
1339
+ #include <string>
1340
+ #include <unordered_map>
1341
+ #include <utility>
1342
+ #include <vector>
1343
+
1344
+ #if defined(__wasm__)
1345
+ #define PEACH_ONE_GUEST_IMPORT(name) __attribute__((import_module("peach_one"), import_name(name)))
1346
+ #define PEACH_ONE_GUEST_EXPORT(name) __attribute__((export_name(name)))
1347
+ #else
1348
+ #define PEACH_ONE_GUEST_IMPORT(name)
1349
+ #define PEACH_ONE_GUEST_EXPORT(name)
1350
+ #endif
1351
+
1352
+ extern "C" {
1353
+ PEACH_ONE_GUEST_IMPORT("emit_container_event")
1354
+ int32_t peach_one_emit_container_event(uint32_t nodeLo, uint32_t nodeHi, const char* eventPtr,
1355
+ uint32_t eventLen, const char* jsonPtr, uint32_t jsonLen);
1356
+ PEACH_ONE_GUEST_IMPORT("node_css_color")
1357
+ uint32_t peach_one_node_css_color(uint32_t nodeLo, uint32_t nodeHi, const char* sourcePtr,
1358
+ uint32_t sourceLen, double* rgbaOut);
1359
+ PEACH_ONE_GUEST_IMPORT("node_layout_size")
1360
+ uint32_t peach_one_node_layout_size(uint32_t nodeLo, uint32_t nodeHi, double* sizeOut);
1361
+ PEACH_ONE_GUEST_IMPORT("wake_stage")
1362
+ void peach_one_wake_stage(void);
1363
+ }
1364
+
1365
+ static inline peach_node joinNode(uint32_t lo, uint32_t hi) {
1366
+ return static_cast<uint64_t>(lo) | (static_cast<uint64_t>(hi) << 32);
1367
+ }
1368
+
1369
+ static inline uint32_t nodeLo(peach_node node) { return static_cast<uint32_t>(node & 0xffffffffu); }
1370
+ static inline uint32_t nodeHi(peach_node node) { return static_cast<uint32_t>(node >> 32); }
1371
+
1372
+ @implementation PeachInputView
1373
+ @end
1374
+
1375
+ @implementation PeachProjectedInputView
1376
+ @end
1377
+
1378
+ @implementation PeachSafeAreaView
1379
+ @end
1380
+
1381
+ uint32_t peach_node_css_color(peach_core*, peach_node node, const char* source, size_t size,
1382
+ double rgba[4]) {
1383
+ if (!source || !rgba) return 0;
1384
+ return peach_one_node_css_color(nodeLo(node), nodeHi(node), source, static_cast<uint32_t>(size),
1385
+ rgba);
1386
+ }
1387
+
1388
+ void OneNativeSyncDidSetExternally(int32_t stateId) { (void)stateId; }
1389
+
1390
+ UIColor* PeachPlatformColor(NSString* keyword) {
1391
+ static NSDictionary<NSString*, UIColor*>* const colors = @{
1392
+ @"-apple-system-label": UIColor.labelColor,
1393
+ @"-apple-system-secondary-label": UIColor.secondaryLabelColor,
1394
+ @"-apple-system-tertiary-label": UIColor.tertiaryLabelColor,
1395
+ @"-apple-system-placeholder-text": UIColor.placeholderTextColor,
1396
+ @"-apple-system-separator": UIColor.separatorColor,
1397
+ @"-apple-system-background": UIColor.systemBackgroundColor,
1398
+ @"-apple-system-secondary-background": UIColor.secondarySystemBackgroundColor,
1399
+ @"-apple-system-tertiary-background": UIColor.tertiarySystemBackgroundColor,
1400
+ @"-apple-system-grouped-background": UIColor.systemGroupedBackgroundColor,
1401
+ @"-apple-system-secondary-grouped-background": UIColor.secondarySystemGroupedBackgroundColor,
1402
+ @"-apple-system-tertiary-fill": UIColor.tertiarySystemFillColor,
1403
+ @"-apple-system-blue": UIColor.systemBlueColor,
1404
+ @"-apple-system-cyan": UIColor.systemCyanColor,
1405
+ @"-apple-system-gray": UIColor.systemGrayColor,
1406
+ @"-apple-system-gray-3": UIColor.systemGray3Color,
1407
+ @"-apple-system-green": UIColor.systemGreenColor,
1408
+ @"-apple-system-indigo": UIColor.systemIndigoColor,
1409
+ @"-apple-system-orange": UIColor.systemOrangeColor,
1410
+ @"-apple-system-pink": UIColor.systemPinkColor,
1411
+ @"-apple-system-purple": UIColor.systemPurpleColor,
1412
+ @"-apple-system-red": UIColor.systemRedColor,
1413
+ @"-apple-system-teal": UIColor.systemTealColor,
1414
+ @"-apple-system-yellow": UIColor.systemYellowColor,
1415
+ };
1416
+ return keyword ? colors[keyword.lowercaseString] : nil;
1417
+ }
1418
+
1419
+ @interface PeachDirectTableListContainer : NSObject <PeachContainer>
1420
+ - (void)refreshLayoutIn:(UIView*)container views:(id<PeachViewLookup>)views;
1421
+ @end
1422
+
1423
+ @implementation PeachDirectTableListContainer {
1424
+ PeachDirectTableList* _impl;
1425
+ NSMutableArray<NSNumber*>* _pendingChildren;
1426
+ }
1427
+
1428
+ - (instancetype)init {
1429
+ if ((self = [super init])) {
1430
+ _impl = [PeachDirectTableList new];
1431
+ _pendingChildren = [NSMutableArray array];
1432
+ }
1433
+ return self;
1434
+ }
1435
+
1436
+ - (void)configure:(NSDictionary*)spec emit:(PeachContainerEmit)emit {
1437
+ [_impl configure:spec emit:^(NSString* event, NSDictionary* payload) {
1438
+ if (emit) emit(event, payload);
1439
+ }];
1440
+ }
1441
+
1442
+ - (void)child:(peach_node)node {
1443
+ [_pendingChildren addObject:@(node)];
1444
+ }
1445
+
1446
+ - (void)mountIn:(UIView*)container views:(id<PeachViewLookup>)views {
1447
+ NSArray<NSNumber*>* children = [_pendingChildren copy];
1448
+ [_pendingChildren removeAllObjects];
1449
+ if (!container) return;
1450
+ [_impl mountIn:container
1451
+ children:children
1452
+ viewForNode:^UIView*(uint64_t node) { return [views viewForNode:node]; }
1453
+ sizeForNode:^CGSize(uint64_t node) { return [views layoutSizeForNode:node]; }];
1454
+ }
1455
+
1456
+ - (void)refreshLayoutIn:(UIView*)container views:(id<PeachViewLookup>)views {
1457
+ if (!container) return;
1458
+ [_impl refreshLayoutIn:container
1459
+ viewForNode:^UIView*(uint64_t node) { return [views viewForNode:node]; }
1460
+ sizeForNode:^CGSize(uint64_t node) { return [views layoutSizeForNode:node]; }];
1461
+ }
1462
+
1463
+ - (BOOL)ownsView:(UIView*)view {
1464
+ return view != nil && [_impl ownsView:view];
1465
+ }
1466
+
1467
+ - (void)command:(NSString*)name payload:(NSDictionary*)payload {
1468
+ [_impl command:name payload:payload ?: @{}];
1469
+ }
1470
+
1471
+ - (id)nativeHandleObject {
1472
+ return _impl.nativeTableView;
1473
+ }
1474
+
1475
+ - (void)unmount {
1476
+ [_impl unmount];
1477
+ }
1478
+
1479
+ - (void)detach {
1480
+ [_pendingChildren removeAllObjects];
1481
+ [_impl detach];
1482
+ }
1483
+
1484
+ @end
1485
+
1486
+ namespace {
1487
+
1488
+ constexpr uint32_t kConfigureMeasurementChanged = 1u << 0;
1489
+ constexpr uint32_t kConfigureUsesCssColors = 1u << 1;
1490
+
1491
+ constexpr uint32_t kChildIsContainer = 1u << 0;
1492
+ constexpr uint32_t kChildReset = 1u << 1;
1493
+
1494
+ constexpr uint32_t kMountIsLeaf = 1u << 0;
1495
+ constexpr uint32_t kMountComposeOnly = 1u << 1;
1496
+ constexpr uint32_t kMountChildrenSent = 1u << 2;
1497
+ constexpr uint32_t kMountDetached = 1u << 3;
1498
+
1499
+ struct DirectContainerRecord {
1500
+ peach_node node = 0;
1501
+ NSString* kind = nil;
1502
+ id<PeachContainer> container = nil;
1503
+ UIView* hostView = nil;
1504
+ std::vector<std::pair<peach_node, bool>> stagedChildren;
1505
+ BOOL composed = NO;
1506
+ peach_node hostContentNode = 0;
1507
+ CGRect frame = CGRectZero;
1508
+ };
1509
+
1510
+ std::unordered_map<peach_node, DirectContainerRecord> gRecords;
1511
+ std::unordered_map<peach_node, UIView*> gContentViews;
1512
+ std::unordered_map<peach_node, UIView*> gTriggerViews;
1513
+ peach_node gInPlaceTriggerNode = 0;
1514
+
1515
+ NSString* nsStringFromBytes(const char* ptr, uint32_t len) {
1516
+ if (!ptr || !len) return @"";
1517
+ return [[NSString alloc] initWithBytes:ptr length:len encoding:NSUTF8StringEncoding] ?: @"";
1518
+ }
1519
+
1520
+ NSDictionary* jsonDictFromBytes(const char* ptr, uint32_t len) {
1521
+ if (!ptr || !len) return @{};
1522
+ NSData* data = [NSData dataWithBytesNoCopy:(void*)ptr length:len freeWhenDone:NO];
1523
+ id parsed = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
1524
+ return [parsed isKindOfClass:NSDictionary.class] ? (NSDictionary*)parsed : @{};
1525
+ }
1526
+
1527
+ int32_t emitEventToHost(peach_node node, NSString* event, NSDictionary* payload) {
1528
+ if ([event isEqualToString:@"layout"]) {
1529
+ [PeachOneDirectStage.shared markDirty];
1530
+ peach_one_wake_stage();
1531
+ }
1532
+ NSData* eventData = [event dataUsingEncoding:NSUTF8StringEncoding];
1533
+ NSData* jsonData = payload
1534
+ ? [NSJSONSerialization dataWithJSONObject:payload options:0 error:nil]
1535
+ : nil;
1536
+ const char* evPtr = eventData ? static_cast<const char*>(eventData.bytes) : "";
1537
+ const uint32_t evLen = eventData ? static_cast<uint32_t>(eventData.length) : 0;
1538
+ const char* jsPtr = jsonData ? static_cast<const char*>(jsonData.bytes) : "{}";
1539
+ const uint32_t jsLen = jsonData ? static_cast<uint32_t>(jsonData.length) : 2;
1540
+ return peach_one_emit_container_event(nodeLo(node), nodeHi(node), evPtr, evLen, jsPtr, jsLen);
1541
+ }
1542
+
1543
+ id<PeachContainer> makeContainer(NSString* kind, peach_node node) {
1544
+ if ([kind isEqualToString:@"swiftUI"]) return [PeachSwiftUI new];
1545
+ if ([kind isEqualToString:@"sheet"]) return [PeachSheet new];
1546
+ if ([kind isEqualToString:@"menu"]) return [PeachMenu new];
1547
+ if ([kind isEqualToString:@"contextMenu"]) return [PeachContextMenu new];
1548
+ if ([kind isEqualToString:@"tableList"]) return [PeachDirectTableListContainer new];
1549
+ if ([kind isEqualToString:@"popover"]) {
1550
+ return [[PeachPopover alloc] initWithDismissRequest:^BOOL(NSInteger revision) {
1551
+ return emitEventToHost(node, @"shouldDismiss", @{@"revision": @(revision)}) != 0;
1552
+ }];
1553
+ }
1554
+ return nil;
1555
+ }
1556
+
1557
+ } // namespace
1558
+
1559
+ @interface PeachOneViewLookup : NSObject <PeachViewLookup>
1560
+ @end
1561
+
1562
+ @implementation PeachOneViewLookup
1563
+
1564
+ - (UIView*)viewForNode:(peach_node)node {
1565
+ if (const auto it = gRecords.find(node); it != gRecords.end() && !it->second.composed) {
1566
+ if (!it->second.hostView) {
1567
+ it->second.hostView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, it->second.frame.size.width, it->second.frame.size.height)];
1568
+ }
1569
+ UIView* hostView = it->second.hostView;
1570
+ [PeachOneDirectStage.shared detachHostView:hostView];
1571
+ return hostView;
1572
+ }
1573
+ // menu triggers lay out and paint in place under their One node; only the overlay button
1574
+ // needs a placeholder UIView, never an adopting OneContentSlotView.
1575
+ if (node != 0 && node == gInPlaceTriggerNode) {
1576
+ auto& trigger = gTriggerViews[node];
1577
+ if (!trigger) {
1578
+ trigger = [[UIView alloc] initWithFrame:CGRectZero];
1579
+ trigger.backgroundColor = UIColor.clearColor;
1580
+ }
1581
+ return trigger;
1582
+ }
1583
+ auto& slot = gContentViews[node];
1584
+ if (!slot) {
1585
+ slot = [[UIView alloc] initWithFrame:CGRectZero];
1586
+ slot.backgroundColor = UIColor.clearColor;
1587
+ [PeachOneDirectStage.shared tagContentView:slot node:node];
1588
+ }
1589
+ return slot;
1590
+ }
1591
+
1592
+ - (CGSize)layoutSizeForNode:(peach_node)node {
1593
+ if (const auto it = gRecords.find(node); it != gRecords.end()) {
1594
+ return it->second.frame.size;
1595
+ }
1596
+ double size[2] = {0, 0};
1597
+ if (node != 0 && peach_one_node_layout_size(nodeLo(node), nodeHi(node), size)) {
1598
+ return CGSizeMake(size[0], size[1]);
1599
+ }
1600
+ return CGSizeZero;
1601
+ }
1602
+
1603
+ @end
1604
+
1605
+ static PeachOneViewLookup* gViewLookup = nil;
1606
+
1607
+ static PeachOneViewLookup* viewLookup() {
1608
+ if (!gViewLookup) gViewLookup = [PeachOneViewLookup new];
1609
+ return gViewLookup;
1610
+ }
1611
+
1612
+ extern "C" {
1613
+
1614
+ void PeachOneDirectHostInit(void) {
1615
+ (void)PeachOneDirectStage.shared;
1616
+ (void)viewLookup();
1617
+ PeachOneDirectStage.shared.onWindowAttached = ^{
1618
+ @autoreleasepool {
1619
+ for (auto& [_, record] : gRecords) {
1620
+ if (!record.container || record.composed || !record.hostView) continue;
1621
+ if ([record.container isKindOfClass:PeachSwiftUI.class]) {
1622
+ auto* swift = static_cast<PeachSwiftUI*>(record.container);
1623
+ if ([swift needsInitialHeight]) [swift layoutInitialHeightInTable:NO];
1624
+ } else if ([record.container isKindOfClass:PeachDirectTableListContainer.class]) {
1625
+ [static_cast<PeachDirectTableListContainer*>(record.container)
1626
+ refreshLayoutIn:record.hostView
1627
+ views:viewLookup()];
1628
+ } else if ([record.container isKindOfClass:PeachPopover.class] &&
1629
+ record.frame.size.width > 0 && record.frame.size.height > 0) {
1630
+ [record.container mountIn:record.hostView views:viewLookup()];
1631
+ }
1632
+ }
1633
+ }
1634
+ };
1635
+ }
1636
+
1637
+ PEACH_ONE_GUEST_EXPORT("peach_one_container_configure")
1638
+ uint32_t peach_one_container_configure(uint32_t targetLo, uint32_t targetHi, const char* kindPtr,
1639
+ uint32_t kindLen, const char* jsonPtr, uint32_t jsonLen) {
1640
+ @autoreleasepool {
1641
+ const peach_node node = joinNode(targetLo, targetHi);
1642
+ NSString* kind = nsStringFromBytes(kindPtr, kindLen);
1643
+ NSDictionary* spec = jsonDictFromBytes(jsonPtr, jsonLen);
1644
+ auto& record = gRecords[node];
1645
+ record.node = node;
1646
+ if (record.container && ![record.kind isEqualToString:kind]) {
1647
+ [record.container detach];
1648
+ if (record.hostView) {
1649
+ [PeachOneDirectStage.shared detachHostView:record.hostView];
1650
+ record.hostView = nil;
1651
+ }
1652
+ record.container = nil;
1653
+ }
1654
+ if (!record.container) {
1655
+ record.kind = kind;
1656
+ record.container = makeContainer(kind, node);
1657
+ if (!record.container) return 0;
1658
+ }
1659
+ PeachContainerEmit emit = ^(NSString* event, NSDictionary* payload) {
1660
+ emitEventToHost(node, event, payload);
1661
+ };
1662
+ [record.container configure:spec emit:emit];
1663
+ uint32_t flags = 0;
1664
+ if ([record.container respondsToSelector:@selector(measurementChanged)] &&
1665
+ record.container.measurementChanged) {
1666
+ flags |= kConfigureMeasurementChanged;
1667
+ }
1668
+ if ([record.container isKindOfClass:PeachSwiftUI.class]) {
1669
+ auto* swift = static_cast<PeachSwiftUI*>(record.container);
1670
+ if (swift.usesCSSColors) flags |= kConfigureUsesCssColors;
1671
+ if (swift.measuresHeight && [spec[@"intrinsicHeight"] boolValue]) {
1672
+ if (!swift.heightChanged) {
1673
+ swift.heightChanged = ^(CGFloat height) {
1674
+ emitEventToHost(node, @"__swiftHeight", @{@"height": @(height)});
1675
+ };
1676
+ }
1677
+ } else if (swift.heightChanged) {
1678
+ swift.heightChanged = nil;
1679
+ emitEventToHost(node, @"__swiftHeight", @{@"height": @(-1)});
1680
+ }
1681
+ }
1682
+ return flags;
1683
+ }
1684
+ }
1685
+
1686
+ PEACH_ONE_GUEST_EXPORT("peach_one_container_child")
1687
+ void peach_one_container_child(uint32_t parentLo, uint32_t parentHi, uint32_t childLo,
1688
+ uint32_t childHi, uint32_t flags) {
1689
+ const peach_node parentNode = joinNode(parentLo, parentHi);
1690
+ const peach_node childNode = joinNode(childLo, childHi);
1691
+ const auto it = gRecords.find(parentNode);
1692
+ if (it == gRecords.end()) return;
1693
+ if (flags & kChildReset) {
1694
+ it->second.stagedChildren.clear();
1695
+ return;
1696
+ }
1697
+ it->second.stagedChildren.emplace_back(childNode, (flags & kChildIsContainer) != 0);
1698
+ }
1699
+
1700
+ PEACH_ONE_GUEST_EXPORT("peach_one_container_mount")
1701
+ void peach_one_container_mount(uint32_t targetLo, uint32_t targetHi, uint32_t parentLo,
1702
+ uint32_t parentHi, uint32_t hostContentLo, uint32_t hostContentHi,
1703
+ uint32_t flags, double x, double y, double w, double h) {
1704
+ @autoreleasepool {
1705
+ const peach_node node = joinNode(targetLo, targetHi);
1706
+ const peach_node parentContainerNode = joinNode(parentLo, parentHi);
1707
+ const peach_node hostContentNode = joinNode(hostContentLo, hostContentHi);
1708
+ const auto it = gRecords.find(node);
1709
+ if (it == gRecords.end() || !it->second.container) return;
1710
+ auto& record = it->second;
1711
+ const BOOL isLeaf = (flags & kMountIsLeaf) != 0;
1712
+ const BOOL composeOnly = (flags & kMountComposeOnly) != 0;
1713
+ const BOOL childrenSent = (flags & kMountChildrenSent) != 0;
1714
+ const BOOL detached = (flags & kMountDetached) != 0;
1715
+ record.frame = CGRectMake(x, y, w, h);
1716
+ record.hostContentNode = hostContentNode;
1717
+
1718
+ if (detached) {
1719
+ if (record.hostView) [PeachOneDirectStage.shared detachHostView:record.hostView];
1720
+ if (childrenSent && [record.container respondsToSelector:@selector(unmount)]) {
1721
+ [record.container unmount];
1722
+ }
1723
+ return;
1724
+ }
1725
+
1726
+ PeachSwiftUI* swift = [record.container isKindOfClass:PeachSwiftUI.class]
1727
+ ? static_cast<PeachSwiftUI*>(record.container)
1728
+ : nil;
1729
+
1730
+ if (composeOnly) {
1731
+ if (swift) {
1732
+ id<PeachContainer> parentContainer = nil;
1733
+ if (parentContainerNode != 0) {
1734
+ const auto pit = gRecords.find(parentContainerNode);
1735
+ if (pit != gRecords.end()) parentContainer = pit->second.container;
1736
+ }
1737
+ NSMutableArray* rowChildren = nil;
1738
+ if ([swift usesSectionRowBoundaryIn:parentContainer]) {
1739
+ rowChildren = [NSMutableArray arrayWithCapacity:record.stagedChildren.size()];
1740
+ for (const auto& [childNode, _] : record.stagedChildren) {
1741
+ const auto cit = gRecords.find(childNode);
1742
+ [rowChildren addObject:(cit != gRecords.end() && cit->second.container)
1743
+ ? (id)cit->second.container
1744
+ : (id)NSNull.null];
1745
+ }
1746
+ }
1747
+ record.composed = [swift composeIn:parentContainer rowChildren:rowChildren measuredLeaf:isLeaf];
1748
+ if (record.composed && record.hostView) {
1749
+ [PeachOneDirectStage.shared detachHostView:record.hostView];
1750
+ record.hostView = nil;
1751
+ }
1752
+ } else {
1753
+ record.composed = NO;
1754
+ }
1755
+ return;
1756
+ }
1757
+
1758
+ if (childrenSent) {
1759
+ if (!record.composed) {
1760
+ if (!record.hostView) {
1761
+ record.hostView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, w, h)];
1762
+ record.hostView.backgroundColor = UIColor.clearColor;
1763
+ }
1764
+ UIView* stageView = PeachOneDirectStage.shared.stageView;
1765
+ if (record.hostView.superview == nil || record.hostView.superview == stageView) {
1766
+ [PeachOneDirectStage.shared tagHostView:record.hostView
1767
+ node:node
1768
+ hostContentNode:hostContentNode];
1769
+ [PeachOneDirectStage.shared attachHostView:record.hostView
1770
+ frame:CGRectMake(0, 0, w, h)];
1771
+ } else {
1772
+ CGRect current = record.hostView.frame;
1773
+ current.size = CGSizeMake(w, h);
1774
+ if (!CGRectEqualToRect(record.hostView.frame, current)) record.hostView.frame = current;
1775
+ }
1776
+ }
1777
+ for (const auto& [childNode, _] : record.stagedChildren) {
1778
+ if (swift) {
1779
+ const auto cit = gRecords.find(childNode);
1780
+ PeachSwiftUI* childSwift =
1781
+ (cit != gRecords.end() && [cit->second.container isKindOfClass:PeachSwiftUI.class])
1782
+ ? static_cast<PeachSwiftUI*>(cit->second.container)
1783
+ : nil;
1784
+ [swift child:childNode control:childSwift];
1785
+ } else {
1786
+ [record.container child:childNode];
1787
+ }
1788
+ }
1789
+ const BOOL isMenuTrigger =
1790
+ ([record.container isKindOfClass:PeachMenu.class] ||
1791
+ [record.container isKindOfClass:PeachContextMenu.class]) &&
1792
+ !record.stagedChildren.empty() && !record.stagedChildren[0].second;
1793
+ gInPlaceTriggerNode = isMenuTrigger ? record.stagedChildren[0].first : 0;
1794
+ [record.container mountIn:(record.composed ? nil : record.hostView) views:viewLookup()];
1795
+ gInPlaceTriggerNode = 0;
1796
+ if (swift && [swift needsInitialHeight]) {
1797
+ [swift layoutInitialHeightInTable:NO];
1798
+ }
1799
+ return;
1800
+ }
1801
+
1802
+ // bounds-only update after layout (never re-runs mountIn on PeachSwiftUI)
1803
+ if (!record.composed && record.hostView) {
1804
+ UIView* stageView = PeachOneDirectStage.shared.stageView;
1805
+ if (record.hostView.superview == stageView) {
1806
+ const CGRect next = CGRectMake(0, 0, w, h);
1807
+ if (!CGRectEqualToRect(record.hostView.frame, next)) {
1808
+ record.hostView.frame = next;
1809
+ for (UIView* sub in record.hostView.subviews) {
1810
+ if (!CGRectEqualToRect(sub.frame, record.hostView.bounds)) {
1811
+ sub.frame = record.hostView.bounds;
1812
+ }
1813
+ }
1814
+ }
1815
+ }
1816
+ if (swift && [swift needsInitialHeight]) {
1817
+ [swift layoutInitialHeightInTable:NO];
1818
+ }
1819
+ if ([record.container isKindOfClass:PeachDirectTableListContainer.class]) {
1820
+ [static_cast<PeachDirectTableListContainer*>(record.container)
1821
+ refreshLayoutIn:record.hostView
1822
+ views:viewLookup()];
1823
+ }
1824
+ if ([record.container isKindOfClass:PeachPopover.class] && w > 0 && h > 0) {
1825
+ [record.container mountIn:record.hostView views:viewLookup()];
1826
+ }
1827
+ }
1828
+ }
1829
+ }
1830
+
1831
+ PEACH_ONE_GUEST_EXPORT("peach_one_container_size")
1832
+ uint32_t peach_one_container_size(uint32_t targetLo, uint32_t targetHi, double width,
1833
+ uint32_t widthMode, double height, uint32_t heightMode,
1834
+ double* outW, double* outH) {
1835
+ @autoreleasepool {
1836
+ const peach_node node = joinNode(targetLo, targetHi);
1837
+ const auto it = gRecords.find(node);
1838
+ if (it == gRecords.end() || !it->second.container ||
1839
+ ![it->second.container respondsToSelector:@selector(sizeThatFits:)]) {
1840
+ if (outW) *outW = 0;
1841
+ if (outH) *outH = 0;
1842
+ return 0;
1843
+ }
1844
+ const CGSize proposal = CGSizeMake(widthMode == 0 ? CGFLOAT_MAX : width,
1845
+ heightMode == 0 ? CGFLOAT_MAX : height);
1846
+ const CGSize size = [it->second.container sizeThatFits:proposal];
1847
+ if (outW) *outW = std::isfinite(size.width) && size.width >= 0 ? size.width : 0;
1848
+ if (outH) *outH = std::isfinite(size.height) && size.height >= 0 ? size.height : 0;
1849
+ return 1;
1850
+ }
1851
+ }
1852
+
1853
+ PEACH_ONE_GUEST_EXPORT("peach_one_container_command")
1854
+ void peach_one_container_command(uint32_t targetLo, uint32_t targetHi, const char* namePtr,
1855
+ uint32_t nameLen, const char* jsonPtr, uint32_t jsonLen) {
1856
+ @autoreleasepool {
1857
+ const peach_node node = joinNode(targetLo, targetHi);
1858
+ NSString* name = nsStringFromBytes(namePtr, nameLen);
1859
+ NSDictionary* payload = jsonDictFromBytes(jsonPtr, jsonLen);
1860
+ if (node == 0) {
1861
+ if ([name isEqualToString:@"completeAction"]) {
1862
+ NSString* identifier = [payload[@"id"] isKindOfClass:NSString.class] ? payload[@"id"] : @"";
1863
+ NSDictionary* result = [payload[@"result"] isKindOfClass:NSDictionary.class]
1864
+ ? payload[@"result"]
1865
+ : nil;
1866
+ PeachSwiftUICompleteAction(identifier, result);
1867
+ }
1868
+ return;
1869
+ }
1870
+ const auto it = gRecords.find(node);
1871
+ if (it == gRecords.end() || !it->second.container) return;
1872
+ if ([it->second.container respondsToSelector:@selector(command:payload:)]) {
1873
+ [it->second.container command:name payload:payload];
1874
+ }
1875
+ }
1876
+ }
1877
+
1878
+ PEACH_ONE_GUEST_EXPORT("peach_one_container_release")
1879
+ void peach_one_container_release(uint32_t targetLo, uint32_t targetHi) {
1880
+ @autoreleasepool {
1881
+ const peach_node node = joinNode(targetLo, targetHi);
1882
+ if (const auto it = gRecords.find(node); it != gRecords.end()) {
1883
+ const BOOL wasSwift = [it->second.container isKindOfClass:PeachSwiftUI.class];
1884
+ [it->second.container detach];
1885
+ if (it->second.hostView) [PeachOneDirectStage.shared detachHostView:it->second.hostView];
1886
+ gRecords.erase(it);
1887
+ if (wasSwift) emitEventToHost(node, @"__swiftHeight", @{@"height": @(-1)});
1888
+ }
1889
+ if (const auto cit = gContentViews.find(node); cit != gContentViews.end()) {
1890
+ [cit->second removeFromSuperview];
1891
+ [PeachOneDirectStage.shared tagContentView:cit->second node:0];
1892
+ gContentViews.erase(cit);
1893
+ }
1894
+ if (const auto tit = gTriggerViews.find(node); tit != gTriggerViews.end()) {
1895
+ [tit->second removeFromSuperview];
1896
+ gTriggerViews.erase(tit);
1897
+ }
1898
+ }
1899
+ }
1900
+
1901
+ PEACH_ONE_GUEST_EXPORT("peach_one_container_update_css_colors")
1902
+ void peach_one_container_update_css_colors(uint32_t targetLo, uint32_t targetHi) {
1903
+ @autoreleasepool {
1904
+ const peach_node node = joinNode(targetLo, targetHi);
1905
+ const auto it = gRecords.find(node);
1906
+ if (it == gRecords.end() || ![it->second.container isKindOfClass:PeachSwiftUI.class]) return;
1907
+ [static_cast<PeachSwiftUI*>(it->second.container) updateCSSColors:node core:nullptr];
1908
+ }
1909
+ }
1910
+
1911
+ PEACH_ONE_GUEST_EXPORT("peach_one_container_flush")
1912
+ void peach_one_container_flush(void) {
1913
+ @autoreleasepool {
1914
+ [PeachOneDirectStage.shared markDirty];
1915
+ peach_one_wake_stage();
1916
+ }
1917
+ }
1918
+
1919
+ PEACH_ONE_GUEST_EXPORT("peach_one_swift_ui_commands")
1920
+ const char* peach_one_swift_ui_commands(const char* namePtr, uint32_t nameLen) {
1921
+ @autoreleasepool {
1922
+ static std::string buffer;
1923
+ NSString* name = nsStringFromBytes(namePtr, nameLen);
1924
+ NSArray<NSString*>* commands = PeachSwiftUICommands(name);
1925
+ if (!commands) return nullptr;
1926
+ NSData* data = [NSJSONSerialization dataWithJSONObject:commands options:0 error:nil];
1927
+ if (!data) return nullptr;
1928
+ buffer.assign(static_cast<const char*>(data.bytes), data.length);
1929
+ return buffer.c_str();
1930
+ }
1931
+ }
1932
+
1933
+ } // extern "C"
1934
+ `