SPB Git

Repository Public MIT

GlassCard.swift 9.8 KB 260 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassComponents/Containers/GlassCard.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/// Surface of a ``GlassCard``.48public enum GlassCardStyle: String, CaseIterable, Sendable {49    /// An opaque themed surface. The default, and the right choice for dense content (text, tables, forms).50    case opaque51    /// A Liquid Glass surface, for a card that floats above other content (a map, a photo, a scrolling feed).52    case floating5354    /// The glass style used for this card, or `nil` when the card is opaque.55    ///56    /// Glass reacts to touch only when the card itself is tappable. The glass is neutral: a card carries57    /// text in the theme's colours, which a theme's glass tint would make hard to read.58    public func surfaceStyle(isTappable: Bool) -> GlassSurfaceStyle? {59        switch self {60        case .opaque: nil61        case .floating: GlassSurfaceStyle(tint: .none, isInteractive: isTappable)62        }63    }64}6566/// A container for one piece of content, with an optional media area, header and footer.67///68/// ```swift69/// GlassCard("Monthly rent") {70///     Text("1,450 $").font(.title)71/// }72///73/// GlassCard(media: { ListingPhoto() }) {74///     Text("Two bedrooms, 74 m², balcony.")75/// } header: {76///     Text("Loft on the canal")77/// } footer: {78///     Button("Book a visit") { book() }79/// }80///81/// GlassCard(style: .floating, action: { openListing() }) {82///     Label("3 listings nearby", systemImage: "mappin.and.ellipse")83/// }84/// ```85///86/// The card is opaque by default so that dense content stays readable. Use `.floating` only for a card that87/// sits above other content. The media area runs edge to edge under the card's rounded top; the footer sits88/// under a hairline. With an `action`, the whole card is one button: do not place other controls in it.89public struct GlassCard<Header: View, Content: View, Footer: View>: View {90    @GlassThemed private var theme91    private let style: GlassCardStyle92    private let padding: GlassSpacingStep93    private let action: (@MainActor () -> Void)?94    private let media: AnyView?95    private let header: Header96    private let content: Content97    private let footer: Footer9899    /// Creates a card with a header and a footer.100    ///101    /// - Parameters:102    ///   - style: `.opaque` for dense content, `.floating` for a card above other content.103    ///   - padding: inner padding, a step of the theme's spacing scale.104    ///   - action: when set, the whole card is a button that calls it.105    public init(106        style: GlassCardStyle = .opaque,107        padding: GlassSpacingStep = .md,108        action: (@MainActor () -> Void)? = nil,109        @ViewBuilder content: () -> Content,110        @ViewBuilder header: () -> Header,111        @ViewBuilder footer: () -> Footer112    ) {113        self.style = style114        self.padding = padding115        self.action = action116        self.media = nil117        self.header = header()118        self.content = content()119        self.footer = footer()120    }121122    /// Creates a card with a media area (a photo, a map, a drawing) above its header.123    ///124    /// The media is drawn edge to edge and clipped to the card's shape; give it a height. It is decoration125    /// unless it carries its own accessibility label.126    public init<Media: View>(127        style: GlassCardStyle = .opaque,128        padding: GlassSpacingStep = .md,129        action: (@MainActor () -> Void)? = nil,130        @ViewBuilder media: () -> Media,131        @ViewBuilder content: () -> Content,132        @ViewBuilder header: () -> Header,133        @ViewBuilder footer: () -> Footer134    ) {135        self.style = style136        self.padding = padding137        self.action = action138        self.media = AnyView(media())139        self.header = header()140        self.content = content()141        self.footer = footer()142    }143144    public var body: some View {145        if let action {146            Button(action: action) { surface(isTappable: true) }147                .buttonStyle(GlassCardButtonStyle())148                .contentShape(theme.shape(\.large))149        } else {150            surface(isTappable: false)151                .accessibilityElement(children: .contain)152        }153    }154155    private var hasHeader: Bool { Header.self != EmptyView.self }156    private var hasFooter: Bool { Footer.self != EmptyView.self }157158    private var stack: some View {159        let inset = theme.spacing[padding]160        return VStack(alignment: .leading, spacing: 0) {161            if let media {162                media163                    .frame(maxWidth: .infinity)164                    .clipped()165            }166            VStack(alignment: .leading, spacing: theme.spacing.xs) {167                if hasHeader {168                    header169                        .font(theme.font(.headline))170                        .foregroundStyle(theme.color(.textPrimary))171                        .accessibilityAddTraits(.isHeader)172                }173                content174                    .font(theme.font(.body))175                    .foregroundStyle(theme.color(.textPrimary))176            }177            .frame(maxWidth: media == nil && !hasFooter ? nil : .infinity, alignment: .leading)178            .padding(inset)179            if hasFooter {180                Rectangle()181                    .fill(theme.color(.separator).opacity(0.7))182                    .frame(height: 1)183                    .accessibilityHidden(true)184                footer185                    .font(theme.font(.callout))186                    .foregroundStyle(theme.color(.textSecondary))187                    .frame(maxWidth: .infinity, alignment: .leading)188                    .padding(.horizontal, inset)189                    .padding(.vertical, max(theme.spacing.xs, inset * 0.75))190            }191        }192        .clipShape(theme.shape(\.large))193    }194195    @ViewBuilder196    private func surface(isTappable: Bool) -> some View {197        if let glass = style.surfaceStyle(isTappable: isTappable) {198            stack.glassSurface(glass, in: theme.shape(\.large))199        } else {200            stack.glassOpaqueSurface(in: theme.shape(\.large))201        }202    }203}204205/// Press feedback of a tappable card: a slight dimming, no movement, so it also suits Reduce Motion.206private struct GlassCardButtonStyle: ButtonStyle {207    func makeBody(configuration: Configuration) -> some View {208        configuration.label.opacity(configuration.isPressed ? 0.72 : 1)209    }210}211212extension GlassCard where Header == EmptyView, Footer == EmptyView {213    /// Creates a card with content only.214    public init(215        style: GlassCardStyle = .opaque,216        padding: GlassSpacingStep = .md,217        action: (@MainActor () -> Void)? = nil,218        @ViewBuilder content: () -> Content219    ) {220        self.init(style: style, padding: padding, action: action, content: content, header: { EmptyView() }, footer: { EmptyView() })221    }222}223224extension GlassCard where Header == Text, Footer == EmptyView {225    /// Creates a card with a localised title as its header.226    public init(227        _ titleKey: LocalizedStringKey,228        style: GlassCardStyle = .opaque,229        padding: GlassSpacingStep = .md,230        action: (@MainActor () -> Void)? = nil,231        @ViewBuilder content: () -> Content232    ) {233        self.init(style: style, padding: padding, action: action, content: content, header: { Text(titleKey) }, footer: { EmptyView() })234    }235236    /// Creates a card whose header is a title that is already a string (data, user content).237    public init<S: StringProtocol>(238        verbatim title: S,239        style: GlassCardStyle = .opaque,240        padding: GlassSpacingStep = .md,241        action: (@MainActor () -> Void)? = nil,242        @ViewBuilder content: () -> Content243    ) {244        self.init(style: style, padding: padding, action: action, content: content, header: { Text(verbatim: String(title)) }, footer: { EmptyView() })245    }246}247248extension GlassCard where Header == EmptyView, Footer == EmptyView {249    /// Creates a card with a media area and content only.250    public init<Media: View>(251        style: GlassCardStyle = .opaque,252        padding: GlassSpacingStep = .md,253        action: (@MainActor () -> Void)? = nil,254        @ViewBuilder media: () -> Media,255        @ViewBuilder content: () -> Content256    ) {257        self.init(style: style, padding: padding, action: action, media: media, content: content, header: { EmptyView() }, footer: { EmptyView() })258    }259}260
Files main
Menu

Theme