Coder Social home page Coder Social logo

msx's Introduction

DEPRECATED

As of Mithril.js v1.0.0, you can use the react-transform-jsx Babel plugin for JSX.

See Mithril.js' JSX documentation for details.


MSX Build Status

MSX is based on version 0.13.2 of React's JSX Transformer

MSX tweaks React's JSX Transformer to output contents compatible with Mithril's m.render() function, allowing you to use HTML-like syntax in your Mithril view code, like this:

var todos = ctrl.list.map(function(task, index) {
  return <li className={task.completed() && 'completed'}>
    <div className="view">
      <input
        className="toggle"
        type="checkbox"
        onclick={m.withAttr('checked', task.completed)}
        checked={task.completed()}
      />
      <label>{task.title()}</label>
      <button className="destroy" onclick={ctrl.remove.bind(ctrl, index)}/>
    </div>
    <input className="edit"/>
  </li>
})

HTML tags and custom elements

For tag names which look like HTML elements or custom elements (lowercase, optionally containing hyphens), raw virtual DOM objects - matching the VirtualElement signature accepted by m.render() - will be generated by default.

Input:

<div id="example">
  <h1>Test</h1>
  <my-element name="test"/>
</div>

Output:

{tag: "div", attrs: {id:"example"}, children: [
  {tag: "h1", attrs: {}, children: ["Test"]},
  {tag: "my-element", attrs: {name:"test"}}
]}

This effectively precompiles your view code for a slight performance tweak.

Mithril components

Otherwise, it's assumed a tag name is a reference to an in-scope variable which is a Mithril component.

Passing attributes or children to a component will generate a call to Mithril's m.component() function, with children always being passed as an Array:

Input:

<form>
  {/* Bare component */}
  <Uploader/>
  {/* Component with attributes */}
  <Uploader onchange={ctrl.files}/>
  {/* Component with attributes and children */}
  <Uploader onchange={ctrl.files}>
    {ctrl.files().map(file => <File {...file}/>)}
  </Uploader>
  <button type="button" onclick={ctrl.save}>Upload</button>
</form>

Output:

{tag: "form", attrs: {}, children: [
  /* Bare component */
  Uploader,
  /* Component with attributes */
  m.component(Uploader, {onchange:ctrl.files}),
  /* Component with attributes and children */
  m.component(Uploader, {onchange:ctrl.files}, [
    ctrl.files().map(function(file)  {return m.component(File, Object.assign({},  file));})
  ]),
  {tag: "button", attrs: {type:"button", onclick:ctrl.save}, children: ["Upload"]}
]}

MSX assumes your component's (optional) controller() and (required) view() functions have the following signatures, where attributes is an Object and children is an Array:

controller([attributes[, children]])
view(ctrl[, attributes[, children]])

As such, if a component has children but no attributes, an empty attributes object will still be passed:

Input:

<Field>
  <input onchange={m.withAttr('value', ctrl.description)} value={ctrl.description()}/>
</Field>

Output:

m.component(Field, {}, [
  {tag: "input", attrs: {onchange:m.withAttr('value', ctrl.description), value:ctrl.description()}}
])

JSX spread attributes and Object.assign()

If you make use of JSX Spread Attributes, the resulting code will make use of Object.assign() to merge attributes - if your code needs to run in environments which don't implement Object.assign() natively, you're responsible for ensuring it's available via a shim, or otherwise.

Other than that, the rest of React's JSX documentation should still apply:

In-browser JSX Transform

For development and quick prototyping, an in-browser MSX transform is available.

Download or use it directly from cdn.rawgit.com:

Include a <script type="text/msx"> tag to engage the MSX transformer.

To enable ES6 transforms, use <script type="text/msx;harmony=true">. Check out the source of the live example of using in-browser JSX + ES6 transforms.

Here's a handy template you can use:

<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/0.2.0/mithril.js"></script>
<script src="https://cdn.rawgit.com/insin/msx/master/dist/MSXTransformer.js"></script>
<div id="app"></div>
<script type="text/msx;harmony=true">void function() { 'use strict';

var Hello = {
  controller() {
    this.who = m.prop('World')
  },

  view(ctrl) {
    return <h1>Hello {ctrl.who()}!</h1>
  }
}

m.mount(document.getElementById('app'), Hello)

}()</script>

Command Line Usage

npm install -g msx
msx --watch src/ build/

To disable precompilation from the command line, pass a --no-precompile flag.

Run msx --help for more information.

Module Usage

npm install msx
var msx = require('msx')

Module API

msx.transform(source: String[, options: Object])

Transforms XML-like syntax in the given source into object literals compatible with Mithril's m.render() function, or to function calls using Mithril's m() function, returning the transformed source.

To enable ES6 transforms supported by JSX Transformer, pass a harmony option:

msx.transform(source, {harmony: true})

