about summary refs log tree commit diff stats
path: root/src/js
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2024-05-05 22:06:52 +0200
committerbptato <nincsnevem662@gmail.com>2024-05-05 22:09:19 +0200
commita62a7077c32c456228f0e48151688151f75deac6 (patch)
tree4ccc7dadf566fde37ec27b4fd6730d243983189f /src/js
parentd9ab24c2f4555e9692d4c0d9794a1d3dd8417005 (diff)
downloadchawan-a62a7077c32c456228f0e48151688151f75deac6.tar.gz
color: separate out JS converters
ansi2html depends on color, but we definitely do not want to link it
to QJS, so the converters must be moved into a separate module.
Diffstat (limited to 'src/js')
-rw-r--r--src/js/jscolor.nim46
1 files changed, 46 insertions, 0 deletions
diff --git a/src/js/jscolor.nim b/src/js/jscolor.nim
new file mode 100644
index 00000000..48f7fb34
--- /dev/null
+++ b/src/js/jscolor.nim
@@ -0,0 +1,46 @@
+import std/strutils
+
+import bindings/quickjs
+import js/error
+import js/fromjs
+import js/javascript
+import js/tojs
+import types/color
+import utils/charcategory
+import utils/twtstr
+
+func parseLegacyColor*(s: string): JSResult[RGBColor] =
+  if s == "":
+    return err(newTypeError("Color value must not be the empty string"))
+  let s = s.strip(chars = AsciiWhitespace).toLowerAscii()
+  if s == "transparent":
+    return err(newTypeError("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 fromJSRGBColor*(ctx: JSContext; val: JSValue): JSResult[RGBColor] =
+  return parseLegacyColor(?fromJS[string](ctx, val))
+
+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 fromJSARGBColor*(ctx: JSContext; val: JSValue): JSResult[ARGBColor] =
+  if JS_IsNumber(val):
+    # as hex
+    return ok(ARGBColor(?fromJS[uint32](ctx, val)))
+  # parse
+  let x = parseARGBColor(?fromJS[string](ctx, val))
+  if x.isSome:
+    return ok(x.get)
+  return errTypeError("Unrecognized color")