Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/SPGlassForms/Forms/GlassSearchField.swift8// Module : SPGlassForms9// 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 SPGlassTokens44import SPGlassThemes45import SPGlassEffects4647/// A search suggestion: what is shown and the text it puts in the search field.48public struct GlassSearchSuggestion: Identifiable, Hashable, Sendable {49 public let id: String50 public var title: String51 public var systemImage: String?52 /// Text placed in the field when the suggestion is chosen.53 public var completion: String5455 public init(id: String? = nil, title: String, systemImage: String? = nil, completion: String? = nil) {56 self.id = id ?? title57 self.title = title58 self.systemImage = systemImage59 self.completion = completion ?? title60 }6162 /// The suggestions whose title contains `query`, ignoring case, diacritics and width. An empty query63 /// keeps them all. At most `limit` are returned, in their original order.64 public static func matching(_ query: String, in suggestions: [GlassSearchSuggestion], limit: Int = 8) -> [GlassSearchSuggestion] {65 let needle = fold(query)66 let matches = needle.isEmpty ? suggestions : suggestions.filter { fold($0.title).contains(needle) }67 return Array(matches.prefix(max(limit, 0)))68 }6970 private static func fold(_ text: String) -> String {71 text.trimmingCharacters(in: .whitespacesAndNewlines)72 .folding(options: [.caseInsensitive, .diacriticInsensitive, .widthInsensitive], locale: nil)73 }74}7576extension View {77 /// Adds the system search field (`.searchable`) with suggestions and a submit action.78 ///79 /// ```swift80 /// List(results) { ResultRow($0) }81 /// .glassSearchable(text: $query, suggestions: GlassSearchSuggestion.matching(query, in: recent)) {82 /// runSearch()83 /// }84 /// ```85 ///86 /// The system places and draws the field: in the navigation bar or bottom toolbar on iOS, in the window87 /// toolbar on macOS. It also provides clearing and cancelling. Use it inside a `NavigationStack` or a88 /// `NavigationSplitView`; elsewhere use ``GlassSearchField``.89 public func glassSearchable(90 text: Binding<String>,91 isPresented: Binding<Bool>? = nil,92 prompt: LocalizedStringKey? = nil,93 suggestions: [GlassSearchSuggestion] = [],94 onSubmit: @escaping @MainActor () -> Void = {}95 ) -> some View {96 modifier(GlassSearchableModifier(text: text, isPresented: isPresented, prompt: prompt.map { Text($0) }, suggestions: suggestions, onSubmit: onSubmit))97 }98}99100private struct GlassSearchableModifier: ViewModifier {101 @Binding var text: String102 let isPresented: Binding<Bool>?103 let prompt: Text?104 let suggestions: [GlassSearchSuggestion]105 let onSubmit: @MainActor () -> Void106107 func body(content: Content) -> some View {108 searchable(content)109 .searchSuggestions {110 ForEach(suggestions) { suggestion in111 GlassSearchSuggestionLabel(suggestion: suggestion)112 .searchCompletion(suggestion.completion)113 }114 }115 .onSubmit(of: .search, onSubmit)116 }117118 @ViewBuilder119 private func searchable(_ content: Content) -> some View {120 let prompt = prompt ?? Text(GlassL10n.string(.search))121 if let isPresented {122 content.searchable(text: $text, isPresented: isPresented, prompt: prompt)123 } else {124 content.searchable(text: $text, prompt: prompt)125 }126 }127}128129private struct GlassSearchSuggestionLabel: View {130 let suggestion: GlassSearchSuggestion131132 var body: some View {133 if let systemImage = suggestion.systemImage {134 Label { Text(verbatim: suggestion.title) } icon: { Image(systemName: systemImage) }135 } else {136 Text(verbatim: suggestion.title)137 }138 }139}140141/// An inline search field for places without a navigation bar: a panel, a sheet, a filter above a grid.142///143/// ```swift144/// GlassSearchField(text: $query, prompt: "Search products") { runSearch() }145/// ```146///147/// It has a clear button while it holds text and, on iOS, a Cancel button while it is focused; Cancel empties148/// the field and gives up the focus. Where a navigation bar exists, prefer149/// ``SwiftUICore/View/glassSearchable(text:isPresented:prompt:suggestions:onSubmit:)``.150public struct GlassSearchField: View {151 @GlassThemed private var theme152 @GlassAccessibility private var accessibility153 @FocusState private var isFocused: Bool154 @Binding private var text: String155 private let prompt: Text156 private let showsCancel: Bool157 private let onSubmit: @MainActor () -> Void158 private let onCancel: @MainActor () -> Void159160 /// - Parameters:161 /// - text: the search text.162 /// - prompt: placeholder. Defaults to the localised "Search".163 /// - showsCancel: shows a Cancel button while the field is focused. `nil` shows it on iOS only.164 /// - onSubmit: called when the user submits the search.165 /// - onCancel: called after Cancel emptied the field.166 public init(167 text: Binding<String>,168 prompt: LocalizedStringKey? = nil,169 showsCancel: Bool? = nil,170 onSubmit: @escaping @MainActor () -> Void = {},171 onCancel: @escaping @MainActor () -> Void = {}172 ) {173 self._text = text174 self.prompt = prompt.map { Text($0) } ?? Text(GlassL10n.string(.search))175 self.showsCancel = showsCancel ?? (GlassPlatform.current != .macOS)176 self.onSubmit = onSubmit177 self.onCancel = onCancel178 }179180 public var body: some View {181 HStack(spacing: theme.spacing.xs) {182 HStack(spacing: theme.spacing.xs) {183 Image(systemName: "magnifyingglass")184 .foregroundStyle(theme.color(.textSecondary))185 .accessibilityHidden(true)186 TextField(text: $text, prompt: prompt) { Text(GlassL10n.string(.search)) }187 .textFieldStyle(.plain)188 .labelsHidden()189 .glassTextInput(GlassTextInputConfiguration(autocorrectionDisabled: true, capitalization: .never))190 .submitLabel(.search)191 .focused($isFocused)192 .onSubmit(onSubmit)193 .accessibilityAddTraits(.isSearchField)194 if !text.isEmpty {195 Button {196 text = ""197 isFocused = true198 } label: {199 Label(GlassL10n.string(.clear), systemImage: "xmark.circle.fill")200 .labelStyle(.iconOnly)201 .foregroundStyle(theme.color(.textSecondary))202 .glassMinimumHitTarget()203 }204 .buttonStyle(.plain)205 }206 }207 .padding(.horizontal, theme.spacing.sm)208 .frame(minHeight: theme.metrics.height(.regular))209 .background(theme.color(.surface), in: Capsule())210 .glassFieldOutline(isFocused: isFocused, in: Capsule())211212 if showsCancel, isFocused {213 Button(GlassL10n.string(.cancel)) {214 text = ""215 isFocused = false216 onCancel()217 }218 .tint(theme.color(.primary))219 .transition(.opacity)220 }221 }222 .animation(theme.animation(.fast, reduceMotion: accessibility.reduceMotion), value: isFocused)223 #if os(macOS)224 .onExitCommand {225 text = ""226 isFocused = false227 onCancel()228 }229 #endif230 }231}232