-
-
Notifications
You must be signed in to change notification settings - Fork 52
Major API change on JSClosure #113
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
4c9b876
Major change on JSClosure
kateinoigakukun df7ff62
Keep JSClosure overloads as derepcated initializer
kateinoigakukun e67b03e
Apply suggestions from code review
kateinoigakukun 65658bd
Update Sources/JavaScriptKit/FundamentalObjects/JSClosure.swift
kateinoigakukun 3b93924
Apply suggestions from code review
kateinoigakukun efd633e
Use JSOneshotClosure in JSTimer
kateinoigakukun 76193c7
Remove JSClosure.callAsFunction
kateinoigakukun 2f84381
Use JSOneshotClosure instead of JSClosure in JSPromise
kateinoigakukun 110b72d
Fix compatibility build target dir
kateinoigakukun aed4312
Add compatibility method for JSValue.function(_:JSClosure)
kateinoigakukun 0896483
Update Sources/JavaScriptKit/JSValue.swift
kateinoigakukun File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
140 changes: 140 additions & 0 deletions
140
Sources/JavaScriptKit/FundamentalObjects/JSClosure.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,140 @@ | ||
import _CJavaScriptKit | ||
|
||
fileprivate var sharedFunctions: [JavaScriptHostFuncRef: ([JSValue]) -> JSValue] = [:] | ||
|
||
/// `JSOneshotClosure` is a JavaScript function that can be called only once. | ||
public class JSOneshotClosure: JSFunction { | ||
private var hostFuncRef: JavaScriptHostFuncRef = 0 | ||
|
||
public init(_ body: @escaping ([JSValue]) -> JSValue) { | ||
// 1. Fill `id` as zero at first to access `self` to get `ObjectIdentifier`. | ||
super.init(id: 0) | ||
let objectId = ObjectIdentifier(self) | ||
let funcRef = JavaScriptHostFuncRef(bitPattern: Int32(objectId.hashValue)) | ||
// 2. Retain the given body in static storage by `funcRef`. | ||
sharedFunctions[funcRef] = body | ||
// 3. Create a new JavaScript function which calls the given Swift function. | ||
var objectRef: JavaScriptObjectRef = 0 | ||
_create_function(funcRef, &objectRef) | ||
|
||
hostFuncRef = funcRef | ||
id = objectRef | ||
} | ||
|
||
public override func callAsFunction(this: JSObject? = nil, arguments: [ConvertibleToJSValue]) -> JSValue { | ||
defer { release() } | ||
return super.callAsFunction(this: this, arguments: arguments) | ||
} | ||
kateinoigakukun marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/// Release this function resource. | ||
/// After calling `release`, calling this function from JavaScript will fail. | ||
public func release() { | ||
sharedFunctions[hostFuncRef] = nil | ||
} | ||
} | ||
|
||
/// `JSClosure` represents a JavaScript function the body of which is written in Swift. | ||
/// This type can be passed as a callback handler to JavaScript functions. | ||
/// Note that the lifetime of `JSClosure` should be managed by users manually | ||
/// due to GC boundary between Swift and JavaScript. | ||
/// For further discussion, see also [swiftwasm/JavaScriptKit #33](https://github.com/swiftwasm/JavaScriptKit/pull/33) | ||
/// | ||
/// e.g. | ||
/// ```swift | ||
/// let eventListenter = JSClosure { _ in | ||
/// ... | ||
/// return JSValue.undefined | ||
/// } | ||
/// | ||
/// button.addEventListener!("click", JSValue.function(eventListenter)) | ||
/// ... | ||
/// button.removeEventListener!("click", JSValue.function(eventListenter)) | ||
/// eventListenter.release() | ||
/// ``` | ||
/// | ||
public class JSClosure: JSOneshotClosure { | ||
|
||
var isReleased: Bool = false | ||
|
||
@available(*, deprecated, message: "This initializer will be removed in the next minor version update. Please use `init(_ body: @escaping ([JSValue]) -> JSValue)`") | ||
kateinoigakukun marked this conversation as resolved.
Show resolved
Hide resolved
|
||
@_disfavoredOverload | ||
public init(_ body: @escaping ([JSValue]) -> ()) { | ||
super.init({ | ||
body($0) | ||
return .undefined | ||
}) | ||
} | ||
j-f1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
public override init(_ body: @escaping ([JSValue]) -> JSValue) { | ||
super.init(body) | ||
} | ||
|
||
public override func callAsFunction(this: JSObject? = nil, arguments: [ConvertibleToJSValue]) -> JSValue { | ||
try! invokeJSFunction(self, arguments: arguments, this: this) | ||
} | ||
|
||
public override func release() { | ||
isReleased = true | ||
super.release() | ||
} | ||
|
||
deinit { | ||
guard isReleased else { | ||
fatalError(""" | ||
release() must be called on closures manually before deallocating. | ||
This is caused by the lack of support for the `FinalizationRegistry` API in Safari. | ||
""") | ||
kateinoigakukun marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} | ||
} | ||
|
||
// MARK: - `JSClosure` mechanism note | ||
// | ||
// 1. Create thunk function in JavaScript world, that has a reference | ||
// to Swift Closure. | ||
// ┌─────────────────────┬──────────────────────────┐ | ||
// │ Swift side │ JavaScript side │ | ||
// │ │ │ | ||
// │ │ │ | ||
// │ │ ┌──[Thunk function]──┐ │ | ||
// │ ┌ ─ ─ ─ ─ ─│─ ─│─ ─ ─ ─ ─ ┐ │ │ | ||
// │ ↓ │ │ │ │ │ | ||
// │ [Swift Closure] │ │ Host Function ID │ │ | ||
// │ │ │ │ │ | ||
// │ │ └────────────────────┘ │ | ||
// └─────────────────────┴──────────────────────────┘ | ||
// | ||
// 2. When thunk function is invoked, it calls Swift Closure via | ||
// `_call_host_function` and callback the result through callback func | ||
// ┌─────────────────────┬──────────────────────────┐ | ||
// │ Swift side │ JavaScript side │ | ||
// │ │ │ | ||
// │ │ │ | ||
// │ Apply ┌──[Thunk function]──┐ │ | ||
// │ ┌ ─ ─ ─ ─ ─│─ ─│─ ─ ─ ─ ─ ┐ │ │ | ||
// │ ↓ │ │ │ │ │ | ||
// │ [Swift Closure] │ │ Host Function ID │ │ | ||
// │ │ │ │ │ │ | ||
// │ │ │ └────────────────────┘ │ | ||
// │ │ │ ↑ │ | ||
// │ │ Apply │ │ | ||
// │ └─[Result]─┼───>[Callback func]─┘ │ | ||
// │ │ │ | ||
// └─────────────────────┴──────────────────────────┘ | ||
kateinoigakukun marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
@_cdecl("_call_host_function_impl") | ||
func _call_host_function_impl( | ||
_ hostFuncRef: JavaScriptHostFuncRef, | ||
_ argv: UnsafePointer<RawJSValue>, _ argc: Int32, | ||
_ callbackFuncRef: JavaScriptObjectRef | ||
) { | ||
guard let hostFunc = sharedFunctions[hostFuncRef] else { | ||
fatalError("The function was already released") | ||
} | ||
let arguments = UnsafeBufferPointer(start: argv, count: Int(argc)).map { | ||
$0.jsValue() | ||
} | ||
let result = hostFunc(arguments) | ||
let callbackFuncRef = JSFunction(id: callbackFuncRef) | ||
_ = callbackFuncRef(result) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.