SPB Git

Repository Public MIT

GlassTabRouter.swift 7.7 KB 187 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassNavigation/Navigation/GlassTabRouter.swift8// Module           : SPGlassNavigation9// 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 Foundation4243/// A badge shown on a tab.44public enum GlassTabBadge: Hashable, Sendable {45    /// A number, formatted for the current locale. Zero or less shows no badge.46    case count(Int)47    /// A short text.48    case text(String)49}5051/// One tab of a ``GlassTabBar``, described by values so that the list can come from data.52public struct GlassTabItem<ID: Hashable & Sendable>: Identifiable, Hashable, Sendable {53    public let id: ID54    /// Title shown with the symbol and read by VoiceOver. Already localised by the host.55    public var title: String56    /// SF Symbol of the tab.57    public var systemImage: String58    public var badge: GlassTabBadge?59    /// Marks the tab as the search tab, which the system places apart from the others.60    public var isSearch: Bool6162    public init(id: ID, title: String, systemImage: String, badge: GlassTabBadge? = nil, isSearch: Bool = false) {63        self.id = id64        self.title = title65        self.systemImage = systemImage66        self.badge = badge67        self.isSearch = isSearch68    }69}7071/// A tab and the navigation path to show inside it.72public struct GlassTabDestination<ID: Hashable & Sendable, Route: Hashable & Sendable>: Hashable, Sendable {73    public var tab: ID74    public var path: [Route]7576    public init(tab: ID, path: [Route] = []) {77        self.tab = tab78        self.path = path79    }80}8182/// The selection of a ``GlassTabBar`` and the navigation path of each of its tabs.83///84/// The host owns one value of this type (`@State`). Because every tab has its own path, switching tabs never85/// loses the place the user had reached in another tab.86public struct GlassTabNavigationState<ID: Hashable & Sendable, Route: Hashable & Sendable>: Equatable, Sendable {87    /// The selected tab.88    public var selection: ID89    private var paths: [ID: [Route]]9091    public init(selection: ID, paths: [ID: [Route]] = [:]) {92        self.selection = selection93        self.paths = paths.filter { !$0.value.isEmpty }94    }9596    /// The navigation path of a tab; empty when the tab shows its root.97    public func path(for tab: ID) -> [Route] {98        paths[tab] ?? []99    }100101    public mutating func setPath(_ path: [Route], for tab: ID) {102        paths[tab] = path.isEmpty ? nil : path103    }104105    /// Pushes a route on the path of a tab (the selected one by default).106    public mutating func push(_ route: Route, in tab: ID? = nil) {107        paths[tab ?? selection, default: []].append(route)108    }109110    /// Returns a tab (the selected one by default) to its root.111    public mutating func popToRoot(_ tab: ID? = nil) {112        paths[tab ?? selection] = nil113    }114115    /// Selects the tab of a destination and replaces its path. Other tabs keep theirs.116    public mutating func open(_ destination: GlassTabDestination<ID, Route>) {117        selection = destination.tab118        setPath(destination.path, for: destination.tab)119    }120121    /// Drops the paths of tabs that no longer exist and, if the selected tab disappeared, selects `fallback`.122    public mutating func reconcile(with tabs: [ID], fallback: ID) {123        let known = Set(tabs)124        paths = paths.filter { known.contains($0.key) }125        if !known.contains(selection) { selection = fallback }126    }127}128129/// Maps deep links to a tab and a navigation path. Pure: it parses, the host applies the result.130///131/// ```swift132/// let router = GlassTabRouter<AppTab, AppRoute>(tabs: ["library": .library, "settings": .settings]) { tab, components, _ in133///     switch (tab, components.first) {134///     case (.library, let id?): [.album(id)]135///     case (_, nil): []136///     default: nil137///     }138/// }139/// if let destination = router.destination(for: url) { state.open(destination) }140/// ```141///142/// With a custom scheme the tab is the host of the URL (`myapp://library/42`); with `http` and `https` it is143/// the first path component (`https://example.com/library/42`).144public struct GlassTabRouter<ID: Hashable & Sendable, Route: Hashable & Sendable>: Sendable {145    /// Builds the path of a tab from the remaining path components and the query items. `nil` rejects the link.146    public typealias PathBuilder = @Sendable (_ tab: ID, _ components: [String], _ query: [URLQueryItem]) -> [Route]?147148    private let schemes: Set<String>149    private let tabs: [String: ID]150    private let path: PathBuilder151152    /// - Parameters:153    ///   - schemes: accepted URL schemes, compared without case. Empty accepts every scheme.154    ///   - tabs: tab of each first component, compared without case.155    ///   - path: builds the path inside the tab. The default accepts only links without further components.156    public init(157        schemes: Set<String> = [],158        tabs: [String: ID],159        path: @escaping PathBuilder = { _, components, _ in components.isEmpty ? [] : nil }160    ) {161        self.schemes = Set(schemes.map { $0.lowercased() })162        self.tabs = Dictionary(tabs.map { ($0.key.lowercased(), $0.value) }, uniquingKeysWith: { first, _ in first })163        self.path = path164    }165166    /// The destination of a URL, or `nil` when the scheme, the tab or the path is not recognised.167    public func destination(for url: URL) -> GlassTabDestination<ID, Route>? {168        guard let parts = URLComponents(url: url, resolvingAgainstBaseURL: false),169              let scheme = parts.scheme?.lowercased() else { return nil }170        if !schemes.isEmpty, !schemes.contains(scheme) { return nil }171172        var components = parts.path.split(separator: "/").map { String($0) }173        if scheme != "http", scheme != "https", let host = parts.host, !host.isEmpty {174            components.insert(host, at: 0)175        }176        guard let first = components.first, let tab = tabs[first.lowercased()] else { return nil }177        guard let route = path(tab, Array(components.dropFirst()), parts.queryItems ?? []) else { return nil }178        return GlassTabDestination(tab: tab, path: route)179    }180181    /// The destination of a typed value, for links that do not come from a URL (notifications, shortcuts).182    /// Returns `nil` when the tab is not one of the router's tabs.183    public func destination(tab: ID, path: [Route] = []) -> GlassTabDestination<ID, Route>? {184        tabs.values.contains(tab) ? GlassTabDestination(tab: tab, path: path) : nil185    }186}187
Files main
Menu

Theme