To disable default precompilation and always output m() calls, pass a precompile option:

msx.transform(source, {precompile: false})

Examples

Example inputs (using some ES6 features) and outputs are in test/jsx and test/js, respectively.

An example gulpfile.js is provided, which implements an msxTransform() step using msx.transform().

Related Modules

MIT Licensed

msx's People

Contributors

insin avatar kolodny avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

msx's Issues

Components

Now that components have landed in Mithril (MithrilJS/mithril.js#413 seems to be the broadest related issue), how should MSX support them?

Will turning every unknown tag name into an m.component() call (or just the component name if it has no attributes or children) work? e.g.:

<Component/> → Component
<Component prop="value"/> → m.component(Component, {prop:'value'})
<Component prop="value">content</Component> → m.component(Component, {prop:'value'}, 'content')

Is there a JSX equivalent to this.props.children?

Hi,

I've switched from React to Mithril, and MSX has been really great. With JSX, you can invoke {this.props.children} to render child components that can be between an opening and closing tag.

<MyComponent>
    <MyHeader>{this.props.heading}</MyHeader>
    <SomeContent>
        <AnotherCustomComponent/>
        <AnotherComponent>
            <ReallyNestedNow/>
        </AnotherComponent>
    </SomeContent>
</MyComponent>

So how does it work?

SomeContent () {
    render () {
        <div>
            <header>
                <h4>Lorem Ipsum</h4>
            </header>
            {this.props.children} 
            // In this example, it would render every component inbetween the opening and closing <SomeContent> tag as seen above.
            <footer>Lalalalalal</footer>
        </div>
    }
}

This makes working with JSX very easy, especially when running into situations where it makes more sense to enclose a component this way.

I'm running into a sitaution with Mithril where I want to do this, but it is not working. Is there any alternative?

Thanks!!
Matt

absolute path for output

Perhaps I'm being really thick, when I try to specify the output directory as an absolute path it always ends up being a relative path in the pwd. Is this intended behaviour?

Rewrite support

Are there plans to support the new syntax introduced in mithril v1.x?

Rendering of false

In JSX one can use {myBoolean && <MyComponent />} for conditional rendering of a component. In MSX the false case renders as "false".

JSX behavior: https://jsfiddle.net/9creowqL/

It would be convenient to render false as the empty string, the way null and undefined are already rendered.

Would you accept a pull request if I put one together?

Optimizing use of the cache

Mithirl caches nodes created via the m() function, indexed by its first argument.

This is an example of a node that caches well:

m('a#google.external[href="http://google.com"]", 'Google'); 

If all those attributes, class, id and href were not part of the first argument, only an empty a node would be cached and the rest of the attributes would have to be assembled one by one, every time that the view is called.

MSX should be able to distinguish attributes that are constant:

<div class="panel-heading">

from those that are variable, that is, that get their value from an expression:

<span class={g.disabled()?'text-muted':''}>

The first should result in:

m('div.panel-heading')

The second in:

m('span',{class:g.disabled()?'text-muted':''})

This would greatly speed up the refresh process.

Upgrade to JSX Transformer 0.12

As of 0.12, the /* @jsx */ pragma comment is no longer required, among other things - would be worth updating to pick up that feature alone.

It doesn't look like the new {...soread} attributes feature will be usable, as it depends on everyone having an implementation of Object.assign/extend available, which would have to live on m.

How to use config callbacks?

How would i use config to call a fuction when an element is rendered?
Here's what i'm trying to achieve using m()

m("div, {
  config: function(element, isInitialized, context) {
    if (!isInitialized) doSomething(element)
  }
}

not support void tag,must be self-closed;

not support void tag

<img>
<input>
...

must be self-closed

<img />
<input />
...

void tag: /^(?:input|img|br|wbr|hr|area|base|col|embed|keygen|link|meta|param|source|track)$/

How to compile .html files?

If I have an html file

<div>sup</div>

How can I compile that into something I can then use in my .js file

Am I supposed to prepend all my compiled .html templates output into my main.js file?
And somehow use grult/gulp to prepend templates[filename] = before each compiled template?

svg foreignObject tag is not supported

I know that this library is wrapping the React JSX one and since react does not have foreignObject support this is expected. I would love it if we could add the foreignObject tag.

Add precompile

It would be awesome if MSX had the ability to precompile the templates.

Typescript JSX support

@insin just wanted to know if there is any idea if Typescript's upcoming (native support for JSX)[http://www.jbrantly.com/typescript-and-jsx/] will also support MSX?

It seems, from the article, that there are some things very specific to JSX/React going on, but since MSX is takes several things from JSX...I wasn't sure

missing comma in options

msx
C:\Users\kdar\AppData\Roaming\npm\node_modules\msx\bin\msx:50
    es6module: this.options.es6module,
    ^^^^^^^^^
SyntaxError: Unexpected identifier
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3```

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.