-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathMyApp.swift
267 lines (223 loc) · 7.96 KB
/
MyApp.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
import JavaScriptEventLoop
import JavaScriptKit
// Simple full-text search service
actor SearchService {
struct Error: Swift.Error, CustomStringConvertible {
let message: String
var description: String {
return self.message
}
}
let serialExecutor: any SerialExecutor
// Simple in-memory index: word -> positions
var index: [String: [Int]] = [:]
var originalContent: String = ""
lazy var console: JSValue = {
JSObject.global.console
}()
nonisolated var unownedExecutor: UnownedSerialExecutor {
return self.serialExecutor.asUnownedSerialExecutor()
}
init(serialExecutor: any SerialExecutor) {
self.serialExecutor = serialExecutor
}
// Utility function for fetch
func fetch(_ url: String) -> JSPromise {
let jsFetch = JSObject.global.fetch.function!
return JSPromise(jsFetch(url).object!)!
}
func fetchAndIndex(url: String) async throws {
let response = try await fetch(url).value()
if response.status != 200 {
throw Error(message: "Failed to fetch content")
}
let text = try await JSPromise(response.text().object!)!.value()
let content = text.string!
index(content)
}
func index(_ contents: String) {
self.originalContent = contents
self.index = [:]
// Simple tokenization and indexing
var position = 0
let words = contents.lowercased().split(whereSeparator: { !$0.isLetter && !$0.isNumber })
for word in words {
let wordStr = String(word)
if wordStr.count > 1 { // Skip single-character words
if index[wordStr] == nil {
index[wordStr] = []
}
index[wordStr]?.append(position)
}
position += 1
}
_ = console.log("Indexing complete with", index.count, "unique words")
}
func search(_ query: String) -> [SearchResult] {
let queryWords = query.lowercased().split(whereSeparator: { !$0.isLetter && !$0.isNumber })
if queryWords.isEmpty {
return []
}
var results: [SearchResult] = []
// Start with the positions of the first query word
guard let firstWord = queryWords.first,
let firstWordPositions = index[String(firstWord)]
else {
return []
}
for position in firstWordPositions {
// Extract context around this position
let words = originalContent.lowercased().split(whereSeparator: {
!$0.isLetter && !$0.isNumber
})
var contextWords: [String] = []
// Get words for context (5 words before, 10 words after)
let contextStart = max(0, position - 5)
let contextEnd = min(position + 10, words.count - 1)
if contextStart <= contextEnd && contextStart < words.count {
for i in contextStart...contextEnd {
if i < words.count {
contextWords.append(String(words[i]))
}
}
}
let context = contextWords.joined(separator: " ")
results.append(SearchResult(position: position, context: context))
}
return results
}
}
struct SearchResult {
let position: Int
let context: String
}
@MainActor
final class App {
private let document = JSObject.global.document
private let alert = JSObject.global.alert.function!
// UI elements
private var container: JSValue
private var urlInput: JSValue
private var indexButton: JSValue
private var searchInput: JSValue
private var searchButton: JSValue
private var statusElement: JSValue
private var resultsElement: JSValue
// Search service
private let service: SearchService
init(service: SearchService) {
self.service = service
container = document.getElementById("container")
urlInput = document.getElementById("urlInput")
indexButton = document.getElementById("indexButton")
searchInput = document.getElementById("searchInput")
searchButton = document.getElementById("searchButton")
statusElement = document.getElementById("status")
resultsElement = document.getElementById("results")
setupEventHandlers()
}
private func setupEventHandlers() {
indexButton.onclick = .object(
JSClosure { [weak self] _ in
guard let self else { return .undefined }
self.performIndex()
return .undefined
}
)
searchButton.onclick = .object(
JSClosure { [weak self] _ in
guard let self else { return .undefined }
self.performSearch()
return .undefined
}
)
}
private func performIndex() {
let url = urlInput.value.string!
if url.isEmpty {
alert("Please enter a URL")
return
}
updateStatus("Downloading and indexing content...")
Task { [weak self] in
guard let self else { return }
do {
try await self.service.fetchAndIndex(url: url)
await MainActor.run {
self.updateStatus("Indexing complete!")
}
} catch {
await MainActor.run {
self.updateStatus("Error: \(error)")
}
}
}
}
private func performSearch() {
let query = searchInput.value.string!
if query.isEmpty {
alert("Please enter a search query")
return
}
updateStatus("Searching...")
Task { [weak self] in
guard let self else { return }
let searchResults = await self.service.search(query)
await MainActor.run {
self.displaySearchResults(searchResults)
}
}
}
private func updateStatus(_ message: String) {
statusElement.innerText = .string(message)
}
private func displaySearchResults(_ results: [SearchResult]) {
statusElement.innerText = .string("Search complete! Found \(results.count) results.")
resultsElement.innerHTML = .string("")
if results.isEmpty {
var noResults = document.createElement("p")
noResults.innerText = .string("No results found.")
_ = resultsElement.appendChild(noResults)
} else {
// Display up to 10 results
for (index, result) in results.prefix(10).enumerated() {
var resultItem = document.createElement("div")
resultItem.style = .string(
"padding: 10px; margin: 5px 0; background: #f5f5f5; border-left: 3px solid blue;"
)
resultItem.innerHTML = .string(
"<strong>Result \(index + 1):</strong> \(result.context)"
)
_ = resultsElement.appendChild(resultItem)
}
}
}
}
@main struct Main {
@MainActor static var app: App?
static func main() {
JavaScriptEventLoop.installGlobalExecutor()
WebWorkerTaskExecutor.installGlobalExecutor()
Task {
// Create dedicated worker and search service
let dedicatedWorker = try await WebWorkerDedicatedExecutor()
let service = SearchService(serialExecutor: dedicatedWorker)
app = App(service: service)
}
}
}
#if canImport(wasi_pthread)
import wasi_pthread
import WASILibc
/// Trick to avoid blocking the main thread. pthread_mutex_lock function is used by
/// the Swift concurrency runtime.
@_cdecl("pthread_mutex_lock")
func pthread_mutex_lock(_ mutex: UnsafeMutablePointer<pthread_mutex_t>) -> Int32 {
// DO NOT BLOCK MAIN THREAD
var ret: Int32
repeat {
ret = pthread_mutex_trylock(mutex)
} while ret == EBUSY
return ret
}
#endif