Commit 5881d304 authored by Richard Musiol's avatar Richard Musiol Committed by Brad Fitzpatrick

syscall/js: turn constant package vars into functions

This is so the values can not be changed and the type is easy to see.

Requested on https://go-review.googlesource.com/c/go/+/120561.

Change-Id: If2ed48ca3ba8874074687bfb2375d2f5592e8e0d
Reviewed-on: https://go-review.googlesource.com/120564Reviewed-by: default avatarBrad Fitzpatrick <bradfitz@golang.org>
parent 9c35c1a5
...@@ -12,7 +12,7 @@ func init() { ...@@ -12,7 +12,7 @@ func init() {
Reader = &reader{} Reader = &reader{}
} }
var jsCrypto = js.Global.Get("crypto") var jsCrypto = js.Global().Get("crypto")
// reader implements a pseudorandom generator // reader implements a pseudorandom generator
// using JavaScript crypto.getRandomValues method. // using JavaScript crypto.getRandomValues method.
......
...@@ -22,28 +22,28 @@ func (t *Transport) RoundTrip(req *Request) (*Response, error) { ...@@ -22,28 +22,28 @@ func (t *Transport) RoundTrip(req *Request) (*Response, error) {
if useFakeNetwork() { if useFakeNetwork() {
return t.roundTrip(req) return t.roundTrip(req)
} }
headers := js.Global.Get("Headers").New() headers := js.Global().Get("Headers").New()
for key, values := range req.Header { for key, values := range req.Header {
for _, value := range values { for _, value := range values {
headers.Call("append", key, value) headers.Call("append", key, value)
} }
} }
ac := js.Global.Get("AbortController") ac := js.Global().Get("AbortController")
if ac != js.Undefined { if ac != js.Undefined() {
// Some browsers that support WASM don't necessarily support // Some browsers that support WASM don't necessarily support
// the AbortController. See // the AbortController. See
// https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility. // https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility.
ac = ac.New() ac = ac.New()
} }
opt := js.Global.Get("Object").New() opt := js.Global().Get("Object").New()
// See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch // See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
// for options available. // for options available.
opt.Set("headers", headers) opt.Set("headers", headers)
opt.Set("method", req.Method) opt.Set("method", req.Method)
opt.Set("credentials", "same-origin") opt.Set("credentials", "same-origin")
if ac != js.Undefined { if ac != js.Undefined() {
opt.Set("signal", ac.Get("signal")) opt.Set("signal", ac.Get("signal"))
} }
...@@ -62,7 +62,7 @@ func (t *Transport) RoundTrip(req *Request) (*Response, error) { ...@@ -62,7 +62,7 @@ func (t *Transport) RoundTrip(req *Request) (*Response, error) {
req.Body.Close() req.Body.Close()
opt.Set("body", body) opt.Set("body", body)
} }
respPromise := js.Global.Call("fetch", req.URL.String(), opt) respPromise := js.Global().Call("fetch", req.URL.String(), opt)
var ( var (
respCh = make(chan *Response, 1) respCh = make(chan *Response, 1)
errCh = make(chan error, 1) errCh = make(chan error, 1)
...@@ -90,7 +90,7 @@ func (t *Transport) RoundTrip(req *Request) (*Response, error) { ...@@ -90,7 +90,7 @@ func (t *Transport) RoundTrip(req *Request) (*Response, error) {
b := result.Get("body") b := result.Get("body")
var body io.ReadCloser var body io.ReadCloser
if b != js.Undefined { if b != js.Undefined() {
body = &streamReader{stream: b.Call("getReader")} body = &streamReader{stream: b.Call("getReader")}
} else { } else {
// Fall back to using ArrayBuffer // Fall back to using ArrayBuffer
...@@ -122,7 +122,7 @@ func (t *Transport) RoundTrip(req *Request) (*Response, error) { ...@@ -122,7 +122,7 @@ func (t *Transport) RoundTrip(req *Request) (*Response, error) {
respPromise.Call("then", success, failure) respPromise.Call("then", success, failure)
select { select {
case <-req.Context().Done(): case <-req.Context().Done():
if ac != js.Undefined { if ac != js.Undefined() {
// Abort the Fetch request // Abort the Fetch request
ac.Call("abort") ac.Call("abort")
} }
...@@ -225,7 +225,7 @@ func (r *arrayReader) Read(p []byte) (n int, err error) { ...@@ -225,7 +225,7 @@ func (r *arrayReader) Read(p []byte) (n int, err error) {
) )
success := js.NewCallback(func(args []js.Value) { success := js.NewCallback(func(args []js.Value) {
// Wrap the input ArrayBuffer with a Uint8Array // Wrap the input ArrayBuffer with a Uint8Array
uint8arrayWrapper := js.Global.Get("Uint8Array").New(args[0]) uint8arrayWrapper := js.Global().Get("Uint8Array").New(args[0])
value := make([]byte, uint8arrayWrapper.Get("byteLength").Int()) value := make([]byte, uint8arrayWrapper.Get("byteLength").Int())
js.ValueOf(value).Call("set", uint8arrayWrapper) js.ValueOf(value).Call("set", uint8arrayWrapper)
bCh <- value bCh <- value
......
...@@ -15,8 +15,8 @@ import ( ...@@ -15,8 +15,8 @@ import (
// Provided by package runtime. // Provided by package runtime.
func now() (sec int64, nsec int32) func now() (sec int64, nsec int32)
var jsProcess = js.Global.Get("process") var jsProcess = js.Global().Get("process")
var jsFS = js.Global.Get("fs") var jsFS = js.Global().Get("fs")
var constants = jsFS.Get("constants") var constants = jsFS.Get("constants")
var ( var (
......
...@@ -8,9 +8,9 @@ package js ...@@ -8,9 +8,9 @@ package js
import "sync" import "sync"
var pendingCallbacks = Global.Get("Array").New() var pendingCallbacks = Global().Get("Array").New()
var makeCallbackHelper = Global.Call("eval", ` var makeCallbackHelper = Global().Call("eval", `
(function(id, pendingCallbacks, resolveCallbackPromise) { (function(id, pendingCallbacks, resolveCallbackPromise) {
return function() { return function() {
pendingCallbacks.push({ id: id, args: arguments }); pendingCallbacks.push({ id: id, args: arguments });
...@@ -19,7 +19,7 @@ var makeCallbackHelper = Global.Call("eval", ` ...@@ -19,7 +19,7 @@ var makeCallbackHelper = Global.Call("eval", `
}) })
`) `)
var makeEventCallbackHelper = Global.Call("eval", ` var makeEventCallbackHelper = Global().Call("eval", `
(function(preventDefault, stopPropagation, stopImmediatePropagation, fn) { (function(preventDefault, stopPropagation, stopImmediatePropagation, fn) {
return function(event) { return function(event) {
if (preventDefault) { if (preventDefault) {
...@@ -118,7 +118,7 @@ func callbackLoop() { ...@@ -118,7 +118,7 @@ func callbackLoop() {
sleepUntilCallback() sleepUntilCallback()
for { for {
cb := pendingCallbacks.Call("shift") cb := pendingCallbacks.Call("shift")
if cb == Undefined { if cb == Undefined() {
break break
} }
...@@ -127,7 +127,7 @@ func callbackLoop() { ...@@ -127,7 +127,7 @@ func callbackLoop() {
f, ok := callbacks[id] f, ok := callbacks[id]
callbacksMu.Unlock() callbacksMu.Unlock()
if !ok { if !ok {
Global.Get("console").Call("error", "call to closed callback") Global().Get("console").Call("error", "call to closed callback")
continue continue
} }
......
...@@ -39,23 +39,29 @@ func (e Error) Error() string { ...@@ -39,23 +39,29 @@ func (e Error) Error() string {
} }
var ( var (
// Undefined is the JavaScript value "undefined". The zero Value equals to Undefined. valueUndefined = makeValue(0)
Undefined = makeValue(0) valueNull = makeValue(1)
valueGlobal = makeValue(2)
// Null is the JavaScript value "null". memory = makeValue(3) // WebAssembly linear memory
Null = makeValue(1) resolveCallbackPromise = makeValue(4) // function that the callback helper uses to resume the execution of Go's WebAssembly code
)
// Global is the JavaScript global object, usually "window" or "global". // Undefined returns the JavaScript value "undefined".
Global = makeValue(2) func Undefined() Value {
return valueUndefined
}
// memory is the WebAssembly linear memory. // Null returns the JavaScript value "null".
memory = makeValue(3) func Null() Value {
return valueNull
}
// resolveCallbackPromise is a function that the callback helper uses to resume the execution of Go's WebAssembly code. // Global returns the JavaScript global object, usually "window" or "global".
resolveCallbackPromise = makeValue(4) func Global() Value {
) return valueGlobal
}
var uint8Array = Global.Get("Uint8Array") var uint8Array = valueGlobal.Get("Uint8Array")
// ValueOf returns x as a JavaScript value. // ValueOf returns x as a JavaScript value.
func ValueOf(x interface{}) Value { func ValueOf(x interface{}) Value {
...@@ -65,7 +71,7 @@ func ValueOf(x interface{}) Value { ...@@ -65,7 +71,7 @@ func ValueOf(x interface{}) Value {
case Callback: case Callback:
return x.enqueueFn return x.enqueueFn
case nil: case nil:
return Null return valueNull
case bool: case bool:
return makeValue(boolVal(x)) return makeValue(boolVal(x))
case int: case int:
......
...@@ -12,7 +12,7 @@ import ( ...@@ -12,7 +12,7 @@ import (
"testing" "testing"
) )
var dummys = js.Global.Call("eval", `({ var dummys = js.Global().Call("eval", `({
someBool: true, someBool: true,
someString: "abc\u1234", someString: "abc\u1234",
someInt: 42, someInt: 42,
...@@ -90,16 +90,16 @@ func TestFloat(t *testing.T) { ...@@ -90,16 +90,16 @@ func TestFloat(t *testing.T) {
} }
func TestUndefined(t *testing.T) { func TestUndefined(t *testing.T) {
dummys.Set("test", js.Undefined) dummys.Set("test", js.Undefined())
if dummys == js.Undefined || dummys.Get("test") != js.Undefined || dummys.Get("xyz") != js.Undefined { if dummys == js.Undefined() || dummys.Get("test") != js.Undefined() || dummys.Get("xyz") != js.Undefined() {
t.Errorf("js.Undefined expected") t.Errorf("js.Undefined expected")
} }
} }
func TestNull(t *testing.T) { func TestNull(t *testing.T) {
dummys.Set("test1", nil) dummys.Set("test1", nil)
dummys.Set("test2", js.Null) dummys.Set("test2", js.Null())
if dummys == js.Null || dummys.Get("test1") != js.Null || dummys.Get("test2") != js.Null { if dummys == js.Null() || dummys.Get("test1") != js.Null() || dummys.Get("test2") != js.Null() {
t.Errorf("js.Null expected") t.Errorf("js.Null expected")
} }
} }
...@@ -128,7 +128,7 @@ func TestCall(t *testing.T) { ...@@ -128,7 +128,7 @@ func TestCall(t *testing.T) {
if got := dummys.Call("add", i, 2).Int(); got != 42 { if got := dummys.Call("add", i, 2).Int(); got != 42 {
t.Errorf("got %#v, want %#v", got, 42) t.Errorf("got %#v, want %#v", got, 42)
} }
if got := dummys.Call("add", js.Global.Call("eval", "40"), 2).Int(); got != 42 { if got := dummys.Call("add", js.Global().Call("eval", "40"), 2).Int(); got != 42 {
t.Errorf("got %#v, want %#v", got, 42) t.Errorf("got %#v, want %#v", got, 42)
} }
} }
...@@ -141,17 +141,17 @@ func TestInvoke(t *testing.T) { ...@@ -141,17 +141,17 @@ func TestInvoke(t *testing.T) {
} }
func TestNew(t *testing.T) { func TestNew(t *testing.T) {
if got := js.Global.Get("Array").New(42).Length(); got != 42 { if got := js.Global().Get("Array").New(42).Length(); got != 42 {
t.Errorf("got %#v, want %#v", got, 42) t.Errorf("got %#v, want %#v", got, 42)
} }
} }
func TestInstanceOf(t *testing.T) { func TestInstanceOf(t *testing.T) {
someArray := js.Global.Get("Array").New() someArray := js.Global().Get("Array").New()
if got, want := someArray.InstanceOf(js.Global.Get("Array")), true; got != want { if got, want := someArray.InstanceOf(js.Global().Get("Array")), true; got != want {
t.Errorf("got %#v, want %#v", got, want) t.Errorf("got %#v, want %#v", got, want)
} }
if got, want := someArray.InstanceOf(js.Global.Get("Function")), false; got != want { if got, want := someArray.InstanceOf(js.Global().Get("Function")), false; got != want {
t.Errorf("got %#v, want %#v", got, want) t.Errorf("got %#v, want %#v", got, want)
} }
} }
...@@ -165,7 +165,7 @@ func TestCallback(t *testing.T) { ...@@ -165,7 +165,7 @@ func TestCallback(t *testing.T) {
c <- struct{}{} c <- struct{}{}
}) })
defer cb.Close() defer cb.Close()
js.Global.Call("setTimeout", cb, 0, 42) js.Global().Call("setTimeout", cb, 0, 42)
<-c <-c
} }
...@@ -186,7 +186,7 @@ func TestEventCallback(t *testing.T) { ...@@ -186,7 +186,7 @@ func TestEventCallback(t *testing.T) {
}) })
defer cb.Close() defer cb.Close()
event := js.Global.Call("eval", fmt.Sprintf("({ called: false, %s: function() { this.called = true; } })", name)) event := js.Global().Call("eval", fmt.Sprintf("({ called: false, %s: function() { this.called = true; } })", name))
js.ValueOf(cb).Invoke(event) js.ValueOf(cb).Invoke(event)
if !event.Get("called").Bool() { if !event.Get("called").Bool() {
t.Errorf("%s not called", name) t.Errorf("%s not called", name)
...@@ -202,5 +202,5 @@ func ExampleNewCallback() { ...@@ -202,5 +202,5 @@ func ExampleNewCallback() {
fmt.Println("button clicked") fmt.Println("button clicked")
cb.Close() // close the callback if the button will not be clicked again cb.Close() // close the callback if the button will not be clicked again
}) })
js.Global.Get("document").Call("getElementById", "myButton").Call("addEventListener", "click", cb) js.Global().Get("document").Call("getElementById", "myButton").Call("addEventListener", "click", cb)
} }
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment