SPB Git

Repository Public MIT

GlassSheet.swift 8.1 KB 205 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 SwiftUI42import SPGlassCore43import SPGlassTokens44import SPGlassThemes45import SPGlassEffects4647/// A resting height of a ``SwiftUICore/View/glassSheet(isPresented:title:configuration:onDismiss:content:)``.48public enum GlassSheetDetent: Hashable, Sendable {49    /// About half of the screen.50    case medium51    /// The full height.52    case large53    /// A fraction of the available height, kept between 0.1 and 1.54    case fraction(Double)55    /// A fixed height in points, at least 44.56    case height(Double)5758    /// The same detent with its value brought inside the accepted range. Non-finite values become `.large`.59    public var normalized: GlassSheetDetent {60        switch self {61        case .medium, .large:62            return self63        case .fraction(let value):64            guard value.isFinite else { return .large }65            return .fraction(min(max(value, 0.1), 1))66        case .height(let value):67            guard value.isFinite else { return .large }68            return .height(max(value, 44))69        }70    }7172    /// The system detent.73    public var presentationDetent: PresentationDetent {74        switch normalized {75        case .medium: .medium76        case .large: .large77        case .fraction(let value): .fraction(value)78        case .height(let value): .height(value)79        }80    }8182    /// The set handed to `presentationDetents`. An empty list means a full-height sheet.83    public static func presentationDetents(_ detents: [GlassSheetDetent]) -> Set<PresentationDetent> {84        detents.isEmpty ? [.large] : Set(detents.map(\.presentationDetent))85    }86}8788/// Options of a glass sheet.89public struct GlassSheetConfiguration: Equatable, Sendable {90    /// Heights the sheet can rest at.91    public var detents: [GlassSheetDetent]92    /// Shows the drag indicator when the sheet has more than one detent or can be dragged.93    public var showsDragIndicator: Bool94    /// Shows a close button in the title bar. Keep it on unless the content has its own way out.95    public var showsCloseButton: Bool96    /// Prevents dismissal by swipe; the close button and the host still dismiss the sheet.97    public var isInteractiveDismissDisabled: Bool98    /// Lets a scroll gesture inside the sheet dismiss the keyboard interactively.99    public var scrollDismissesKeyboard: Bool100101    public init(102        detents: [GlassSheetDetent] = [.large],103        showsDragIndicator: Bool = true,104        showsCloseButton: Bool = true,105        isInteractiveDismissDisabled: Bool = false,106        scrollDismissesKeyboard: Bool = true107    ) {108        self.detents = detents109        self.showsDragIndicator = showsDragIndicator110        self.showsCloseButton = showsCloseButton111        self.isInteractiveDismissDisabled = isInteractiveDismissDisabled112        self.scrollDismissesKeyboard = scrollDismissesKeyboard113    }114115    /// A full-height sheet with a close button.116    public static let standard = GlassSheetConfiguration()117    /// A sheet that rests at half height and can be pulled to full height.118    public static let halfAndFull = GlassSheetConfiguration(detents: [.medium, .large])119120    /// Whether the content is wrapped in a navigation bar (a title or a close button is requested).121    public func needsTitleBar(hasTitle: Bool) -> Bool {122        hasTitle || showsCloseButton123    }124}125126extension View {127    /// Presents a system sheet with detents, an optional title bar and an accessible close button.128    ///129    /// ```swift130    /// .glassSheet(isPresented: $showsFilters, title: "Filters", configuration: .halfAndFull) {131    ///     FiltersForm()132    /// }133    /// ```134    ///135    /// The system draws the sheet, including its Liquid Glass background at partial height; GlassKit does not136    /// add a surface. Keyboard avoidance is the system's. The title bar is a `NavigationStack` toolbar, so the137    /// content can add its own toolbar items.138    public func glassSheet<SheetContent: View>(139        isPresented: Binding<Bool>,140        title: LocalizedStringKey? = nil,141        configuration: GlassSheetConfiguration = .standard,142        onDismiss: (@MainActor () -> Void)? = nil,143        @ViewBuilder content: @escaping () -> SheetContent144    ) -> some View {145        sheet(isPresented: isPresented, onDismiss: onDismiss.map { handler in { handler() } }) {146            GlassSheetChrome(title: title.map { Text($0) }, configuration: configuration, content: content())147        }148    }149150    /// Presents a system sheet for an optional item; the sheet is dismissed when the item becomes `nil`.151    public func glassSheet<Item: Identifiable, SheetContent: View>(152        item: Binding<Item?>,153        title: LocalizedStringKey? = nil,154        configuration: GlassSheetConfiguration = .standard,155        onDismiss: (@MainActor () -> Void)? = nil,156        @ViewBuilder content: @escaping (Item) -> SheetContent157    ) -> some View {158        sheet(item: item, onDismiss: onDismiss.map { handler in { handler() } }) { value in159            GlassSheetChrome(title: title.map { Text($0) }, configuration: configuration, content: content(value))160        }161    }162}163164/// The inside of a glass sheet: presentation options, title bar and close button.165struct GlassSheetChrome<Content: View>: View {166    @Environment(\.dismiss) private var dismiss167    let title: Text?168    let configuration: GlassSheetConfiguration169    let content: Content170171    var body: some View {172        framed173            .presentationDetents(GlassSheetDetent.presentationDetents(configuration.detents))174            .presentationDragIndicator(configuration.showsDragIndicator ? .visible : .hidden)175            .interactiveDismissDisabled(configuration.isInteractiveDismissDisabled)176    }177178    @ViewBuilder179    private var framed: some View {180        if configuration.needsTitleBar(hasTitle: title != nil) {181            NavigationStack {182                scrolling183                    .navigationTitle(title ?? Text(verbatim: ""))184                    #if !os(macOS)185                    .navigationBarTitleDisplayMode(.inline)186                    #endif187                    .toolbar {188                        if configuration.showsCloseButton {189                            ToolbarItem(placement: .cancellationAction) {190                                // The system close role supplies the symbol and the accessibility label.191                                Button(role: .close) { dismiss() }192                            }193                        }194                    }195            }196        } else {197            scrolling198        }199    }200201    private var scrolling: some View {202        content.scrollDismissesKeyboard(configuration.scrollDismissesKeyboard ? .interactively : .automatic)203    }204}205
Files main
Menu

Theme