SPB Git

Repository Public

Surfaces.swift 14.1 KB 358 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraUI/Surfaces.swift8// Module           : Qyvora UI9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0512// Last Modified    : 2026-12-0513//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          : None specified (no license file in this repository)33//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// MARK: - Pressed states4445/// Pressed state of anything tappable that is not a primary button: the content dims and settles slightly.46public struct QPressableStyle: ButtonStyle {47    @Environment(\.isEnabled) private var enabled48    public init() {}4950    public func makeBody(configuration: Configuration) -> some View {51        configuration.label52            .opacity(enabled ? (configuration.isPressed ? 0.68 : 1) : 0.4)53            .scaleEffect(configuration.isPressed ? 0.985 : 1)54            .qAnimation(value: configuration.isPressed)55    }56}5758/// Pressed state of a full-width row inside a card: the row takes the raised surface while it is held.59public struct QRowButtonStyle: ButtonStyle {60    public init() {}6162    public func makeBody(configuration: Configuration) -> some View {63        configuration.label64            .frame(maxWidth: .infinity, alignment: .leading)65            .contentShape(Rectangle())66            .background(configuration.isPressed ? QColor.surfaceRaised : Color.clear)67            .qAnimation(value: configuration.isPressed)68    }69}7071public extension ButtonStyle where Self == QPressableStyle {72    static var qPressable: QPressableStyle { QPressableStyle() }73}7475public extension ButtonStyle where Self == QRowButtonStyle {76    static var qRow: QRowButtonStyle { QRowButtonStyle() }77}7879// MARK: - List section8081/// A titled group of rows in one card, for screens built with a scroll view rather than a `List`. Rows are82/// separated by hairlines that start after the leading glyph, like the system's inset lists.83public struct QListSection<Content: View>: View {84    let title: String?85    let footnote: String?86    let separatorInset: CGFloat87    let content: Content8889    /// - Parameter separatorInset: where the hairlines start, from the leading edge of the card (68 clears a 40-point glyph).90    public init(_ title: String? = nil, footnote: String? = nil, separatorInset: CGFloat = 68, @ViewBuilder content: () -> Content) {91        self.title = title92        self.footnote = footnote93        self.separatorInset = separatorInset94        self.content = content()95    }9697    public var body: some View {98        let shape = RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous)99        VStack(alignment: .leading, spacing: QSpace.s) {100            if let title { QEyebrow(title).padding(.leading, 2) }101            VStack(alignment: .leading, spacing: 0) {102                Group(subviews: content) { subviews in103                    ForEach(Array(subviews.enumerated()), id: \.element.id) { index, subview in104                        subview.padding(.horizontal, QMetric.padding)105                        if index < subviews.count - 1 { QSeparator().padding(.leading, separatorInset) }106                    }107                }108            }109            .frame(maxWidth: .infinity, alignment: .leading)110            .background(QColor.surface)111            .clipShape(shape)112            .overlay(shape.strokeBorder(QColor.stroke, lineWidth: 1))113            if let footnote {114                Text(footnote).font(QFont.caption).foregroundStyle(QColor.textSecondary)115                    .fixedSize(horizontal: false, vertical: true)116                    .padding(.horizontal, 2)117            }118        }119    }120}121122// MARK: - Skeleton123124struct QSkeletonModifier: ViewModifier {125    let active: Bool126    @Environment(\.accessibilityReduceMotion) private var reduceMotion127    @State private var phase: CGFloat = -1128129    func body(content: Content) -> some View {130        if active {131            content132                .redacted(reason: .placeholder)133                .overlay {134                    if !reduceMotion {135                        GeometryReader { geo in136                            LinearGradient(colors: [.clear, QColor.background.opacity(0.55), .clear], startPoint: .leading, endPoint: .trailing)137                                .frame(width: geo.size.width * 0.6)138                                .offset(x: phase * geo.size.width)139                        }140                        .mask(content.redacted(reason: .placeholder))141                        .allowsHitTesting(false)142                        .onAppear {143                            phase = -0.6144                            withAnimation(.linear(duration: 1.6).repeatForever(autoreverses: false)) { phase = 1 }145                        }146                    }147                }148                .allowsHitTesting(false)149                .accessibilityElement(children: .ignore)150                .accessibilityLabel("Loading")151        } else {152            content153        }154    }155}156157public extension View {158    /// Shows the view as a loading placeholder: its texts become neutral bars with the same layout, and a slow band159    /// of light crosses them. The band does not move under Reduce Motion. Use it on a row built with placeholder160    /// strings of a plausible length — never to show invented figures.161    func qSkeleton(_ active: Bool = true) -> some View { modifier(QSkeletonModifier(active: active)) }162}163164/// A neutral bar, for skeletons assembled by hand.165public struct QSkeletonBlock: View {166    let width: CGFloat?167    let height: CGFloat168169    public init(width: CGFloat? = nil, height: CGFloat = 12) {170        self.width = width171        self.height = height172    }173174    public var body: some View {175        RoundedRectangle(cornerRadius: min(6, height / 2), style: .continuous)176            .fill(QColor.textTertiary.opacity(0.3))177            .frame(width: width, height: height)178            .frame(maxWidth: width == nil ? .infinity : nil)179            .accessibilityHidden(true)180    }181}182183/// The placeholder of a list row while its data loads: a glyph, two lines and a trailing figure.184public struct QSkeletonRow: View {185    @ScaledMetric(relativeTo: .body) private var glyph: CGFloat = 40186187    public init() {}188189    public var body: some View {190        HStack(spacing: QSpace.m) {191            RoundedRectangle(cornerRadius: glyph * 0.3, style: .continuous).fill(QColor.textTertiary.opacity(0.3)).frame(width: glyph, height: glyph)192            VStack(alignment: .leading, spacing: 7) {193                QSkeletonBlock(width: 112, height: 13)194                QSkeletonBlock(width: 64, height: 10)195            }196            Spacer(minLength: QSpace.s)197            VStack(alignment: .trailing, spacing: 7) {198                QSkeletonBlock(width: 84, height: 13)199                QSkeletonBlock(width: 48, height: 10)200            }201        }202        .padding(.vertical, QSpace.s)203        .frame(minHeight: QMetric.rowMinHeight)204        .qSkeleton()205    }206}207208// MARK: - Toast209210/// A short confirmation that does not block the screen ("Address copied").211public struct QToastMessage: Identifiable, Equatable, Sendable {212    public let id: UUID213    public let text: String214    public let systemImage: String215    public let tone: QTone216217    public init(_ text: String, systemImage: String = "checkmark", tone: QTone = .positive) {218        self.id = UUID()219        self.text = text220        self.systemImage = systemImage221        self.tone = tone222    }223224    /// "Address copied", "Transaction ID copied"…225    public static func copied(_ what: String = "") -> QToastMessage {226        QToastMessage(what.isEmpty ? "Copied" : "\(what) copied", systemImage: "doc.on.doc")227    }228}229230/// The toast itself: a glyph and a few words in a capsule.231public struct QToast: View {232    let message: QToastMessage233234    public init(_ message: QToastMessage) { self.message = message }235236    public var body: some View {237        HStack(spacing: QSpace.s) {238            Image(systemName: message.systemImage)239                .font(.footnote.weight(.bold))240                .foregroundStyle(message.tone == .neutral ? QColor.textSecondary : message.tone.color)241            Text(message.text).font(QFont.subheadline).foregroundStyle(QColor.textPrimary).lineLimit(2)242        }243        .padding(.horizontal, QSpace.l)244        .padding(.vertical, 11)245        .background(QColor.surfaceRaised, in: Capsule())246        .overlay(Capsule().strokeBorder(QColor.strokeStrong.opacity(0.6), lineWidth: 1))247        .accessibilityElement(children: .combine)248    }249}250251struct QToastModifier: ViewModifier {252    @Binding var message: QToastMessage?253    let duration: TimeInterval254    let edge: VerticalEdge255    @Environment(\.accessibilityReduceMotion) private var reduceMotion256257    func body(content: Content) -> some View {258        content259            .overlay(alignment: edge == .top ? .top : .bottom) {260                if let message {261                    QToast(message)262                        .padding(.horizontal, QMetric.screenPadding)263                        .padding(edge == .top ? .top : .bottom, QSpace.l)264                        .transition(reduceMotion ? .opacity : .opacity.combined(with: .move(edge: edge == .top ? .top : .bottom)))265                        .allowsHitTesting(false)266                        .id(message.id)267                }268            }269            .animation(QMotion.resolved(QMotion.emphasized, reduceMotion: reduceMotion), value: message)270            .qHaptic(trigger: message) { $0.map { $0.tone == .critical ? .failed : ($0.tone == .warning ? .warning : .copied) } }271            .task(id: message?.id) {272                guard let shown = message else { return }273                AccessibilityNotification.Announcement(shown.text).post()274                try? await Task.sleep(for: .seconds(duration))275                if !Task.isCancelled, message?.id == shown.id { message = nil }276            }277    }278}279280public extension View {281    /// Shows a toast while `message` is set, then clears it. The text is announced to VoiceOver; the toast never282    /// takes touches and never moves the layout.283    func qToast(_ message: Binding<QToastMessage?>, duration: TimeInterval = 2.2, edge: VerticalEdge = .bottom) -> some View {284        modifier(QToastModifier(message: message, duration: duration, edge: edge))285    }286}287288// MARK: - Sheets289290/// Usual heights of a sheet.291public enum QDetents {292    /// A short confirmation or a picker with a few rows.293    public static let compact: Set<PresentationDetent> = [.height(340), .large]294    /// Half the screen first, the whole screen on demand.295    public static let half: Set<PresentationDetent> = [.medium, .large]296    public static let full: Set<PresentationDetent> = [.large]297}298299/// The body of a sheet: a title block with a close control, scrolling content and a footer for the actions that300/// stays above the keyboard and the home indicator.301public struct QSheetScaffold<Content: View, Footer: View>: View {302    let title: String303    let subtitle: String?304    let onClose: (() -> Void)?305    let content: Content306    let footer: Footer307308    public init(_ title: String, subtitle: String? = nil, onClose: (() -> Void)? = nil, @ViewBuilder content: () -> Content,309                @ViewBuilder footer: () -> Footer) {310        self.title = title311        self.subtitle = subtitle312        self.onClose = onClose313        self.content = content()314        self.footer = footer()315    }316317    public var body: some View {318        VStack(spacing: 0) {319            SheetHeader(title, subtitle: subtitle, onClose: onClose)320                .padding(.horizontal, QMetric.screenPadding)321                .padding(.top, QSpace.xl)322                .padding(.bottom, QSpace.m)323            ScrollView {324                VStack(alignment: .leading, spacing: QSpace.l) { content }325                    .padding(.horizontal, QMetric.screenPadding)326                    .padding(.bottom, QSpace.xl)327                    .frame(maxWidth: .infinity, alignment: .leading)328            }329            .scrollBounceBehavior(.basedOnSize)330            if Footer.self != EmptyView.self {331                QSeparator()332                VStack(spacing: QSpace.m) { footer }333                    .padding(.horizontal, QMetric.screenPadding)334                    .padding(.vertical, QSpace.m)335            }336        }337        .background(QColor.background.ignoresSafeArea())338    }339}340341public extension QSheetScaffold where Footer == EmptyView {342    init(_ title: String, subtitle: String? = nil, onClose: (() -> Void)? = nil, @ViewBuilder content: () -> Content) {343        self.init(title, subtitle: subtitle, onClose: onClose, content: content) { EmptyView() }344    }345}346347public extension View {348    /// The presentation chrome shared by every sheet: a visible grabber, the application background, the large349    /// corner radius and the given heights.350    func qSheetChrome(detents: Set<PresentationDetent> = QDetents.half) -> some View {351        self352            .presentationDetents(detents)353            .presentationDragIndicator(.visible)354            .presentationBackground(QColor.background)355            .presentationCornerRadius(QMetric.radiusLarge)356    }357}358
Files main
Menu

Theme