├── .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 | [](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 |
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 |
60 |
{m}
61 |
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 |
74 |
75 |
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 |
139 |
140 |
{m}
141 |
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 |
157 |
158 |
{m}
159 |
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 |
196 |
197 |
{user.name}
198 |
199 |
200 |
201 | ```
202 | Will be converted to
203 | ```html
204 |
205 |
206 |
207 |
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 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/examples/todomvc/js/components/app.html:
--------------------------------------------------------------------------------
1 |