import SwiftUI

public extension View {
    func selfSizingPresentation() -> some View {
        modifier(SelfSizingDetentViewModifier())
    }
}

private struct SelfSizingDetentViewModifier: ViewModifier {
    @State private var detentHeight: CGFloat = 0

    func body(content: Content) -> some View {
        VStack(spacing: 0) {
            content
                .onGeometryChange(for: CGSize.self) { proxy in proxy.size } action: {
                    detentHeight = $0.height
                }
                .presentationDetents([.height(detentHeight)])

            Spacer(minLength: 0) /// `VStack` + `Spacer()` pushes the content to the top, making for a more natural self-sizing behavior when the sheet is dragged.
        }
    }
}
