forked from itsjustcon/JavaScriptCoreBrowserObjectModel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSDocumentViewController.swift
More file actions
254 lines (213 loc) · 10.9 KB
/
JSDocumentViewController.swift
File metadata and controls
254 lines (213 loc) · 10.9 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
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
//
// JSDocumentViewController.swift
// JS Notepad
//
// Created by Connor Grady on 1/6/18.
// Copyright © 2018 Connor Grady. All rights reserved.
//
import UIKit
import JavaScriptCore
import JavaScriptCoreBrowserObjectModel
class JSDocumentViewController: UIViewController {
var document: JSDocument? {
willSet {
//document?.removeObserver(self, forKeyPath: "hasUnsavedChanges", context: nil)
if currentJSContext != nil {
currentJSContext = nil
}
}
//didSet {
// document?.addObserver(self, forKeyPath: "hasUnsavedChanges", options: .new, context: nil)
//}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@IBOutlet weak var consoleTextView: UITextView!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
private var isTrackingBottomOfTextView: Bool = true
var currentJSContext: JSContext?
private func createContext() -> JSContext {
let jsContext = JSContext2()!
jsContext.exceptionHandler = { [weak consoleTextView] (context, exception) in
print("jsContext.exceptionHandler()\n\(String(describing: exception))")
print(" exception.isString: \(exception!.isString)")
print(" exception.isObject: \(exception!.isObject)")
print(" exception.isError: \(exception!.isError)")
if let exception = exception, exception.isObject {
print("\(exception.toObject())")
}
consoleTextView?.text.append("\n[ERROR] \(exception?.debugDescription ?? "nil")\n\n")
}
// inject `JavaScriptCoreBrowserObjectModel` stuff
// Console
jsContext.setObject(Console.self, forKeyedSubscript: "Console" as (NSCopying & NSObjectProtocol))
//let oStream = TextViewOutputStream(textView: consoleTextView)
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "HH:mm:ss.SSS"
let oStream = TextViewOutputStream(textView: consoleTextView, dateFormatter: dateFormatter)
let console = Console(stdout: oStream, stderr: oStream)
jsContext.setObject(console, forKeyedSubscript: "console" as (NSCopying & NSObjectProtocol))
// Timers
//context.setObject(Timers.self, forKeyedSubscript: "Timers" as (NSCopying & NSObjectProtocol))
Timers.extend(jsContext)
// XMLHttpRequest
jsContext.setObject(XMLHttpRequest.self, forKeyedSubscript: "XMLHttpRequest" as (NSCopying & NSObjectProtocol))
// babel-polyfill
let babelPolyfillUrl = Bundle(for: type(of: self)).url(forResource: "polyfill", withExtension: "js", subdirectory: "js-libs/babel-polyfill")!
let babelPolyfill = try! String(contentsOf: babelPolyfillUrl)
jsContext.evaluateScript(babelPolyfill)
// whatwg-fetch
let fetchPolyfillUrl = Bundle(for: type(of: self)).url(forResource: "fetch", withExtension: "js", subdirectory: "js-libs/whatwg-fetch")!
let fetchPolyfill = try! String(contentsOf: fetchPolyfillUrl)
jsContext.evaluateScript(fetchPolyfill)
return jsContext
}
override func viewDidLoad() {
super.viewDidLoad()
consoleTextView.contentInset.bottom = consoleTextView.font?.lineHeight ?? 8
consoleTextView.addObserver(self, forKeyPath: "contentSize", options: [ .new, .old ], context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let object = object as? UITextView, object === consoleTextView, keyPath == "contentSize" {
if isTrackingBottomOfTextView {
consoleTextView.scrollToBottom(animated: false)
}
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
override func viewWillAppear(_ animated: Bool) {
print("JSDocumentViewController viewWillAppear( animated: \(animated) )")
super.viewWillAppear(animated)
title = document?.fileURL.lastPathComponent
self.currentJSContext = nil
consoleTextView.text = ""
loadingIndicator.startAnimating()
// Access the document
document?.open(completionHandler: { success in
if success {
self.consoleTextView.text = "[INFO] Loaded \(self.document?.fileURL.lastPathComponent ?? "")\n"
} else {
// Make sure to handle the failed import appropriately, e.g., by presenting an error message to the user.
//self.consoleTextView.text = "\n[ERROR] Failed to open \(self.document!.fileURL.path)\n\n"
self.consoleTextView.text = "\n[ERROR] Failed to open \(self.document?.fileURL.lastPathComponent ?? "nil")\n\n"
}
self.loadingIndicator.stopAnimating()
})
}
@IBAction func dismissDocumentViewController() {
dismiss(animated: true) {
self.document?.close(completionHandler: nil)
//self.document?.close(completionHandler: { success in
// self.document = nil
//})
self.currentJSContext = nil
self.consoleTextView.text = ""
}
}
@IBAction func clearConsoleOutput() {
consoleTextView.text = ""
}
@IBAction func executeDocument(_ sender: UIBarButtonItem?) {
let jsContext = createContext()
currentJSContext = jsContext // retain context
if consoleTextView.text.count > 0 {
consoleTextView.text.append("\n\n\n\n")
// figure out how many lines it takes to fill the visible height of `consoleTextView`
//let lineHeight = consoleTextView.font?.lineHeight ?? 8
//let visibleHeight = consoleTextView.visibleContentFrame.height
//let lineCount = Int(floor(visibleHeight / lineHeight))
//consoleTextView.text.append(String(repeating: "\n", count: lineCount))
}
consoleTextView.text.append("\n[INFO] executing \(document!.fileURL.lastPathComponent) ...\n\n")
//JSCheckScriptSyntax(jsContext.jsGlobalContextRef, JSStringCreateWithCFString(document!.scriptText! as CFString), JSStringCreateWithCFString(document!.localizedName as CFString), 0, nil)
//let scriptFn = JSObjectMakeFunction(jsContext.jsGlobalContextRef, JSStringCreateWithCFString(document!.localizedName as CFString), 0, nil, JSStringCreateWithCFString(document!.scriptText! as CFString), JSStringCreateWithCFString(document!.localizedName as CFString), 0, nil)!
//JSObjectCallAsFunction(jsContext.jsGlobalContextRef, scriptFn, jsContext.jsGlobalContextRef, 0, nil, nil)
var mainFn = jsContext.evaluateScript(document!.scriptText!)!
if !mainFn.isFunction {
mainFn = jsContext.objectForKeyedSubscript("main")
}
if mainFn.isFunction {
mainFn.callAsync(withArguments: []) { [unowned self, weak jsContext] (result, error) in
DispatchQueue.main.async {
if let error = error/*, error.isError*/ {
print(" error: \(error.debugDescription)")
print(" error.isString: \(error.isString)")
print(" error.isObject: \(error.isObject)")
print(" error.isError: \(error.isError)")
if error.isError {
print("\(error.toObject())")
//print("\(String(describing: error.value(forKey: "stack")))")
print("\(String(describing: error.forProperty("stack")))")
}
self.consoleTextView.text.append("\n[ERROR] \(error.debugDescription)\n\n")
} else if let result = result, !result.isUndefined, !result.isNull {
print(" result: \(String(describing: result))")
self.consoleTextView.text.append("\n[INFO] Script returned:\n\(result.debugDescription)\n\n")
} else {
self.consoleTextView.text.append("\n[INFO] Script finished executing\n\n")
}
//self.currentJSContext = nil // release context
//JSGlobalContextRelease(jsContext.jsGlobalContextRef) // release context
if jsContext != nil, self.currentJSContext === jsContext {
self.currentJSContext = nil // release context
}
}
}
} else {
consoleTextView.text.append("\n[INFO] Script finished executing\n\n")
currentJSContext = nil // release context
}
}
}
extension JSDocumentViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
if isTrackingBottomOfTextView {
textView.scrollToBottom(animated: true)
}
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isTrackingBottomOfTextView = false
}
func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) {
if isTrackingBottomOfTextView {
scrollView.scrollToBottom(animated: true)
}
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let adjustedTargetContentOffset = CGPoint(
x: targetContentOffset.pointee.x + scrollView.adjustedContentInset.left,
y: targetContentOffset.pointee.y + scrollView.adjustedContentInset.top
)
let targetMaxY = adjustedTargetContentOffset.y + scrollView.visibleContentFrame.height
if targetMaxY >= scrollView.contentSize.height {
isTrackingBottomOfTextView = true
}
}
}
extension UIScrollView {
var visibleContentFrame: CGRect {
return UIEdgeInsetsInsetRect(bounds, adjustedContentInset)
}
var isScrolledToBottom: Bool {
return visibleContentFrame.maxY >= contentSize.height
}
func scrollToBottom(animated: Bool) {
//guard !isScrolledToBottom else { return }
let deltaY = contentSize.height - visibleContentFrame.maxY
guard deltaY > 0 else { return }
//let newContentOffset = CGPoint(x: 0, y: contentOffset.y + deltaY)
let newContentOffset = CGPoint(x: contentOffset.x, y: contentOffset.y + deltaY)
//setContentOffset(newContentOffset, animated: animated)
DispatchQueue.main.async { [unowned self] in
self.setContentOffset(newContentOffset, animated: animated)
}
}
}
class JSContext2: JSContext {
deinit {
print("JSContext2 deinit")
}
}