defer imports
This commit is contained in:
parent
5445e5e0de
commit
72790df1eb
1 changed files with 48 additions and 23 deletions
33
d2js/js.go
33
d2js/js.go
|
|
@ -5,7 +5,9 @@ package main
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"io"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"syscall/js"
|
"syscall/js"
|
||||||
|
|
||||||
|
|
@ -133,20 +135,42 @@ type jsParseResponse struct {
|
||||||
D2Error string `json:"d2Error"`
|
D2Error string `json:"d2Error"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type blockFS struct{}
|
type emptyFile struct{}
|
||||||
|
|
||||||
func (blockFS blockFS) Open(name string) (fs.File, error) {
|
func (f *emptyFile) Stat() (os.FileInfo, error) {
|
||||||
return nil, errors.New("import statements not currently implemented")
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *emptyFile) Read(p []byte) (int, error) {
|
||||||
|
return 0, io.EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *emptyFile) Close() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type detectFS struct {
|
||||||
|
importUsed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (detectFS detectFS) Open(name string) (fs.File, error) {
|
||||||
|
detectFS.importUsed = true
|
||||||
|
return &emptyFile{}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func jsParse(this js.Value, args []js.Value) interface{} {
|
func jsParse(this js.Value, args []js.Value) interface{} {
|
||||||
dsl := args[0].String()
|
dsl := args[0].String()
|
||||||
themeID := args[1].Int()
|
themeID := args[1].Int()
|
||||||
|
|
||||||
|
detectFS := detectFS{}
|
||||||
|
|
||||||
g, err := d2compiler.Compile("", strings.NewReader(dsl), &d2compiler.CompileOptions{
|
g, err := d2compiler.Compile("", strings.NewReader(dsl), &d2compiler.CompileOptions{
|
||||||
UTF16: true,
|
UTF16: true,
|
||||||
FS: blockFS{},
|
FS: detectFS,
|
||||||
})
|
})
|
||||||
|
// If an import was used, client side D2 cannot reliably compile
|
||||||
|
// Defer to backend compilation
|
||||||
|
if !detectFS.importUsed {
|
||||||
var pe *d2parser.ParseError
|
var pe *d2parser.ParseError
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.As(err, &pe) {
|
if errors.As(err, &pe) {
|
||||||
|
|
@ -174,6 +198,7 @@ func jsParse(this js.Value, args []js.Value) interface{} {
|
||||||
str, _ := json.Marshal(ret)
|
str, _ := json.Marshal(ret)
|
||||||
return string(str)
|
return string(str)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
m, err := d2parser.Parse("", strings.NewReader(dsl), nil)
|
m, err := d2parser.Parse("", strings.NewReader(dsl), nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue