forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeiumWebView.swift
More file actions
72 lines (61 loc) · 2.14 KB
/
CodeiumWebView.swift
File metadata and controls
72 lines (61 loc) · 2.14 KB
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
import ComposableArchitecture
import Foundation
import Logger
import Preferences
import WebKit
class ScriptHandler: NSObject, WKScriptMessageHandlerWithReply {
@MainActor
func userContentController(
_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage
) async -> (Any?, String?) {
if message.name == "decodeBase64", let code = message.body as? String {
return (String(data: Data(base64Encoded: code) ?? Data(), encoding: .utf8), nil)
}
return (nil, nil)
}
}
@MainActor
class CodeiumWebView: WKWebView {
var getEditorContent: () async -> CodeiumChatTab.EditorContent
let scriptHandler = ScriptHandler()
weak var store: StoreOf<CodeiumChatBrowser>?
init(getEditorContent: @escaping () async -> CodeiumChatTab.EditorContent) {
self.getEditorContent = getEditorContent
super.init(frame: .zero, configuration: WKWebViewConfiguration())
if #available(macOS 13.3, *) {
#if DEBUG
isInspectable = true
#endif
}
configuration.userContentController.addScriptMessageHandler(
scriptHandler,
contentWorld: .page,
name: "decodeBase64"
)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@discardableResult
func evaluateJavaScript(safe javaScriptString: String) async throws -> Any? {
try await withUnsafeThrowingContinuation { continuation in
evaluateJavaScript(javaScriptString) { result, error in
if let error {
print(javaScriptString, error.localizedDescription)
continuation.resume(throwing: error)
} else {
continuation.resume(returning: result)
}
}
}
}
}
// MARK: - WebView Delegate
final class WKWebViewDelegate: NSObject, ObservableObject, WKNavigationDelegate, WKUIDelegate {
let store: StoreOf<CodeiumChatBrowser>
init(store: StoreOf<CodeiumChatBrowser>) {
self.store = store
}
}