Skip to content

Commit 499a745

Browse files
committed
AppKit: Add asWidget and update methods back.
Signed-off-by: furby™ <devs@wabi.foundation>
1 parent db85feb commit 499a745

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

Sources/AppKitBackend/NSViewRepresentable.swift

+62
Original file line numberDiff line numberDiff line change
@@ -120,10 +120,72 @@ extension View where Self: NSViewRepresentable {
120120
) -> [LayoutSystem.LayoutableChild] {
121121
[]
122122
}
123+
124+
public func asWidget<Backend: AppBackend>(
125+
_: any ViewGraphNodeChildren,
126+
backend _: Backend
127+
) -> Backend.Widget {
128+
if let widget = RepresentingWidget(representable: self) as? Backend.Widget {
129+
return widget
130+
} else {
131+
fatalError("NSViewRepresentable requested by \(Backend.self)")
132+
}
133+
}
134+
135+
@MainActor
136+
public func update<Backend: AppBackend>(
137+
_ widget: Backend.Widget,
138+
children _: any ViewGraphNodeChildren,
139+
proposedSize: SIMD2<Int>,
140+
environment: EnvironmentValues,
141+
backend _: Backend,
142+
dryRun: Bool
143+
) -> ViewUpdateResult {
144+
let representingWidget = widget as! RepresentingWidget<Self>
145+
representingWidget.update(with: environment)
146+
147+
let size =
148+
representingWidget.representable.determineViewSize(
149+
for: proposedSize,
150+
nsView: representingWidget.subview,
151+
context: representingWidget.context!
152+
)
153+
154+
return ViewUpdateResult.leafView(size: size)
155+
}
123156
}
124157

125158
extension NSViewRepresentable where Coordinator == Void {
126159
public func makeCoordinator() {
127160
return ()
128161
}
129162
}
163+
164+
165+
final class RepresentingWidget<Representable: NSViewRepresentable> {
166+
var representable: Representable
167+
var context: NSViewRepresentableContext<Representable.Coordinator>?
168+
169+
@MainActor
170+
lazy var subview: Representable.NSViewType = {
171+
let view = representable.makeNSView(context: context!)
172+
173+
view.translatesAutoresizingMaskIntoConstraints = false
174+
175+
return view
176+
}()
177+
178+
@MainActor
179+
func update(with environment: EnvironmentValues) {
180+
if context == nil {
181+
context = .init(coordinator: representable.makeCoordinator(), environment: environment)
182+
} else {
183+
context!.environment = environment
184+
representable.updateNSView(subview, context: context!)
185+
}
186+
}
187+
188+
init(representable: Representable) {
189+
self.representable = representable
190+
}
191+
}

0 commit comments

Comments
 (0)