Repository Public MIT
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 SwiftUI42import SPGlassCore43import SPGlassTokens44import SPGlassThemes45import SPGlassEffects4647/// Bounds of a resizable ``GlassPanel`` and the pure rules that keep a size inside them.48public struct GlassPanelSizeLimits: Equatable, Sendable {49 /// Smallest size the panel can take.50 public var minimum: CGSize51 /// Largest size the panel can take.52 public var maximum: CGSize5354 /// Creates limits. A maximum below the minimum is raised to the minimum; negative values count as zero.55 public init(minimum: CGSize = CGSize(width: 240, height: 160), maximum: CGSize = CGSize(width: 720, height: 640)) {56 let minWidth = Self.sanitize(minimum.width), minHeight = Self.sanitize(minimum.height)57 self.minimum = CGSize(width: minWidth, height: minHeight)58 self.maximum = CGSize(width: max(minWidth, Self.sanitize(maximum.width)), height: max(minHeight, Self.sanitize(maximum.height)))59 }6061 /// 240 × 160 to 720 × 640 points.62 public static let standard = GlassPanelSizeLimits()6364 /// The size nearest to `size` that respects the limits. Non-finite components fall back to the minimum.65 public func clamp(_ size: CGSize) -> CGSize {66 CGSize(67 width: Self.clamp(size.width, minimum.width, maximum.width),68 height: Self.clamp(size.height, minimum.height, maximum.height)69 )70 }7172 /// The size after dragging the trailing-bottom handle by `translation` from `start`.73 ///74 /// In a right-to-left layout the handle sits on the left, so a drag to the left widens the panel.75 public func resized(from start: CGSize, translation: CGSize, isRightToLeft: Bool = false) -> CGSize {76 let horizontal = isRightToLeft ? -translation.width : translation.width77 return clamp(CGSize(width: start.width + horizontal, height: start.height + translation.height))78 }7980 private static func sanitize(_ value: CGFloat) -> CGFloat {81 value.isFinite ? max(0, value) : 082 }8384 private static func clamp(_ value: CGFloat, _ lower: CGFloat, _ upper: CGFloat) -> CGFloat {85 guard value.isFinite else { return lower }86 return min(max(value, lower), upper)87 }88}8990/// A floating glass panel of actions or short content, with a title and an optional close button.91///92/// ```swift93/// GlassPanel("Layers", size: $panelSize, onClose: { showsLayers = false }) {94/// Toggle("Transit", isOn: $showsTransit)95/// Toggle("Traffic", isOn: $showsTraffic)96/// }97/// ```98///99/// The panel belongs to the navigation layer: it floats above content and holds controls, not long text.100/// On macOS, pass a `size` binding to let the user resize it with the handle in the trailing-bottom corner101/// (drag, arrow keys or VoiceOver adjust); keyboard focus moves inside the panel as one section and Escape102/// calls `onClose`. On iOS and iPadOS the panel sizes itself to its content and `size` is ignored.103public struct GlassPanel<Content: View>: View {104 @GlassThemed private var theme105 @Environment(\.layoutDirection) private var layoutDirection106 @Namespace private var focusNamespace107 @State private var dragStart: CGSize?108 private let title: Text109 private let size: Binding<CGSize>?110 private let limits: GlassPanelSizeLimits111 private let onClose: (@MainActor () -> Void)?112 private let content: Content113114 /// Creates a panel.115 ///116 /// - Parameters:117 /// - title: heading of the panel, also its accessibility label.118 /// - size: controlled size on macOS. `nil` sizes the panel to its content and hides the resize handle.119 /// - sizeLimits: bounds applied to `size`.120 /// - onClose: when set, a close button is shown and Escape calls it.121 public init(122 _ title: LocalizedStringKey,123 size: Binding<CGSize>? = nil,124 sizeLimits: GlassPanelSizeLimits = .standard,125 onClose: (@MainActor () -> Void)? = nil,126 @ViewBuilder content: () -> Content127 ) {128 self.init(title: Text(title), size: size, sizeLimits: sizeLimits, onClose: onClose, content: content)129 }130131 /// Creates a panel whose title is already a `Text`.132 public init(133 title: Text,134 size: Binding<CGSize>? = nil,135 sizeLimits: GlassPanelSizeLimits = .standard,136 onClose: (@MainActor () -> Void)? = nil,137 @ViewBuilder content: () -> Content138 ) {139 self.title = title140 self.size = size141 self.limits = sizeLimits142 self.onClose = onClose143 self.content = content()144 }145146 public var body: some View {147 platformBehaviour(148 sized(149 VStack(alignment: .leading, spacing: 0) {150 titleBar151 .padding(.leading, theme.spacing.md)152 .padding(.trailing, theme.spacing.xs)153 .padding(.vertical, theme.spacing.xxs)154 Rectangle()155 .fill(theme.color(.textPrimary).opacity(0.12))156 .frame(height: 1)157 .accessibilityHidden(true)158 VStack(alignment: .leading, spacing: theme.spacing.sm) {159 content160 .font(theme.font(.body))161 .foregroundStyle(theme.color(.textPrimary))162 }163 .padding(theme.spacing.md)164 }165 )166 // Neutral glass: the panel carries text and controls in the theme's colours.167 .glassSurface(.regular.tinted(.none), in: theme.shape(\.large))168 .overlay(alignment: .bottomTrailing) { resizeHandle }169 )170 .accessibilityElement(children: .contain)171 .accessibilityLabel(title)172 }173174 private var titleBar: some View {175 HStack(alignment: .center, spacing: theme.spacing.xs) {176 title177 .font(theme.font(.headline))178 .foregroundStyle(theme.color(.textPrimary))179 .lineLimit(2)180 .accessibilityAddTraits(.isHeader)181 Spacer(minLength: theme.spacing.xs)182 if let onClose {183 // A plain system button: the panel is already glass, and glass never sits inside glass.184 Button(action: onClose) {185 Label(GlassL10n.string(.close), systemImage: "xmark")186 .labelStyle(.iconOnly)187 .font(.system(.footnote, weight: .bold))188 .foregroundStyle(theme.color(.textSecondary))189 .frame(width: 28, height: 28)190 .background(theme.color(.textPrimary).opacity(0.1), in: Circle())191 }192 .buttonStyle(.plain)193 .glassMinimumHitTarget()194 #if !os(macOS)195 .keyboardShortcut(.cancelAction)196 #endif197 } else {198 Color.clear.frame(width: 1, height: 44).accessibilityHidden(true)199 }200 }201 }202203 @ViewBuilder204 private func sized(_ view: some View) -> some View {205 #if os(macOS)206 if let size {207 let clamped = limits.clamp(size.wrappedValue)208 view.frame(width: clamped.width, height: clamped.height, alignment: .topLeading)209 } else {210 view211 }212 #else213 view214 #endif215 }216217 @ViewBuilder218 private func platformBehaviour(_ view: some View) -> some View {219 #if os(macOS)220 if let onClose {221 view.focusScope(focusNamespace).focusSection().onExitCommand { onClose() }222 } else {223 view.focusScope(focusNamespace).focusSection()224 }225 #else226 view227 #endif228 }229230 @ViewBuilder231 private var resizeHandle: some View {232 #if os(macOS)233 if let size {234 let step = theme.spacing.md235 Image(systemName: "arrow.up.left.and.arrow.down.right")236 .font(theme.font(.caption))237 .foregroundStyle(theme.color(.textSecondary))238 .padding(theme.spacing.xs)239 .glassMinimumHitTarget()240 .gesture(241 DragGesture(minimumDistance: 1)242 .onChanged { value in243 let start = dragStart ?? limits.clamp(size.wrappedValue)244 dragStart = start245 size.wrappedValue = limits.resized(from: start, translation: value.translation, isRightToLeft: layoutDirection == .rightToLeft)246 }247 .onEnded { _ in dragStart = nil }248 )249 .focusable()250 .onMoveCommand { direction in251 let delta: CGSize = switch direction {252 case .left: CGSize(width: -step, height: 0)253 case .right: CGSize(width: step, height: 0)254 case .up: CGSize(width: 0, height: -step)255 case .down: CGSize(width: 0, height: step)256 @unknown default: .zero257 }258 size.wrappedValue = limits.resized(from: limits.clamp(size.wrappedValue), translation: delta)259 }260 .accessibilityElement()261 .accessibilityLabel(GlassL10n.string(.resizePanel))262 .accessibilityValue(GlassL10n.string(.panelSize, Int(limits.clamp(size.wrappedValue).width), Int(limits.clamp(size.wrappedValue).height)))263 .accessibilityAdjustableAction { direction in264 let amount: CGFloat = direction == .increment ? step : -step265 size.wrappedValue = limits.resized(from: limits.clamp(size.wrappedValue), translation: CGSize(width: amount, height: amount))266 }267 }268 #endif269 }270}271