SPB Git

Repository Public MIT

GlassPanel.swift 11.1 KB 267 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassComponents/Containers/GlassPanel.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/// Bounds of a resizable ``GlassPanel`` and the pure rules that keep a size inside them.44public struct GlassPanelSizeLimits: Equatable, Sendable {45    /// Smallest size the panel can take.46    public var minimum: CGSize47    /// Largest size the panel can take.48    public var maximum: CGSize4950    /// Creates limits. A maximum below the minimum is raised to the minimum; negative values count as zero.51    public init(minimum: CGSize = CGSize(width: 240, height: 160), maximum: CGSize = CGSize(width: 720, height: 640)) {52        let minWidth = Self.sanitize(minimum.width), minHeight = Self.sanitize(minimum.height)53        self.minimum = CGSize(width: minWidth, height: minHeight)54        self.maximum = CGSize(width: max(minWidth, Self.sanitize(maximum.width)), height: max(minHeight, Self.sanitize(maximum.height)))55    }5657    /// 240 × 160 to 720 × 640 points.58    public static let standard = GlassPanelSizeLimits()5960    /// The size nearest to `size` that respects the limits. Non-finite components fall back to the minimum.61    public func clamp(_ size: CGSize) -> CGSize {62        CGSize(63            width: Self.clamp(size.width, minimum.width, maximum.width),64            height: Self.clamp(size.height, minimum.height, maximum.height)65        )66    }6768    /// The size after dragging the trailing-bottom handle by `translation` from `start`.69    ///70    /// In a right-to-left layout the handle sits on the left, so a drag to the left widens the panel.71    public func resized(from start: CGSize, translation: CGSize, isRightToLeft: Bool = false) -> CGSize {72        let horizontal = isRightToLeft ? -translation.width : translation.width73        return clamp(CGSize(width: start.width + horizontal, height: start.height + translation.height))74    }7576    private static func sanitize(_ value: CGFloat) -> CGFloat {77        value.isFinite ? max(0, value) : 078    }7980    private static func clamp(_ value: CGFloat, _ lower: CGFloat, _ upper: CGFloat) -> CGFloat {81        guard value.isFinite else { return lower }82        return min(max(value, lower), upper)83    }84}8586/// A floating glass panel of actions or short content, with a title and an optional close button.87///88/// ```swift89/// GlassPanel("Layers", size: $panelSize, onClose: { showsLayers = false }) {90///     Toggle("Transit", isOn: $showsTransit)91///     Toggle("Traffic", isOn: $showsTraffic)92/// }93/// ```94///95/// The panel belongs to the navigation layer: it floats above content and holds controls, not long text.96/// On macOS, pass a `size` binding to let the user resize it with the handle in the trailing-bottom corner97/// (drag, arrow keys or VoiceOver adjust); keyboard focus moves inside the panel as one section and Escape98/// calls `onClose`. On iOS and iPadOS the panel sizes itself to its content and `size` is ignored.99public struct GlassPanel<Content: View>: View {100    @GlassThemed private var theme101    @Environment(\.layoutDirection) private var layoutDirection102    @Namespace private var focusNamespace103    @State private var dragStart: CGSize?104    private let title: Text105    private let size: Binding<CGSize>?106    private let limits: GlassPanelSizeLimits107    private let onClose: (@MainActor () -> Void)?108    private let content: Content109110    /// Creates a panel.111    ///112    /// - Parameters:113    ///   - title: heading of the panel, also its accessibility label.114    ///   - size: controlled size on macOS. `nil` sizes the panel to its content and hides the resize handle.115    ///   - sizeLimits: bounds applied to `size`.116    ///   - onClose: when set, a close button is shown and Escape calls it.117    public init(118        _ title: LocalizedStringKey,119        size: Binding<CGSize>? = nil,120        sizeLimits: GlassPanelSizeLimits = .standard,121        onClose: (@MainActor () -> Void)? = nil,122        @ViewBuilder content: () -> Content123    ) {124        self.init(title: Text(title), size: size, sizeLimits: sizeLimits, onClose: onClose, content: content)125    }126127    /// Creates a panel whose title is already a `Text`.128    public init(129        title: Text,130        size: Binding<CGSize>? = nil,131        sizeLimits: GlassPanelSizeLimits = .standard,132        onClose: (@MainActor () -> Void)? = nil,133        @ViewBuilder content: () -> Content134    ) {135        self.title = title136        self.size = size137        self.limits = sizeLimits138        self.onClose = onClose139        self.content = content()140    }141142    public var body: some View {143        platformBehaviour(144            sized(145                VStack(alignment: .leading, spacing: 0) {146                    titleBar147                        .padding(.leading, theme.spacing.md)148                        .padding(.trailing, theme.spacing.xs)149                        .padding(.vertical, theme.spacing.xxs)150                    Rectangle()151                        .fill(theme.color(.textPrimary).opacity(0.12))152                        .frame(height: 1)153                        .accessibilityHidden(true)154                    VStack(alignment: .leading, spacing: theme.spacing.sm) {155                        content156                            .font(theme.font(.body))157                            .foregroundStyle(theme.color(.textPrimary))158                    }159                    .padding(theme.spacing.md)160                }161            )162            // Neutral glass: the panel carries text and controls in the theme's colours.163            .glassSurface(.regular.tinted(.none), in: theme.shape(\.large))164            .overlay(alignment: .bottomTrailing) { resizeHandle }165        )166        .accessibilityElement(children: .contain)167        .accessibilityLabel(title)168    }169170    private var titleBar: some View {171        HStack(alignment: .center, spacing: theme.spacing.xs) {172            title173                .font(theme.font(.headline))174                .foregroundStyle(theme.color(.textPrimary))175                .lineLimit(2)176                .accessibilityAddTraits(.isHeader)177            Spacer(minLength: theme.spacing.xs)178            if let onClose {179                // A plain system button: the panel is already glass, and glass never sits inside glass.180                Button(action: onClose) {181                    Label(GlassL10n.string(.close), systemImage: "xmark")182                        .labelStyle(.iconOnly)183                        .font(.system(.footnote, weight: .bold))184                        .foregroundStyle(theme.color(.textSecondary))185                        .frame(width: 28, height: 28)186                        .background(theme.color(.textPrimary).opacity(0.1), in: Circle())187                }188                .buttonStyle(.plain)189                .glassMinimumHitTarget()190                #if !os(macOS)191                .keyboardShortcut(.cancelAction)192                #endif193            } else {194                Color.clear.frame(width: 1, height: 44).accessibilityHidden(true)195            }196        }197    }198199    @ViewBuilder200    private func sized(_ view: some View) -> some View {201        #if os(macOS)202        if let size {203            let clamped = limits.clamp(size.wrappedValue)204            view.frame(width: clamped.width, height: clamped.height, alignment: .topLeading)205        } else {206            view207        }208        #else209        view210        #endif211    }212213    @ViewBuilder214    private func platformBehaviour(_ view: some View) -> some View {215        #if os(macOS)216        if let onClose {217            view.focusScope(focusNamespace).focusSection().onExitCommand { onClose() }218        } else {219            view.focusScope(focusNamespace).focusSection()220        }221        #else222        view223        #endif224    }225226    @ViewBuilder227    private var resizeHandle: some View {228        #if os(macOS)229        if let size {230            let step = theme.spacing.md231            Image(systemName: "arrow.up.left.and.arrow.down.right")232                .font(theme.font(.caption))233                .foregroundStyle(theme.color(.textSecondary))234                .padding(theme.spacing.xs)235                .glassMinimumHitTarget()236                .gesture(237                    DragGesture(minimumDistance: 1)238                        .onChanged { value in239                            let start = dragStart ?? limits.clamp(size.wrappedValue)240                            dragStart = start241                            size.wrappedValue = limits.resized(from: start, translation: value.translation, isRightToLeft: layoutDirection == .rightToLeft)242                        }243                        .onEnded { _ in dragStart = nil }244                )245                .focusable()246                .onMoveCommand { direction in247                    let delta: CGSize = switch direction {248                    case .left: CGSize(width: -step, height: 0)249                    case .right: CGSize(width: step, height: 0)250                    case .up: CGSize(width: 0, height: -step)251                    case .down: CGSize(width: 0, height: step)252                    @unknown default: .zero253                    }254                    size.wrappedValue = limits.resized(from: limits.clamp(size.wrappedValue), translation: delta)255                }256                .accessibilityElement()257                .accessibilityLabel(GlassL10n.string(.resizePanel))258                .accessibilityValue(GlassL10n.string(.panelSize, Int(limits.clamp(size.wrappedValue).width), Int(limits.clamp(size.wrappedValue).height)))259                .accessibilityAdjustableAction { direction in260                    let amount: CGFloat = direction == .increment ? step : -step261                    size.wrappedValue = limits.resized(from: limits.clamp(size.wrappedValue), translation: CGSize(width: amount, height: amount))262                }263        }264        #endif265    }266}267
Files main
Menu

Theme