SPB Git

Repository Public MIT

GlassCard.swift 9.7 KB 256 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 SwiftUI4243/// Surface of a ``GlassCard``.44public enum GlassCardStyle: String, CaseIterable, Sendable {45    /// An opaque themed surface. The default, and the right choice for dense content (text, tables, forms).46    case opaque47    /// A Liquid Glass surface, for a card that floats above other content (a map, a photo, a scrolling feed).48    case floating4950    /// The glass style used for this card, or `nil` when the card is opaque.51    ///52    /// Glass reacts to touch only when the card itself is tappable. The glass is neutral: a card carries53    /// text in the theme's colours, which a theme's glass tint would make hard to read.54    public func surfaceStyle(isTappable: Bool) -> GlassSurfaceStyle? {55        switch self {56        case .opaque: nil57        case .floating: GlassSurfaceStyle(tint: .none, isInteractive: isTappable)58        }59    }60}6162/// A container for one piece of content, with an optional media area, header and footer.63///64/// ```swift65/// GlassCard("Monthly rent") {66///     Text("1,450 $").font(.title)67/// }68///69/// GlassCard(media: { ListingPhoto() }) {70///     Text("Two bedrooms, 74 m², balcony.")71/// } header: {72///     Text("Loft on the canal")73/// } footer: {74///     Button("Book a visit") { book() }75/// }76///77/// GlassCard(style: .floating, action: { openListing() }) {78///     Label("3 listings nearby", systemImage: "mappin.and.ellipse")79/// }80/// ```81///82/// The card is opaque by default so that dense content stays readable. Use `.floating` only for a card that83/// sits above other content. The media area runs edge to edge under the card's rounded top; the footer sits84/// under a hairline. With an `action`, the whole card is one button: do not place other controls in it.85public struct GlassCard<Header: View, Content: View, Footer: View>: View {86    @GlassThemed private var theme87    private let style: GlassCardStyle88    private let padding: GlassSpacingStep89    private let action: (@MainActor () -> Void)?90    private let media: AnyView?91    private let header: Header92    private let content: Content93    private let footer: Footer9495    /// Creates a card with a header and a footer.96    ///97    /// - Parameters:98    ///   - style: `.opaque` for dense content, `.floating` for a card above other content.99    ///   - padding: inner padding, a step of the theme's spacing scale.100    ///   - action: when set, the whole card is a button that calls it.101    public init(102        style: GlassCardStyle = .opaque,103        padding: GlassSpacingStep = .md,104        action: (@MainActor () -> Void)? = nil,105        @ViewBuilder content: () -> Content,106        @ViewBuilder header: () -> Header,107        @ViewBuilder footer: () -> Footer108    ) {109        self.style = style110        self.padding = padding111        self.action = action112        self.media = nil113        self.header = header()114        self.content = content()115        self.footer = footer()116    }117118    /// Creates a card with a media area (a photo, a map, a drawing) above its header.119    ///120    /// The media is drawn edge to edge and clipped to the card's shape; give it a height. It is decoration121    /// unless it carries its own accessibility label.122    public init<Media: View>(123        style: GlassCardStyle = .opaque,124        padding: GlassSpacingStep = .md,125        action: (@MainActor () -> Void)? = nil,126        @ViewBuilder media: () -> Media,127        @ViewBuilder content: () -> Content,128        @ViewBuilder header: () -> Header,129        @ViewBuilder footer: () -> Footer130    ) {131        self.style = style132        self.padding = padding133        self.action = action134        self.media = AnyView(media())135        self.header = header()136        self.content = content()137        self.footer = footer()138    }139140    public var body: some View {141        if let action {142            Button(action: action) { surface(isTappable: true) }143                .buttonStyle(GlassCardButtonStyle())144                .contentShape(theme.shape(\.large))145        } else {146            surface(isTappable: false)147                .accessibilityElement(children: .contain)148        }149    }150151    private var hasHeader: Bool { Header.self != EmptyView.self }152    private var hasFooter: Bool { Footer.self != EmptyView.self }153154    private var stack: some View {155        let inset = theme.spacing[padding]156        return VStack(alignment: .leading, spacing: 0) {157            if let media {158                media159                    .frame(maxWidth: .infinity)160                    .clipped()161            }162            VStack(alignment: .leading, spacing: theme.spacing.xs) {163                if hasHeader {164                    header165                        .font(theme.font(.headline))166                        .foregroundStyle(theme.color(.textPrimary))167                        .accessibilityAddTraits(.isHeader)168                }169                content170                    .font(theme.font(.body))171                    .foregroundStyle(theme.color(.textPrimary))172            }173            .frame(maxWidth: media == nil && !hasFooter ? nil : .infinity, alignment: .leading)174            .padding(inset)175            if hasFooter {176                Rectangle()177                    .fill(theme.color(.separator).opacity(0.7))178                    .frame(height: 1)179                    .accessibilityHidden(true)180                footer181                    .font(theme.font(.callout))182                    .foregroundStyle(theme.color(.textSecondary))183                    .frame(maxWidth: .infinity, alignment: .leading)184                    .padding(.horizontal, inset)185                    .padding(.vertical, max(theme.spacing.xs, inset * 0.75))186            }187        }188        .clipShape(theme.shape(\.large))189    }190191    @ViewBuilder192    private func surface(isTappable: Bool) -> some View {193        if let glass = style.surfaceStyle(isTappable: isTappable) {194            stack.glassSurface(glass, in: theme.shape(\.large))195        } else {196            stack.glassOpaqueSurface(in: theme.shape(\.large))197        }198    }199}200201/// Press feedback of a tappable card: a slight dimming, no movement, so it also suits Reduce Motion.202private struct GlassCardButtonStyle: ButtonStyle {203    func makeBody(configuration: Configuration) -> some View {204        configuration.label.opacity(configuration.isPressed ? 0.72 : 1)205    }206}207208extension GlassCard where Header == EmptyView, Footer == EmptyView {209    /// Creates a card with content only.210    public init(211        style: GlassCardStyle = .opaque,212        padding: GlassSpacingStep = .md,213        action: (@MainActor () -> Void)? = nil,214        @ViewBuilder content: () -> Content215    ) {216        self.init(style: style, padding: padding, action: action, content: content, header: { EmptyView() }, footer: { EmptyView() })217    }218}219220extension GlassCard where Header == Text, Footer == EmptyView {221    /// Creates a card with a localised title as its header.222    public init(223        _ titleKey: LocalizedStringKey,224        style: GlassCardStyle = .opaque,225        padding: GlassSpacingStep = .md,226        action: (@MainActor () -> Void)? = nil,227        @ViewBuilder content: () -> Content228    ) {229        self.init(style: style, padding: padding, action: action, content: content, header: { Text(titleKey) }, footer: { EmptyView() })230    }231232    /// Creates a card whose header is a title that is already a string (data, user content).233    public init<S: StringProtocol>(234        verbatim title: S,235        style: GlassCardStyle = .opaque,236        padding: GlassSpacingStep = .md,237        action: (@MainActor () -> Void)? = nil,238        @ViewBuilder content: () -> Content239    ) {240        self.init(style: style, padding: padding, action: action, content: content, header: { Text(verbatim: String(title)) }, footer: { EmptyView() })241    }242}243244extension GlassCard where Header == EmptyView, Footer == EmptyView {245    /// Creates a card with a media area and content only.246    public init<Media: View>(247        style: GlassCardStyle = .opaque,248        padding: GlassSpacingStep = .md,249        action: (@MainActor () -> Void)? = nil,250        @ViewBuilder media: () -> Media,251        @ViewBuilder content: () -> Content252    ) {253        self.init(style: style, padding: padding, action: action, media: media, content: content, header: { EmptyView() }, footer: { EmptyView() })254    }255}256
Files main
Menu

Theme