No description
Find a file
Felipe S. S. Schneider f02971aced Improve buttons example
2021-07-04 22:39:29 -03:00
examples Improve buttons example 2021-07-04 22:39:29 -03:00
src Improve buttons example 2021-07-04 22:39:29 -03:00
tests Improve buttons example 2021-07-04 22:39:29 -03:00
.gitignore Begin project 2021-07-01 22:28:21 -03:00
hyperscript.nimble Support 1.2.6+ 2021-07-01 22:29:20 -03:00
LICENSE Initial commit 2021-07-01 22:26:34 -03:00
README.md Update README.md 2021-07-04 10:58:51 -03:00

hyperscript

A functional Nim library for combining DOM pieces, with compile-time superpowers. hyperscript creates composable HTML and SVG with Nim, both client- and server-side:

import hyperscript

let example =
  h("div#page",
    h("div#header",
      h("h1.classy", "h", { style: {"background-color": "#22f"} })),
    h("div#menu", { style: {"background-color": "#2f2"} },
      h("ul",
        h("li", "one"),
        h("li", "two"),
        h("li", "three"))),
      h("h2", "content title",  { style: {"background-color": "#f22"} }),
      h("p",
        "so it's just like a templating engine,\n",
        "but easy to use inline with Nim\n"),
      h("p",
        "the intention is for this to be used to create\n",
        "reusable, interactive HTML widgets. "))

(Currently, only literal arguments are supported, but this limitation will be removed in a future release, see #8 and #10.)

Installation

hyperscript works with Nim 1.2.6+ and can be installed using Nimble:

$ nimble install hyperscript

How does it work?

The basic design consists of compiling down to efficient calls to the DOM (through the dom standard library). As such, the following,

let example = h("p#example",
  h("input.name[value=Name]",
    style: {"background": "yellow"},
  ),
)

compiles roughly to

let example =
  let node = document.createElement("p")
  for attr in items([("id", "example")]):
    node.setAttribute(attr[0], attr[1])
  for child in items([
    let node = document.createElement("input")
    for attr in items([("value", "Name"), ("class", "name"), ("style", "background: yellow;")]):
      node.setAttribute(attr[0], attr[1])
    node]):
    node.appendChild(child)
  node

(We intend to unroll all loops in the future, see #6.)

When not compiling to JavaScript, XmlNode objects are generated using the xmltree standard library. Using the C backend, for instance, the example above compiles to

let example =
  newXmlTree("p", [
      newXmlTree("input", @[],
        {"value": "Name", "class": "name", "style": "background: yellow;"}.toXmlAttributes,
      ),
    ], {"id": "example"}.toXmlAttributes,
  )

Some references

Convert HTML snippets to hyperscript: