├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── cli.js ├── conv.js ├── examples └── todomvc │ ├── .gitignore │ ├── bower.json │ ├── index.html │ └── js │ ├── components │ ├── app.html │ ├── app.js │ ├── build │ │ ├── app.js │ │ ├── footer.js │ │ └── todoItem.js │ ├── footer.html │ ├── footer.js │ ├── index.html │ ├── todoItem.html │ └── todoItem.js │ ├── todoModel.js │ └── utils.js ├── lib ├── dom-utils.js ├── parser.js └── stringify.js ├── package.json └── test ├── index.js ├── js ├── menu.html ├── menu.js └── menu.jsx ├── stringify.html ├── stringify.js └── stringify.jsx /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | 3 | # Logs 4 | logs 5 | *.log 6 | 7 | # Runtime data 8 | pids 9 | *.pid 10 | *.seed 11 | 12 | # Directory for instrumented libs generated by jscoverage/JSCover 13 | lib-cov 14 | 15 | # Coverage directory used by tools like istanbul 16 | coverage 17 | 18 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 19 | .grunt 20 | 21 | # Compiled binary addons (http://nodejs.org/api/addons.html) 22 | build/Release 23 | 24 | # Dependency directory 25 | # Commenting this out is preferred by some people, see 26 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- 27 | node_modules 28 | 29 | # Users Environment Variables 30 | .lock-wscript 31 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "0.10" -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Sergii Kliuchnyk 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | React separate template 2 | ======================= 3 | 4 | [![Build Status](https://travis-ci.org/redexp/react-separate-template.png?branch=master)](http://travis-ci.org/redexp/react-separate-template) 5 | 6 | 1. [Solution description](#solution-description) 7 | 1. [@render](#render) 8 | 2. [jsx-tpl](#jsx-tpl) 9 | 3. [jsx-class](#jsx-class) 10 | 3. [jsx-instance](#jsx-instance) 11 | 2. [TodoMVC example](#todomvc-example) 12 | 3. [Installation](#installation) 13 | 4. [Usage from command line](#usage-from-command-line) 14 | 5. [Usage from code](#usage-from-code) 15 | 6. [Additional features](#additional-features) 16 | 7. [Gulp plugin](#gulp-plugin) 17 | 8. [Grunt plugin](#grunt-plugin) 18 | 19 | First problem of react is HTML inside our JS files and there is no way to make them separate. 20 | 21 | ## Solution description 22 | 23 | So I want to take out HTML from this class to separate file 24 | ```javascript 25 | var MenuExample = React.createClass({ 26 | getInitialState: function() { 27 | return {focused: 0}; 28 | }, 29 | clicked: function(index) { 30 | this.setState({focused: index}); 31 | }, 32 | render: function() { 33 | var self = this; 34 | 35 | return ( 36 |
37 | 48 | 49 |

Selected: {this.props.items[this.state.focused]}

50 |
51 | ); 52 | } 53 | }); 54 | ``` 55 | But if we just take out everything after `return` it's not what I want. I need absolutely clear HTML so I can write 56 | my CSS and see results without running whole app. I want to se template like this 57 | ```html 58 |
59 | 62 | 63 |

Selected: {this.props.items[this.state.focused]}

64 |
65 | ``` 66 | Okay, first of all we need to put `this.props.items.map(...)` in `ul`. I thought, annotation is good enough to make link 67 | to some function like this 68 | 69 | ### @render 70 | 71 | ```html 72 |
73 | 76 | 77 |

Selected: {this.props.items[this.state.focused]}

