about summary refs log tree commit diff stats
path: root/src/js/console.nim
blob: 755910a594770282aefae761807c7a5a067c17e5 (plain) (blame)
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import io/dynstream
import monoucha/fromjs
import monoucha/javascript
import types/opt

type Console* = ref object
  err*: DynStream
  clearFun: proc()
  showFun: proc()
  hideFun: proc()

jsDestructor(Console)

proc newConsole*(err: DynStream; clearFun: proc() = nil; showFun: proc() = nil;
    hideFun: proc() = nil): Console =
  return Console(
    err: err,
    clearFun: clearFun,
    showFun: showFun,
    hideFun: hideFun
  )

proc log*(console: Console; ss: varargs[string]) =
  var buf = ""
  for i, s in ss:
    buf &= s
    if i != ss.high:
      buf &= ' '
  buf &= '\n'
  console.err.write(buf)

proc error*(console: Console; ss: varargs[string]) =
  console.log(ss)

proc log*(ctx: JSContext; console: Console; ss: varargs[JSValue]): Opt[void]
    {.jsfunc.} =
  var buf = ""
  for i, val in ss:
    var res: string
    ?ctx.fromJS(val, res)
    buf &= res
    if i != ss.high:
      buf &= ' '
  buf &= '\n'
  console.err.write(buf)
  ok()

proc clear(console: Console) {.jsfunc.} =
  if console.clearFun != nil:
    console.clearFun()

# For now, these are the same as log().
proc debug(ctx: JSContext; console: Console; ss: varargs[JSValue]): Opt[void]
    {.jsfunc.} =
  return log(ctx, console, ss)

proc error(ctx: JSContext; console: Console; ss: varargs[JSValue]): Opt[void]
    {.jsfunc.} =
  return log(ctx, console, ss)

proc info(ctx: JSContext; console: Console; ss: varargs[JSValue]): Opt[void]
    {.jsfunc.} =
  return log(ctx, console, ss)

proc warn(ctx: JSContext; console: Console; ss: varargs[JSValue]): Opt[void]
    {.jsfunc.} =
  return log(ctx, console, ss)

proc show(console: Console) {.jsfunc.} =
  if console.showFun != nil:
    console.showFun()

proc hide(console: Console) {.jsfunc.} =
  if console.hideFun != nil:
    console.hideFun()

proc addConsoleModule*(ctx: JSContext) =
  #TODO console should not have a prototype
  # "For historical reasons, console is lowercased."
  ctx.registerType(Console, nointerface = true, name = "console")

proc writeException*(ctx: JSContext; s: DynStream) =
  s.write(ctx.getExceptionMsg())
  s.sflush()