SPB Git

Repository Public MIT

GlassGallery.swift 14.3 KB 342 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassMedia/Media/GlassGallery.swift8// Module           : SPGlassMedia9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0313//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 CoreGraphics43import SPGlassCore44import SPGlassTokens45import SPGlassThemes46import SPGlassEffects4748/// One image of a ``GlassGallery``: an identifier, a description and a way to obtain the image.49public struct GlassGalleryItem: Identifiable, Sendable {50    public let id: String51    /// What the image shows. Read by VoiceOver after "Image n of m" and shown as the caption in the viewer.52    public let description: String53    let localImage: Image?54    let loader: (@Sendable () async throws -> Image)?5556    /// An image that is already in memory or in the asset catalogue of the host.57    public init(id: String, description: String, image: Image) {58        self.id = id59        self.description = description60        localImage = image61        loader = nil62    }6364    /// An image produced asynchronously. The closure runs when the cell appears and is cancelled when it65    /// disappears; it should honour cancellation (`try Task.checkCancellation()`, cancellable I/O).66    public init(id: String, description: String, load: @escaping @Sendable () async throws -> Image) {67        self.id = id68        self.description = description69        localImage = nil70        loader = load71    }7273    /// An image decoded asynchronously as a `CGImage`.74    public init(id: String, description: String, loadCGImage: @escaping @Sendable () async throws -> CGImage) {75        self.init(id: id, description: description) {76            Image(decorative: try await loadCGImage(), scale: 1)77        }78    }79}8081/// Loading rule of gallery images, separated from the views so that it can be tested.82public enum GlassGalleryLoading {83    /// Resolves the image of `item`: the local image, else the cached one, else the loader's result (then cached).84    ///85    /// A cancelled load returns `.idle` and caches nothing; any other error returns `.failed`.86    public static func load(_ item: GlassGalleryItem, cache: GlassGalleryCache) async -> GlassLoadState<Image> {87        if let image = item.localImage { return .loaded(image) }88        guard let loader = item.loader else { return .empty }89        if let cached = await cache.value(for: item.id) { return .loaded(cached) }90        do {91            let image = try await loader()92            try Task.checkCancellation()93            await cache.insert(image, for: item.id)94            return .loaded(image)95        } catch is CancellationError {96            return .idle97        } catch {98            return .failed(message: GlassL10n.string(.mediaUnavailable))99        }100    }101102    /// The accessibility label of an image: "Image n of m" followed by the caller's description.103    public static func accessibilityLabel(index: Int, count: Int, description: String) -> String {104        let position = GlassL10n.string(.imageOfCount, index + 1, count)105        let trimmed = description.trimmingCharacters(in: .whitespacesAndNewlines)106        return trimmed.isEmpty ? position : "\(position), \(trimmed)"107    }108}109110/// How a ``GlassGallery`` arranges its tiles.111public enum GlassGalleryLayout: String, CaseIterable, Sendable {112    /// Square tiles in as many columns as the width allows.113    case grid114    /// A large first tile beside two small ones, then rows of three. Needs at least three images; with fewer115    /// the gallery falls back to ``grid``.116    case featured117118    /// Number of images the featured header takes.119    public static let featuredCount = 3120121    /// The layout actually used for `count` images.122    public func resolved(itemCount count: Int) -> GlassGalleryLayout {123        self == .featured && count >= Self.featuredCount ? .featured : .grid124    }125}126127/// A lazy grid of images with a zoomable viewer.128///129/// ```swift130/// GlassGallery(items: photos.map { photo in131///     GlassGalleryItem(id: photo.id, description: photo.caption) {132///         try await photo.loadThumbnail()133///     }134/// }, layout: .featured, selection: currentPhotoID)135/// ```136///137/// Cells are created lazily; each one loads its image in a task that is cancelled when the cell leaves the138/// screen. Loaded images go to a bounded in-memory cache (least recently used first out). Tapping a cell139/// opens a viewer with previous and next navigation, pinch and double-tap zoom. The tile whose identifier is140/// `selection` is outlined and carries the selected trait.141public struct GlassGallery: View {142    @GlassThemed private var theme143    private let items: [GlassGalleryItem]144    private let injectedCache: GlassGalleryCache?145    private let minimumCellWidth: CGFloat146    private let layout: GlassGalleryLayout147    private let selection: GlassGalleryItem.ID?148    @State private var ownedCache: GlassGalleryCache149    @State private var viewerIndex = 0150    @State private var isViewerPresented = false151152    /// - Parameters:153    ///   - items: the images, in display order. Identifiers must be unique.154    ///   - cache: a cache shared with other views; by default the gallery owns one.155    ///   - cacheCapacity: capacity of the owned cache.156    ///   - minimumCellWidth: smallest width of a cell; the grid fits as many columns as the width allows.157    ///   - layout: ``GlassGalleryLayout/grid`` (default) or ``GlassGalleryLayout/featured``.158    ///   - selection: identifier of the image to outline, for example the one shown elsewhere on screen.159    public init(160        items: [GlassGalleryItem],161        cache: GlassGalleryCache? = nil,162        cacheCapacity: Int = 64,163        minimumCellWidth: CGFloat = 104,164        layout: GlassGalleryLayout = .grid,165        selection: GlassGalleryItem.ID? = nil166    ) {167        self.items = items168        injectedCache = cache169        self.minimumCellWidth = max(minimumCellWidth, 44)170        self.layout = layout171        self.selection = selection172        _ownedCache = State(initialValue: GlassGalleryCache(capacity: cacheCapacity))173    }174175    private var cache: GlassGalleryCache { injectedCache ?? ownedCache }176177    private static var gap: CGFloat { 6 }178179    public var body: some View {180        Group {181            if items.isEmpty {182                ContentUnavailableView(GlassL10n.string(.noData), systemImage: "photo.on.rectangle")183            } else {184                grid185            }186        }187        #if os(iOS)188        .fullScreenCover(isPresented: $isViewerPresented) { viewer }189        #else190        .sheet(isPresented: $isViewerPresented) {191            viewer.frame(minWidth: 520, minHeight: 400)192        }193        #endif194    }195196    private var grid: some View {197        let indexed = Array(items.enumerated())198        return ScrollView {199            switch layout.resolved(itemCount: items.count) {200            case .featured:201                VStack(spacing: Self.gap) {202                    GlassGalleryFeaturedLayout(spacing: Self.gap) {203                        ForEach(indexed.prefix(GlassGalleryLayout.featuredCount), id: \.element.id) { index, item in204                            tile(index: index, item: item, isSquare: false)205                        }206                    }207                    LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: Self.gap), count: 3), spacing: Self.gap) {208                        ForEach(indexed.dropFirst(GlassGalleryLayout.featuredCount), id: \.element.id) { index, item in209                            tile(index: index, item: item, isSquare: true)210                        }211                    }212                }213                .padding(Self.gap)214            case .grid:215                LazyVGrid(columns: [GridItem(.adaptive(minimum: minimumCellWidth), spacing: Self.gap)], spacing: Self.gap) {216                    ForEach(indexed, id: \.element.id) { index, item in217                        tile(index: index, item: item, isSquare: true)218                    }219                }220                .padding(Self.gap)221            }222        }223    }224225    private func tile(index: Int, item: GlassGalleryItem, isSquare: Bool) -> some View {226        let shape = theme.shape(\.small)227        let isSelected = item.id == selection228        return Button {229            viewerIndex = index230            isViewerPresented = true231        } label: {232            Color.clear233                .aspectRatio(isSquare ? 1 : nil, contentMode: .fit)234                .overlay {235                    GlassGalleryImage(item: item, cache: cache, contentMode: .fill)236                }237                .clipShape(shape)238                .overlay(shape.strokeBorder(theme.color(.separator).opacity(0.7), lineWidth: 0.5))239                .overlay {240                    if isSelected {241                        // Two rings: the background colour detaches the primary ring from any image.242                        shape.strokeBorder(theme.color(.background), lineWidth: 5)243                        shape.strokeBorder(theme.color(.primary), lineWidth: 3)244                    }245                }246                .overlay(alignment: .bottomTrailing) {247                    if isSelected {248                        Image(systemName: "checkmark.circle.fill")249                            .font(.system(size: 20, weight: .semibold))250                            .symbolRenderingMode(.palette)251                            .foregroundStyle(theme.onColor(.primary), theme.color(.primary))252                            .padding(8)253                            .accessibilityHidden(true)254                    }255                }256                .contentShape(shape)257        }258        .buttonStyle(.plain)259        .accessibilityLabel(Text(GlassGalleryLoading.accessibilityLabel(index: index, count: items.count, description: item.description)))260        .accessibilityAddTraits(isSelected ? [.isImage, .isSelected] : .isImage)261    }262263    private var viewer: some View {264        GlassGalleryViewer(items: items, cache: cache, index: $viewerIndex) {265            isViewerPresented = false266        }267    }268}269270/// The header of the featured layout: the first subview takes two columns and two rows, the next two are271/// stacked beside it. All three are square.272struct GlassGalleryFeaturedLayout: Layout {273    let spacing: CGFloat274275    /// Side of a small tile for a container `width`: a third of the width, less the gaps.276    static func smallSide(width: CGFloat, spacing: CGFloat) -> CGFloat {277        max((width - 2 * spacing) / 3, 0)278    }279280    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {281        let width = proposal.width ?? 320282        guard width.isFinite else { return CGSize(width: 320, height: 2 * Self.smallSide(width: 320, spacing: spacing) + spacing) }283        return CGSize(width: width, height: 2 * Self.smallSide(width: width, spacing: spacing) + spacing)284    }285286    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {287        let small = Self.smallSide(width: bounds.width, spacing: spacing)288        let large = 2 * small + spacing289        for (index, subview) in subviews.enumerated() {290            switch index {291            case 0:292                subview.place(at: bounds.origin, anchor: .topLeading, proposal: ProposedViewSize(width: large, height: large))293            case 1, 2:294                let origin = CGPoint(x: bounds.minX + large + spacing, y: bounds.minY + CGFloat(index - 1) * (small + spacing))295                subview.place(at: origin, anchor: .topLeading, proposal: ProposedViewSize(width: small, height: small))296            default:297                subview.place(at: bounds.origin, anchor: .topLeading, proposal: .zero)298            }299        }300    }301}302303/// One image of the gallery: placeholder while loading, the image, or a failure message.304struct GlassGalleryImage: View {305    @GlassThemed private var theme306    let item: GlassGalleryItem307    let cache: GlassGalleryCache308    let contentMode: ContentMode309    @State private var phase: GlassLoadState<Image> = .idle310311    var body: some View {312        ZStack {313            theme.color(.surface)314            switch phase {315            case .loaded(let image):316                image317                    .resizable()318                    .aspectRatio(contentMode: contentMode)319            case .failed, .empty:320                VStack(spacing: theme.spacing.xxs) {321                    Image(systemName: "exclamationmark.triangle")322                        .font(.system(size: 18, weight: .medium))323                    Text(GlassL10n.string(.mediaUnavailable))324                        .font(theme.font(.caption))325                        .multilineTextAlignment(.center)326                        .minimumScaleFactor(0.8)327                }328                .foregroundStyle(theme.color(.textSecondary))329                .padding(theme.spacing.xxs)330            case .idle, .loading:331                ProgressView()332                    .accessibilityLabel(Text(GlassL10n.string(.loading)))333            }334        }335        .task(id: item.id) {336            if phase.value == nil { phase = .loading }337            let result = await GlassGalleryLoading.load(item, cache: cache)338            if !Task.isCancelled { phase = result }339        }340    }341}342
Files main
Menu

Theme