-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs_builtins.go
50 lines (42 loc) · 1.04 KB
/
js_builtins.go
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
// +build js
package hush
import (
"fmt"
"io/ioutil"
"strings"
"syscall/js"
"github.com/fatih/color"
"github.com/pkg/errors"
)
var (
jsFunction = js.Global().Get("Function")
)
func init() {
builtins["jseval"] = jseval
builtins["jsdownload"] = jsdownload
color.NoColor = false // override, since wasm isn't considered a "tty"
}
func jsEval(funcStr string, args ...interface{}) js.Value {
f := jsFunction.Invoke(`"use strict";` + funcStr)
return f.Invoke(args...)
}
func jseval(term console, args ...string) error {
if len(args) < 1 {
return errors.New("Must provide a string to run as a function")
}
result := jsEval(args[0], strings.Join(args[1:], " "))
fmt.Fprintln(term.Stdout(), result)
return nil
}
func jsdownload(term console, args ...string) error {
if len(args) < 1 {
return errors.New("Must provide a file to download")
}
filePath := args[0]
fileContents, err := ioutil.ReadFile(filePath)
if err != nil {
return errors.Wrap(err, "Error reading file for download")
}
startDownload("", filePath, fileContents)
return nil
}