SPB Git

Repository Public MIT

GlassPanel.swift 10.1 KB 250 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: theme.spacing.sm) {146                    titleBar147                    content148                        .font(theme.font(.body))149                        .foregroundStyle(theme.color(.textPrimary))150                }151                .padding(theme.spacing.md)152            )153            .glassSurface(.regular, in: theme.shape(\.large))154            .overlay(alignment: .bottomTrailing) { resizeHandle }155        )156        .accessibilityElement(children: .contain)157        .accessibilityLabel(title)158    }159160    private var titleBar: some View {161        HStack(alignment: .firstTextBaseline, spacing: theme.spacing.xs) {162            title163                .font(theme.font(.headline))164                .foregroundStyle(theme.color(.textPrimary))165                .accessibilityAddTraits(.isHeader)166            Spacer(minLength: theme.spacing.xs)167            if let onClose {168                // A plain system button: the panel is already glass, and glass never sits inside glass.169                Button(action: onClose) {170                    Label(GlassL10n.string(.close), systemImage: "xmark")171                        .labelStyle(.iconOnly)172                }173                .buttonStyle(.borderless)174                .glassMinimumHitTarget()175                #if !os(macOS)176                .keyboardShortcut(.cancelAction)177                #endif178            }179        }180    }181182    @ViewBuilder183    private func sized(_ view: some View) -> some View {184        #if os(macOS)185        if let size {186            let clamped = limits.clamp(size.wrappedValue)187            view.frame(width: clamped.width, height: clamped.height, alignment: .topLeading)188        } else {189            view190        }191        #else192        view193        #endif194    }195196    @ViewBuilder197    private func platformBehaviour(_ view: some View) -> some View {198        #if os(macOS)199        if let onClose {200            view.focusScope(focusNamespace).focusSection().onExitCommand { onClose() }201        } else {202            view.focusScope(focusNamespace).focusSection()203        }204        #else205        view206        #endif207    }208209    @ViewBuilder210    private var resizeHandle: some View {211        #if os(macOS)212        if let size {213            let step = theme.spacing.md214            Image(systemName: "arrow.up.left.and.arrow.down.right")215                .font(theme.font(.caption))216                .foregroundStyle(theme.color(.textSecondary))217                .padding(theme.spacing.xs)218                .glassMinimumHitTarget()219                .gesture(220                    DragGesture(minimumDistance: 1)221                        .onChanged { value in222                            let start = dragStart ?? limits.clamp(size.wrappedValue)223                            dragStart = start224                            size.wrappedValue = limits.resized(from: start, translation: value.translation, isRightToLeft: layoutDirection == .rightToLeft)225                        }226                        .onEnded { _ in dragStart = nil }227                )228                .focusable()229                .onMoveCommand { direction in230                    let delta: CGSize = switch direction {231                    case .left: CGSize(width: -step, height: 0)232                    case .right: CGSize(width: step, height: 0)233                    case .up: CGSize(width: 0, height: -step)234                    case .down: CGSize(width: 0, height: step)235                    @unknown default: .zero236                    }237                    size.wrappedValue = limits.resized(from: limits.clamp(size.wrappedValue), translation: delta)238                }239                .accessibilityElement()240                .accessibilityLabel(GlassL10n.string(.resizePanel))241                .accessibilityValue(GlassL10n.string(.panelSize, Int(limits.clamp(size.wrappedValue).width), Int(limits.clamp(size.wrappedValue).height)))242                .accessibilityAdjustableAction { direction in243                    let amount: CGFloat = direction == .increment ? step : -step244                    size.wrappedValue = limits.resized(from: limits.clamp(size.wrappedValue), translation: CGSize(width: amount, height: amount))245                }246        }247        #endif248    }249}250
Files main
Menu

Theme