78 |
79 | ``` 80 | But where should be that `list` function? What if it will be right after our `return`, where was this template? 81 | ```javascript 82 | var MenuExample = React.createClass({ 83 | 84 | //... 85 | 86 | render: function() { 87 | var self = this; 88 | 89 | return { 90 | list: function () { 91 | this.props.items.map(function(m, index) { 92 | var style = ''; 93 | 94 | if (self.state.focused == index) { 95 | style = 'focused'; 96 | } 97 | 98 | return
  • {m}
  • ; 99 | }) 100 | } 101 | }; 102 | } 103 | }); 104 | ``` 105 | But wait, not that again, HTML in code, maybe we can take it out, but it should be in same template file. Maybe we will 106 | make some annotation which will be replaced with HTML (with some unique id) from our template? 107 | 108 | ### jsx-tpl 109 | 110 | ```javascript 111 | var MenuExample = React.createClass({ 112 | 113 | //... 114 | 115 | render: function() { 116 | var self = this; 117 | 118 | return { 119 | list: function () { 120 | this.props.items.map(function(m, index) { 121 | var style = ''; 122 | 123 | if (self.state.focused == index) { 124 | style = 'focused'; 125 | } 126 | 127 | return "@jsx-tpl item"; 128 | }) 129 | } 130 | }; 131 | } 132 | }); 133 | ``` 134 | Annotation not in comment because it is a value, not just some meta information. 135 | Lets call attribute with this unique id just like annotation. 136 | ```html 137 |
    138 | 142 | 143 |

    Selected: {this.props.items[this.state.focused]}

    144 |
    145 | ``` 146 | Lets say that all tags with attribute `jsx-tpl` will be detached from template and can be used only in classes to replace 147 | `@jsx-tpl` annotations. So basically they can be anywhere in template. 148 | 149 | ### jsx-class 150 | 151 | Last thing, what if we want many templates in one html file? Lets add `jsx-class` attribute with [displayName](http://facebook.github.io/react/docs/component-specs.html#displayname) value of 152 | react class to element in template to join them 153 | 154 | ```html 155 |
    156 | 160 | 161 |

    Selected: {this.props.items[this.state.focused]}

    162 |
    163 | 164 |
    165 | ... 166 |
    167 | ``` 168 | So we should add to our classes filed `displayName:` 169 | ```javascript 170 | var MenuExample = React.createClass({ 171 | displayName: 'Menu', 172 | //... 173 | render: function () { 174 | //... 175 | } 176 | }); 177 | 178 | var x = React.createClass({ 179 | displayName: 'SomeOtherComponent', 180 | //... 181 | render: function () { 182 | //... 183 | } 184 | }); 185 | ``` 186 | 187 | ### jsx-instance 188 | 189 | If you define `jsx-class` in another `jsx-class` or `jsx-tpl` then this definition will be replaced to the end of body, but what if you need instance of this class right in this place? Just add `jsx-instance="true"` to it. All attributes with curly brackets will be with instance. 190 | 191 | 192 | Example 193 | ```html 194 |
    195 | 200 |
    201 | ``` 202 | Will be converted to 203 | ```html 204 |
    205 | 208 |
    209 | 210 |
  • 211 |

    {user.name}

    212 |
  • 213 | ``` 214 | 215 | ## TodoMVC Example 216 | 217 | Here original implementation of [TodoMVC project on React](https://github.com/tastejs/todomvc/tree/gh-pages/examples/react) and here same project but with separated html [examples/todomvc](examples/todomvc). You can see that each component has it template. 218 | But wait, checkout one combined template [components/index.html](examples/todomvc/js/components/index.html) for all components. You can use it to compile all components. You can just open it and see how your app looks like without running js code. How cool is that? 219 | 220 | ## Installation 221 | 222 | `npm install react-st` 223 | 224 | ## Usage from command line 225 | 226 | Just run `react-st -j test/js/menu.js`. It will take file [test/js/menu.js](test/js/menu.js), join with [test/js/menu.html](test/js/menu.html) 227 | and save to [test/js/menu.jsx](test/js/menu.jsx) 228 | 229 | To see all options run `react-st -h` 230 | 231 | ## Usage from code 232 | 233 | Example 234 | ```javascript 235 | var convert = require('react-st'); 236 | 237 | convert(jsString, htmlString, function (err, jsxString) { 238 | // check err 239 | // save jsxString to file or whatever you want 240 | }); 241 | ``` 242 | 243 | ## Additional features 244 | 245 | * All `class` attributes will renamed to `className` 246 | * All `jsx-spread="someVar"` attributes will be converted to [Spread Attribute](http://facebook.github.io/react/docs/jsx-spread.html#spread-attributes) `{...someVar}` 247 | * I added syntax like this `class="item {style}"` and it will be converted to `className={"item " + style}`. Helpful for 248 | styling html without running js code 249 | 250 | ### Notice 251 | 252 | All attributes with curly brackets will be converted to react jsx version. If you will write something like this 253 | `data-bind="attr: {active: isActive}"` it will be converted to `data-bind={'attr: ' + active: isActive}`, so be careful. 254 | 255 | ## Gulp plugin 256 | 257 | See https://github.com/redexp/gulp-react-st 258 | 259 | ## Grunt plugin 260 | 261 | See https://github.com/TheWolfNL/grunt-react-separate-templates 262 | 263 | ## Contribute! 264 | 265 | I will be glad if you have any suggestions, just create an issue. 266 | -------------------------------------------------------------------------------- /cli.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | var fs = require('fs'), 3 | convert = require('./conv'), 4 | app = require('commander'), 5 | react = require('react-tools'); 6 | 7 | app 8 | .version('0.3.0') 9 | .usage('-j [options]') 10 | .option('-j, --js ', 'Input js file path') 11 | .option('-x, --html [path]', 'Input html file path, default is js file path but with .html extension') 12 | .option('-o, --out [path]', 'Output file path, default is js file path but with .jsx extension') 13 | .option('-r, --target [file|stdout]', 'Type of output: file (default) or stdout') 14 | .option('-t, --type [jsx|js]', 'Type of output file, default is jsx. If you will specify js then jsx code will be converted to js with react-tools') 15 | .parse(process.argv); 16 | 17 | var fileJs = app.js, 18 | fileHtml = app.html || fileJs.replace(/\.js$/, '.html'), 19 | fileJsx = app.out || fileJs.replace(/\.js$/, '.jsx'), 20 | js = fs.readFileSync(fileJs).toString(), 21 | html = fs.readFileSync(fileHtml).toString(); 22 | 23 | convert(js, html, function (err, jsx) { 24 | if (err) { 25 | throw err; 26 | } 27 | 28 | if (app.type === 'js') { 29 | jsx = react.transform(jsx); 30 | } 31 | 32 | if (app.target === 'stdout') { 33 | console.log(jsx); 34 | } 35 | else { 36 | fs.writeFileSync(fileJsx, jsx); 37 | } 38 | }); -------------------------------------------------------------------------------- /conv.js: -------------------------------------------------------------------------------- 1 | var toDom = require('./lib/parser'), 2 | dom = require('./lib/dom-utils'), 3 | q = require('simple-object-query'), 4 | find = q.find, 5 | replace = q.replace, 6 | where = q.where, 7 | toHtml = require('./lib/stringify'), 8 | gen = require('escodegen'), 9 | toAst = require('esprima').parse, 10 | extend = require('node.extend'); 11 | 12 | module.exports = convert; 13 | 14 | var tplAttr = 'jsx-tpl', 15 | classAttr = 'jsx-class', 16 | instanceAttr = 'jsx-instance', 17 | renderAnnotation = /^\s*@render\s+([\w\-\$]+)/, 18 | renderAnnotationCommentSelector = { 19 | type: 'comment', 20 | data: renderAnnotation 21 | }, 22 | tplAnnotation = /^\s*@jsx\-tpl\s+([\w\-\$]+)/, 23 | tplAnnotationSelector = { 24 | "type": "Literal", 25 | "value": tplAnnotation 26 | }, 27 | classSelectors = [ 28 | { 29 | selector: { 30 | 'id.type': 'Identifier', 31 | 'init.callee.object.name': 'React', 32 | 'init.callee.property.name': 'createClass' 33 | }, 34 | map: function (item) { 35 | return { 36 | name: item.id.name, 37 | body: item.init 38 | } 39 | } 40 | }, 41 | { 42 | selector: { 43 | 'key.type': 'Identifier', 44 | 'value.callee.object.name': 'React', 45 | 'value.callee.property.name': 'createClass' 46 | }, 47 | map: function (item) { 48 | return { 49 | name: item.key.name, 50 | body: item.value 51 | } 52 | } 53 | }, 54 | { 55 | selector: { 56 | 'left.type': 'MemberExpression', 57 | 'right.callee.object.name': 'React', 58 | 'right.callee.property.name': 'createClass' 59 | }, 60 | map: function (item) { 61 | return { 62 | name: item.left.object.name + '.' + item.left.property.name, 63 | body: item.right 64 | } 65 | } 66 | } 67 | ], 68 | renderReturnSelector = [ 69 | { 70 | 'key.name': 'render' 71 | }, 72 | 'value.body.body', 73 | q.flatten, 74 | { 75 | 'type': 'ReturnStatement' 76 | } 77 | ], 78 | startWithReturn = /^\s*return\s+/, 79 | endWithSemicolon = /\s*;\s*$/; 80 | 81 | function convert(js, html, callback) { 82 | js = toAst(js); 83 | 84 | var body = toDom(html); 85 | 86 | var htmlClasses = {}; 87 | 88 | var classes = dom.findNodesByAttr(body, classAttr); 89 | classes.forEach(function (item) { 90 | htmlClasses[item.attr[classAttr]] = item; 91 | 92 | if (item.attr[instanceAttr] === 'true') { 93 | delete item.attr[instanceAttr]; 94 | 95 | var newNode = dom.replaceWith(item, { 96 | type: 'tag', 97 | name: item.attr[classAttr], 98 | attr: clone(item.attr), 99 | children: [], 100 | unary: true 101 | }); 102 | 103 | delete newNode.attr[classAttr]; 104 | delete newNode.attr['className']; 105 | delete item.attr[tplAttr]; 106 | 107 | for (var attr in item.attr) { 108 | if (!has(item.attr, attr)) continue; 109 | 110 | delete item.attr[attr]; 111 | } 112 | } 113 | else { 114 | dom.removeNode(item); 115 | } 116 | 117 | dom.appendTo(body, item); 118 | 119 | delete item.attr[classAttr]; 120 | }); 121 | 122 | var tplNodeList = dom.findNodesByAttr(body, tplAttr); 123 | 124 | var htmlTemplates = {}; 125 | tplNodeList.forEach(function (node) { 126 | var name = node.attr[tplAttr]; 127 | delete node.attr[tplAttr]; 128 | 129 | htmlTemplates[name] = toHtml(node); 130 | }); 131 | 132 | dom.removeNodes(tplNodeList); 133 | 134 | try { 135 | replace(js, tplAnnotationSelector, function (tpl) { 136 | var name = tpl.value.match(tplAnnotation)[1]; 137 | if (!htmlTemplates[name]) { 138 | throw new Error('HTML template for jsx-tpl "'+ name +'" not found'); 139 | } 140 | return verbatimLiteral(htmlTemplates[name]); 141 | }); 142 | } 143 | catch (e) { 144 | return callback(e, null); 145 | } 146 | 147 | var reactClasses = classSelectors.map(function (item) { 148 | return find(js, item.selector).map(item.map); 149 | }); 150 | 151 | reactClasses = Array.prototype.concat.apply([], reactClasses); 152 | 153 | try { 154 | reactClasses.forEach(function(reactClass) { 155 | var name = reactClass.name, 156 | _return = where(reactClass.body.arguments[0].properties, renderReturnSelector); 157 | 158 | if (!name || _return.length === 0) return; 159 | 160 | _return = _return[0]; 161 | 162 | var htmlDom = htmlClasses[name]; 163 | 164 | if (!htmlDom) return; 165 | 166 | var returnProps = {}; 167 | 168 | if (_return.argument && _return.argument.type === 'ObjectExpression') { 169 | _return.argument.properties.forEach(function(prop) { 170 | var name = prop.key.name, 171 | body = prop.value.body; 172 | 173 | returnProps[name] = body.body; 174 | }); 175 | } 176 | 177 | replace({ 178 | source: htmlDom, 179 | query: renderAnnotationCommentSelector, 180 | exclude: ['parent', 'next', 'prev'], 181 | callback: function(comment) { 182 | var name = comment.data.match(renderAnnotation)[1]; 183 | 184 | if (!returnProps[name]) { 185 | throw new Error('Render return function "' + name + '" for class ' + reactClass.name + ' not found'); 186 | } 187 | 188 | var data = toJs({type: 'Program', body: returnProps[name]}) 189 | .replace(startWithReturn, '') 190 | .replace(endWithSemicolon, ''); 191 | 192 | return { 193 | type: 'verbatim', 194 | data: '{' + data + '}' 195 | }; 196 | } 197 | }); 198 | 199 | _return.argument = verbatimLiteral(toHtml(htmlDom)); 200 | }); 201 | } 202 | catch (e) { 203 | return callback(e, null); 204 | } 205 | 206 | callback(null, toJs(js)); 207 | } 208 | 209 | function toJs(ast) { 210 | return gen.generate(ast, {verbatim: 'x-verbatim-property'}); 211 | } 212 | 213 | function has(obj, field) { 214 | return Object.prototype.hasOwnProperty.call(obj, field); 215 | } 216 | 217 | function clone(obj) { 218 | return extend(true, Array.isArray(obj) ? [] : {}, obj); 219 | } 220 | 221 | function verbatimLiteral(str) { 222 | return { 223 | type: 'Literal', 224 | value: 0, 225 | 'x-verbatim-property': { 226 | content: str, 227 | precedence : gen.Precedence.Primary 228 | } 229 | } 230 | } -------------------------------------------------------------------------------- /examples/todomvc/.gitignore: -------------------------------------------------------------------------------- 1 | bower_components -------------------------------------------------------------------------------- /examples/todomvc/bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "todomvc-react", 3 | "version": "0.0.0", 4 | "dependencies": { 5 | "todomvc-common": "~0.3.0", 6 | "director": "~1.2.0", 7 | "react": "~0.12.0" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /examples/todomvc/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | React • TodoMVC 6 | 7 | 8 | 9 |
    10 |
    11 |

    Double-click to edit a todo

    12 |

    Created by petehunt

    13 |

    Part of TodoMVC

    14 |
    15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /examples/todomvc/js/components/app.html: -------------------------------------------------------------------------------- 1 |
    2 | 10 | 11 |
    12 | 16 | 17 |
      18 | {todoItems} 19 |
    20 |
    21 | 22 | 23 |
    -------------------------------------------------------------------------------- /examples/todomvc/js/components/app.js: -------------------------------------------------------------------------------- 1 | /*jshint quotmark:false */ 2 | /*jshint white:false */ 3 | /*jshint trailing:false */ 4 | /*jshint newcap:false */ 5 | /*global React, Router*/ 6 | var app = app || {}; 7 | 8 | (function () { 9 | 'use strict'; 10 | 11 | app.ALL_TODOS = 'all'; 12 | app.ACTIVE_TODOS = 'active'; 13 | app.COMPLETED_TODOS = 'completed'; 14 | var TodoFooter = app.TodoFooter; 15 | var TodoItem = app.TodoItem; 16 | 17 | var ENTER_KEY = 13; 18 | 19 | var TodoApp = React.createClass({ 20 | displayName: 'TodoApp', 21 | 22 | getInitialState: function () { 23 | return { 24 | nowShowing: app.ALL_TODOS, 25 | editing: null 26 | }; 27 | }, 28 | 29 | componentDidMount: function () { 30 | var setState = this.setState; 31 | var router = Router({ 32 | '/': setState.bind(this, {nowShowing: app.ALL_TODOS}), 33 | '/active': setState.bind(this, {nowShowing: app.ACTIVE_TODOS}), 34 | '/completed': setState.bind(this, {nowShowing: app.COMPLETED_TODOS}) 35 | }); 36 | router.init('/'); 37 | }, 38 | 39 | handleNewTodoKeyDown: function (event) { 40 | if (event.which !== ENTER_KEY) { 41 | return; 42 | } 43 | 44 | event.preventDefault(); 45 | 46 | var val = this.refs.newField.getDOMNode().value.trim(); 47 | 48 | if (val) { 49 | this.props.model.addTodo(val); 50 | this.refs.newField.getDOMNode().value = ''; 51 | } 52 | }, 53 | 54 | toggleAll: function (event) { 55 | var checked = event.target.checked; 56 | this.props.model.toggleAll(checked); 57 | }, 58 | 59 | toggle: function (todoToToggle) { 60 | this.props.model.toggle(todoToToggle); 61 | }, 62 | 63 | destroy: function (todo) { 64 | this.props.model.destroy(todo); 65 | }, 66 | 67 | edit: function (todo, callback) { 68 | // refer to todoItem.js `handleEdit` for the reasoning behind the 69 | // callback 70 | this.setState({editing: todo.id}, function () { 71 | callback(); 72 | }); 73 | }, 74 | 75 | save: function (todoToSave, text) { 76 | this.props.model.save(todoToSave, text); 77 | this.setState({editing: null}); 78 | }, 79 | 80 | cancel: function () { 81 | this.setState({editing: null}); 82 | }, 83 | 84 | clearCompleted: function () { 85 | this.props.model.clearCompleted(); 86 | }, 87 | 88 | render: function () { 89 | var footer; 90 | var main; 91 | var todos = this.props.model.todos; 92 | var cx = React.addons.classSet; 93 | 94 | var shownTodos = todos.filter(function (todo) { 95 | switch (this.state.nowShowing) { 96 | case app.ACTIVE_TODOS: 97 | return !todo.completed; 98 | case app.COMPLETED_TODOS: 99 | return todo.completed; 100 | default: 101 | return true; 102 | } 103 | }, this); 104 | 105 | var todoItems = shownTodos.map(function (todo) { 106 | return React.createElement(TodoItem, { 107 | key: todo.id, 108 | todo: todo, 109 | onToggle: this.toggle.bind(this, todo), 110 | onDestroy: this.destroy.bind(this, todo), 111 | onEdit: this.edit.bind(this, todo), 112 | editing: this.state.editing === todo.id, 113 | onSave: this.save.bind(this, todo), 114 | onCancel: this.cancel 115 | }); 116 | }, this); 117 | 118 | var activeTodoCount = todos.reduce(function (accum, todo) { 119 | return todo.completed ? accum : accum + 1; 120 | }, 0); 121 | 122 | var completedCount = todos.length - activeTodoCount; 123 | 124 | if (activeTodoCount || completedCount) { 125 | footer = React.createElement(TodoFooter, { 126 | count: activeTodoCount, 127 | completedCount: completedCount, 128 | nowShowing: this.state.nowShowing, 129 | onClearCompleted: this.clearCompleted 130 | }); 131 | } 132 | 133 | return { 134 | todoItems: function () { 135 | return todoItems; 136 | }, 137 | footer: function () { 138 | return footer; 139 | } 140 | }; 141 | } 142 | }); 143 | 144 | var model = new app.TodoModel('react-todos'); 145 | 146 | function render() { 147 | React.render( 148 | React.createElement(TodoApp, {model: model}), 149 | document.getElementById('todoapp') 150 | ); 151 | } 152 | 153 | model.subscribe(render); 154 | render(); 155 | })(); 156 | -------------------------------------------------------------------------------- /examples/todomvc/js/components/build/app.js: -------------------------------------------------------------------------------- 1 | /*jshint quotmark:false */ 2 | /*jshint white:false */ 3 | /*jshint trailing:false */ 4 | /*jshint newcap:false */ 5 | /*global React, Router*/ 6 | var app = app || {}; 7 | 8 | (function () { 9 | 'use strict'; 10 | 11 | app.ALL_TODOS = 'all'; 12 | app.ACTIVE_TODOS = 'active'; 13 | app.COMPLETED_TODOS = 'completed'; 14 | var TodoFooter = app.TodoFooter; 15 | var TodoItem = app.TodoItem; 16 | 17 | var ENTER_KEY = 13; 18 | 19 | var TodoApp = React.createClass({ 20 | displayName: 'TodoApp', 21 | 22 | getInitialState: function () { 23 | return { 24 | nowShowing: app.ALL_TODOS, 25 | editing: null 26 | }; 27 | }, 28 | 29 | componentDidMount: function () { 30 | var setState = this.setState; 31 | var router = Router({ 32 | '/': setState.bind(this, {nowShowing: app.ALL_TODOS}), 33 | '/active': setState.bind(this, {nowShowing: app.ACTIVE_TODOS}), 34 | '/completed': setState.bind(this, {nowShowing: app.COMPLETED_TODOS}) 35 | }); 36 | router.init('/'); 37 | }, 38 | 39 | handleNewTodoKeyDown: function (event) { 40 | if (event.which !== ENTER_KEY) { 41 | return; 42 | } 43 | 44 | event.preventDefault(); 45 | 46 | var val = this.refs.newField.getDOMNode().value.trim(); 47 | 48 | if (val) { 49 | this.props.model.addTodo(val); 50 | this.refs.newField.getDOMNode().value = ''; 51 | } 52 | }, 53 | 54 | toggleAll: function (event) { 55 | var checked = event.target.checked; 56 | this.props.model.toggleAll(checked); 57 | }, 58 | 59 | toggle: function (todoToToggle) { 60 | this.props.model.toggle(todoToToggle); 61 | }, 62 | 63 | destroy: function (todo) { 64 | this.props.model.destroy(todo); 65 | }, 66 | 67 | edit: function (todo, callback) { 68 | // refer to todoItem.js `handleEdit` for the reasoning behind the 69 | // callback 70 | this.setState({editing: todo.id}, function () { 71 | callback(); 72 | }); 73 | }, 74 | 75 | save: function (todoToSave, text) { 76 | this.props.model.save(todoToSave, text); 77 | this.setState({editing: null}); 78 | }, 79 | 80 | cancel: function () { 81 | this.setState({editing: null}); 82 | }, 83 | 84 | clearCompleted: function () { 85 | this.props.model.clearCompleted(); 86 | }, 87 | 88 | render: function () { 89 | var footer; 90 | var main; 91 | var todos = this.props.model.todos; 92 | var cx = React.addons.classSet; 93 | 94 | var shownTodos = todos.filter(function (todo) { 95 | switch (this.state.nowShowing) { 96 | case app.ACTIVE_TODOS: 97 | return !todo.completed; 98 | case app.COMPLETED_TODOS: 99 | return todo.completed; 100 | default: 101 | return true; 102 | } 103 | }, this); 104 | 105 | var todoItems = shownTodos.map(function (todo) { 106 | return React.createElement(TodoItem, { 107 | key: todo.id, 108 | todo: todo, 109 | onToggle: this.toggle.bind(this, todo), 110 | onDestroy: this.destroy.bind(this, todo), 111 | onEdit: this.edit.bind(this, todo), 112 | editing: this.state.editing === todo.id, 113 | onSave: this.save.bind(this, todo), 114 | onCancel: this.cancel 115 | }); 116 | }, this); 117 | 118 | var activeTodoCount = todos.reduce(function (accum, todo) { 119 | return todo.completed ? accum : accum + 1; 120 | }, 0); 121 | 122 | var completedCount = todos.length - activeTodoCount; 123 | 124 | if (activeTodoCount || completedCount) { 125 | footer = React.createElement(TodoFooter, { 126 | count: activeTodoCount, 127 | completedCount: completedCount, 128 | nowShowing: this.state.nowShowing, 129 | onClearCompleted: this.clearCompleted 130 | }); 131 | } 132 | 133 | return React.createElement("div", null, 134 | React.createElement("header", {id: "header"}, 135 | React.createElement("h1", null, "todos"), 136 | React.createElement("input", {ref: "newField", id: "new-todo", placeholder: "What needs to be done?", onKeyDown: this.handleNewTodoKeyDown, autoFocus: true}) 137 | ), 138 | 139 | React.createElement("section", {id: "main", className: cx({hidden: todos.length === 0})}, 140 | React.createElement("input", {id: "toggle-all", type: "checkbox", onChange: this.toggleAll, checked: activeTodoCount === 0}), 141 | 142 | React.createElement("ul", {id: "todo-list"}, 143 | todoItems 144 | 145 | 146 | ) 147 | ), 148 | 149 | footer 150 | 151 | 152 | ); 153 | } 154 | }); 155 | 156 | var model = new app.TodoModel('react-todos'); 157 | 158 | function render() { 159 | React.render( 160 | React.createElement(TodoApp, {model: model}), 161 | document.getElementById('todoapp') 162 | ); 163 | } 164 | 165 | model.subscribe(render); 166 | render(); 167 | })(); 168 | -------------------------------------------------------------------------------- /examples/todomvc/js/components/build/footer.js: -------------------------------------------------------------------------------- 1 | /*jshint quotmark:false */ 2 | /*jshint white:false */ 3 | /*jshint trailing:false */ 4 | /*jshint newcap:false */ 5 | /*global React */ 6 | var app = app || {}; 7 | 8 | (function () { 9 | 'use strict'; 10 | 11 | app.TodoFooter = React.createClass({ 12 | displayName: 'TodoFooter', 13 | render: function () { 14 | var activeTodoWord = app.Utils.pluralize(this.props.count, 'item'); 15 | var clearButton = null; 16 | 17 | if (this.props.completedCount > 0) { 18 | clearButton = React.createElement("button", {id: "clear-completed", onClick: this.props.onClearCompleted}, 19 | "Clear completed (", this.props.completedCount, ")" 20 | ); 21 | } 22 | 23 | // React idiom for shortcutting to `classSet` since it'll be used often 24 | var cx = React.addons.classSet; 25 | var nowShowing = this.props.nowShowing; 26 | 27 | return React.createElement("footer", {id: "footer"}, 28 | React.createElement("span", {id: "todo-count"}, 29 | React.createElement("strong", null, this.props.count), " ", activeTodoWord, " left" 30 | ), 31 | React.createElement("ul", {id: "filters"}, 32 | React.createElement("li", null, 33 | React.createElement("a", {href: "#/", className: cx({selected: nowShowing=== app.ALL_TODOS})}, 34 | "All" 35 | ) 36 | ), 37 | ' ', 38 | React.createElement("li", null, 39 | React.createElement("a", {href: "#/active", className: cx({selected: nowShowing=== app.ACTIVE_TODOS})}, 40 | "Active" 41 | ) 42 | ), 43 | ' ', 44 | React.createElement("li", null, 45 | React.createElement("a", {href: "#/completed", className: cx({selected: nowShowing=== app.COMPLETED_TODOS})}, 46 | "Completed" 47 | ) 48 | ) 49 | ), 50 | 51 | clearButton 52 | 53 | 54 | ); 55 | } 56 | }); 57 | })(); 58 | -------------------------------------------------------------------------------- /examples/todomvc/js/components/build/todoItem.js: -------------------------------------------------------------------------------- 1 | /*jshint quotmark: false */ 2 | /*jshint white: false */ 3 | /*jshint trailing: false */ 4 | /*jshint newcap: false */ 5 | /*global React */ 6 | var app = app || {}; 7 | 8 | (function () { 9 | 'use strict'; 10 | 11 | var ESCAPE_KEY = 27; 12 | var ENTER_KEY = 13; 13 | 14 | app.TodoItem = React.createClass({ 15 | displayName: 'TodoItem', 16 | handleSubmit: function (event) { 17 | var val = this.state.editText.trim(); 18 | if (val) { 19 | this.props.onSave(val); 20 | this.setState({editText: val}); 21 | } else { 22 | this.props.onDestroy(); 23 | } 24 | }, 25 | 26 | handleEdit: function () { 27 | // react optimizes renders by batching them. This means you can't call 28 | // parent's `onEdit` (which in this case triggeres a re-render), and 29 | // immediately manipulate the DOM as if the rendering's over. Put it as a 30 | // callback. Refer to app.jsx' `edit` method 31 | this.props.onEdit(function () { 32 | var node = this.refs.editField.getDOMNode(); 33 | node.focus(); 34 | node.setSelectionRange(node.value.length, node.value.length); 35 | }.bind(this)); 36 | this.setState({editText: this.props.todo.title}); 37 | }, 38 | 39 | handleKeyDown: function (event) { 40 | if (event.which === ESCAPE_KEY) { 41 | this.setState({editText: this.props.todo.title}); 42 | this.props.onCancel(event); 43 | } else if (event.which === ENTER_KEY) { 44 | this.handleSubmit(event); 45 | } 46 | }, 47 | 48 | handleChange: function (event) { 49 | this.setState({editText: event.target.value}); 50 | }, 51 | 52 | getInitialState: function () { 53 | return {editText: this.props.todo.title}; 54 | }, 55 | 56 | /** 57 | * This is a completely optional performance enhancement that you can 58 | * implement on any React component. If you were to delete this method 59 | * the app would still work correctly (and still be very performant!), we 60 | * just use it as an example of how little code it takes to get an order 61 | * of magnitude performance improvement. 62 | */ 63 | shouldComponentUpdate: function (nextProps, nextState) { 64 | return ( 65 | nextProps.todo !== this.props.todo || 66 | nextProps.editing !== this.props.editing || 67 | nextState.editText !== this.state.editText 68 | ); 69 | }, 70 | 71 | render: function () { 72 | var classes = React.addons.classSet({ 73 | completed: this.props.todo.completed, 74 | editing: this.props.editing 75 | }); 76 | 77 | return React.createElement("li", {className: classes}, 78 | React.createElement("div", {className: "view"}, 79 | React.createElement("input", {type: "checkbox", checked: this.props.todo.completed, onChange: this.props.onToggle, className: "toggle"}), 80 | 81 | React.createElement("label", {onDoubleClick: this.handleEdit}, 82 | this.props.todo.title 83 | ), 84 | 85 | React.createElement("button", {onClick: this.props.onDestroy, className: "destroy"}) 86 | ), 87 | 88 | React.createElement("input", {ref: "editField", value: this.state.editText, onBlur: this.handleSubmit, onChange: this.handleChange, onKeyDown: this.handleKeyDown, className: "edit"}) 89 | ); 90 | } 91 | }); 92 | })(); 93 | -------------------------------------------------------------------------------- /examples/todomvc/js/components/footer.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/todomvc/js/components/footer.js: -------------------------------------------------------------------------------- 1 | /*jshint quotmark:false */ 2 | /*jshint white:false */ 3 | /*jshint trailing:false */ 4 | /*jshint newcap:false */ 5 | /*global React */ 6 | var app = app || {}; 7 | 8 | (function () { 9 | 'use strict'; 10 | 11 | app.TodoFooter = React.createClass({ 12 | displayName: 'TodoFooter', 13 | render: function () { 14 | var activeTodoWord = app.Utils.pluralize(this.props.count, 'item'); 15 | var clearButton = null; 16 | 17 | if (this.props.completedCount > 0) { 18 | clearButton = "@jsx-tpl clear-completed"; 19 | } 20 | 21 | // React idiom for shortcutting to `classSet` since it'll be used often 22 | var cx = React.addons.classSet; 23 | var nowShowing = this.props.nowShowing; 24 | 25 | return { 26 | clearButton: function () { 27 | return clearButton; 28 | }, 29 | space: function () { 30 | return ' '; 31 | } 32 | }; 33 | } 34 | }); 35 | })(); 36 | -------------------------------------------------------------------------------- /examples/todomvc/js/components/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | React • TodoMVC 6 | 7 | 8 | 9 | 10 |
    11 |
    12 | 20 | 21 |
    22 | 26 | 27 |
      28 | 29 | 30 |
    • 31 |
      32 | 36 | 37 | 38 | 39 |
      41 | 42 | 48 |
    • 49 |
    50 |
    51 | 52 | 53 | 54 | 86 |
    87 |
    88 | 89 |
    90 |

    Double-click to edit a todo

    91 |

    Created by petehunt

    92 |

    Part of TodoMVC

    93 |
    94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /examples/todomvc/js/components/todoItem.html: -------------------------------------------------------------------------------- 1 |
  • 2 |
    3 | 7 | 8 | 11 | 12 |
    14 | 15 | 21 |
  • -------------------------------------------------------------------------------- /examples/todomvc/js/components/todoItem.js: -------------------------------------------------------------------------------- 1 | /*jshint quotmark: false */ 2 | /*jshint white: false */ 3 | /*jshint trailing: false */ 4 | /*jshint newcap: false */ 5 | /*global React */ 6 | var app = app || {}; 7 | 8 | (function () { 9 | 'use strict'; 10 | 11 | var ESCAPE_KEY = 27; 12 | var ENTER_KEY = 13; 13 | 14 | app.TodoItem = React.createClass({ 15 | displayName: 'TodoItem', 16 | handleSubmit: function (event) { 17 | var val = this.state.editText.trim(); 18 | if (val) { 19 | this.props.onSave(val); 20 | this.setState({editText: val}); 21 | } else { 22 | this.props.onDestroy(); 23 | } 24 | }, 25 | 26 | handleEdit: function () { 27 | // react optimizes renders by batching them. This means you can't call 28 | // parent's `onEdit` (which in this case triggeres a re-render), and 29 | // immediately manipulate the DOM as if the rendering's over. Put it as a 30 | // callback. Refer to app.jsx' `edit` method 31 | this.props.onEdit(function () { 32 | var node = this.refs.editField.getDOMNode(); 33 | node.focus(); 34 | node.setSelectionRange(node.value.length, node.value.length); 35 | }.bind(this)); 36 | this.setState({editText: this.props.todo.title}); 37 | }, 38 | 39 | handleKeyDown: function (event) { 40 | if (event.which === ESCAPE_KEY) { 41 | this.setState({editText: this.props.todo.title}); 42 | this.props.onCancel(event); 43 | } else if (event.which === ENTER_KEY) { 44 | this.handleSubmit(event); 45 | } 46 | }, 47 | 48 | handleChange: function (event) { 49 | this.setState({editText: event.target.value}); 50 | }, 51 | 52 | getInitialState: function () { 53 | return {editText: this.props.todo.title}; 54 | }, 55 | 56 | /** 57 | * This is a completely optional performance enhancement that you can 58 | * implement on any React component. If you were to delete this method 59 | * the app would still work correctly (and still be very performant!), we 60 | * just use it as an example of how little code it takes to get an order 61 | * of magnitude performance improvement. 62 | */ 63 | shouldComponentUpdate: function (nextProps, nextState) { 64 | return ( 65 | nextProps.todo !== this.props.todo || 66 | nextProps.editing !== this.props.editing || 67 | nextState.editText !== this.state.editText 68 | ); 69 | }, 70 | 71 | render: function () { 72 | var classes = React.addons.classSet({ 73 | completed: this.props.todo.completed, 74 | editing: this.props.editing 75 | }); 76 | 77 | return; 78 | } 79 | }); 80 | })(); 81 | -------------------------------------------------------------------------------- /examples/todomvc/js/todoModel.js: -------------------------------------------------------------------------------- 1 | /*jshint quotmark:false */ 2 | /*jshint white:false */ 3 | /*jshint trailing:false */ 4 | /*jshint newcap:false */ 5 | var app = app || {}; 6 | 7 | (function () { 8 | 'use strict'; 9 | 10 | var Utils = app.Utils; 11 | // Generic "model" object. You can use whatever 12 | // framework you want. For this application it 13 | // may not even be worth separating this logic 14 | // out, but we do this to demonstrate one way to 15 | // separate out parts of your application. 16 | app.TodoModel = function (key) { 17 | this.key = key; 18 | this.todos = Utils.store(key); 19 | this.onChanges = []; 20 | }; 21 | 22 | app.TodoModel.prototype.subscribe = function (onChange) { 23 | this.onChanges.push(onChange); 24 | }; 25 | 26 | app.TodoModel.prototype.inform = function () { 27 | Utils.store(this.key, this.todos); 28 | this.onChanges.forEach(function (cb) { cb(); }); 29 | }; 30 | 31 | app.TodoModel.prototype.addTodo = function (title) { 32 | this.todos = this.todos.concat({ 33 | id: Utils.uuid(), 34 | title: title, 35 | completed: false 36 | }); 37 | 38 | this.inform(); 39 | }; 40 | 41 | app.TodoModel.prototype.toggleAll = function (checked) { 42 | // Note: it's usually better to use immutable data structures since they're 43 | // easier to reason about and React works very well with them. That's why 44 | // we use map() and filter() everywhere instead of mutating the array or 45 | // todo items themselves. 46 | this.todos = this.todos.map(function (todo) { 47 | return Utils.extend({}, todo, {completed: checked}); 48 | }); 49 | 50 | this.inform(); 51 | }; 52 | 53 | app.TodoModel.prototype.toggle = function (todoToToggle) { 54 | this.todos = this.todos.map(function (todo) { 55 | return todo !== todoToToggle ? 56 | todo : 57 | Utils.extend({}, todo, {completed: !todo.completed}); 58 | }); 59 | 60 | this.inform(); 61 | }; 62 | 63 | app.TodoModel.prototype.destroy = function (todo) { 64 | this.todos = this.todos.filter(function (candidate) { 65 | return candidate !== todo; 66 | }); 67 | 68 | this.inform(); 69 | }; 70 | 71 | app.TodoModel.prototype.save = function (todoToSave, text) { 72 | this.todos = this.todos.map(function (todo) { 73 | return todo !== todoToSave ? todo : Utils.extend({}, todo, {title: text}); 74 | }); 75 | 76 | this.inform(); 77 | }; 78 | 79 | app.TodoModel.prototype.clearCompleted = function () { 80 | this.todos = this.todos.filter(function (todo) { 81 | return !todo.completed; 82 | }); 83 | 84 | this.inform(); 85 | }; 86 | 87 | })(); 88 | -------------------------------------------------------------------------------- /examples/todomvc/js/utils.js: -------------------------------------------------------------------------------- 1 | var app = app || {}; 2 | 3 | (function () { 4 | 'use strict'; 5 | 6 | app.Utils = { 7 | uuid: function () { 8 | /*jshint bitwise:false */ 9 | var i, random; 10 | var uuid = ''; 11 | 12 | for (i = 0; i < 32; i++) { 13 | random = Math.random() * 16 | 0; 14 | if (i === 8 || i === 12 || i === 16 || i === 20) { 15 | uuid += '-'; 16 | } 17 | uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random)) 18 | .toString(16); 19 | } 20 | 21 | return uuid; 22 | }, 23 | 24 | pluralize: function (count, word) { 25 | return count === 1 ? word : word + 's'; 26 | }, 27 | 28 | store: function (namespace, data) { 29 | if (data) { 30 | return localStorage.setItem(namespace, JSON.stringify(data)); 31 | } 32 | 33 | var store = localStorage.getItem(namespace); 34 | return (store && JSON.parse(store)) || []; 35 | }, 36 | 37 | extend: function () { 38 | var newObj = {}; 39 | for (var i = 0; i < arguments.length; i++) { 40 | var obj = arguments[i]; 41 | for (var key in obj) { 42 | if (obj.hasOwnProperty(key)) { 43 | newObj[key] = obj[key]; 44 | } 45 | } 46 | } 47 | return newObj; 48 | } 49 | }; 50 | })(); 51 | -------------------------------------------------------------------------------- /lib/dom-utils.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | findNodes: findNodes, 3 | findNodesByAttr: findNodesByAttr, 4 | findNodesByAttrValue: findNodesByAttrValue, 5 | removeNodes: removeNodes, 6 | removeNode: removeNode, 7 | replaceWith: replaceWith, 8 | appendTo: appendTo, 9 | closestParentWithAttrList: closestParentWithAttrList 10 | }; 11 | 12 | function findNodes(node, test) { 13 | var result = []; 14 | 15 | if(test(node)) { 16 | result.push(node); 17 | } 18 | 19 | for(var i = 0, len = node.children.length; i < len; i++){ 20 | result = result.concat(findNodes(node.children[i], test)); 21 | } 22 | 23 | return result; 24 | } 25 | 26 | function findNodesByAttr(body, name) { 27 | return findNodes(body, function (node) { 28 | return node.attr.hasOwnProperty(name); 29 | }); 30 | } 31 | 32 | function findNodesByAttrValue(body, name, value) { 33 | return findNodes(body, function (node) { 34 | return node.attr[name] === value; 35 | }); 36 | } 37 | 38 | function removeNodes(nodeArray) { 39 | nodeArray.forEach(removeNode); 40 | } 41 | 42 | function removeNode(node) { 43 | if(node.prev) { 44 | node.prev.next = node.next; 45 | } 46 | if(node.next) { 47 | node.next.prev = node.prev; 48 | } 49 | 50 | if(node.parent){ 51 | var children = node.parent.children; 52 | children.splice(children.lastIndexOf(node), 1); 53 | } 54 | 55 | node.prev = null; 56 | node.next = null; 57 | node.parent = null; 58 | } 59 | 60 | function replaceWith(node, newNode) { 61 | newNode.prev = node.prev; 62 | newNode.next = node.next; 63 | newNode.parent = node.parent; 64 | if (node.prev) { 65 | node.prev.next = newNode; 66 | } 67 | if (node.next) { 68 | node.next.prev = newNode; 69 | } 70 | if (node.parent) { 71 | var list = node.parent.children; 72 | list.splice(list.indexOf(node), 1, newNode); 73 | } 74 | 75 | return newNode; 76 | } 77 | 78 | function lastChild(node) { 79 | return node.children.length > 0 ? node.children[node.children.length - 1] : null; 80 | } 81 | 82 | function appendTo(target, node) { 83 | var last = lastChild(target); 84 | target.children.push(node); 85 | node.parent = target; 86 | if (last) { 87 | last.next = node; 88 | node.prev = last; 89 | node.next = null; 90 | } 91 | } 92 | 93 | function closestParentWithAttrList(node, names) { 94 | if (node.parent) { 95 | for (var i = 0; i < names.length; i++) { 96 | if (node.parent.attr.hasOwnProperty(names[i])) { 97 | return node.parent; 98 | } 99 | } 100 | 101 | return closestParentWithAttrList(node.parent, names); 102 | } 103 | 104 | return null; 105 | } -------------------------------------------------------------------------------- /lib/parser.js: -------------------------------------------------------------------------------- 1 | var parser = require('html-parser'); 2 | 3 | module.exports = parse; 4 | 5 | function parse(html) { 6 | var body = { 7 | type: 'tag', 8 | name: 'body', 9 | attr: {}, 10 | closed: false, 11 | children: [] 12 | }; 13 | 14 | var current = body; 15 | 16 | parser.parse(html, { 17 | openElement: function(name) { 18 | open({ 19 | type: 'tag', 20 | closed: false, 21 | name: name 22 | }); 23 | }, 24 | text: function (value) { 25 | open({ 26 | type: 'text', 27 | closed: true, 28 | data: value 29 | }); 30 | }, 31 | comment: function(value) { 32 | open({ 33 | type: 'comment', 34 | closed: true, 35 | data: value 36 | }); 37 | }, 38 | closeOpenedElement: function(name, token) { 39 | current.closed = current.unary = token === '/>'; 40 | }, 41 | closeElement: function(name) { 42 | if (current.closed) { 43 | current.parent.closed = true; 44 | current = current.parent; 45 | } 46 | else { 47 | current.closed = true; 48 | } 49 | }, 50 | attribute: function(name, value) { 51 | current.attr[name] = value; 52 | } 53 | }); 54 | 55 | return body; 56 | 57 | function open(tag) { 58 | tag.attr = {}; 59 | tag.children = []; 60 | 61 | if (current.closed) { 62 | tag.prev = current; 63 | tag.parent = current.parent; 64 | current.next = tag; 65 | current.parent.children.push(tag); 66 | current = tag; 67 | } 68 | else { 69 | tag.parent = current; 70 | tag.prev = null; 71 | current.children.push(tag); 72 | current = tag; 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /lib/stringify.js: -------------------------------------------------------------------------------- 1 | module.exports = getOuterHTML; 2 | 3 | function getOuterHTML (node) { 4 | if (node.type === 'text') { 5 | return node.data; 6 | } 7 | 8 | if (node.type === 'verbatim') { 9 | return node.data; 10 | } 11 | 12 | if (node.type !== 'tag') return ''; 13 | 14 | var ret = "<" + node.name; 15 | 16 | for (var attr in node.attr) { 17 | if (!has(node.attr, attr)) continue; 18 | 19 | var value = node.attr[attr]; 20 | 21 | if (attr === 'class') { 22 | attr = 'className'; 23 | } 24 | else if (attr === 'jsx-spread') { 25 | ret += " {..." + value + "}"; 26 | continue; 27 | } 28 | 29 | ret += " " + attr + '=' + htmlAttrToJsx(value); 30 | } 31 | 32 | return ret + (node.unary ? " />" : ">" + getInnerHTML(node) + ""); 33 | } 34 | 35 | function getInnerHTML (elem) { 36 | return elem.children.length ? elem.children.map(getOuterHTML).join("") : ""; 37 | } 38 | 39 | function bracketsParser(str) { 40 | var results = [], 41 | level = 0, 42 | i = 0, 43 | len, 44 | char; 45 | 46 | len = str.length; 47 | while (i < len) { 48 | char = str.charAt(i); 49 | if (char === '{') { 50 | if (level === 0) { 51 | results.push(i); 52 | } 53 | level++; 54 | } 55 | else if (char === '}') { 56 | level--; 57 | if (level === 0) { 58 | results.push(i + 1); 59 | } 60 | } 61 | 62 | i++; 63 | } 64 | 65 | var list = []; 66 | for (i = 0, len = results.length; i < len; i += 2) { 67 | list.push({ 68 | start: results[i], 69 | end: results[i + 1] 70 | }); 71 | } 72 | 73 | return list; 74 | } 75 | 76 | function htmlAttrToJsx(attr, list) { 77 | var parts = [], 78 | start = 0; 79 | 80 | list = list || bracketsParser(attr); 81 | 82 | var q = '"'; 83 | 84 | var i, len, item; 85 | 86 | for (i = 0, len = list.length; i < len; i++) { 87 | item = list[i]; 88 | 89 | if (item.start - start > 0) { 90 | parts.push(q + attr.slice(start, item.start) + q); 91 | } 92 | 93 | parts.push(attr.slice(item.start + 1, item.end - 1)); 94 | start = item.end; 95 | } 96 | 97 | if (start < attr.length) { 98 | parts.push(q + attr.slice(start) + q); 99 | } 100 | 101 | return "{" + parts.join(' + ') + "}"; 102 | } 103 | 104 | function has(obj, field) { 105 | return Object.prototype.hasOwnProperty.call(obj, field); 106 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-st", 3 | "version": "1.0.0", 4 | "description": "React separate template", 5 | "main": "conv.js", 6 | "dependencies": { 7 | "commander": "2.*", 8 | "escodegen": "1.*", 9 | "esprima": "2.*", 10 | "html-parser": "0.*", 11 | "node.extend": "1.*", 12 | "react-tools": "0.*", 13 | "simple-object-query": "1.*" 14 | }, 15 | "devDependencies": { 16 | "mocha": "2.*", 17 | "chai": "1.*" 18 | }, 19 | "scripts": { 20 | "test": "./node_modules/.bin/mocha -R spec ./test" 21 | }, 22 | "bin": { 23 | "react-st": "cli.js" 24 | }, 25 | "repository": { 26 | "type": "git", 27 | "url": "git://github.com/redexp/react-separate-template.git" 28 | }, 29 | "keywords": [ 30 | "react", 31 | "separate", 32 | "template", 33 | "html", 34 | "converter" 35 | ], 36 | "author": "Sergii Kliuchnyk", 37 | "license": "MIT", 38 | "bugs": { 39 | "url": "https://github.com/redexp/react-separate-template/issues" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | var conv = require('../conv'), 2 | expect = require('chai').expect, 3 | fs = require('fs'); 4 | 5 | function file(path) { 6 | return fs.readFileSync(__dirname + '/js/' + path).toString(); 7 | } 8 | 9 | describe('convert function', function () { 10 | var js = file('menu.js'), 11 | html = file('menu.html'); 12 | 13 | it ('should convert js + html to jsx', function (done) { 14 | conv(js, html, function (err, jsx) { 15 | expect(err).to.be.null; 16 | expect(jsx).to.equal(file('menu.jsx')); 17 | done(); 18 | }); 19 | }); 20 | 21 | it ('should throw error: "Render not found"', function (done) { 22 | var badHtml = html.replace('@render list', '@render test'); 23 | 24 | conv(js, badHtml, function (err, jsx) { 25 | expect(err).not.to.be.null; 26 | expect(err.message).to.equal('Render return function "test" for class List not found'); 27 | done(); 28 | }); 29 | }); 30 | 31 | it ('should throw error: "HTML template not found"', function (done) { 32 | var badJs = js.replace('@jsx-tpl item', '@jsx-tpl test'); 33 | 34 | conv(badJs, html, function (err, jsx) { 35 | expect(err).not.to.be.null; 36 | expect(err.message).to.equal('HTML template for jsx-tpl "test" not found'); 37 | done(); 38 | }); 39 | }); 40 | 41 | }); -------------------------------------------------------------------------------- /test/js/menu.html: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 |
  • 9 | 10 |
  • 11 | 12 | -------------------------------------------------------------------------------- /test/js/menu.js: -------------------------------------------------------------------------------- 1 | var List = React.createClass({ 2 | getInitialState: function() { 3 | return {focused: 0}; 4 | }, 5 | 6 | render: function() { 7 | var self = this; 8 | 9 | return { 10 | list: function () { 11 | this.props.items.map(function(m, index) { 12 | var style = ''; 13 | 14 | if (self.state.focused == index) { 15 | style = 'focused'; 16 | } 17 | 18 | var attr = {name: 'value'}; 19 | 20 | return "@jsx-tpl item"; 21 | }) 22 | }, 23 | foo: function () { 24 | self.state 25 | } 26 | }; 27 | } 28 | }); 29 | 30 | var Item = React.createClass({ 31 | render: function () { 32 | console.log('test'); 33 | return; 34 | } 35 | }); 36 | var Users = {}; 37 | Users.List = React.createClass({ 38 | render: function () { 39 | return { 40 | users: function () { 41 | this.props.users.map(function (user) { 42 | return "@jsx-tpl user"; 43 | }); 44 | } 45 | }; 46 | } 47 | }); 48 | 49 | var Friends = { 50 | FriendsList: React.createClass({ 51 | render: function () { 52 | return { 53 | friends: function () { 54 | this.props.friends.map(function (friend) { 55 | return "@jsx-tpl friend"; 56 | }); 57 | } 58 | }; 59 | } 60 | }) 61 | }; 62 | 63 | var TestList = React.createClass({ 64 | render: function () { 65 | var x = "@jsx-tpl test-item"; 66 | return { 67 | item: function () { 68 | return x; 69 | } 70 | }; 71 | } 72 | }); 73 | 74 | var TestItem = React.createClass({ 75 | render: function () { 76 | return; 77 | } 78 | }); 79 | 80 | var TestWithoutRender = React.createClass({ 81 | 82 | }); 83 | 84 | var TestWithoutTemplate = React.createClass({ 85 | render: function () { 86 | return { 87 | item: function () { 88 | this; 89 | } 90 | }; 91 | } 92 | }); -------------------------------------------------------------------------------- /test/js/menu.jsx: -------------------------------------------------------------------------------- 1 | var List = React.createClass({ 2 | getInitialState: function () { 3 | return { focused: 0 }; 4 | }, 5 | render: function () { 6 | var self = this; 7 | return ; 19 | } 20 | }); 21 | var Item = React.createClass({ 22 | render: function () { 23 | console.log('test'); 24 | return
  • 25 | 26 |
  • ; 27 | } 28 | }); 29 | var Users = {}; 30 | Users.List = React.createClass({ 31 | render: function () { 32 | return ; 44 | } 45 | }); 46 | var Friends = { 47 | FriendsList: React.createClass({ 48 | render: function () { 49 | return ; 57 | } 58 | }) 59 | }; 60 | var TestList = React.createClass({ 61 | render: function () { 62 | var x = ; 63 | return
    64 | {x} 65 | 66 |
    ; 67 | } 68 | }); 69 | var TestItem = React.createClass({ 70 | render: function () { 71 | return
  • 72 | {test.name} 73 |
  • ; 74 | } 75 | }); 76 | var TestWithoutRender = React.createClass({}); 77 | var TestWithoutTemplate = React.createClass({ 78 | render: function () { 79 | return { 80 | item: function () { 81 | this; 82 | } 83 | }; 84 | } 85 | }); -------------------------------------------------------------------------------- /test/stringify.html: -------------------------------------------------------------------------------- 1 |
    2 | 3 | 4 | 5 | 6 | 7 |
    -------------------------------------------------------------------------------- /test/stringify.js: -------------------------------------------------------------------------------- 1 | var toHtml = require('../lib/stringify'), 2 | toDom = require('../lib/parser'), 3 | expect = require('chai').expect, 4 | fs = require('fs'); 5 | 6 | function file(path) { 7 | return fs.readFileSync(__dirname + '/js/' + path).toString(); 8 | } 9 | 10 | describe('stringify', function () { 11 | 12 | it ('should convert dom to jsx html', function () { 13 | var html = fs.readFileSync(__dirname + '/stringify.html').toString(); 14 | var jsx = fs.readFileSync(__dirname + '/stringify.jsx').toString(); 15 | 16 | expect(toHtml(toDom(html).children[0])).to.equal(jsx); 17 | }); 18 | 19 | }); -------------------------------------------------------------------------------- /test/stringify.jsx: -------------------------------------------------------------------------------- 1 |
    2 | 3 | 4 | 5 | 6 | 7 |
    --------------------------------------------------------------------------------