SPB Git

Repository Public MIT

GlassGallery+Viewer.swift 9.1 KB 221 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassMedia/Media/GlassGallery+Viewer.swift8// Module           : SPGlassMedia9// 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 SPGlassEffects46import SPGlassComponents4748/// Zoom and navigation rules of the gallery viewer.49public enum GlassGalleryZoom {50    public static let minimumScale: CGFloat = 151    public static let maximumScale: CGFloat = 452    /// Scale reached by a double tap from the unzoomed state.53    public static let doubleTapScale: CGFloat = 2.554    /// Factor applied by one step of the accessibility zoom action.55    public static let stepFactor: CGFloat = 1.55657    /// Clamps a scale to 1…4; NaN becomes 1.58    public static func clampedScale(_ scale: CGFloat) -> CGFloat {59        scale.isNaN ? minimumScale : min(max(scale, minimumScale), maximumScale)60    }6162    /// The scale after a double tap: zoom in when unzoomed, back to 1 otherwise.63    public static func toggledScale(_ scale: CGFloat) -> CGFloat {64        clampedScale(scale) > minimumScale ? minimumScale : doubleTapScale65    }6667    /// Keeps a pan offset inside the zoomed image: at scale 1 there is no offset.68    public static func clampedOffset(_ offset: CGSize, scale: CGFloat, container: CGSize) -> CGSize {69        let factor = clampedScale(scale) - 170        let limitX = max(container.width, 0) * factor / 271        let limitY = max(container.height, 0) * factor / 272        func clamp(_ value: CGFloat, _ limit: CGFloat) -> CGFloat {73            value.isNaN ? 0 : min(max(value, -limit), limit)74        }75        return CGSize(width: clamp(offset.width, limitX), height: clamp(offset.height, limitY))76    }7778    /// The index after moving by `delta`, kept inside `0..<count`. The viewer does not wrap around.79    public static func index(_ index: Int, movedBy delta: Int, count: Int) -> Int {80        guard count > 0 else { return 0 }81        return min(max(index + delta, 0), count - 1)82    }83}8485/// The full-size viewer of a ``GlassGallery``.86struct GlassGalleryViewer: View {87    @GlassThemed private var theme88    @GlassAccessibility private var accessibility89    let items: [GlassGalleryItem]90    let cache: GlassGalleryCache91    @Binding var index: Int92    let onClose: @MainActor () -> Void9394    @State private var scale: CGFloat = 195    @State private var gestureStartScale: CGFloat?96    @State private var offset: CGSize = .zero97    @State private var gestureStartOffset: CGSize?9899    private var safeIndex: Int { GlassGalleryZoom.index(index, movedBy: 0, count: items.count) }100101    var body: some View {102        ZStack {103            theme.color(.background).ignoresSafeArea()104            if items.indices.contains(safeIndex) {105                zoomableImage(items[safeIndex])106            }107        }108        .safeAreaInset(edge: .top) { topBar }109        .safeAreaInset(edge: .bottom) { navigationBar }110        .onChange(of: index) { resetZoom(animated: false) }111    }112113    private func zoomableImage(_ item: GlassGalleryItem) -> some View {114        GeometryReader { proxy in115            GlassGalleryImage(item: item, cache: cache, contentMode: .fit)116                .id(item.id)117                .scaleEffect(scale)118                .offset(offset)119                .frame(width: proxy.size.width, height: proxy.size.height)120                .contentShape(Rectangle())121                .gesture(magnification(in: proxy.size))122                .simultaneousGesture(pan(in: proxy.size), isEnabled: scale > GlassGalleryZoom.minimumScale)123                .onTapGesture(count: 2) {124                    setScale(GlassGalleryZoom.toggledScale(scale), in: proxy.size, animated: true)125                }126                .accessibilityElement()127                .accessibilityLabel(Text(GlassGalleryLoading.accessibilityLabel(index: safeIndex, count: items.count, description: item.description)))128                .accessibilityAddTraits(.isImage)129                .accessibilityZoomAction { action in130                    let factor = action.direction == .zoomIn ? GlassGalleryZoom.stepFactor : 1 / GlassGalleryZoom.stepFactor131                    setScale(scale * factor, in: proxy.size, animated: false)132                }133        }134        .clipped()135    }136137    private var topBar: some View {138        HStack(alignment: .top, spacing: theme.spacing.sm) {139            VStack(alignment: .leading, spacing: theme.spacing.xxs) {140                Text(GlassL10n.string(.imageOfCount, safeIndex + 1, items.count))141                    .font(theme.font(.headline))142                    .foregroundStyle(theme.color(.textPrimary))143                if items.indices.contains(safeIndex), !items[safeIndex].description.isEmpty {144                    Text(verbatim: items[safeIndex].description)145                        .font(theme.font(.callout))146                        .foregroundStyle(theme.color(.textSecondary))147                }148            }149            .accessibilityHidden(true)150            Spacer(minLength: theme.spacing.xs)151            GlassIconButton(systemImage: "xmark", label: Text(GlassL10n.string(.close)), action: onClose)152                .keyboardShortcut(.cancelAction)153        }154        .padding(theme.spacing.md)155    }156157    private var navigationBar: some View {158        GlassGroup(spacing: theme.spacing.sm) {159            HStack(spacing: theme.spacing.sm) {160                GlassIconButton(systemImage: "chevron.backward", label: Text(GlassL10n.string(.previous))) {161                    index = GlassGalleryZoom.index(safeIndex, movedBy: -1, count: items.count)162                }163                .keyboardShortcut(.leftArrow, modifiers: [])164                .disabled(safeIndex <= 0)165                GlassIconButton(systemImage: "chevron.forward", label: Text(GlassL10n.string(.next))) {166                    index = GlassGalleryZoom.index(safeIndex, movedBy: 1, count: items.count)167                }168                .keyboardShortcut(.rightArrow, modifiers: [])169                .disabled(safeIndex >= items.count - 1)170            }171        }172        .padding(theme.spacing.md)173    }174175    private func magnification(in size: CGSize) -> some Gesture {176        MagnifyGesture()177            .onChanged { value in178                let start = gestureStartScale ?? scale179                gestureStartScale = start180                scale = GlassGalleryZoom.clampedScale(start * value.magnification)181                offset = GlassGalleryZoom.clampedOffset(offset, scale: scale, container: size)182            }183            .onEnded { _ in184                gestureStartScale = nil185            }186    }187188    private func pan(in size: CGSize) -> some Gesture {189        DragGesture()190            .onChanged { value in191                let start = gestureStartOffset ?? offset192                gestureStartOffset = start193                let proposed = CGSize(width: start.width + value.translation.width, height: start.height + value.translation.height)194                offset = GlassGalleryZoom.clampedOffset(proposed, scale: scale, container: size)195            }196            .onEnded { _ in197                gestureStartOffset = nil198            }199    }200201    private func setScale(_ newScale: CGFloat, in size: CGSize, animated: Bool) {202        let target = GlassGalleryZoom.clampedScale(newScale)203        let change = {204            scale = target205            offset = GlassGalleryZoom.clampedOffset(offset, scale: target, container: size)206        }207        if animated {208            withAnimation(theme.animation(.standard, reduceMotion: accessibility.reduceMotion), change)209        } else {210            change()211        }212    }213214    private func resetZoom(animated: Bool) {215        scale = GlassGalleryZoom.minimumScale216        offset = .zero217        gestureStartScale = nil218        gestureStartOffset = nil219    }220}221
Files main
Menu

Theme