1
0
mirror of https://github.com/bobwen-dev/react-templates synced 2025-04-12 00:56:39 +02:00

enable rules no-var and prefer-const and fix errors

This commit is contained in:
Omer Ganim 2016-04-27 14:04:02 +03:00
parent 4c385d5525
commit 4cb8c4524c
26 changed files with 301 additions and 321 deletions

View File

@ -1,3 +1,4 @@
{ {
"presets": ["es2015"] "presets": ["es2015"],
"ignore": "test/data"
} }

View File

@ -3,10 +3,8 @@
"plugins": ["lodash", "wix-editor"], "plugins": ["lodash", "wix-editor"],
"rules": { "rules": {
"semi": [2, "always"], "semi": [2, "always"],
"no-var": 0,
"object-shorthand": 0, "object-shorthand": 0,
"prefer-arrow-callback": 0, "prefer-arrow-callback": 0,
"prefer-const": 0,
"prefer-spread": 0, "prefer-spread": 0,
"prefer-template": 0, "prefer-template": 0,
"consistent-return": 0, "consistent-return": 0,

View File

@ -106,10 +106,9 @@ module.exports = function (grunt) {
grunt.registerTask('test', ['tape']); grunt.registerTask('test', ['tape']);
grunt.registerTask('rt', function () { grunt.registerTask('rt', function () {
var reactTemplates = require('./src/cli'); const reactTemplates = require('./src/cli');
var files = grunt.file.expand('playground/*.rt'); const files = grunt.file.expand('playground/*.rt');
var conf = {modules: 'amd', force: true, _: files}; const ret = reactTemplates.execute({modules: 'amd', force: true, _: files});
var ret = reactTemplates.execute(conf);
return ret === 0; return ret === 0;
}); });

View File

@ -1,6 +1,6 @@
#!/usr/bin/env node #!/usr/bin/env node
'use strict'; 'use strict';
var cli = require('../dist/cli'); const cli = require('../dist/cli');
var exitCode = cli.execute(process.argv); const exitCode = cli.execute(process.argv);
/*eslint no-process-exit:0*/ /*eslint no-process-exit:0*/
process.exit(exitCode); process.exit(exitCode);

View File

@ -1,6 +1,7 @@
{ {
"rules": { "rules": {
"strict": [2, "function"] "strict": [2, "function"],
"no-var": 0
}, },
"env": { "env": {
"browser": true, "browser": true,

View File

@ -1,6 +1,7 @@
{ {
"rules": { "rules": {
"strict": [2, "function"] "strict": [2, "function"],
"no-var": 0
}, },
"env": { "env": {
"browser": true, "browser": true,

View File

@ -1,6 +1,6 @@
'use strict'; 'use strict';
var util = require('util'); const util = require('util');
var _ = require('lodash'); const _ = require('lodash');
/** /**
@ -16,7 +16,7 @@ function getLine(html, node) {
if (!node) { if (!node) {
return {line: 1, col: 1}; return {line: 1, col: 1};
} }
var linesUntil = html.substring(0, node.startIndex).split('\n'); const linesUntil = html.substring(0, node.startIndex).split('\n');
return {line: linesUntil.length, col: linesUntil[linesUntil.length - 1].length + 1}; return {line: linesUntil.length, col: linesUntil[linesUntil.length - 1].length + 1};
} }
@ -24,10 +24,10 @@ function getLine(html, node) {
// if (!node) { // if (!node) {
// return 0; // return 0;
// } // }
// var line = 0; // const line = 0;
// var prev = node.prev; // const prev = node.prev;
// while (prev) { // while (prev) {
// var nl = prev.data.split('\n').length - 1; // const nl = prev.data.split('\n').length - 1;
// line += nl; // line += nl;
// prev = prev.prev; // prev = prev.prev;
// } // }
@ -111,7 +111,7 @@ RTCodeError.buildFormat = _.rest(buildFormat, 3);
* @return {RTCodeError} * @return {RTCodeError}
*/ */
function buildError(context, node, msg) { function buildError(context, node, msg) {
var loc = getNodeLoc(context, node); const loc = getNodeLoc(context, node);
return new RTCodeError(msg, loc.start, loc.end, loc.pos.line, loc.pos.col); return new RTCodeError(msg, loc.start, loc.end, loc.pos.line, loc.pos.col);
} }
@ -121,8 +121,8 @@ function buildError(context, node, msg) {
* @return {{pos:Pos, start:number, end:number}} * @return {{pos:Pos, start:number, end:number}}
*/ */
function getNodeLoc(context, node) { function getNodeLoc(context, node) {
var pos = getLine(context.html, node); const pos = getLine(context.html, node);
var end; let end;
if (node.data) { if (node.data) {
end = node.startIndex + node.data.length; end = node.startIndex + node.data.length;
} else if (node.next) { // eslint-disable-line } else if (node.next) { // eslint-disable-line

View File

@ -1,12 +1,12 @@
'use strict'; 'use strict';
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
var chalk = require('chalk'); const chalk = require('chalk');
var reactTemplates = require('./reactTemplates'); const reactTemplates = require('./reactTemplates');
var fsUtil = require('./fsUtil'); const fsUtil = require('./fsUtil');
var convertRT = reactTemplates.convertRT; const convertRT = reactTemplates.convertRT;
var convertJSRTToJS = reactTemplates.convertJSRTToJS; const convertJSRTToJS = reactTemplates.convertJSRTToJS;
/** /**
* @param {string} source * @param {string} source
@ -15,10 +15,6 @@ var convertJSRTToJS = reactTemplates.convertJSRTToJS;
* @param {CONTEXT} context * @param {CONTEXT} context
*/ */
function convertFile(source, target, options, context) { function convertFile(source, target, options, context) {
// if (path.extname(filename) !== ".html") {
// console.log('invalid file, only handle html files');
// return;// only handle html files
// }
options = options || {}; options = options || {};
options.fileName = source; options.fileName = source;
@ -27,21 +23,21 @@ function convertFile(source, target, options, context) {
return; return;
} }
var html = fs.readFileSync(source).toString(); const html = fs.readFileSync(source).toString();
if (path.extname(source) === '.rts') { if (path.extname(source) === '.rts') {
var rtStyle = require('./rtStyle'); const rtStyle = require('./rtStyle');
var out = rtStyle.convert(html); const out = rtStyle.convert(html);
if (!options.dryRun) { if (!options.dryRun) {
fs.writeFileSync(target, out); fs.writeFileSync(target, out);
} }
return; return;
} }
var shouldAddName = options.modules === 'none' && !options.name; const shouldAddName = options.modules === 'none' && !options.name;
if (shouldAddName) { if (shouldAddName) {
options.name = reactTemplates.normalizeName(path.basename(source, path.extname(source))) + 'RT'; options.name = reactTemplates.normalizeName(path.basename(source, path.extname(source))) + 'RT';
} }
options.readFileSync = fsUtil.createRelativeReadFileSync(source); options.readFileSync = fsUtil.createRelativeReadFileSync(source);
var js = options.modules === 'jsrt' ? convertJSRTToJS(html, context, options) : convertRT(html, context, options); const js = options.modules === 'jsrt' ? convertJSRTToJS(html, context, options) : convertRT(html, context, options);
if (!options.dryRun) { if (!options.dryRun) {
fs.writeFileSync(target, js); fs.writeFileSync(target, js);
} }
@ -51,7 +47,6 @@ function convertFile(source, target, options, context) {
} }
module.exports = { module.exports = {
// convertTemplateToReact: convertTemplateToReact,
convertFile: convertFile, convertFile: convertFile,
context: require('./context'), context: require('./context'),
_test: {} _test: {}

View File

@ -1,23 +1,23 @@
#!/usr/bin/env node #!/usr/bin/env node
'use strict'; 'use strict';
var _ = require('lodash'); const _ = require('lodash');
var path = require('path'); const path = require('path');
var api = require('./api'); const api = require('./api');
var context = require('./context'); const context = require('./context');
var shell = require('./shell'); const shell = require('./shell');
var pkg = require('../package.json'); const pkg = require('../package.json');
var options = require('./options'); const options = require('./options');
var reactDOMSupport = require('./reactDOMSupport'); const reactDOMSupport = require('./reactDOMSupport');
var reactTemplates = require('./reactTemplates'); const reactTemplates = require('./reactTemplates');
var rtStyle = require('./rtStyle'); const rtStyle = require('./rtStyle');
/** /**
* @param {Options} currentOptions * @param {Options} currentOptions
* @return {number} * @return {number}
*/ */
function executeOptions(currentOptions) { function executeOptions(currentOptions) {
var ret = 0; let ret = 0;
var files = currentOptions._; const files = currentOptions._;
context.options.format = currentOptions.format || 'stylish'; context.options.format = currentOptions.format || 'stylish';
if (currentOptions.version) { if (currentOptions.version) {
@ -40,9 +40,7 @@ function executeOptions(currentOptions) {
} }
function printVersions(currentOptions) { function printVersions(currentOptions) {
var ret = Object.keys(reactDOMSupport); const ret = Object.keys(reactDOMSupport);
//const out = currentOptions.format === 'json' ? JSON.stringify(ret, undefined, 2) : ret.join(', ');
//console.log(out);
if (currentOptions.format === 'json') { if (currentOptions.format === 'json') {
console.log(JSON.stringify(ret, undefined, 2)); console.log(JSON.stringify(ret, undefined, 2));
} else { } else {
@ -56,8 +54,8 @@ function printVersions(currentOptions) {
*/ */
function handleSingleFile(currentOptions, filename) { function handleSingleFile(currentOptions, filename) {
try { try {
var sourceExt = path.extname(filename); const sourceExt = path.extname(filename);
var outputFilename; let outputFilename;
if (sourceExt === '.rt') { if (sourceExt === '.rt') {
outputFilename = filename + (currentOptions.modules === 'typescript' ? '.ts' : '.js'); outputFilename = filename + (currentOptions.modules === 'typescript' ? '.ts' : '.js');
} else if (sourceExt === '.jsrt') { } else if (sourceExt === '.jsrt') {
@ -82,7 +80,7 @@ function handleSingleFile(currentOptions, filename) {
* @returns {int} The exit code for the operation. * @returns {int} The exit code for the operation.
*/ */
function execute(args) { function execute(args) {
var currentOptions; let currentOptions;
try { try {
currentOptions = options.parse(args); currentOptions = options.parse(args);
} catch (error) { } catch (error) {

View File

@ -10,21 +10,21 @@
* Enum for tri-state values. * Enum for tri-state values.
* @enum {string} * @enum {string}
*/ */
var MESSAGE_LEVEL = { const MESSAGE_LEVEL = {
ERROR: 'ERROR', ERROR: 'ERROR',
WARN: 'WARN', WARN: 'WARN',
INFO: 'INFO' INFO: 'INFO'
}; };
var _ = require('lodash'); const _ = require('lodash');
var err = require('./RTCodeError'); const err = require('./RTCodeError');
var norm = err.RTCodeError.norm; const norm = err.RTCodeError.norm;
/** /**
* @type {CONTEXT} * @type {CONTEXT}
*/ */
var context = { const context = {
/** @type {Array.<MESSAGE>} */ /** @type {Array.<MESSAGE>} */
messages: [], messages: [],
/** @type {boolean} */ /** @type {boolean} */

View File

@ -2,9 +2,9 @@
/** /**
* @type {Chalk.ChalkModule} * @type {Chalk.ChalkModule}
*/ */
var chalk = require('chalk'); const chalk = require('chalk');
var _ = require('lodash'); const _ = require('lodash');
var table = require('text-table'); const table = require('text-table');
///** ///**
// * @param {MESSAGE} message // * @param {MESSAGE} message
@ -43,13 +43,13 @@ function lineText(line) {
} }
//module.exports = function (warnings/*, config*/) { //module.exports = function (warnings/*, config*/) {
// var _ = require('lodash'); // const _ = require('lodash');
// var table = require('text-table'); // const table = require('text-table');
// //var verbosity = false; // //const verbosity = false;
// var UNICODE_HEAVY_MULTIPLICATION_X = '\u2716'; // const UNICODE_HEAVY_MULTIPLICATION_X = '\u2716';
// //
// // context.report(JSON.stringify(warnings, undefined, 2)); // // context.report(JSON.stringify(warnings, undefined, 2));
// var output = table( // const output = table(
// warnings.map(function (message) { // warnings.map(function (message) {
// return [ // return [
// '', // '',
@ -71,22 +71,22 @@ function lineText(line) {
// //} // //}
// ); // );
// //
// var buf = []; // const buf = [];
// //
// buf.push(output); // buf.push(output);
// //
// var grouped = _.groupBy(warnings, 'level'); // const grouped = _.groupBy(warnings, 'level');
// //
// var errCount = grouped.ERROR ? grouped.ERROR.length : 0; // const errCount = grouped.ERROR ? grouped.ERROR.length : 0;
// var warnCount = grouped.WARN ? grouped.WARN.length : 0; // const warnCount = grouped.WARN ? grouped.WARN.length : 0;
// //var infoCount = grouped.INFO ? grouped.INFO.length : 0; // //const infoCount = grouped.INFO ? grouped.INFO.length : 0;
// //
//// buf.push(errCount + ' ' + warnCount + ' ' + infoCount + '\n'); //// buf.push(errCount + ' ' + warnCount + ' ' + infoCount + '\n');
// //
// if (errCount === 0 && warnCount === 0) { // if (errCount === 0 && warnCount === 0) {
// buf.push(chalk.green('React templates done')); // buf.push(chalk.green('React templates done'));
// } else { // } else {
// var msg = []; // const msg = [];
// if (errCount > 0) { // if (errCount > 0) {
// msg.push(errCount + ' ' + pluralize(errCount, 'error', 'errors')); // msg.push(errCount + ' ' + pluralize(errCount, 'error', 'errors'));
// } else { // } else {
@ -113,15 +113,15 @@ function lineText(line) {
module.exports = function (results) { module.exports = function (results) {
results = _.groupBy(results, 'file'); results = _.groupBy(results, 'file');
var output = '\n'; let output = '\n';
var total = 0; let total = 0;
var errors = 0; let errors = 0;
var warnings = 0; let warnings = 0;
var infos = 0; let infos = 0;
var summaryColor = 'cyan'; let summaryColor = 'cyan';
_.forEach(results, function (result, k) { _.forEach(results, function (result, k) {
var messages = result; const messages = result;
if (messages.length === 0) { if (messages.length === 0) {
return; return;
@ -132,7 +132,7 @@ module.exports = function (results) {
output += table( output += table(
messages.map(function (message) { messages.map(function (message) {
var messageType; let messageType;
if (message.level === 'ERROR') { if (message.level === 'ERROR') {
messageType = chalk.red('error'); messageType = chalk.red('error');

View File

@ -1,6 +1,6 @@
'use strict'; 'use strict';
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
/** /**
* @param {string} source * @param {string} source
@ -11,13 +11,13 @@ function isStale(source, target) {
if (!fs.existsSync(target)) { if (!fs.existsSync(target)) {
return true; return true;
} }
var sourceTime = fs.statSync(source).mtime; const sourceTime = fs.statSync(source).mtime;
var targetTime = fs.statSync(target).mtime; const targetTime = fs.statSync(target).mtime;
return sourceTime.getTime() > targetTime.getTime(); return sourceTime.getTime() > targetTime.getTime();
} }
function createRelativeReadFileSync(baseFile) { function createRelativeReadFileSync(baseFile) {
var basePath = path.dirname(baseFile); const basePath = path.dirname(baseFile);
return filename => fs.readFileSync(path.resolve(basePath, filename)); return filename => fs.readFileSync(path.resolve(basePath, filename));
} }

View File

@ -8,10 +8,10 @@
// Requirements // Requirements
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
var optionator = require('optionator'); const optionator = require('optionator');
var pkg = require('../package.json'); const pkg = require('../package.json');
var reactDOMSupport = require('./reactDOMSupport'); const reactDOMSupport = require('./reactDOMSupport');
var reactNativeSupport = require('./reactNativeSupport'); const reactNativeSupport = require('./reactNativeSupport');
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Initialization and Public Interface // Initialization and Public Interface

View File

@ -1,14 +1,14 @@
'use strict'; 'use strict';
var ver0_12_0 = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', const ver0_12_0 = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data',
'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', 'circle', 'defs', 'ellipse', 'g', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan']; 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', 'circle', 'defs', 'ellipse', 'g', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan'];
var ver0_11_2 = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', 'circle', 'defs', 'ellipse', 'g', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan', 'injection']; const ver0_11_2 = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', 'circle', 'defs', 'ellipse', 'g', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan', 'injection'];
var ver0_11_0 = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', 'circle', 'defs', 'ellipse', 'g', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan', 'injection']; const ver0_11_0 = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', 'circle', 'defs', 'ellipse', 'g', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan', 'injection'];
var ver0_10_0 = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', 'circle', 'defs', 'g', 'line', 'linearGradient', 'path', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'injection']; const ver0_10_0 = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', 'circle', 'defs', 'g', 'line', 'linearGradient', 'path', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'injection'];
var svg = ['a', 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animate', 'animateMotion', 'animateTransform', 'circle', 'clipPath', 'color-profile', 'cursor', 'defs', 'desc', 'ellipse', 'feBlend', 'g', 'image', 'line', const svg = ['a', 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animate', 'animateMotion', 'animateTransform', 'circle', 'clipPath', 'color-profile', 'cursor', 'defs', 'desc', 'ellipse', 'feBlend', 'g', 'image', 'line',
'linearGradient', 'marker', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tref', 'tspan', 'use']; 'linearGradient', 'marker', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tref', 'tspan', 'use'];
var v12_svg = ver0_12_0.concat(svg); const v12_svg = ver0_12_0.concat(svg);
var versions = { const versions = {
'0.14.0': v12_svg, '0.14.0': v12_svg,
'0.13.1': v12_svg, '0.13.1': v12_svg,
'0.12.2': v12_svg, '0.12.2': v12_svg,

View File

@ -1,8 +1,8 @@
'use strict'; 'use strict';
var ver0_9_0 = ['ActivityIndicatorIOS', 'DatePickerIOS', 'Image', 'ListView', 'MapView', 'Navigator', 'NavigatorIOS', 'PickerIOS', 'ScrollView', 'SliderIOS', 'SwitchIOS', 'TabBarIOS', 'Text', 'TextInput', 'TouchableHighlight', 'TouchableOpacity', 'TouchableWithoutFeedback', 'View', 'WebView']; const ver0_9_0 = ['ActivityIndicatorIOS', 'DatePickerIOS', 'Image', 'ListView', 'MapView', 'Navigator', 'NavigatorIOS', 'PickerIOS', 'ScrollView', 'SliderIOS', 'SwitchIOS', 'TabBarIOS', 'Text', 'TextInput', 'TouchableHighlight', 'TouchableOpacity', 'TouchableWithoutFeedback', 'View', 'WebView'];
var versions = { const versions = {
'0.9.0': ver0_9_0, '0.9.0': ver0_9_0,
default: '0.9.0' default: '0.9.0'
}; };

View File

@ -1,6 +1,6 @@
'use strict'; 'use strict';
var native = { const native = {
'0.9.0': { '0.9.0': {
ListView: { ListView: {
Row: {prop: 'renderRow', arguments: ['rowData', 'sectionID', 'rowID', 'highlightRow']}, Row: {prop: 'renderRow', arguments: ['rowData', 'sectionID', 'rowID', 'highlightRow']},

View File

@ -1,5 +1,5 @@
'use strict'; 'use strict';
var _ = require('lodash'); const _ = require('lodash');
/** /**
* @param {Context} context * @param {Context} context
@ -17,14 +17,14 @@ function shouldUseCreateElement(context) {
} }
} }
var reactSupportedAttributes = ['accept', 'acceptCharset', 'accessKey', 'action', 'allowFullScreen', 'allowTransparency', 'alt', 'async', 'autoComplete', 'autoPlay', 'cellPadding', 'cellSpacing', 'charSet', 'checked', const reactSupportedAttributes = ['accept', 'acceptCharset', 'accessKey', 'action', 'allowFullScreen', 'allowTransparency', 'alt', 'async', 'autoComplete', 'autoPlay', 'cellPadding', 'cellSpacing', 'charSet', 'checked',
'classID', 'className', 'cols', 'colSpan', 'content', 'contentEditable', 'contextMenu', 'controls', 'coords', 'crossOrigin', 'data', 'dateTime', 'defer', 'dir', 'disabled', 'download', 'classID', 'className', 'cols', 'colSpan', 'content', 'contentEditable', 'contextMenu', 'controls', 'coords', 'crossOrigin', 'data', 'dateTime', 'defer', 'dir', 'disabled', 'download',
'draggable', 'encType', 'form', 'formNoValidate', 'frameBorder', 'height', 'hidden', 'href', 'hrefLang', 'htmlFor', 'httpEquiv', 'icon', 'id', 'label', 'lang', 'list', 'loop', 'manifest', 'draggable', 'encType', 'form', 'formNoValidate', 'frameBorder', 'height', 'hidden', 'href', 'hrefLang', 'htmlFor', 'httpEquiv', 'icon', 'id', 'label', 'lang', 'list', 'loop', 'manifest',
'max', 'maxLength', 'media', 'mediaGroup', 'method', 'min', 'multiple', 'muted', 'name', 'noValidate', 'open', 'pattern', 'placeholder', 'poster', 'preload', 'radioGroup', 'readOnly', 'rel', 'max', 'maxLength', 'media', 'mediaGroup', 'method', 'min', 'multiple', 'muted', 'name', 'noValidate', 'open', 'pattern', 'placeholder', 'poster', 'preload', 'radioGroup', 'readOnly', 'rel',
'required', 'role', 'rows', 'rowSpan', 'sandbox', 'scope', 'scrolling', 'seamless', 'selected', 'shape', 'size', 'sizes', 'span', 'spellCheck', 'src', 'srcDoc', 'srcSet', 'start', 'step', 'required', 'role', 'rows', 'rowSpan', 'sandbox', 'scope', 'scrolling', 'seamless', 'selected', 'shape', 'size', 'sizes', 'span', 'spellCheck', 'src', 'srcDoc', 'srcSet', 'start', 'step',
'style', 'tabIndex', 'target', 'title', 'type', 'useMap', 'value', 'width', 'wmode']; 'style', 'tabIndex', 'target', 'title', 'type', 'useMap', 'value', 'width', 'wmode'];
var classNameProp = 'className'; const classNameProp = 'className';
var attributesMapping = {'class': classNameProp, 'rt-class': classNameProp, 'for': 'htmlFor'}; //eslint-disable-line quote-props const attributesMapping = {'class': classNameProp, 'rt-class': classNameProp, 'for': 'htmlFor'}; //eslint-disable-line quote-props
_.forEach(reactSupportedAttributes, function (attributeReactName) { _.forEach(reactSupportedAttributes, function (attributeReactName) {
if (attributeReactName !== attributeReactName.toLowerCase()) { if (attributeReactName !== attributeReactName.toLowerCase()) {
@ -32,21 +32,21 @@ _.forEach(reactSupportedAttributes, function (attributeReactName) {
} }
}); });
var htmlSelfClosingTags = ['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr']; const htmlSelfClosingTags = ['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'];
var templateAMDTemplate = _.template("define(<%= name ? '\"'+name + '\", ' : '' %>[<%= requirePaths %>], function (<%= requireNames %>) {\n'use strict';\n <%= injectedFunctions %>\nreturn function(){ return <%= body %>};\n});"); const templateAMDTemplate = _.template("define(<%= name ? '\"'+name + '\", ' : '' %>[<%= requirePaths %>], function (<%= requireNames %>) {\n'use strict';\n <%= injectedFunctions %>\nreturn function(){ return <%= body %>};\n});");
var templateCommonJSTemplate = _.template("'use strict';\n<%= vars %>\n\n<%= injectedFunctions %>\nmodule.exports = function(){ return <%= body %>};\n"); const templateCommonJSTemplate = _.template("'use strict';\n<%= vars %>\n\n<%= injectedFunctions %>\nmodule.exports = function(){ return <%= body %>};\n");
var templateES6Template = _.template('<%= vars %>\n\n<%= injectedFunctions %>\nexport default function(){ return <%= body %>}\n'); const templateES6Template = _.template('<%= vars %>\n\n<%= injectedFunctions %>\nexport default function(){ return <%= body %>}\n');
var templatePJSTemplate = _.template(`var <%= name %> = function () { const templatePJSTemplate = _.template(`var <%= name %> = function () {
<%= injectedFunctions %> <%= injectedFunctions %>
return <%= body %> return <%= body %>
}; };
`); `);
var templateTypescriptTemplate = _.template('<%= vars %>\n\n<%= injectedFunctions %>\nvar fn = function() { return <%= body %> };\nexport = fn\n'); const templateTypescriptTemplate = _.template('<%= vars %>\n\n<%= injectedFunctions %>\nvar fn = function() { return <%= body %> };\nexport = fn\n');
var templateJSRTTemplate = _.template('(function () {\n <%= injectedFunctions %>\n return function(){\nreturn <%= body %>}}\n)()'); const templateJSRTTemplate = _.template('(function () {\n <%= injectedFunctions %>\n return function(){\nreturn <%= body %>}}\n)()');
var templates = { const templates = {
amd: templateAMDTemplate, amd: templateAMDTemplate,
commonjs: templateCommonJSTemplate, commonjs: templateCommonJSTemplate,
typescript: templateTypescriptTemplate, typescript: templateTypescriptTemplate,

View File

@ -1,24 +1,24 @@
'use strict'; 'use strict';
var cheerio = require('cheerio'); const cheerio = require('cheerio');
var _ = require('lodash'); const _ = require('lodash');
var esprima = require('esprima'); const esprima = require('esprima');
var escodegen = require('escodegen'); const escodegen = require('escodegen');
var reactDOMSupport = require('./reactDOMSupport'); const reactDOMSupport = require('./reactDOMSupport');
var reactNativeSupport = require('./reactNativeSupport'); const reactNativeSupport = require('./reactNativeSupport');
var reactPropTemplates = require('./reactPropTemplates'); const reactPropTemplates = require('./reactPropTemplates');
var stringUtils = require('./stringUtils'); const stringUtils = require('./stringUtils');
var rtError = require('./RTCodeError'); const rtError = require('./RTCodeError');
var reactSupport = require('./reactSupport'); const reactSupport = require('./reactSupport');
var templates = reactSupport.templates; const templates = reactSupport.templates;
var utils = require('./utils'); const utils = require('./utils');
var util = require('util'); const util = require('util');
var validateJS = utils.validateJS; const validateJS = utils.validateJS;
var RTCodeError = rtError.RTCodeError; const RTCodeError = rtError.RTCodeError;
var repeatTemplate = _.template('_.map(<%= collection %>,<%= repeatFunction %>.bind(<%= repeatBinds %>))'); const repeatTemplate = _.template('_.map(<%= collection %>,<%= repeatFunction %>.bind(<%= repeatBinds %>))');
var ifTemplate = _.template('((<%= condition %>)?(<%= body %>):null)'); const ifTemplate = _.template('((<%= condition %>)?(<%= body %>):null)');
var propsTemplateSimple = _.template('_.assign({}, <%= generatedProps %>, <%= rtProps %>)'); const propsTemplateSimple = _.template('_.assign({}, <%= generatedProps %>, <%= rtProps %>)');
var propsTemplate = _.template('mergeProps( <%= generatedProps %>, <%= rtProps %>)'); const propsTemplate = _.template('mergeProps( <%= generatedProps %>, <%= rtProps %>)');
const propsMergeFunction = `function mergeProps(inline,external) { const propsMergeFunction = `function mergeProps(inline,external) {
var res = _.assign({},inline,external) var res = _.assign({},inline,external)
@ -32,7 +32,7 @@ const propsMergeFunction = `function mergeProps(inline,external) {
} }
`; `;
var classSetTemplate = _.template('_(<%= classSet %>).transform(function(res, value, key){ if(value){ res.push(key); } }, []).join(" ")'); const classSetTemplate = _.template('_(<%= classSet %>).transform(function(res, value, key){ if(value){ res.push(key); } }, []).join(" ")');
function getTagTemplateString(simpleTagTemplate, shouldCreateElement) { function getTagTemplateString(simpleTagTemplate, shouldCreateElement) {
if (simpleTagTemplate) { if (simpleTagTemplate) {
@ -42,20 +42,20 @@ function getTagTemplateString(simpleTagTemplate, shouldCreateElement) {
} }
var commentTemplate = _.template(' /* <%= data %> */ '); const commentTemplate = _.template(' /* <%= data %> */ ');
var repeatAttr = 'rt-repeat'; const repeatAttr = 'rt-repeat';
var ifAttr = 'rt-if'; const ifAttr = 'rt-if';
var classSetAttr = 'rt-class'; const classSetAttr = 'rt-class';
var classAttr = 'class'; const classAttr = 'class';
var scopeAttr = 'rt-scope'; const scopeAttr = 'rt-scope';
var propsAttr = 'rt-props'; const propsAttr = 'rt-props';
var templateNode = 'rt-template'; const templateNode = 'rt-template';
var virtualNode = 'rt-virtual'; const virtualNode = 'rt-virtual';
var includeNode = 'rt-include'; const includeNode = 'rt-include';
var includeSrcAttr = 'src'; const includeSrcAttr = 'src';
var reactTemplatesSelfClosingTags = [includeNode]; const reactTemplatesSelfClosingTags = [includeNode];
/** /**
* @param {Options} options * @param {Options} options
@ -63,7 +63,7 @@ var reactTemplatesSelfClosingTags = [includeNode];
*/ */
function getOptions(options) { function getOptions(options) {
options = options || {}; options = options || {};
var defaultOptions = { const defaultOptions = {
modules: options.native ? 'commonjs' : 'amd', modules: options.native ? 'commonjs' : 'amd',
version: false, version: false,
force: false, force: false,
@ -76,9 +76,9 @@ function getOptions(options) {
flow: options.flow flow: options.flow
}; };
var finalOptions = _.defaults({}, options, defaultOptions); const finalOptions = _.defaults({}, options, defaultOptions);
var defaultPropTemplates = finalOptions.native ? const defaultPropTemplates = finalOptions.native ?
reactPropTemplates.native[finalOptions.nativeTargetVersion] : reactPropTemplates.native[finalOptions.nativeTargetVersion] :
reactPropTemplates.dom[finalOptions.targetVersion]; reactPropTemplates.dom[finalOptions.targetVersion];
@ -116,23 +116,23 @@ const curlyMap = {'{': 1, '}': -1};
* @return {string} * @return {string}
*/ */
function convertText(node, context, txt) { function convertText(node, context, txt) {
var res = ''; let res = '';
var first = true; let first = true;
var concatChar = node.type === 'text' ? ',' : '+'; const concatChar = node.type === 'text' ? ',' : '+';
while (_.includes(txt, '{')) { while (_.includes(txt, '{')) {
var start = txt.indexOf('{'); const start = txt.indexOf('{');
var pre = txt.substr(0, start); const pre = txt.substr(0, start);
if (pre) { if (pre) {
res += (first ? '' : concatChar) + JSON.stringify(pre); res += (first ? '' : concatChar) + JSON.stringify(pre);
first = false; first = false;
} }
var curlyCounter = 1; let curlyCounter = 1;
var end; let end;
for (end = start + 1; end < txt.length && curlyCounter > 0; end++) { //eslint-disable-line no-restricted-syntax for (end = start + 1; end < txt.length && curlyCounter > 0; end++) { //eslint-disable-line no-restricted-syntax
curlyCounter += curlyMap[txt.charAt(end)] || 0; curlyCounter += curlyMap[txt.charAt(end)] || 0;
} }
if (curlyCounter === 0) { if (curlyCounter === 0) {
var needsParens = start !== 0 || end !== txt.length - 1; const needsParens = start !== 0 || end !== txt.length - 1;
res += (first ? '' : concatChar) + (needsParens ? '(' : '') + txt.substr(start + 1, end - start - 2) + (needsParens ? ')' : ''); res += (first ? '' : concatChar) + (needsParens ? '(' : '') + txt.substr(start + 1, end - start - 2) + (needsParens ? ')' : '');
first = false; first = false;
txt = txt.substr(end); txt = txt.substr(end);
@ -158,8 +158,8 @@ function convertText(node, context, txt) {
*/ */
function generateInjectedFunc(context, namePrefix, body, params) { function generateInjectedFunc(context, namePrefix, body, params) {
params = params || context.boundParams; params = params || context.boundParams;
var funcName = namePrefix.replace(',', '') + (context.injectedFunctions.length + 1); const funcName = namePrefix.replace(',', '') + (context.injectedFunctions.length + 1);
var funcText = `function ${funcName}(${params.join(',')}) { const funcText = `function ${funcName}(${params.join(',')}) {
${body} ${body}
} }
`; `;
@ -168,16 +168,16 @@ function generateInjectedFunc(context, namePrefix, body, params) {
} }
function generateTemplateProps(node, context) { function generateTemplateProps(node, context) {
var propTemplateDefinition = context.options.propTemplates[node.name]; const propTemplateDefinition = context.options.propTemplates[node.name];
var propertiesTemplates = _(node.children) const propertiesTemplates = _(node.children)
.map(function (child, index) { .map(function (child, index) {
var templateProp = null; let templateProp = null;
if (child.name === templateNode) { // Generic explicit template tag if (child.name === templateNode) { // Generic explicit template tag
if (!_.has(child.attribs, 'prop')) { if (!_.has(child.attribs, 'prop')) {
throw RTCodeError.build(context, child, 'rt-template must have a prop attribute'); throw RTCodeError.build(context, child, 'rt-template must have a prop attribute');
} }
var childTemplate = _.find(context.options.propTemplates, {prop: child.attribs.prop}) || {arguments: []}; const childTemplate = _.find(context.options.propTemplates, {prop: child.attribs.prop}) || {arguments: []};
templateProp = { templateProp = {
prop: child.attribs.prop, prop: child.attribs.prop,
arguments: (child.attribs.arguments ? child.attribs.arguments.split(',') : childTemplate.arguments) || [] arguments: (child.attribs.arguments ? child.attribs.arguments.split(',') : childTemplate.arguments) || []
@ -199,15 +199,15 @@ function generateTemplateProps(node, context) {
.value(); .value();
return _.transform(propertiesTemplates, function (props, templateProp) { return _.transform(propertiesTemplates, function (props, templateProp) {
var functionParams = _.values(context.boundParams).concat(templateProp.arguments); const functionParams = _.values(context.boundParams).concat(templateProp.arguments);
var oldBoundParams = context.boundParams; const oldBoundParams = context.boundParams;
context.boundParams = context.boundParams.concat(templateProp.arguments); context.boundParams = context.boundParams.concat(templateProp.arguments);
var functionBody = 'return ' + convertHtmlToReact(templateProp.content, context); const functionBody = 'return ' + convertHtmlToReact(templateProp.content, context);
context.boundParams = oldBoundParams; context.boundParams = oldBoundParams;
var generatedFuncName = generateInjectedFunc(context, templateProp.prop, functionBody, functionParams); const generatedFuncName = generateInjectedFunc(context, templateProp.prop, functionBody, functionParams);
props[templateProp.prop] = genBind(generatedFuncName, _.values(context.boundParams)); props[templateProp.prop] = genBind(generatedFuncName, _.values(context.boundParams));
// Remove the template child from the children definition. // Remove the template child from the children definition.
@ -221,9 +221,9 @@ function generateTemplateProps(node, context) {
* @return {string} * @return {string}
*/ */
function generateProps(node, context) { function generateProps(node, context) {
var props = {}; const props = {};
_.forOwn(node.attribs, function (val, key) { _.forOwn(node.attribs, function (val, key) {
var propKey = reactSupport.attributesMapping[key.toLowerCase()] || key; const propKey = reactSupport.attributesMapping[key.toLowerCase()] || key;
if (props.hasOwnProperty(propKey) && propKey !== reactSupport.classNameProp) { if (props.hasOwnProperty(propKey) && propKey !== reactSupport.classNameProp) {
throw RTCodeError.build(context, node, `duplicate definition of ${propKey} ${JSON.stringify(node.attribs)}`); throw RTCodeError.build(context, node, `duplicate definition of ${propKey} ${JSON.stringify(node.attribs)}`);
} }
@ -235,7 +235,7 @@ function generateProps(node, context) {
// Processing for both class and rt-class conveniently return strings that // Processing for both class and rt-class conveniently return strings that
// represent JS expressions, each evaluating to a space-separated set of class names. // represent JS expressions, each evaluating to a space-separated set of class names.
// We can just join them with another space here. // We can just join them with another space here.
var existing = props[propKey] ? `${props[propKey]} + " " + ` : ''; const existing = props[propKey] ? `${props[propKey]} + " " + ` : '';
if (key === classSetAttr) { if (key === classSetAttr) {
props[propKey] = existing + classSetTemplate({classSet: val}); props[propKey] = existing + classSetTemplate({classSet: val});
} else if (key === classAttr || key === reactSupport.classNameProp) { } else if (key === classAttr || key === reactSupport.classNameProp) {
@ -252,17 +252,17 @@ function generateProps(node, context) {
} }
function handleEventHandler(val, context, node, key) { function handleEventHandler(val, context, node, key) {
var funcParts = val.split('=>'); const funcParts = val.split('=>');
if (funcParts.length !== 2) { if (funcParts.length !== 2) {
throw RTCodeError.build(context, node, `when using 'on' events, use lambda '(p1,p2)=>body' notation or use {} to return a callback function. error: [${key}='${val}']`); throw RTCodeError.build(context, node, `when using 'on' events, use lambda '(p1,p2)=>body' notation or use {} to return a callback function. error: [${key}='${val}']`);
} }
var evtParams = funcParts[0].replace('(', '').replace(')', '').trim(); const evtParams = funcParts[0].replace('(', '').replace(')', '').trim();
var funcBody = funcParts[1].trim(); const funcBody = funcParts[1].trim();
var params = context.boundParams; let params = context.boundParams;
if (evtParams.trim() !== '') { if (evtParams.trim() !== '') {
params = params.concat([evtParams.trim()]); params = params.concat([evtParams.trim()]);
} }
var generatedFuncName = generateInjectedFunc(context, key, funcBody, params); const generatedFuncName = generateInjectedFunc(context, key, funcBody, params);
return genBind(generatedFuncName, context.boundParams); return genBind(generatedFuncName, context.boundParams);
} }
@ -296,7 +296,7 @@ function convertTagNameToConstructor(tagName, context) {
if (context.options.native) { if (context.options.native) {
return _.includes(reactNativeSupport[context.options.nativeTargetVersion], tagName) ? 'React.' + tagName : tagName; return _.includes(reactNativeSupport[context.options.nativeTargetVersion], tagName) ? 'React.' + tagName : tagName;
} }
var isHtmlTag = _.includes(reactDOMSupport[context.options.targetVersion], tagName); let isHtmlTag = _.includes(reactDOMSupport[context.options.targetVersion], tagName);
if (reactSupport.shouldUseCreateElement(context)) { if (reactSupport.shouldUseCreateElement(context)) {
isHtmlTag = isHtmlTag || tagName.match(/^\w+(-\w+)$/); isHtmlTag = isHtmlTag || tagName.match(/^\w+(-\w+)$/);
return isHtmlTag ? `'${tagName}'` : tagName; return isHtmlTag ? `'${tagName}'` : tagName;
@ -311,7 +311,7 @@ function convertTagNameToConstructor(tagName, context) {
* @return {Context} * @return {Context}
*/ */
function defaultContext(html, options, reportContext) { function defaultContext(html, options, reportContext) {
var defaultDefines = {}; const defaultDefines = {};
defaultDefines[options.reactImportPath] = 'React'; defaultDefines[options.reactImportPath] = 'React';
defaultDefines[options.lodashImportPath] = '_'; defaultDefines[options.lodashImportPath] = '_';
return { return {
@ -344,7 +344,7 @@ function convertHtmlToReact(node, context) {
}, context); }, context);
if (node.type === 'tag' && node.name === includeNode) { if (node.type === 'tag' && node.name === includeNode) {
var srcFile = node.attribs[includeSrcAttr]; const srcFile = node.attribs[includeSrcAttr];
if (!srcFile) { if (!srcFile) {
throw RTCodeError.build(context, node, 'rt-include must supply a source attribute'); throw RTCodeError.build(context, node, 'rt-include must supply a source attribute');
} }
@ -360,12 +360,12 @@ function convertHtmlToReact(node, context) {
return parseAndConvertHtmlToReact(context.html, context); return parseAndConvertHtmlToReact(context.html, context);
} }
var data = {name: convertTagNameToConstructor(node.name, context)}; const data = {name: convertTagNameToConstructor(node.name, context)};
// Order matters. We need to add the item and itemIndex to context.boundParams before // Order matters. We need to add the item and itemIndex to context.boundParams before
// the rt-scope directive is processed, lest they are not passed to the child scopes // the rt-scope directive is processed, lest they are not passed to the child scopes
if (node.attribs[repeatAttr]) { if (node.attribs[repeatAttr]) {
var arr = node.attribs[repeatAttr].split(' in '); const arr = node.attribs[repeatAttr].split(' in ');
if (arr.length !== 2) { if (arr.length !== 2) {
throw RTCodeError.build(context, node, `rt-repeat invalid 'in' expression '${node.attribs[repeatAttr]}'`); throw RTCodeError.build(context, node, `rt-repeat invalid 'in' expression '${node.attribs[repeatAttr]}'`);
} }
@ -400,8 +400,8 @@ function convertHtmlToReact(node, context) {
} }
} }
var children = _.map(node.children, function (child) { const children = _.map(node.children, function (child) {
var code = convertHtmlToReact(child, context); const code = convertHtmlToReact(child, context);
validateJS(code, child, context); validateJS(code, child, context);
return code; return code;
}); });
@ -415,8 +415,8 @@ function convertHtmlToReact(node, context) {
} }
if (node.attribs[scopeAttr]) { if (node.attribs[scopeAttr]) {
var functionBody = _.values(data.innerScope.innerMapping).join('\n') + `return ${data.body}`; const functionBody = _.values(data.innerScope.innerMapping).join('\n') + `return ${data.body}`;
var generatedFuncName = generateInjectedFunc(context, 'scope' + data.innerScope.scopeName, functionBody, _.keys(data.innerScope.outerMapping)); const generatedFuncName = generateInjectedFunc(context, 'scope' + data.innerScope.scopeName, functionBody, _.keys(data.innerScope.outerMapping));
data.body = `${generatedFuncName}.apply(this, [${_.values(data.innerScope.outerMapping).join(',')}])`; data.body = `${generatedFuncName}.apply(this, [${_.values(data.innerScope.outerMapping).join(',')}])`;
} }
@ -448,12 +448,12 @@ function handleScopeAttribute(node, context, data) {
data.innerScope.outerMapping = _.zipObject(context.boundParams, context.boundParams); data.innerScope.outerMapping = _.zipObject(context.boundParams, context.boundParams);
_(node.attribs[scopeAttr]).split(';').invokeMap('trim').compact().forEach(scopePart => { _(node.attribs[scopeAttr]).split(';').invokeMap('trim').compact().forEach(scopePart => {
var scopeSubParts = _(scopePart).split(' as ').invokeMap('trim').value(); const scopeSubParts = _(scopePart).split(' as ').invokeMap('trim').value();
if (scopeSubParts.length < 2) { if (scopeSubParts.length < 2) {
throw RTCodeError.build(context, node, `invalid scope part '${scopePart}'`); throw RTCodeError.build(context, node, `invalid scope part '${scopePart}'`);
} }
var alias = scopeSubParts[1]; const alias = scopeSubParts[1];
var value = scopeSubParts[0]; const value = scopeSubParts[0];
validateJS(alias, node, context); validateJS(alias, node, context);
// this adds both parameters to the list of parameters passed further down // this adds both parameters to the list of parameters passed further down
@ -468,8 +468,8 @@ function handleScopeAttribute(node, context, data) {
} }
function validateIfAttribute(node, context, data) { function validateIfAttribute(node, context, data) {
var innerMappingKeys = _.keys(data.innerScope && data.innerScope.innerMapping || {}); const innerMappingKeys = _.keys(data.innerScope && data.innerScope.innerMapping || {});
var ifAttributeTree = null; let ifAttributeTree = null;
try { try {
ifAttributeTree = esprima.parse(node.attribs[ifAttr]); ifAttributeTree = esprima.parse(node.attribs[ifAttr]);
} catch (e) { } catch (e) {
@ -495,7 +495,7 @@ function isTag(node) {
function handleSelfClosingHtmlTags(nodes) { function handleSelfClosingHtmlTags(nodes) {
return _.flatMap(nodes, function (node) { return _.flatMap(nodes, function (node) {
var externalNodes = []; let externalNodes = [];
node.children = handleSelfClosingHtmlTags(node.children); node.children = handleSelfClosingHtmlTags(node.children);
if (node.type === 'tag' && (_.includes(reactSupport.htmlSelfClosingTags, node.name) || if (node.type === 'tag' && (_.includes(reactSupport.htmlSelfClosingTags, node.name) ||
_.includes(reactTemplatesSelfClosingTags, node.name))) { _.includes(reactTemplatesSelfClosingTags, node.name))) {
@ -508,19 +508,19 @@ function handleSelfClosingHtmlTags(nodes) {
} }
function convertTemplateToReact(html, options) { function convertTemplateToReact(html, options) {
var context = require('./context'); const context = require('./context');
return convertRT(html, context, options); return convertRT(html, context, options);
} }
function parseAndConvertHtmlToReact(html, context) { function parseAndConvertHtmlToReact(html, context) {
var rootNode = cheerio.load(html, {lowerCaseTags: false, lowerCaseAttributeNames: false, xmlMode: true, withStartIndices: true}); const rootNode = cheerio.load(html, {lowerCaseTags: false, lowerCaseAttributeNames: false, xmlMode: true, withStartIndices: true});
utils.validate(context.options, context, context.reportContext, rootNode.root()[0]); utils.validate(context.options, context, context.reportContext, rootNode.root()[0]);
var rootTags = _.filter(rootNode.root()[0].children, isTag); let rootTags = _.filter(rootNode.root()[0].children, isTag);
rootTags = handleSelfClosingHtmlTags(rootTags); rootTags = handleSelfClosingHtmlTags(rootTags);
if (!rootTags || rootTags.length === 0) { if (!rootTags || rootTags.length === 0) {
throw new RTCodeError('Document should have a root element'); throw new RTCodeError('Document should have a root element');
} }
var firstTag = null; let firstTag = null;
_.forEach(rootTags, function (tag) { _.forEach(rootTags, function (tag) {
if (tag.name === 'rt-require') { if (tag.name === 'rt-require') {
if (!tag.attribs.dependency || !tag.attribs.as) { if (!tag.attribs.dependency || !tag.attribs.as) {
@ -552,14 +552,14 @@ function parseAndConvertHtmlToReact(html, context) {
function convertRT(html, reportContext, options) { function convertRT(html, reportContext, options) {
options = getOptions(options); options = getOptions(options);
var context = defaultContext(html, options, reportContext); const context = defaultContext(html, options, reportContext);
var body = parseAndConvertHtmlToReact(html, context); const body = parseAndConvertHtmlToReact(html, context);
var requirePaths = _(context.defines) const requirePaths = _(context.defines)
.keys() .keys()
.map(def => `"${def}"`) .map(def => `"${def}"`)
.join(','); .join(',');
var buildImport; let buildImport;
if (options.modules === 'typescript') { if (options.modules === 'typescript') {
buildImport = (v, p) => `import ${v} = require('${p}');`; buildImport = (v, p) => `import ${v} = require('${p}');`;
} else if (options.modules === 'es6') { // eslint-disable-line } else if (options.modules === 'es6') { // eslint-disable-line
@ -569,8 +569,8 @@ function convertRT(html, reportContext, options) {
} }
const header = options.flow ? '/* @flow */\n' : ''; const header = options.flow ? '/* @flow */\n' : '';
const vars = header + _(context.defines).map(buildImport).join('\n'); const vars = header + _(context.defines).map(buildImport).join('\n');
var data = {body, injectedFunctions: context.injectedFunctions.join('\n'), requireNames: _.values(context.defines).join(','), requirePaths, vars, name: options.name}; const data = {body, injectedFunctions: context.injectedFunctions.join('\n'), requireNames: _.values(context.defines).join(','), requirePaths, vars, name: options.name};
var code = generate(data, options); let code = generate(data, options);
if (options.modules !== 'typescript' && options.modules !== 'jsrt') { if (options.modules !== 'typescript' && options.modules !== 'jsrt') {
code = parseJS(code); code = parseJS(code);
} }
@ -579,7 +579,7 @@ function convertRT(html, reportContext, options) {
function parseJS(code) { function parseJS(code) {
try { try {
var tree = esprima.parse(code, {range: true, tokens: true, comment: true, sourceType: 'module'}); let tree = esprima.parse(code, {range: true, tokens: true, comment: true, sourceType: 'module'});
tree = escodegen.attachComments(tree, tree.comments, tree.tokens); tree = escodegen.attachComments(tree, tree.comments, tree.tokens);
return escodegen.generate(tree, {comment: true}); return escodegen.generate(tree, {comment: true});
} catch (e) { } catch (e) {
@ -590,14 +590,14 @@ function parseJS(code) {
function convertJSRTToJS(text, reportContext, options) { function convertJSRTToJS(text, reportContext, options) {
options = getOptions(options); options = getOptions(options);
options.modules = 'jsrt'; options.modules = 'jsrt';
var templateMatcherJSRT = /<template>([^]*?)<\/template>/gm; const templateMatcherJSRT = /<template>([^]*?)<\/template>/gm;
var code = text.replace(templateMatcherJSRT, (template, html) => convertRT(html, reportContext, options).replace(/;$/, '')); const code = text.replace(templateMatcherJSRT, (template, html) => convertRT(html, reportContext, options).replace(/;$/, ''));
code = parseJS(code);
return code; return parseJS(code);
} }
function generate(data, options) { function generate(data, options) {
var template = templates[options.modules]; const template = templates[options.modules];
return template(data); return template(data);
} }

View File

@ -1,5 +1,5 @@
'use strict'; 'use strict';
var map = { const map = {
/*flex*/ /*flex*/
alignItems: 'string', // "enum('flex-start', 'flex-end', 'center', 'stretch')", alignItems: 'string', // "enum('flex-start', 'flex-end', 'center', 'stretch')",
alignSelf: 'string', // "enum('auto', 'flex-start', 'flex-end', 'center', 'stretch')", alignSelf: 'string', // "enum('auto', 'flex-start', 'flex-end', 'center', 'stretch')",

View File

@ -1,10 +1,10 @@
'use strict'; 'use strict';
var css = require('css'); const css = require('css');
var _ = require('lodash'); const _ = require('lodash');
var rtnData = require('./rt-style-support-data.js'); const rtnData = require('./rt-style-support-data.js');
var templateCommonJSTemplate = _.template( const templateCommonJSTemplate = _.template(
`'use strict'; `'use strict';
var style = <%= body %>; var style = <%= body %>;
module.exports = style; module.exports = style;
@ -16,34 +16,26 @@ function convert(text) {
function convertBody(text) { function convertBody(text) {
//source //source
var obj = css.parse(text, {silent: false}); const obj = css.parse(text, {silent: false});
var result = _.reduce(obj.stylesheet.rules, processRule2, {}); const result = _.reduce(obj.stylesheet.rules, processRule2, {});
//var out = _.map(obj.stylesheet.rules, processRule).join(', ');
console.log(result); console.log(result);
return JSON.stringify(result, undefined, 2); return JSON.stringify(result, undefined, 2);
} }
function processRule2(result, rule) { function processRule2(result, rule) {
var name = rule.selectors[0].substring(1); const name = rule.selectors[0].substring(1);
result[name] = _.reduce(rule.declarations, processDeclaration, {}); result[name] = _.reduce(rule.declarations, processDeclaration, {});
return result; return result;
} }
function processDeclaration(result, dec) { function processDeclaration(result, dec) {
var prop = _.camelCase(dec.property); const prop = _.camelCase(dec.property);
result[prop] = convertValue(prop, dec.value); result[prop] = convertValue(prop, dec.value);
return result; return result;
} }
//function processRule(rule) {
// return rule.declarations.map(function (dec) {
// return stringUtils.convertToCamelCase(dec.property) + ': ' + convertValue(dec.property, dec.value);
// }).join(', ');
//}
function convertValue(p, v) { function convertValue(p, v) {
if (rtnData[p] === 'string') { if (rtnData[p] === 'string') {
//return "'" + v + "'";
return v; return v;
} }
// TODO remove units // TODO remove units

View File

@ -1,15 +1,15 @@
'use strict'; 'use strict';
var _ = require('lodash'); const _ = require('lodash');
/** /**
* @param {CONTEXT} context * @param {CONTEXT} context
* @return {number} * @return {number}
*/ */
function printResults(context) { function printResults(context) {
var warnings = context.getMessages(); const warnings = context.getMessages();
var out = require(`./formatters/${context.options.format}`)(warnings); const out = require(`./formatters/${context.options.format}`)(warnings);
context.report(out); context.report(out);
var grouped = _.groupBy(warnings, 'level'); const grouped = _.groupBy(warnings, 'level');
return grouped.ERROR ? grouped.ERROR.length : 0; return grouped.ERROR ? grouped.ERROR.length : 0;
} }

View File

@ -1,5 +1,5 @@
'use strict'; 'use strict';
var _ = require('lodash'); const _ = require('lodash');
/** /**
* @param {Array.<*>} array * @param {Array.<*>} array

View File

@ -1,8 +1,8 @@
'use strict'; 'use strict';
var _ = require('lodash'); const _ = require('lodash');
var esprima = require('esprima'); const esprima = require('esprima');
var rtError = require('./RTCodeError'); const rtError = require('./RTCodeError');
var RTCodeError = rtError.RTCodeError; const RTCodeError = rtError.RTCodeError;
/** /**
* @param {string} code * @param {string} code
@ -50,7 +50,7 @@ function addIfMissing(array, obj) {
* @return {string} * @return {string}
*/ */
function concatChildren(children) { function concatChildren(children) {
var res = ''; let res = '';
_.forEach(children, function (child) { _.forEach(children, function (child) {
if (child && !_.startsWith(child, ' /*')) { if (child && !_.startsWith(child, ' /*')) {
res += ','; res += ',';
@ -69,7 +69,7 @@ function concatChildren(children) {
*/ */
function validate(options, context, reportContext, node) { function validate(options, context, reportContext, node) {
if (node.type === 'tag' && node.attribs['rt-if'] && !node.attribs.key) { if (node.type === 'tag' && node.attribs['rt-if'] && !node.attribs.key) {
var loc = rtError.getNodeLoc(context, node); const loc = rtError.getNodeLoc(context, node);
reportContext.warn('rt-if without a key', options.fileName, loc.pos.line, loc.pos.col, loc.start, loc.end); reportContext.warn('rt-if without a key', options.fileName, loc.pos.line, loc.pos.col, loc.start, loc.end);
} }
if (node.children) { if (node.children) {

View File

@ -1,11 +1,11 @@
'use strict'; 'use strict';
var test = require('tape'); const test = require('tape');
var rtStyle = require('../../src/rtStyle'); const rtStyle = require('../../src/rtStyle');
var text = '.text { background-color: #00346E; padding: 3px; }'; const text = '.text { background-color: #00346E; padding: 3px; }';
var textEp = '{\n "text": {\n "backgroundColor": "#00346E",\n "padding": 3\n }\n}'; const textEp = '{\n "text": {\n "backgroundColor": "#00346E",\n "padding": 3\n }\n}';
test('html tests', function (t) { test('html tests', function (t) {
var res = rtStyle.convertBody(text); const res = rtStyle.convertBody(text);
t.equal(res, textEp); t.equal(res, textEp);
t.end(); t.end();
}); });

View File

@ -1,18 +1,18 @@
'use strict'; 'use strict';
var test = require('tape'); const test = require('tape');
var reactTemplates = require('../../src/reactTemplates'); const reactTemplates = require('../../src/reactTemplates');
var context = require('../../src/context'); const context = require('../../src/context');
var util = require('./util'); const util = require('./util');
var fsUtil = require('../../src/fsUtil'); const fsUtil = require('../../src/fsUtil');
var readFileNormalized = util.readFileNormalized; const readFileNormalized = util.readFileNormalized;
var compareAndWrite = util.compareAndWrite; const compareAndWrite = util.compareAndWrite;
var fs = require('fs'); const fs = require('fs');
var _ = require('lodash'); const _ = require('lodash');
var path = require('path'); const path = require('path');
var RTCodeError = reactTemplates.RTCodeError; const RTCodeError = reactTemplates.RTCodeError;
var dataPath = path.resolve(__dirname, '..', 'data'); const dataPath = path.resolve(__dirname, '..', 'data');
var invalidFiles = [ const invalidFiles = [
{file: 'if-with-scope/invalid-if-scope-1.rt', issue: new RTCodeError("invalid scope mapping used in if part 'this.bar(activeUsers.length)'", 0, 160, 1, 1)}, {file: 'if-with-scope/invalid-if-scope-1.rt', issue: new RTCodeError("invalid scope mapping used in if part 'this.bar(activeUsers.length)'", 0, 160, 1, 1)},
{file: 'if-with-scope/invalid-if-scope-2.rt', issue: new RTCodeError("invalid scope mapping used in if part 'this.bar[activeUsers || 0]'", 0, 158, 1, 1)}, {file: 'if-with-scope/invalid-if-scope-2.rt', issue: new RTCodeError("invalid scope mapping used in if part 'this.bar[activeUsers || 0]'", 0, 158, 1, 1)},
{file: 'if-with-scope/invalid-if-scope-3.rt', issue: new RTCodeError("invalid scope mapping used in if part 'this.foo + activeUsers.length > this.bar'", 0, 172, 1, 1)}, {file: 'if-with-scope/invalid-if-scope-3.rt', issue: new RTCodeError("invalid scope mapping used in if part 'this.foo + activeUsers.length > this.bar'", 0, 172, 1, 1)},
@ -37,9 +37,9 @@ test('invalid tests', function (t) {
invalidFiles.forEach(check); invalidFiles.forEach(check);
function check(testFile) { function check(testFile) {
var filename = path.join(dataPath, testFile.file); const filename = path.join(dataPath, testFile.file);
var html = util.readFileNormalized(filename); const html = util.readFileNormalized(filename);
var error = null; let error = null;
try { try {
reactTemplates.convertTemplateToReact(html); reactTemplates.convertTemplateToReact(html);
} catch (e) { } catch (e) {
@ -63,15 +63,15 @@ function normalizeError(err) {
} }
test('invalid tests json', function (t) { test('invalid tests json', function (t) {
var cli = require('../../src/cli'); const cli = require('../../src/cli');
t.plan(invalidFiles.length); t.plan(invalidFiles.length);
invalidFiles.forEach(check); invalidFiles.forEach(check);
function check(testFile) { function check(testFile) {
context.clear(); context.clear();
var filename = path.join(dataPath, testFile.file); const filename = path.join(dataPath, testFile.file);
var options = {format: 'json', force: true}; const options = {format: 'json', force: true};
cli.handleSingleFile(options, filename); cli.handleSingleFile(options, filename);
t.deepEqual(normalizeError(context.getMessages()[0]), errorEqualMessage(testFile.issue, filename), 'Expect cli to produce valid output messages'); t.deepEqual(normalizeError(context.getMessages()[0]), errorEqualMessage(testFile.issue, filename), 'Expect cli to produce valid output messages');
} }
@ -100,32 +100,32 @@ function errorEqualMessage(err, file) {
} }
test('rt-if with rt-scope test', function (t) { test('rt-if with rt-scope test', function (t) {
var files = ['if-with-scope/valid-if-scope.rt']; const files = ['if-with-scope/valid-if-scope.rt'];
testFiles(t, files); testFiles(t, files);
}); });
test('conversion test', function (t) { test('conversion test', function (t) {
var files = ['div.rt', 'test.rt', 'repeat.rt', 'inputs.rt', 'require.rt']; const files = ['div.rt', 'test.rt', 'repeat.rt', 'inputs.rt', 'require.rt'];
testFiles(t, files); testFiles(t, files);
}); });
test('prop template conversion test', function (t) { test('prop template conversion test', function (t) {
var options = { const options = {
propTemplates: { propTemplates: {
List: { List: {
Row: {prop: 'renderRow', arguments: ['rowData']} Row: {prop: 'renderRow', arguments: ['rowData']}
} }
} }
}; };
var files = ['propTemplates/simpleTemplate.rt', 'propTemplates/templateInScope.rt', 'propTemplates/implicitTemplate.rt', 'propTemplates/twoTemplates.rt']; const files = ['propTemplates/simpleTemplate.rt', 'propTemplates/templateInScope.rt', 'propTemplates/implicitTemplate.rt', 'propTemplates/twoTemplates.rt'];
testFiles(t, files, options); testFiles(t, files, options);
}); });
function checkFile(t, options, testFile) { function checkFile(t, options, testFile) {
var filename = path.join(dataPath, testFile); const filename = path.join(dataPath, testFile);
var html = readFileNormalized(filename); const html = readFileNormalized(filename);
var expected = readFileNormalized(filename + '.js'); const expected = readFileNormalized(filename + '.js');
var actual = reactTemplates.convertTemplateToReact(html, options).replace(/\r/g, '').trim(); const actual = reactTemplates.convertTemplateToReact(html, options).replace(/\r/g, '').trim();
compareAndWrite(t, actual, expected, filename); compareAndWrite(t, actual, expected, filename);
} }
@ -135,7 +135,7 @@ function testFiles(t, files, options) {
} }
test('conversion test - native', function (t) { test('conversion test - native', function (t) {
var options = { const options = {
propTemplates: { propTemplates: {
MyComp: { MyComp: {
Row: {prop: 'renderRow', arguments: ['rowData']} Row: {prop: 'renderRow', arguments: ['rowData']}
@ -143,12 +143,12 @@ test('conversion test - native', function (t) {
}, },
native: true native: true
}; };
var files = ['nativeView.rt', 'listViewTemplate.rt', 'listViewAndCustomTemplate.rt']; const files = ['nativeView.rt', 'listViewTemplate.rt', 'listViewAndCustomTemplate.rt'];
testFiles(t, files, options); testFiles(t, files, options);
}); });
test('convert div with all module types', function (t) { test('convert div with all module types', function (t) {
var files = [ const files = [
{source: 'div.rt', expected: 'div.rt.commonjs.js', options: {modules: 'commonjs'}}, {source: 'div.rt', expected: 'div.rt.commonjs.js', options: {modules: 'commonjs'}},
{source: 'div.rt', expected: 'div.rt.amd.js', options: {modules: 'amd', name: 'div'}}, {source: 'div.rt', expected: 'div.rt.amd.js', options: {modules: 'amd', name: 'div'}},
{source: 'div.rt', expected: 'div.rt.globals.js', options: {modules: 'none', name: 'div'}}, {source: 'div.rt', expected: 'div.rt.globals.js', options: {modules: 'none', name: 'div'}},
@ -159,32 +159,30 @@ test('convert div with all module types', function (t) {
files.forEach(check); files.forEach(check);
function check(testData) { function check(testData) {
var filename = path.join(dataPath, testData.source); const filename = path.join(dataPath, testData.source);
var html = readFileNormalized(filename); const html = readFileNormalized(filename);
var expected = readFileNormalized(path.join(dataPath, testData.expected)); const expected = readFileNormalized(path.join(dataPath, testData.expected));
// var expected = fs.readFileSync(filename.replace(".html", ".js")).toString(); const actual = reactTemplates.convertTemplateToReact(html, testData.options).replace(/\r/g, '').trim();
var actual = reactTemplates.convertTemplateToReact(html, testData.options).replace(/\r/g, '').trim();
compareAndWrite(t, actual, expected, filename); compareAndWrite(t, actual, expected, filename);
} }
}); });
test('convert jsrt and test source results', function (t) { test('convert jsrt and test source results', function (t) {
var files = ['simple.jsrt']; const files = ['simple.jsrt'];
t.plan(files.length); t.plan(files.length);
files.forEach(check); files.forEach(check);
function check(file) { function check(file) {
var filename = path.join(dataPath, file); const filename = path.join(dataPath, file);
var js = readFileNormalized(filename); const js = readFileNormalized(filename);
var expected = readFileNormalized(path.join(dataPath, file.replace('.jsrt', '.js'))); const expected = readFileNormalized(path.join(dataPath, file.replace('.jsrt', '.js')));
// var expected = fs.readFileSync(filename.replace(".html", ".js")).toString(); const actual = reactTemplates.convertJSRTToJS(js, context).replace(/\r/g, '').trim();
var actual = reactTemplates.convertJSRTToJS(js, context).replace(/\r/g, '').trim();
compareAndWrite(t, actual, expected, filename); compareAndWrite(t, actual, expected, filename);
} }
}); });
test('html tests', function (t) { test('html tests', function (t) {
var files = [ const files = [
'scope.rt', 'scope.rt',
'scope-trailing-semicolon.rt', 'scope-trailing-semicolon.rt',
'scope-variable-references.rt', 'scope-variable-references.rt',
@ -212,20 +210,17 @@ test('html tests', function (t) {
files.forEach(check); files.forEach(check);
function check(testFile) { function check(testFile) {
var filename = path.join(dataPath, testFile); const filename = path.join(dataPath, testFile);
var options = { const options = {
readFileSync: fsUtil.createRelativeReadFileSync(filename) readFileSync: fsUtil.createRelativeReadFileSync(filename)
}; };
var code = ''; let code = '';
try { try {
var html = fs.readFileSync(filename).toString(); const html = fs.readFileSync(filename).toString();
var expected = readFileNormalized(filename + '.html'); const expected = util.normalizeHtml(readFileNormalized(filename + '.html'));
// var expected = fs.readFileSync(filename.replace(".html", ".js")).toString();
code = reactTemplates.convertTemplateToReact(html, options).replace(/\r/g, ''); code = reactTemplates.convertTemplateToReact(html, options).replace(/\r/g, '');
var actual = util.codeToHtml(code); const actual = util.normalizeHtml(util.codeToHtml(code));
actual = util.normalizeHtml(actual); const equal = compareAndWrite(t, actual, expected, filename);
expected = util.normalizeHtml(expected);
var equal = compareAndWrite(t, actual, expected, filename);
if (!equal) { if (!equal) {
fs.writeFileSync(filename + '.code.js', code); fs.writeFileSync(filename + '.code.js', code);
} }
@ -248,17 +243,17 @@ test('test context', function (t) {
}); });
test('test shell', function (t) { test('test shell', function (t) {
var shell = require('../../src/shell'); const shell = require('../../src/shell');
var newContext = _.cloneDeep(context); const newContext = _.cloneDeep(context);
var outputJSON = ''; let outputJSON = '';
newContext.options.format = 'json'; newContext.options.format = 'json';
newContext.report = function (text) { outputJSON = text; }; newContext.report = function (text) { outputJSON = text; };
var r = shell.printResults(newContext); let r = shell.printResults(newContext);
t.equal(r, 0); t.equal(r, 0);
context.error('hi', '', 1, 1); context.error('hi', '', 1, 1);
r = shell.printResults(newContext); r = shell.printResults(newContext);
t.equal(r, 1); t.equal(r, 1);
var output = JSON.parse(outputJSON); const output = JSON.parse(outputJSON);
t.deepEqual(output, [{ t.deepEqual(output, [{
column: 1, column: 1,
endOffset: -1, endOffset: -1,
@ -274,40 +269,40 @@ test('test shell', function (t) {
}); });
test('test shell', function (t) { test('test shell', function (t) {
var filename = path.join(dataPath, 'div.rt'); const filename = path.join(dataPath, 'div.rt');
var cli = require('../../src/cli'); const cli = require('../../src/cli');
var r = cli.execute(`${filename} -r --dry-run`); const r = cli.execute(`${filename} -r --dry-run`);
t.equal(r, 0); t.equal(r, 0);
t.end(); t.end();
}); });
test('test convertText', function (t) { test('test convertText', function (t) {
var texts = [ const texts = [
{input: '{}', expected: '()'}, {input: '{}', expected: '()'},
{input: "a {'b'}", expected: '"a "+(\'b\')'} {input: "a {'b'}", expected: '"a "+(\'b\')'}
]; ];
t.plan(texts.length); t.plan(texts.length);
texts.forEach(check); texts.forEach(check);
function check(testData) { function check(testData) {
var r = reactTemplates._test.convertText({}, {}, testData.input); const r = reactTemplates._test.convertText({}, {}, testData.input);
t.equal(r, testData.expected); t.equal(r, testData.expected);
} }
}); });
test('util.isStale', function (t) { test('util.isStale', function (t) {
var a = path.join(dataPath, 'a.tmp'); const a = path.join(dataPath, 'a.tmp');
var b = path.join(dataPath, 'b.tmp'); const b = path.join(dataPath, 'b.tmp');
fs.writeFileSync(a, 'actual'); fs.writeFileSync(a, 'actual');
fs.writeFileSync(b, 'actual'); fs.writeFileSync(b, 'actual');
var mtime1 = new Date(1995, 11, 17, 3, 24, 0); const mtime1 = new Date(1995, 11, 17, 3, 24, 0);
fs.utimesSync(a, mtime1, mtime1); fs.utimesSync(a, mtime1, mtime1);
var mtime2 = new Date(1995, 11, 17, 3, 24, 1); const mtime2 = new Date(1995, 11, 17, 3, 24, 1);
fs.utimesSync(b, mtime2, mtime2); fs.utimesSync(b, mtime2, mtime2);
var actual = fsUtil.isStale(a, b); let actual = fsUtil.isStale(a, b);
t.equal(actual, false); t.equal(actual, false);
actual = fsUtil.isStale(b, a); actual = fsUtil.isStale(b, a);
t.equal(actual, true); t.equal(actual, true);

View File

@ -1,11 +1,11 @@
'use strict'; 'use strict';
var cheerio = require('cheerio'); const cheerio = require('cheerio');
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
var reactTemplates = require('../../src/reactTemplates'); const reactTemplates = require('../../src/reactTemplates');
var React = require('react'); const React = require('react');
var ReactDOMServer = require('react-dom/server'); const ReactDOMServer = require('react-dom/server');
var _ = require('lodash'); const _ = require('lodash');
/** /**
* @param {string} html * @param {string} html
@ -42,7 +42,7 @@ function readFileNormalized(filename) {
return readFile(filename).replace(/\r/g, '').trim(); return readFile(filename).replace(/\r/g, '').trim();
} }
//var dataPath = path.resolve(__dirname, '..', 'data'); //const dataPath = path.resolve(__dirname, '..', 'data');
/** /**
* @param {string} filename * @param {string} filename
* @return {string} * @return {string}
@ -52,23 +52,23 @@ function readFile(filename) {
} }
function joinDataPath(fileName) { function joinDataPath(fileName) {
var dataPath = path.resolve(__dirname, '..', 'data'); const dataPath = path.resolve(__dirname, '..', 'data');
return path.join(dataPath, fileName); return path.join(dataPath, fileName);
} }
function rtToHtml(rt) { function rtToHtml(rt) {
var code = reactTemplates.convertTemplateToReact(rt).replace(/\r/g, ''); const code = reactTemplates.convertTemplateToReact(rt).replace(/\r/g, '');
return codeToHtml(code); return codeToHtml(code);
} }
function codeToHtml(code) { function codeToHtml(code) {
var defineMap = {'react/addons': React, lodash: _}; const defineMap = {'react/addons': React, lodash: _};
//noinspection JSUnusedLocalSymbols //noinspection JSUnusedLocalSymbols
var define = function (requirementsNames, content) { //eslint-disable-line no-unused-vars,func-style const define = function (requirementsNames, content) { //eslint-disable-line no-unused-vars,func-style
var requirements = _.map(requirementsNames, reqName => defineMap[reqName]); const requirements = _.map(requirementsNames, reqName => defineMap[reqName]);
return content.apply(this, requirements); return content.apply(this, requirements);
}; };
var comp = React.createFactory(React.createClass({ const comp = React.createFactory(React.createClass({
displayName: 'testClass', displayName: 'testClass',
render: eval(code) //eslint-disable-line no-eval render: eval(code) //eslint-disable-line no-eval
})); }));