SPB Git

Repository Public MIT

GlassSearchDebouncer.swift 5.5 KB 148 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassForms/Forms/GlassSearchDebouncer.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 Foundation42import Observation4344/// Delays an asynchronous search until typing pauses, and cancels the searches that were overtaken.45///46/// ```swift47/// @State private var debouncer = GlassSearchDebouncer()48///49/// .onChange(of: query) { _, newValue in50///     debouncer.submit(newValue) { query in51///         results = await service.search(query)   // checks Task.isCancelled before assigning52///     }53/// }54/// ```55///56/// Each call to ``submit(_:operation:)`` cancels the previous one, whether it was still waiting or already57/// running: only the latest query reaches the end. The operation runs on the main actor and should stop when58/// its task is cancelled.59@MainActor60@Observable61public final class GlassSearchDebouncer {62    /// The pause after the last input before a search starts.63    public let delay: Duration64    /// Whether a search is waiting or running.65    public private(set) var isPending = false6667    @ObservationIgnored private let sleep: @Sendable (Duration) async throws -> Void68    @ObservationIgnored private var generation = 069    @ObservationIgnored private(set) var task: Task<Void, Never>?7071    /// - Parameters:72    ///   - delay: pause after the last input.73    ///   - sleep: the waiting function; tests inject their own. It must throw when its task is cancelled.74    public init(75        delay: Duration = .milliseconds(300),76        sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }77    ) {78        self.delay = delay79        self.sleep = sleep80    }8182    /// Schedules `operation` for `query` after the delay, replacing any search waiting or running.83    public func submit(_ query: String, operation: @escaping @MainActor (String) async -> Void) {84        task?.cancel()85        generation += 186        let current = generation87        isPending = true88        task = Task { [sleep, delay] in89            do {90                try await sleep(delay)91                try Task.checkCancellation()92                await operation(query)93            } catch {94                // Cancelled while waiting: a newer query replaced this one.95            }96            self.finish(current)97        }98    }99100    /// Schedules a search whose result is delivered only if no newer query replaced it in the meantime.101    ///102    /// Unlike ``submit(_:operation:)`` this form does not rely on `search` noticing its cancellation: a result103    /// that arrives late is dropped, so an old answer can never overwrite a newer one.104    ///105    /// - Parameters:106    ///   - search: the asynchronous search, run off the main actor's critical path.107    ///   - deliver: receives the result of the latest query.108    ///   - failure: receives an error thrown by the latest query. Cancellation is not reported.109    public func submit<Value: Sendable>(110        _ query: String,111        search: @escaping @Sendable (String) async throws -> Value,112        deliver: @escaping @MainActor (Value) -> Void,113        failure: @escaping @MainActor (any Error) -> Void = { _ in }114    ) {115        task?.cancel()116        generation += 1117        let current = generation118        isPending = true119        task = Task { [sleep, delay] in120            do {121                try await sleep(delay)122                try Task.checkCancellation()123                let value = try await search(query)124                if current == self.generation, !Task.isCancelled { deliver(value) }125            } catch is CancellationError {126                // A newer query replaced this one.127            } catch {128                if current == self.generation, !Task.isCancelled { failure(error) }129            }130            self.finish(current)131        }132    }133134    /// Cancels the search waiting or running, if any.135    public func cancel() {136        task?.cancel()137        task = nil138        generation += 1139        isPending = false140    }141142    private func finish(_ finished: Int) {143        guard finished == generation else { return }144        task = nil145        isPending = false146    }147}148
Files main
Menu

Theme