SPB Git

Repository Public MIT

GlassSidebar.swift 8.9 KB 224 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassNavigation/Navigation/GlassSidebar.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 SwiftUI42import SPGlassCore43import SPGlassThemes4445/// One row of a ``GlassSidebar``.46public struct GlassSidebarItem<ID: Hashable & Sendable>: Identifiable, Hashable, Sendable {47    public let id: ID48    /// Title of the row, already localised by the host.49    public var title: String50    public var systemImage: String?51    /// A count shown at the trailing edge; `nil` or zero shows nothing.52    public var badge: Int?53    /// Extra words the search matches besides the title.54    public var keywords: [String]5556    public init(id: ID, title: String, systemImage: String? = nil, badge: Int? = nil, keywords: [String] = []) {57        self.id = id58        self.title = title59        self.systemImage = systemImage60        self.badge = badge61        self.keywords = keywords62    }63}6465/// A titled group of rows.66public struct GlassSidebarSection<ID: Hashable & Sendable>: Identifiable, Hashable, Sendable {67    public let id: String68    /// Header of the section; `nil` shows the rows without a header.69    public var title: String?70    public var items: [GlassSidebarItem<ID>]7172    public init(id: String, title: String? = nil, items: [GlassSidebarItem<ID>]) {73        self.id = id74        self.title = title75        self.items = items76    }77}7879/// The search of a sidebar. Pure, so that it can be tested and reused by the host.80public enum GlassSidebarFilter {81    /// Folds case, diacritics and width, and trims white space: "  Événements " becomes "evenements".82    public static func normalize(_ text: String, locale: Locale? = nil) -> String {83        text.trimmingCharacters(in: .whitespacesAndNewlines)84            .folding(options: [.caseInsensitive, .diacriticInsensitive, .widthInsensitive], locale: locale)85    }8687    /// Whether an item matches a query: every word of the query must appear in the title or in a keyword.88    public static func matches<ID>(_ item: GlassSidebarItem<ID>, query: String, locale: Locale? = nil) -> Bool {89        let words = normalize(query, locale: locale).split(whereSeparator: \.isWhitespace)90        if words.isEmpty { return true }91        let haystack = ([item.title] + item.keywords).map { normalize($0, locale: locale) }92        return words.allSatisfy { word in haystack.contains { $0.contains(word) } }93    }9495    /// The sections with only the matching items; sections left empty are dropped. Order is kept.96    /// A section whose own title matches keeps all its items.97    public static func filter<ID>(_ sections: [GlassSidebarSection<ID>], query: String, locale: Locale? = nil) -> [GlassSidebarSection<ID>] {98        let normalized = normalize(query, locale: locale)99        if normalized.isEmpty { return sections }100        return sections.compactMap { section in101            if let title = section.title, normalize(title, locale: locale).contains(normalized) { return section }102            let items = section.items.filter { matches($0, query: query, locale: locale) }103            return items.isEmpty ? nil : GlassSidebarSection(id: section.id, title: section.title, items: items)104        }105    }106}107108/// A `NavigationSplitView` with a sidebar built from sections: typed selection, search and adaptive collapse.109///110/// ```swift111/// @State private var selection: Folder.ID?112///113/// GlassSidebar("Mail", sections: sections, selection: $selection) { id in114///     if let id { FolderView(id: id) } else { Text("Select a folder") }115/// }116/// ```117///118/// The system draws the sidebar and its glass, collapses it into a stack on a compact width and provides the119/// toggle button. Bind `columnVisibility` to collapse or show the sidebar from code.120public struct GlassSidebar<ID: Hashable & Sendable, Detail: View>: View {121    @GlassThemed private var theme122    private let title: Text123    private let sections: [GlassSidebarSection<ID>]124    @Binding private var selection: ID?125    private let externalSearch: Binding<String>?126    private let externalVisibility: Binding<NavigationSplitViewVisibility>?127    private let isSearchable: Bool128    private let searchPrompt: Text129    private let detail: (ID?) -> Detail130    @State private var ownSearch = ""131    @State private var ownVisibility: NavigationSplitViewVisibility = .automatic132133    /// - Parameters:134    ///   - title: title of the sidebar column.135    ///   - sections: the rows, grouped.136    ///   - selection: the selected row; `nil` when nothing is selected.137    ///   - searchText: the search text, when the host needs it; `nil` lets the sidebar own it.138    ///   - columnVisibility: visibility of the sidebar, when the host drives it; `nil` lets the system own it.139    ///   - isSearchable: adds the system search field to the sidebar.140    ///   - searchPrompt: placeholder of the search field. Defaults to the localised "Search".141    ///   - detail: the detail column for the current selection.142    public init(143        _ title: LocalizedStringKey,144        sections: [GlassSidebarSection<ID>],145        selection: Binding<ID?>,146        searchText: Binding<String>? = nil,147        columnVisibility: Binding<NavigationSplitViewVisibility>? = nil,148        isSearchable: Bool = true,149        searchPrompt: LocalizedStringKey? = nil,150        @ViewBuilder detail: @escaping (ID?) -> Detail151    ) {152        self.title = Text(title)153        self.sections = sections154        self._selection = selection155        self.externalSearch = searchText156        self.externalVisibility = columnVisibility157        self.isSearchable = isSearchable158        self.searchPrompt = searchPrompt.map { Text($0) } ?? Text(GlassL10n.string(.search))159        self.detail = detail160    }161162    public var body: some View {163        NavigationSplitView(columnVisibility: externalVisibility ?? $ownVisibility) {164            searchable(list)165                .navigationTitle(title)166        } detail: {167            detail(selection)168        }169        .tint(theme.color(.primary))170    }171172    private var query: String { (externalSearch ?? $ownSearch).wrappedValue }173174    private var list: some View {175        let visible = GlassSidebarFilter.filter(sections, query: query)176        return List(selection: $selection) {177            ForEach(visible) { section in178                if let header = section.title {179                    Section { rows(section.items) } header: { Text(verbatim: header) }180                } else {181                    Section { rows(section.items) }182                }183            }184        }185        .overlay {186            if visible.isEmpty, !query.isEmpty {187                ContentUnavailableView.search(text: query)188            }189        }190        .accessibilityLabel(Text(GlassL10n.string(.sidebar)))191    }192193    private func rows(_ items: [GlassSidebarItem<ID>]) -> some View {194        ForEach(items) { item in195            row(item).tag(item.id)196        }197    }198199    @ViewBuilder200    private func row(_ item: GlassSidebarItem<ID>) -> some View {201        let label = Group {202            if let systemImage = item.systemImage {203                Label { Text(verbatim: item.title) } icon: { Image(systemName: systemImage) }204            } else {205                Text(verbatim: item.title)206            }207        }208        if let badge = item.badge, badge > 0 {209            label.badge(badge)210        } else {211            label212        }213    }214215    @ViewBuilder216    private func searchable(_ view: some View) -> some View {217        if isSearchable {218            view.searchable(text: externalSearch ?? $ownSearch, placement: .sidebar, prompt: searchPrompt)219        } else {220            view221        }222    }223}224
Files main
Menu

Theme