From 04779f85028c69574f79549387e4057af507dd5f Mon Sep 17 00:00:00 2001 From: Timothee Cour Date: Wed, 7 Oct 2020 03:23:16 -0700 Subject: [PATCH] add toCss: allows tdiv(style = "font-style: oblique; color: pink".toCss) (#158) * add toCss: allows tdiv(style = "font-style: oblique; color: pink".toCss) * fixup to work with nim c --- examples/hellostyle.nim | 17 +++++++++++++++++ karax/vstyles.nim | 24 +++++++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 examples/hellostyle.nim diff --git a/examples/hellostyle.nim b/examples/hellostyle.nim new file mode 100644 index 0000000..716c2f0 --- /dev/null +++ b/examples/hellostyle.nim @@ -0,0 +1,17 @@ +include karax / prelude +import karax / vstyles + +proc createDom(): VNode = + result = buildHtml(tdiv): + tdiv(style = style(StyleAttr.color, "red".cstring)): + text "red" + tdiv(style = style(StyleAttr.color, "blue")): + text "blue" + # explicit `kstring` required for varargs overload + tdiv(style = style((fontStyle, "italic".kstring), (color, "orange".kstring))): + text "italic orange" + # can use a string directly + tdiv(style = "font-style: oblique; color: pink".toCss): + text "oblique pink" + +setRenderer createDom diff --git a/karax/vstyles.nim b/karax/vstyles.nim index a5971a9..7097aee 100644 --- a/karax/vstyles.nim +++ b/karax/vstyles.nim @@ -1,5 +1,9 @@ +##[ +see examples/hellostyle.nim +]## -import macros, kbase +import std/[macros, strutils] +import kbase when defined(js): import kdom, jdict @@ -292,6 +296,24 @@ proc style*(a: StyleAttr; val: kstring): VStyle {.noSideEffect.} = result[] = @[] result.setAttr a, val +proc toCss*(a: string): VStyle = + ##[ + See example in hellostyle.nim + Allows passing a css string directly, eg: + tdiv(style = style((fontStyle, "italic".kstring), (color, "orange".kstring))): discard + tdiv(style = "font-style: oblique; color: pink".toCss): discard + ]## + when defined(js): + result = newJSeq[cstring]() + else: + new(result) + result[] = @[] + for ai in a.split(";"): + var ai = ai.strip + if ai.len == 0: continue + let aj = ai.strip.split(":", maxsplit=1) + result.setAttr(aj[0], aj[1]) + when defined(js): proc setStyle(d: Style; key, val: cstring) {.importcpp: "#[#] = #", noSideEffect.}