SPB Git

Repository Public MIT

GlassSheet.swift 8.1 KB 201 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassComponents/Containers/GlassSheet.swift8// Module           : SPGlassComponents9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI4243/// A resting height of a ``SwiftUICore/View/glassSheet(isPresented:title:configuration:onDismiss:content:)``.44public enum GlassSheetDetent: Hashable, Sendable {45    /// About half of the screen.46    case medium47    /// The full height.48    case large49    /// A fraction of the available height, kept between 0.1 and 1.50    case fraction(Double)51    /// A fixed height in points, at least 44.52    case height(Double)5354    /// The same detent with its value brought inside the accepted range. Non-finite values become `.large`.55    public var normalized: GlassSheetDetent {56        switch self {57        case .medium, .large:58            return self59        case .fraction(let value):60            guard value.isFinite else { return .large }61            return .fraction(min(max(value, 0.1), 1))62        case .height(let value):63            guard value.isFinite else { return .large }64            return .height(max(value, 44))65        }66    }6768    /// The system detent.69    public var presentationDetent: PresentationDetent {70        switch normalized {71        case .medium: .medium72        case .large: .large73        case .fraction(let value): .fraction(value)74        case .height(let value): .height(value)75        }76    }7778    /// The set handed to `presentationDetents`. An empty list means a full-height sheet.79    public static func presentationDetents(_ detents: [GlassSheetDetent]) -> Set<PresentationDetent> {80        detents.isEmpty ? [.large] : Set(detents.map(\.presentationDetent))81    }82}8384/// Options of a glass sheet.85public struct GlassSheetConfiguration: Equatable, Sendable {86    /// Heights the sheet can rest at.87    public var detents: [GlassSheetDetent]88    /// Shows the drag indicator when the sheet has more than one detent or can be dragged.89    public var showsDragIndicator: Bool90    /// Shows a close button in the title bar. Keep it on unless the content has its own way out.91    public var showsCloseButton: Bool92    /// Prevents dismissal by swipe; the close button and the host still dismiss the sheet.93    public var isInteractiveDismissDisabled: Bool94    /// Lets a scroll gesture inside the sheet dismiss the keyboard interactively.95    public var scrollDismissesKeyboard: Bool9697    public init(98        detents: [GlassSheetDetent] = [.large],99        showsDragIndicator: Bool = true,100        showsCloseButton: Bool = true,101        isInteractiveDismissDisabled: Bool = false,102        scrollDismissesKeyboard: Bool = true103    ) {104        self.detents = detents105        self.showsDragIndicator = showsDragIndicator106        self.showsCloseButton = showsCloseButton107        self.isInteractiveDismissDisabled = isInteractiveDismissDisabled108        self.scrollDismissesKeyboard = scrollDismissesKeyboard109    }110111    /// A full-height sheet with a close button.112    public static let standard = GlassSheetConfiguration()113    /// A sheet that rests at half height and can be pulled to full height.114    public static let halfAndFull = GlassSheetConfiguration(detents: [.medium, .large])115116    /// Whether the content is wrapped in a navigation bar (a title or a close button is requested).117    public func needsTitleBar(hasTitle: Bool) -> Bool {118        hasTitle || showsCloseButton119    }120}121122extension View {123    /// Presents a system sheet with detents, an optional title bar and an accessible close button.124    ///125    /// ```swift126    /// .glassSheet(isPresented: $showsFilters, title: "Filters", configuration: .halfAndFull) {127    ///     FiltersForm()128    /// }129    /// ```130    ///131    /// The system draws the sheet, including its Liquid Glass background at partial height; GlassKit does not132    /// add a surface. Keyboard avoidance is the system's. The title bar is a `NavigationStack` toolbar, so the133    /// content can add its own toolbar items.134    public func glassSheet<SheetContent: View>(135        isPresented: Binding<Bool>,136        title: LocalizedStringKey? = nil,137        configuration: GlassSheetConfiguration = .standard,138        onDismiss: (@MainActor () -> Void)? = nil,139        @ViewBuilder content: @escaping () -> SheetContent140    ) -> some View {141        sheet(isPresented: isPresented, onDismiss: onDismiss.map { handler in { handler() } }) {142            GlassSheetChrome(title: title.map { Text($0) }, configuration: configuration, content: content())143        }144    }145146    /// Presents a system sheet for an optional item; the sheet is dismissed when the item becomes `nil`.147    public func glassSheet<Item: Identifiable, SheetContent: View>(148        item: Binding<Item?>,149        title: LocalizedStringKey? = nil,150        configuration: GlassSheetConfiguration = .standard,151        onDismiss: (@MainActor () -> Void)? = nil,152        @ViewBuilder content: @escaping (Item) -> SheetContent153    ) -> some View {154        sheet(item: item, onDismiss: onDismiss.map { handler in { handler() } }) { value in155            GlassSheetChrome(title: title.map { Text($0) }, configuration: configuration, content: content(value))156        }157    }158}159160/// The inside of a glass sheet: presentation options, title bar and close button.161struct GlassSheetChrome<Content: View>: View {162    @Environment(\.dismiss) private var dismiss163    let title: Text?164    let configuration: GlassSheetConfiguration165    let content: Content166167    var body: some View {168        framed169            .presentationDetents(GlassSheetDetent.presentationDetents(configuration.detents))170            .presentationDragIndicator(configuration.showsDragIndicator ? .visible : .hidden)171            .interactiveDismissDisabled(configuration.isInteractiveDismissDisabled)172    }173174    @ViewBuilder175    private var framed: some View {176        if configuration.needsTitleBar(hasTitle: title != nil) {177            NavigationStack {178                scrolling179                    .navigationTitle(title ?? Text(verbatim: ""))180                    #if !os(macOS)181                    .navigationBarTitleDisplayMode(.inline)182                    #endif183                    .toolbar {184                        if configuration.showsCloseButton {185                            ToolbarItem(placement: .cancellationAction) {186                                // The system close role supplies the symbol and the accessibility label.187                                Button(role: .close) { dismiss() }188                            }189                        }190                    }191            }192        } else {193            scrolling194        }195    }196197    private var scrolling: some View {198        content.scrollDismissesKeyboard(configuration.scrollDismissesKeyboard ? .interactively : .automatic)199    }200}201
Files main
Menu

Theme