about summary refs log tree commit diff stats
path: root/src/js/jscolor.nim
blob: fef9c8aaacaa8c380ded7ed62dee08ae291b9a38 (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
import std/strutils

import monoucha/fromjs
import monoucha/javascript
import monoucha/quickjs
import monoucha/tojs
import types/color
import types/opt
import utils/charcategory
import utils/twtstr

func parseLegacyColor*(s: string): Result[RGBColor, cstring] =
  if s == "":
    return err(cstring"color value must not be the empty string")
  let s = s.strip(chars = AsciiWhitespace).toLowerAscii()
  if s == "transparent":
    return err(cstring"color must not be transparent")
  return ok(parseLegacyColor0(s))

proc toJS*(ctx: JSContext; rgb: RGBColor): JSValue =
  var res = "#"
  res.pushHex(rgb.r)
  res.pushHex(rgb.g)
  res.pushHex(rgb.b)
  return toJS(ctx, res)

proc fromJS*(ctx: JSContext; val: JSValue; res: var RGBColor): Err[void] =
  var s: string
  ?ctx.fromJS(val, s)
  let x = parseLegacyColor(s)
  if x.isNone:
    JS_ThrowTypeError(ctx, x.error)
    return err()
  res = x.get
  return ok()

proc toJS*(ctx: JSContext; rgba: ARGBColor): JSValue =
  var res = "#"
  res.pushHex(rgba.r)
  res.pushHex(rgba.g)
  res.pushHex(rgba.b)
  res.pushHex(rgba.a)
  return toJS(ctx, res)

proc fromJS*(ctx: JSContext; val: JSValue; res: var ARGBColor): Err[void] =
  if JS_IsNumber(val):
    # as hex
    ?ctx.fromJS(val, uint32(res))
    return ok()
  # parse
  var s: string
  ?ctx.fromJS(val, s)
  if (let x = parseARGBColor(s); x.isSome):
    res = x.get
    return ok()
  JS_ThrowTypeError(ctx, "unrecognized color")
  return err()