SPB Git

Repository Public MIT

NavigationDescriptors.swift 21.6 KB 419 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Apps/GlassStudio/Kit/Descriptors/NavigationDescriptors.swift8// Module           : GlassStudio9// 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 SPGlassKit4344extension ComponentCatalog {45    static var navigationDescriptors: [ComponentDescriptor] {46        [glassTabBar, glassNavigationBar, glassToolbar, glassSidebar, glassBreadcrumb]47    }4849    // MARK: Sample data (fictitious)5051    /// A sample toolbar action, used by the preview and by the snippet so that both show the same thing.52    private struct SampleAction {53        let id: String, title: String, symbol: String54        var priority: GlassToolbarActionPriority = .normal55        var isDestructive = false5657        @MainActor var action: GlassToolbarAction {58            GlassToolbarAction(id: id, verbatim: title, systemImage: symbol, role: isDestructive ? .destructive : nil, priority: priority) {}59        }6061        var code: String {62            var arguments = ["id: \(SwiftLiteral.string(id))", "title: \(SwiftLiteral.string(title))", "systemImage: \(SwiftLiteral.string(symbol))"]63            if isDestructive { arguments.append("role: .destructive") }64            switch priority {65            case .low: arguments.append("priority: .low")66            case .high: arguments.append("priority: .high")67            case .normal: break68            }69            return "GlassToolbarAction(\(arguments.joined(separator: ", "))) { }"70        }71    }7273    /// One element per line, each followed by a comma, indented.74    private static func list(_ lines: [String], levels: Int) -> String {75        SwiftLiteral.indent(lines.map { $0 + "," }.joined(separator: "\n"), levels: levels)76    }7778    // MARK: GlassTabBar7980    private static let sampleTabs = [("today", "Today", "sun.max"), ("inbox", "Inbox", "tray"), ("library", "Library", "square.stack"), ("profile", "Profile", "person")]8182    private static func tabItems(_ values: InspectorValues) -> [GlassTabItem<String>] {83        var items = sampleTabs.prefix(Int(values.number("tabs"))).map { id, title, symbol in84            GlassTabItem(id: id, title: title, systemImage: symbol, badge: id == "inbox" && values.number("badge") > 0 ? .count(Int(values.number("badge"))) : nil)85        }86        if values.bool("search") { items.append(GlassTabItem(id: "search", title: "Search", systemImage: "magnifyingglass", isSearch: true)) }87        return items88    }8990    private static var glassTabBar: ComponentDescriptor {91        ComponentDescriptor(92            "glass-tab-bar",93            fields: [94                .number("tabs", "Tabs", in: 2...4, default: 3),95                .number("badge", "Inbox badge", in: 0...99, default: 3),96                .toggle("search", "Search tab", default: true),97                .choice("minimize", "Minimize behavior", options: [.init("automatic", "Automatic"), .init("onScrollDown", "On scroll down"), .init("onScrollUp", "On scroll up"), .init("never", "Never")]),98                .toggle("accessory", "Bottom accessory"),99            ],100            variants: [101                ComponentVariant("two-tabs", "Two tabs", ["tabs": .number(2), "search": .bool(false), "badge": .number(0)]),102                ComponentVariant("accessory", "Bottom accessory", ["accessory": .bool(true)]),103                ComponentVariant("minimize", "Minimizes on scroll", ["minimize": .choice("onScrollDown"), "tabs": .number(4)]),104            ],105            preview: { values in106                TabBarPreview(107                    tabs: tabItems(values),108                    minimizeBehavior: GlassTabBarMinimizeBehavior(rawValue: values.choice("minimize")) ?? .automatic,109                    showsAccessory: values.bool("accessory")110                )111                .id("\(values.number("tabs"))-\(values.bool("search"))")112                .frame(minHeight: 360)113            },114            snippet: { values in115                var tabs = sampleTabs.prefix(Int(values.number("tabs"))).map { id, title, symbol in116                    var arguments = ["id: \(SwiftLiteral.string(id))", "title: \(SwiftLiteral.string(title))", "systemImage: \(SwiftLiteral.string(symbol))"]117                    if id == "inbox", values.number("badge") > 0 { arguments.append("badge: .count(\(SwiftLiteral.number(values.number("badge"))))") }118                    return "GlassTabItem(\(arguments.joined(separator: ", ")))"119                }120                if values.bool("search") { tabs.append(#"GlassTabItem(id: "search", title: "Search", systemImage: "magnifyingglass", isSearch: true)"#) }121                var code = "GlassTabBar(\n    tabs: [\n\(list(tabs, levels: 2))\n    ],\n"122                code += "    // Use a @State property in a real screen: a constant keeps the first tab selected.\n"123                code += "    state: .constant(GlassTabNavigationState<String, String>(selection: \"today\"))"124                if values.choice("minimize") != "automatic" { code += ",\n    minimizeBehavior: \(SwiftLiteral.enumCase(values.choice("minimize"), fallback: "automatic"))" }125                code += #"""126127                ) { tab in128                    List(1...8, id: \.self) { index in129                        NavigationLink("\(tab.capitalized) \(index)", value: "\(tab.capitalized) \(index)")130                    }131                    .navigationTitle(tab.capitalized)132                } destination: { route in133                    Text(route)134                }135                """#136                if values.bool("accessory") { code += " bottomAccessory: {\n    Label(\"Now playing\", systemImage: \"play.fill\")\n}" }137                return code138            }139        )140    }141142    // MARK: GlassNavigationBar143144    private static let sampleNotes = ["Quarterly review", "Trip to Lisbon", "Reading list"]145    private static let leadingActions = [SampleAction(id: "sort", title: "Sort", symbol: "arrow.up.arrow.down")]146    private static let trailingActions = [147        SampleAction(id: "new", title: "New note", symbol: "square.and.pencil", priority: .high),148        SampleAction(id: "share", title: "Share", symbol: "square.and.arrow.up"),149        SampleAction(id: "flag", title: "Flag", symbol: "flag"),150        SampleAction(id: "delete", title: "Delete all", symbol: "trash", priority: .low, isDestructive: true),151    ]152153    private static var glassNavigationBar: ComponentDescriptor {154        ComponentDescriptor(155            "glass-navigation-bar",156            fields: [157                .text("title", "Title", default: "Notes", maxLength: 40),158                .text("subtitle", "Subtitle", default: "3 notes", maxLength: 60),159                .choice("display", "Title display", options: [.init("automatic", "Automatic"), .init("inline", "Inline"), .init("large", "Large")]),160                .toggle("leading", "Leading action"),161                .number("trailing", "Trailing actions", in: 0...4, default: 2),162            ],163            variants: [164                ComponentVariant("large", "Large title", ["display": .choice("large")]),165                ComponentVariant("inline", "Inline", ["display": .choice("inline"), "subtitle": .text("")]),166                ComponentVariant("actions", "Many actions", ["leading": .bool(true), "trailing": .number(4)]),167            ],168            preview: { values in169                GlassNavigationBar(170                    LocalizedStringKey(values.text("title")),171                    subtitle: values.text("subtitle").isEmpty ? nil : LocalizedStringKey(values.text("subtitle")),172                    titleDisplay: GlassNavigationTitleDisplay(rawValue: values.choice("display")) ?? .automatic,173                    leading: values.bool("leading") ? leadingActions.map(\.action) : [],174                    trailing: trailingActions.prefix(Int(values.number("trailing"))).map(\.action)175                ) {176                    List(sampleNotes, id: \.self) { note in177                        Text(verbatim: note)178                    }179                }180                .frame(minHeight: 360)181            },182            snippet: { values in183                var arguments = [SwiftLiteral.string(values.text("title"))]184                if !values.text("subtitle").isEmpty { arguments.append("subtitle: \(SwiftLiteral.string(values.text("subtitle")))") }185                if values.choice("display") != "automatic" { arguments.append("titleDisplay: \(SwiftLiteral.enumCase(values.choice("display"), fallback: "automatic"))") }186                if values.bool("leading") { arguments.append("leading: [\n\(list(leadingActions.map(\.code), levels: 1))\n]") }187                let trailing = trailingActions.prefix(Int(values.number("trailing")))188                if !trailing.isEmpty { arguments.append("trailing: [\n\(list(trailing.map(\.code), levels: 1))\n]") }189                let notes = sampleNotes.map(SwiftLiteral.string).joined(separator: ", ")190                return "GlassNavigationBar(\(arguments.joined(separator: ", "))) {\n    List([\(notes)], id: \\.self) { note in\n        Text(note)\n    }\n}"191            }192        )193    }194195    // MARK: GlassToolbar196197    private static let toolbarActions = [198        SampleAction(id: "share", title: "Share", symbol: "square.and.arrow.up", priority: .high),199        SampleAction(id: "pin", title: "Pin", symbol: "pin"),200        SampleAction(id: "duplicate", title: "Duplicate", symbol: "plus.square.on.square"),201        SampleAction(id: "archive", title: "Archive", symbol: "archivebox", priority: .low),202        SampleAction(id: "delete", title: "Delete", symbol: "trash", priority: .low, isDestructive: true),203    ]204205    private static var glassToolbar: ComponentDescriptor {206        ComponentDescriptor(207            "glass-toolbar",208            fields: [209                .choice("placement", "Placement", options: [210                    .init("automatic", "Automatic"), .init("leading", "Leading"), .init("trailing", "Trailing"), .init("primary", "Primary"),211                    .init("secondary", "Secondary"), .init("bottom", "Bottom bar"),212                ], default: "trailing"),213                .number("actions", "Actions", in: 1...5, default: 4),214                .toggle("limited", "Fixed capacity"),215                .number("capacity", "Capacity", in: 1...5, default: 2),216            ],217            variants: [218                ComponentVariant("overflow", "Overflow menu", ["actions": .number(5), "limited": .bool(true), "capacity": .number(2)]),219                ComponentVariant("bottom", "Bottom bar", ["placement": .choice("bottom"), "actions": .number(3)]),220                ComponentVariant("secondary", "Secondary", ["placement": .choice("secondary")]),221            ],222            preview: { values in223                NavigationStack {224                    List(1...6, id: \.self) { index in225                        Text(verbatim: "Row \(index)")226                    }227                    .navigationTitle(Text(verbatim: "Document"))228                    .glassToolbar([229                        GlassToolbarGroup(230                            id: "document",231                            placement: GlassToolbarPlacement(rawValue: values.choice("placement")) ?? .trailing,232                            capacity: values.bool("limited") ? Int(values.number("capacity")) : nil,233                            actions: toolbarActions.prefix(Int(values.number("actions"))).map(\.action)234                        ),235                    ])236                }237                .frame(minHeight: 360)238            },239            snippet: { values in240                var arguments = [#"id: "document""#]241                if values.choice("placement") != "automatic" { arguments.append("placement: \(SwiftLiteral.enumCase(values.choice("placement"), fallback: "trailing"))") }242                if values.bool("limited") { arguments.append("capacity: \(SwiftLiteral.number(values.number("capacity")))") }243                let actions = list(toolbarActions.prefix(Int(values.number("actions"))).map(\.code), levels: 3)244                return "NavigationStack {\n    List(1...6, id: \\.self) { index in\n        Text(\"Row \\(index)\")\n    }\n    .navigationTitle(\"Document\")\n    .glassToolbar([\n        GlassToolbarGroup(\(arguments.joined(separator: ", ")), actions: [\n\(actions)\n        ]),\n    ])\n}"245            }246        )247    }248249    // MARK: GlassSidebar250251    private typealias SampleRow = (id: String, title: String, symbol: String, badge: Int?)252    private static let sampleSections: [(id: String, title: String, rows: [SampleRow])] = [253        ("mailboxes", "Mailboxes", [("inbox", "Inbox", "tray", 12), ("drafts", "Drafts", "doc", 2), ("sent", "Sent", "paperplane", nil), ("archive", "Archive", "archivebox", nil)]),254        ("labels", "Labels", [("travel", "Travel", "airplane", nil), ("receipts", "Receipts", "receipt", 4)]),255    ]256257    private static var glassSidebar: ComponentDescriptor {258        ComponentDescriptor(259            "glass-sidebar",260            fields: [261                .text("title", "Title", default: "Mail", maxLength: 40),262                .number("sections", "Sections", in: 1...2, default: 2),263                .toggle("badges", "Badges", default: true),264                .toggle("searchable", "Searchable", default: true),265                .text("prompt", "Search prompt", default: "Search mailboxes", maxLength: 60),266            ],267            variants: [268                ComponentVariant("plain", "No search", ["searchable": .bool(false)]),269                ComponentVariant("single", "Single section", ["sections": .number(1), "badges": .bool(false)]),270            ],271            preview: { values in272                SidebarPreview(273                    title: values.text("title"),274                    sections: sampleSections.prefix(Int(values.number("sections"))).map { section in275                        GlassSidebarSection(id: section.id, title: section.title, items: section.rows.map {276                            GlassSidebarItem(id: $0.id, title: $0.title, systemImage: $0.symbol, badge: values.bool("badges") ? $0.badge : nil)277                        })278                    },279                    isSearchable: values.bool("searchable"),280                    prompt: values.text("prompt")281                )282                .frame(minHeight: 360)283            },284            snippet: { values in285                let sections = sampleSections.prefix(Int(values.number("sections"))).map { section in286                    let rows = section.rows.map { row in287                        var arguments = ["id: \(SwiftLiteral.string(row.id))", "title: \(SwiftLiteral.string(row.title))", "systemImage: \(SwiftLiteral.string(row.symbol))"]288                        if values.bool("badges"), let badge = row.badge { arguments.append("badge: \(SwiftLiteral.number(Double(badge)))") }289                        return "GlassSidebarItem(\(arguments.joined(separator: ", ")))"290                    }291                    return "GlassSidebarSection(id: \(SwiftLiteral.string(section.id)), title: \(SwiftLiteral.string(section.title)), items: [\n\(list(rows, levels: 1))\n])"292                }293                // A constant binding keeps the snippet a single expression; a real screen holds the selection in @State.294                var arguments = [SwiftLiteral.string(values.text("title")), "sections: [\n\(list(sections, levels: 1))\n]", #"selection: .constant("inbox")"#]295                if !values.bool("searchable") {296                    arguments.append("isSearchable: false")297                } else if !values.text("prompt").isEmpty {298                    arguments.append("searchPrompt: \(SwiftLiteral.string(values.text("prompt")))")299                }300                return "GlassSidebar(\(arguments.joined(separator: ", "))) { id in\n    Text(id ?? \"Select a mailbox\")\n}"301            }302        )303    }304305    // MARK: GlassBreadcrumb306307    private static let sampleLevels = ["Home", "Projects", "2026", "Client workshop", "Archive"]308309    /// The levels of the sample path: fixed folders, then the editable current level.310    private static func breadcrumbLevels(_ values: InspectorValues) -> [(title: String, symbol: String?)] {311        let parents: [(title: String, symbol: String?)] = sampleLevels.prefix(Int(values.number("depth")) - 1).enumerated().map { index, title in312            (title: title, symbol: index == 0 && values.bool("rootSymbol") ? "house" : nil)313        }314        return parents + [(title: values.text("current"), symbol: nil)]315    }316317    private static var glassBreadcrumb: ComponentDescriptor {318        ComponentDescriptor(319            "glass-breadcrumb",320            fields: [321                .number("depth", "Levels", in: 2...6, default: 4),322                .number("maxVisible", "Visible levels", in: 1...6, default: 4),323                .text("current", "Current level", default: "Photos", maxLength: 40),324                .toggle("rootSymbol", "Root symbol", default: true),325            ],326            variants: [327                ComponentVariant("collapsed", "Collapsed", ["depth": .number(6), "maxVisible": .number(2)]),328                ComponentVariant("short", "Short path", ["depth": .number(2), "rootSymbol": .bool(false)]),329            ],330            isComposable: true,331            preview: { values in332                BreadcrumbPreview(333                    items: breadcrumbLevels(values).enumerated().map { GlassBreadcrumbItem(id: $0.offset, title: $0.element.title, systemImage: $0.element.symbol) },334                    maxVisibleItems: Int(values.number("maxVisible"))335                )336                .id(values)337            },338            snippet: { values in339                let items = breadcrumbLevels(values).enumerated().map { index, level in340                    var arguments = ["id: \(index)", "title: \(SwiftLiteral.string(level.title))"]341                    if let symbol = level.symbol { arguments.append("systemImage: \(SwiftLiteral.string(symbol))") }342                    return "GlassBreadcrumbItem(\(arguments.joined(separator: ", ")))"343                }344                let limit = values.number("maxVisible") == 4 ? "" : ", maxVisibleItems: \(SwiftLiteral.number(values.number("maxVisible")))"345                return "GlassBreadcrumb([\n\(list(items, levels: 1))\n]\(limit)) { _ in\n    // navigate to the selected level\n}"346            }347        )348    }349}350351// MARK: - Stateful preview hosts352353/// Holds the tab navigation state of the tab bar preview.354private struct TabBarPreview: View {355    let tabs: [GlassTabItem<String>]356    let minimizeBehavior: GlassTabBarMinimizeBehavior357    let showsAccessory: Bool358    @State private var state = GlassTabNavigationState<String, String>(selection: "today")359360    var body: some View {361        if showsAccessory {362            GlassTabBar(tabs: tabs, state: $state, minimizeBehavior: minimizeBehavior) { tab in363                root(tab)364            } destination: { route in365                Text(verbatim: route)366            } bottomAccessory: {367                Label { Text(verbatim: "Now playing") } icon: { Image(systemName: "play.fill") }368            }369        } else {370            GlassTabBar(tabs: tabs, state: $state, minimizeBehavior: minimizeBehavior) { tab in371                root(tab)372            } destination: { route in373                Text(verbatim: route)374            }375        }376    }377378    private func root(_ tab: String) -> some View {379        List(1...8, id: \.self) { index in380            NavigationLink(value: "\(tab.capitalized) \(index)") { Text(verbatim: "\(tab.capitalized) \(index)") }381        }382        .navigationTitle(Text(verbatim: tab.capitalized))383    }384}385386/// Holds the selection of the sidebar preview.387private struct SidebarPreview: View {388    let title: String389    let sections: [GlassSidebarSection<String>]390    let isSearchable: Bool391    let prompt: String392    @State private var selection: String? = "inbox"393394    var body: some View {395        GlassSidebar(396            LocalizedStringKey(title),397            sections: sections,398            selection: $selection,399            isSearchable: isSearchable,400            searchPrompt: isSearchable && !prompt.isEmpty ? LocalizedStringKey(prompt) : nil401        ) { id in402            Text(verbatim: id ?? "Select a mailbox")403        }404    }405}406407/// Lets the breadcrumb preview navigate up: choosing a level shortens the path.408private struct BreadcrumbPreview: View {409    let items: [GlassBreadcrumbItem<Int>]410    let maxVisibleItems: Int411    @State private var depth: Int?412413    var body: some View {414        GlassBreadcrumb(Array(items.prefix(depth ?? items.count)), maxVisibleItems: maxVisibleItems) { id in415            depth = id + 1416        }417    }418}419
Files main
Menu

Theme