xūs

logic-less applications.

wercker status

introduction

xūs is the name of the simple templating languge, it's parser and the runtime library.

It brings the simplicity of mustache and the expressiveness of mobx-state-tree together, and makes laying out reactive user interfaces incredibly easy.

In combination with React and mobx, xūs can compile itself into an observer component tree, allowing it to get notified of the changes on the state and re-render the tree when it's necessary, as how it was structured in xūs in the first place.

A state can be a simple observable value, or a more sophisticated state definition like a mobx-state-tree.

getting started

An in-depth getting started guide can be found here: "Introducing xūs: A reactive template engine on top of mobx"

If you are curious why I’ve started this project and how this could play a role within a larger framework, take a look at "Templates, state trees, a school of ‘whatever’ and a state definition language".

install

With npm, or yarn, do:

npm install xus

You can also install the UMD bundle into the HTML with <script> tag:

<script src="//unpkg.com/xus/dist/xus.js"></script>

However, the prefered method is using browserify with the xusify transform which gives you pre-compiled render functions when you require() html files. For more information and examples, see xusify.

example

given this template:

<div>
  <p>You have completed <b>{completedCount}</b> of your tasks.</p>
  <ul>
    {#todos}
      <li class="{#done}finished{/done}" onClick="toggle">{title}</li>
    {/todos}
  </ul>
</div>

and this state definition:

import { types } from "mobx-state-tree"

const Todo = types.model("Todo", {
    title: types.string,
    done: false
}, {
    toggle() {
        this.done = !this.done
    }
})

const State = types.model("State", {
    todos: types.array(Todo),
    get completedCount() {
        return this.todos.reduce((count, todo) => (todo.done ? count + 1 : count), 0)
    }
})

create a new state:

const state = State.create({
  todos: [
    { title: "Get coffee", done: false },
    { title: "Wake up", done: true }
  ]
})

then produce a ReactElement with xus and render it using ReactDOM:

var options = {
  createElement: React.createElement,
  observer: mobxReact.observer
}

xus(template, state, options, function(er, newElement) {
  if (er) throw er

  ReactDOM.render(newElement, el)
})

See the full example here.

See also "Introducing xūs: A reactive template engine on top of mobx" for a detailed explanation of this example.

language

xūs supports mustache spec with the exception of lambdas and partials.

variables

template:

<h1>{name}</h1>

state:

{
  "name": "Paul Atreides"
}

output:

<h1>Paul Atreides</h1>

Note that, xūs does not recursively check the parent contexts if name key is not found.

sections

A section property can be an object, a boolean or an array that will be iterated.

template:

<ul>
  {#fruits}
  <li>
    {name}
    {#vitamins}
      <span>{name}</span>
    {/vitamins}
  </li>
  {/fruits}
</ul>

state:

{
  "fruits": [
    {
      "name": "Kiwi",
      "vitamins": [ { "name": "B-6" }, { "name": "C" } ]
    },
    {
      "name": "Mango"
    }
  ]
}

output:

<ul>
  <li>
    Kiwi
    <span>B-6</span>
    <span>C</span>
  </li>
  <li>
    Mango
  </li>
</ul>

inverted sections

Inverted sections may render text once based on the inverse value of the key. That is, they will be rendered if the key doesn't exist, is false, or is an empty list.

template:

<div>
  {^fruits}
    No fruits :(
  {/fruits}
</div>

state:

{
  "fruits": []
}

output:

<div>
  No fruits :(
</div>

comments

Comments begin with a bang and are ignored.

template:

<h1>Today{! ignore me }.</h1>

will render as follows:

<h1>Today.</h1>

Comments may contain newlines.

registry mechanism

You can pass in your own component factories in options.registry.

By default, xūs will assume your HTML tags are normal HTML tags unless they resolve to something else in the registry you provided.

example:

const state = { n: 1 }

function foo(props) {
    return <p className={ props.className }>
        <b>bold</b>
        { props.children }
    </p>
}

const optionsWithRegistry = {
    ...options,
    ...{
        registry: {
            foo: foo
        }
    }
}

xus("<foo class=bla><div>{n}</div></foo>", state, optionsWithRegistry, (err, res) => {
  if (err) throw err

  ReactDOM.render(res, el)
})

internals

import * as xus from "xus"

The main function that is exposed is called xus, and it's only good for creating React/mobx trees.

However, xūs does not ship with React, mobx-react and/or mobx-state-tree, and it can be rendered into a virtual tree (or just tree) of any kind, not necessarily into an observer component tree.

The following example shows how you can build a virtual-dom tree instead of React:

import { Template } from "xus/runtime"
const createElement = require("virtual-dom/create-element")

const tree = render.call(new Template, { n: 1, m: 2 })

// ... you should also move props.attributes to attributes in here, but you get the idea :)

const rootNode = createElement(tree)

xūs Templates are mainly just straight-forward render(state, options) methods and they can be extended very easily.

See the API Reference for more information.

typed

Installing xūs with npm brings with it type definitions for TypeScript as well.

streams

xūs can handle nodejs streams.

roadmap

See the Issues page for a list of known bugs and planned features.

index

Type aliases

CompileOptions

CompileOptions: LexerOptions

ObserverFactory

ObserverFactory: function

An ObserverFactory is a Function that turns a ReactComponent into a reactive ReactComponent, an example implementation on top of mobx is mobx-react.

Type declaration

    • (componentClass: ComponentClass<P> | StatelessComponent<P>): ReactElement<P>
    • Parameters

      • componentClass: ComponentClass<P> | StatelessComponent<P>

      Returns ReactElement<P>

TemplateContext

TemplateContext: function

A TemplateContext is a Function that has a local value of a ParseTree.

It will either instantiate a new Template or use the provided one in ctor parameter, and call Template.render method with this value.

Type declaration

    • (state: any, options: RenderOptions<U>, ctor?: TemplateConstructor<U>): U[]
    • Parameters

      • state: any
      • options: RenderOptions<U>
      • Optional ctor: TemplateConstructor<U>

      Returns U[]

Functions

compile

  • compile<T>(template: string, options?: CompileOptions, cb?: function): ReadableStream
  • Given a a xūs template as input, will produce rows of pre-compiled functions that can be evaluated for rendering and have the following structure:

    function render(state, options, constructor)

    You can pass a constructor to create an execution context at runtime, or use render.call() to bind an existing one.

    Type parameters

    • T

    Parameters

    • template: string

      xūs template string.

    • Optional options: CompileOptions
    • Optional cb: function

      If provided, the emitted rows are also passed to the callback function.

    Returns ReadableStream

parse

  • parse(): ReadWriteStream
  • Returns a duplex stream that takes rows of LexerTokens and produces rows of ParseTrees.

    Returns ReadWriteStream

render

  • Renders a TemplateContext into a ReactElement.

    If a tag name doesn't resolve to a ComponentClass in the provided options.registry, xūs will by default assume it is an ordinary HTML tag and wrap it in observer. If a ComponentClass is found instead, then it's up to the provider to make this an observer, or not.

    Type parameters

    • P

    Parameters

    Returns ReactElement<P>

tokenize

  • Given a a xūs template as input, will produce rows of LexerTokens.

    Parameters

    • Default value options: LexerOptions = { xmlMode: false }

      Override the symbol map and default matchers.

    Returns ReadWriteStream

xus

  • xus<P>(template: string, state: object, options: RenderOptions<P>, cb: function): ReadableStream
  • Turns a xūs template into a reactive component tree using React and mobx-react.

    Returns a ReactElement which then can be rendered into DOM with ReactDOM.render.

    Type parameters

    • P

    Parameters

    • template: string
    • state: object
      • [s: string]: any
    • options: RenderOptions<P>
    • cb: function
        • (error: Error, element?: ReactElement<P>, template?: string): void
        • Parameters

          • error: Error
          • Optional element: ReactElement<P>
          • Optional template: string

          Returns void

    Returns ReadableStream

legend

  • Module
  • Object literal
  • Variable
  • Function
  • Function with type parameter
  • Index signature
  • Type alias
  • Enumeration
  • Enumeration member
  • Property
  • Method
  • Interface
  • Interface with type parameter
  • Constructor
  • Property
  • Method
  • Index signature
  • Class
  • Class with type parameter
  • Constructor
  • Property
  • Method
  • Accessor
  • Index signature
  • Inherited constructor
  • Inherited property
  • Inherited method
  • Inherited accessor
  • Protected property
  • Protected method
  • Protected accessor
  • Private property
  • Private method
  • Private accessor
  • Static property
  • Static method

Generated with typedoc.