SPB Git

Repository Public MIT

GlassBreadcrumb.swift 8.5 KB 219 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassNavigation/Navigation/GlassBreadcrumb.swift8// Module           : SPGlassNavigation9// 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 SPGlassCore43import SPGlassTokens44import SPGlassThemes45import SPGlassEffects4647/// One level of a ``GlassBreadcrumb``.48public struct GlassBreadcrumbItem<ID: Hashable & Sendable>: Identifiable, Hashable, Sendable {49    public let id: ID50    /// Name of the level, already localised by the host (or data, such as a folder name).51    public var title: String52    public var systemImage: String?5354    public init(id: ID, title: String, systemImage: String? = nil) {55        self.id = id56        self.title = title57        self.systemImage = systemImage58    }59}6061/// Which levels of a path are shown and which go to the overflow menu. Pure.62public struct GlassBreadcrumbLayout: Equatable, Sendable {63    /// Indices shown before the overflow menu: the root, or nothing.64    public let leading: Range<Int>65    /// Indices held by the overflow menu.66    public let hidden: Range<Int>67    /// Indices shown after the overflow menu, ending with the current location.68    public let trailing: Range<Int>6970    /// Indices of every visible level, in order.71    public var visible: [Int] { Array(leading) + Array(trailing) }7273    /// Lays out `count` levels with at most `maxVisible` of them visible.74    ///75    /// When the path fits, every level is visible. Otherwise the root stays, the levels closest to the current76    /// location stay, and the middle goes to the menu. With a single visible level only the current location77    /// stays. `maxVisible` below one is treated as one.78    public init(count: Int, maxVisible: Int) {79        let count = max(count, 0)80        let limit = max(maxVisible, 1)81        if count <= limit {82            leading = 0..<count83            hidden = count..<count84            trailing = count..<count85        } else {86            let head = limit >= 2 ? 1 : 087            let tail = limit - head88            leading = 0..<head89            hidden = head..<(count - tail)90            trailing = (count - tail)..<count91        }92    }93}9495/// A path of levels on a glass bar; each level is a button and the last one is the current location.96///97/// ```swift98/// GlassBreadcrumb(path, maxVisibleItems: 3) { id in99///     navigate(to: id)100/// }101/// ```102///103/// Levels that do not fit go to a menu between the root and the last levels. When the bar is narrower than104/// its content it shows fewer levels before it ever truncates a title.105public struct GlassBreadcrumb<ID: Hashable & Sendable>: View {106    @GlassThemed private var theme107    private let items: [GlassBreadcrumbItem<ID>]108    private let maxVisibleItems: Int109    private let onSelect: @MainActor (ID) -> Void110111    /// - Parameters:112    ///   - items: the path, from the root to the current location.113    ///   - maxVisibleItems: largest number of levels shown at once; the others go to the overflow menu.114    ///   - onSelect: called with the identifier of the activated level.115    public init(_ items: [GlassBreadcrumbItem<ID>], maxVisibleItems: Int = 4, onSelect: @escaping @MainActor (ID) -> Void) {116        self.items = items117        self.maxVisibleItems = maxVisibleItems118        self.onSelect = onSelect119    }120121    public var body: some View {122        if !items.isEmpty {123            ViewThatFits(in: .horizontal) {124                ForEach(Self.candidates(count: items.count, maxVisible: maxVisibleItems), id: \.self) { limit in125                    row(GlassBreadcrumbLayout(count: items.count, maxVisible: limit), allowsTruncation: limit == 1)126                }127            }128            .padding(.horizontal, theme.spacing.sm)129            .padding(.vertical, theme.spacing.xxs)130            // Never tinted: the bar carries text in the theme's text colours, which a tinted glass (Aurora,131            // Neon…) would make illegible.132            .glassSurface(.regular.tinted(.none), in: Capsule())133            .accessibilityElement(children: .contain)134            .accessibilityLabel(Text(GlassL10n.string(.breadcrumb)))135        }136    }137138    /// The limits tried in turn, from the requested one down to a single level.139    static func candidates(count: Int, maxVisible: Int) -> [Int] {140        let first = min(max(maxVisible, 1), max(count, 1))141        return Array((1...first).reversed())142    }143144    private func row(_ layout: GlassBreadcrumbLayout, allowsTruncation: Bool) -> some View {145        HStack(spacing: theme.spacing.xxs) {146            ForEach(layout.leading, id: \.self) { index in147                crumb(index, allowsTruncation: allowsTruncation)148                // When the whole path fits, the leading run ends with the current level: no chevron after it.149                if index != items.count - 1 { separator }150            }151            if !layout.hidden.isEmpty {152                overflowMenu(layout.hidden)153                separator154            }155            ForEach(layout.trailing, id: \.self) { index in156                crumb(index, allowsTruncation: allowsTruncation)157                if index != items.count - 1 { separator }158            }159        }160    }161162    private var separator: some View {163        Image(systemName: "chevron.forward")164            .font(theme.font(.caption))165            .foregroundStyle(theme.color(.textSecondary))166            .accessibilityHidden(true)167    }168169    @ViewBuilder170    private func crumb(_ index: Int, allowsTruncation: Bool) -> some View {171        let item = items[index]172        let isCurrent = index == items.count - 1173        Button {174            onSelect(item.id)175        } label: {176            label(item)177                .font(theme.font(isCurrent ? .headline : .callout))178                .foregroundStyle(theme.color(isCurrent ? .textPrimary : .textSecondary))179                .lineLimit(1)180                .truncationMode(.middle)181                .fixedSize(horizontal: !allowsTruncation, vertical: false)182                .glassMinimumHitTarget()183        }184        .buttonStyle(.plain)185        .accessibilityValue(isCurrent ? Text(GlassL10n.string(.currentLocation)) : Text(verbatim: ""))186        .accessibilityAddTraits(isCurrent ? .isSelected : [])187    }188189    @ViewBuilder190    private func label(_ item: GlassBreadcrumbItem<ID>) -> some View {191        if let systemImage = item.systemImage {192            Label { Text(verbatim: item.title) } icon: { Image(systemName: systemImage) }193        } else {194            Text(verbatim: item.title)195        }196    }197198    private func overflowMenu(_ hidden: Range<Int>) -> some View {199        Menu {200            ForEach(hidden, id: \.self) { index in201                Button {202                    onSelect(items[index].id)203                } label: {204                    label(items[index])205                }206            }207        } label: {208            Label(GlassL10n.string(.hiddenLevels, hidden.count), systemImage: "ellipsis")209                .labelStyle(.iconOnly)210                .foregroundStyle(theme.color(.textSecondary))211                .glassMinimumHitTarget()212        }213        .menuStyle(.button)214        .buttonStyle(.plain)215        .menuIndicator(.hidden)216        .fixedSize()217    }218}219
Files main
Menu

Theme