github.com/psilva261/sparkle@v0.0.0-20220717092738-fab67056f0bd/console/module.go (about)

     1  package console
     2  
     3  import (
     4  	"log"
     5  
     6  	"github.com/psilva261/sparkle/js"
     7  	"github.com/psilva261/sparkle/require"
     8  	_ "github.com/psilva261/sparkle/util"
     9  )
    10  
    11  type Console struct {
    12  	runtime *js.Runtime
    13  	util    *js.Object
    14  	printer Printer
    15  }
    16  
    17  type Printer interface {
    18  	Log(string)
    19  	Warn(string)
    20  	Error(string)
    21  }
    22  
    23  type PrinterFunc func(s string)
    24  
    25  func (p PrinterFunc) Log(s string) { p(s) }
    26  
    27  func (p PrinterFunc) Warn(s string) { p(s) }
    28  
    29  func (p PrinterFunc) Error(s string) { p(s) }
    30  
    31  var defaultPrinter Printer = PrinterFunc(func(s string) { log.Print(s) })
    32  
    33  func (c *Console) log(p func(string)) func(js.FunctionCall) js.Value {
    34  	return func(call js.FunctionCall) js.Value {
    35  		if format, ok := js.AssertFunction(c.util.Get("format")); ok {
    36  			ret, err := format(c.util, call.Arguments...)
    37  			if err != nil {
    38  				panic(err)
    39  			}
    40  
    41  			p(ret.String())
    42  		} else {
    43  			panic(c.runtime.NewTypeError("util.format is not a function"))
    44  		}
    45  
    46  		return nil
    47  	}
    48  }
    49  
    50  func Require(runtime *js.Runtime, module *js.Object) {
    51  	requireWithPrinter(defaultPrinter)(runtime, module)
    52  }
    53  
    54  func RequireWithPrinter(printer Printer) require.ModuleLoader {
    55  	return requireWithPrinter(printer)
    56  }
    57  
    58  func requireWithPrinter(printer Printer) require.ModuleLoader {
    59  	return func(runtime *js.Runtime, module *js.Object) {
    60  		c := &Console{
    61  			runtime: runtime,
    62  			printer: printer,
    63  		}
    64  
    65  		c.util = require.Require(runtime, "util").(*js.Object)
    66  
    67  		o := module.Get("exports").(*js.Object)
    68  		o.Set("log", c.log(c.printer.Log))
    69  		o.Set("error", c.log(c.printer.Error))
    70  		o.Set("warn", c.log(c.printer.Warn))
    71  	}
    72  }
    73  
    74  func Enable(runtime *js.Runtime) {
    75  	runtime.Set("console", require.Require(runtime, "console"))
    76  }
    77  
    78  func init() {
    79  	require.RegisterNativeModule("console", Require)
    80  }