Download this file
| 1 | import AppKit |
| 2 | import SwiftUI |
| 3 | |
| 4 | /// SwiftUI reports its natural height even after asynchronous content changes. |
| 5 | /// The transcript keeps its row identity and shifts everything below it. |
| 6 | @MainActor final class ResizingHostingView<Content: View>: NSHostingView<MeasuredContent<Content>> { |
| 7 | init(content: Content, width: CGFloat, onHeightChange: @escaping (NSView, CGFloat) -> Void) { |
| 8 | super.init(rootView: MeasuredContent(content: content, width: width, changed: { _ in })) |
| 9 | rootView = MeasuredContent(content: content, width: width) { [weak self] height in |
| 10 | Task { @MainActor [weak self] in |
| 11 | await Task.yield() |
| 12 | guard let self else { return } |
| 13 | onHeightChange(self, ceil(height)) |
| 14 | } |
| 15 | } |
| 16 | frame.size = NSSize(width: width, height: ceil(fittingSize.height)) |
| 17 | } |
| 18 | required init(rootView: MeasuredContent<Content>) { super.init(rootView: rootView) } |
| 19 | required init?(coder: NSCoder) { fatalError() } |
| 20 | } |
| 21 | |
| 22 | struct MeasuredContent<Content: View>: View { |
| 23 | let content: Content |
| 24 | let width: CGFloat |
| 25 | let changed: (CGFloat) -> Void |
| 26 | var body: some View { |
| 27 | content.frame(width: width, alignment: .leading) |
| 28 | .fixedSize(horizontal: false, vertical: true) |
| 29 | .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { changed($0) } |
| 30 | } |
| 31 | } |
| 32 | |