first commit

This commit is contained in:
JinJiangHuang
2026-03-01 14:04:44 +08:00
commit 61e97da938
62 changed files with 9947 additions and 0 deletions
+82
View File
@@ -0,0 +1,82 @@
import Foundation
import SwiftUI
/// ViewModel
@MainActor
class SearchViewModel: ObservableObject {
@Published var keyword: String = ""
@Published var results: [Movie.Video] = []
@Published var isSearching = false
@Published var searchHistory: [String] = []
@Published var errorMessage: String?
private let sourceService = SourceService.shared
init() {
loadSearchHistory()
}
///
func search() async {
let trimmed = keyword.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
isSearching = true
errorMessage = nil
results = []
//
addToHistory(trimmed)
let videos = await sourceService.searchAll(keyword: trimmed)
self.results = videos
if videos.isEmpty {
errorMessage = "未找到相关内容"
}
isSearching = false
}
///
func searchInSource(_ source: SourceBean) async {
let trimmed = keyword.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
isSearching = true
do {
let videos = try await sourceService.search(sourceBean: source, keyword: trimmed)
self.results = videos
} catch {
errorMessage = error.localizedDescription
}
isSearching = false
}
// MARK: -
private func loadSearchHistory() {
searchHistory = UserDefaults.standard.stringArray(forKey: HawkConfig.SEARCH_HISTORY) ?? []
}
private func addToHistory(_ keyword: String) {
searchHistory.removeAll { $0 == keyword }
searchHistory.insert(keyword, at: 0)
if searchHistory.count > 20 {
searchHistory = Array(searchHistory.prefix(20))
}
UserDefaults.standard.set(searchHistory, forKey: HawkConfig.SEARCH_HISTORY)
}
func clearHistory() {
searchHistory = []
UserDefaults.standard.removeObject(forKey: HawkConfig.SEARCH_HISTORY)
}
func removeFromHistory(_ keyword: String) {
searchHistory.removeAll { $0 == keyword }
UserDefaults.standard.set(searchHistory, forKey: HawkConfig.SEARCH_HISTORY)
}
}