Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Search iOS9// File : Core/Sources/SPSearchKit/HistoryStore.swift10// Description : Recent searches kept on the device only (UserDefaults),11// with an on/off switch.12// Module : SPSearchKit13// Repository : https://git.spboucher.ai/sp-search-ios14// Project Website : https://search.spboucher.ai15// Created : 2026-12-0116// Last Modified : 2026-12-0117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : None specified (no license file in this repository)83// Maintainer : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation9192public struct HistoryEntry: Codable, Sendable, Hashable, Identifiable {93 public let query: String94 public let date: Date95 public var id: String { query }96 public init(query: String, date: Date) { self.query = query; self.date = date }97}9899/// Recent searches. They live in this app's UserDefaults and nowhere else; nothing here touches the network.100public struct HistoryStore {101 public static let enabledKey = "history.enabled"102 public static let itemsKey = "history.items"103 public static let limit = 50104105 private let defaults: UserDefaults106 public init(defaults: UserDefaults = .standard) { self.defaults = defaults }107108 /// On by default.109 public var isEnabled: Bool {110 get { defaults.object(forKey: Self.enabledKey) as? Bool ?? true }111 nonmutating set { defaults.set(newValue, forKey: Self.enabledKey) }112 }113114 public var entries: [HistoryEntry] {115 guard let data = defaults.data(forKey: Self.itemsKey) else { return [] }116 return (try? JSONDecoder().decode([HistoryEntry].self, from: data)) ?? []117 }118119 /// Records a search at the top of the list; the same query (whatever its case) is not listed twice. Does nothing when off.120 @discardableResult121 public func record(_ query: String, at date: Date = Date()) -> [HistoryEntry] {122 let q = SearchRequest.normalise(query)123 guard isEnabled, !q.isEmpty else { return entries }124 var list = entries.filter { $0.query.caseInsensitiveCompare(q) != .orderedSame }125 list.insert(HistoryEntry(query: q, date: date), at: 0)126 return save(Array(list.prefix(Self.limit)))127 }128129 @discardableResult130 public func remove(_ query: String) -> [HistoryEntry] { save(entries.filter { $0.query != query }) }131132 public func clear() { defaults.removeObject(forKey: Self.itemsKey) }133134 /// Version 1.0 kept the recent searches in the app's own defaults; 2.0 keeps them in the app group so the widget135 /// can list them. The move happens once: entries and the on/off switch are copied, then removed from the source.136 /// What is already in the destination wins; nothing is lost if the move runs twice.137 @discardableResult138 public static func migrate(from source: UserDefaults, to destination: UserDefaults) -> Bool {139 guard source !== destination else { return false }140 let hasItems = source.data(forKey: itemsKey) != nil, hasSwitch = source.object(forKey: enabledKey) != nil141 guard hasItems || hasSwitch else { return false }142 if hasSwitch, destination.object(forKey: enabledKey) == nil { destination.set(source.bool(forKey: enabledKey), forKey: enabledKey) }143 if hasItems {144 let old = HistoryStore(defaults: source).entries145 let new = HistoryStore(defaults: destination)146 var merged = new.entries147 for e in old where !merged.contains(where: { $0.query.caseInsensitiveCompare(e.query) == .orderedSame }) { merged.append(e) }148 merged.sort { $0.date > $1.date }149 _ = new.save(Array(merged.prefix(limit)))150 }151 source.removeObject(forKey: itemsKey)152 source.removeObject(forKey: enabledKey)153 return true154 }155156 private func save(_ list: [HistoryEntry]) -> [HistoryEntry] {157 if let data = try? JSONEncoder().encode(list) { defaults.set(data, forKey: Self.itemsKey) }158 return list159 }160}161162/// Where the app and its widget both read: the app group's defaults, or the app's own when the group is unavailable.163public enum SharedStore {164 public static let groupID = "group.ai.spboucher.spsearch"165 public static var defaults: UserDefaults { UserDefaults(suiteName: groupID) ?? .standard }166}167