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"],
"rules": {
"semi": [2, "always"],
"no-var": 0,
"object-shorthand": 0,
"prefer-arrow-callback": 0,
"prefer-const": 0,
"prefer-spread": 0,
"prefer-template": 0,
"consistent-return": 0,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,14 +1,14 @@
'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'];
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'];
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'];
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'];
var svg = ['a', 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animate', 'animateMotion', 'animateTransform', 'circle', 'clipPath', 'color-profile', 'cursor', 'defs', 'desc', 'ellipse', 'feBlend', 'g', 'image', 'line',
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'];
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'];
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'];
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'];
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.13.1': v12_svg,
'0.12.2': v12_svg,

View File

@ -1,10 +1,10 @@
'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,
default: '0.9.0'
};
module.exports = versions;
module.exports = versions;

View File

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

View File

@ -1,5 +1,5 @@
'use strict';
var _ = require('lodash');
const _ = require('lodash');
/**
* @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',
'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',
'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'];
var classNameProp = 'className';
var attributesMapping = {'class': classNameProp, 'rt-class': classNameProp, 'for': 'htmlFor'}; //eslint-disable-line quote-props
const classNameProp = 'className';
const attributesMapping = {'class': classNameProp, 'rt-class': classNameProp, 'for': 'htmlFor'}; //eslint-disable-line quote-props
_.forEach(reactSupportedAttributes, function (attributeReactName) {
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});");
var 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');
var templatePJSTemplate = _.template(`var <%= name %> = function () {
const templateAMDTemplate = _.template("define(<%= name ? '\"'+name + '\", ' : '' %>[<%= requirePaths %>], function (<%= requireNames %>) {\n'use strict';\n <%= injectedFunctions %>\nreturn function(){ return <%= body %>};\n});");
const templateCommonJSTemplate = _.template("'use strict';\n<%= vars %>\n\n<%= injectedFunctions %>\nmodule.exports = function(){ return <%= body %>};\n");
const templateES6Template = _.template('<%= vars %>\n\n<%= injectedFunctions %>\nexport default function(){ return <%= body %>}\n');
const templatePJSTemplate = _.template(`var <%= name %> = function () {
<%= injectedFunctions %>
return <%= body %>
};
`);
var 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 templateTypescriptTemplate = _.template('<%= vars %>\n\n<%= injectedFunctions %>\nvar fn = function() { return <%= body %> };\nexport = fn\n');
const templateJSRTTemplate = _.template('(function () {\n <%= injectedFunctions %>\n return function(){\nreturn <%= body %>}}\n)()');
var templates = {
const templates = {
amd: templateAMDTemplate,
commonjs: templateCommonJSTemplate,
typescript: templateTypescriptTemplate,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,8 +1,8 @@
'use strict';
var _ = require('lodash');
var esprima = require('esprima');
var rtError = require('./RTCodeError');
var RTCodeError = rtError.RTCodeError;
const _ = require('lodash');
const esprima = require('esprima');
const rtError = require('./RTCodeError');
const RTCodeError = rtError.RTCodeError;
/**
* @param {string} code
@ -50,7 +50,7 @@ function addIfMissing(array, obj) {
* @return {string}
*/
function concatChildren(children) {
var res = '';
let res = '';
_.forEach(children, function (child) {
if (child && !_.startsWith(child, ' /*')) {
res += ',';
@ -69,7 +69,7 @@ function concatChildren(children) {
*/
function validate(options, context, reportContext, node) {
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);
}
if (node.children) {

View File

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

View File

@ -1,18 +1,18 @@
'use strict';
var test = require('tape');
var reactTemplates = require('../../src/reactTemplates');
var context = require('../../src/context');
var util = require('./util');
var fsUtil = require('../../src/fsUtil');
var readFileNormalized = util.readFileNormalized;
var compareAndWrite = util.compareAndWrite;
var fs = require('fs');
var _ = require('lodash');
var path = require('path');
var RTCodeError = reactTemplates.RTCodeError;
var dataPath = path.resolve(__dirname, '..', 'data');
const test = require('tape');
const reactTemplates = require('../../src/reactTemplates');
const context = require('../../src/context');
const util = require('./util');
const fsUtil = require('../../src/fsUtil');
const readFileNormalized = util.readFileNormalized;
const compareAndWrite = util.compareAndWrite;
const fs = require('fs');
const _ = require('lodash');
const path = require('path');
const RTCodeError = reactTemplates.RTCodeError;
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-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)},
@ -37,9 +37,9 @@ test('invalid tests', function (t) {
invalidFiles.forEach(check);
function check(testFile) {
var filename = path.join(dataPath, testFile.file);
var html = util.readFileNormalized(filename);
var error = null;
const filename = path.join(dataPath, testFile.file);
const html = util.readFileNormalized(filename);
let error = null;
try {
reactTemplates.convertTemplateToReact(html);
} catch (e) {
@ -63,15 +63,15 @@ function normalizeError(err) {
}
test('invalid tests json', function (t) {
var cli = require('../../src/cli');
const cli = require('../../src/cli');
t.plan(invalidFiles.length);
invalidFiles.forEach(check);
function check(testFile) {
context.clear();
var filename = path.join(dataPath, testFile.file);
var options = {format: 'json', force: true};
const filename = path.join(dataPath, testFile.file);
const options = {format: 'json', force: true};
cli.handleSingleFile(options, filename);
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) {
var files = ['if-with-scope/valid-if-scope.rt'];
const files = ['if-with-scope/valid-if-scope.rt'];
testFiles(t, files);
});
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);
});
test('prop template conversion test', function (t) {
var options = {
const options = {
propTemplates: {
List: {
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);
});
function checkFile(t, options, testFile) {
var filename = path.join(dataPath, testFile);
var html = readFileNormalized(filename);
var expected = readFileNormalized(filename + '.js');
var actual = reactTemplates.convertTemplateToReact(html, options).replace(/\r/g, '').trim();
const filename = path.join(dataPath, testFile);
const html = readFileNormalized(filename);
const expected = readFileNormalized(filename + '.js');
const actual = reactTemplates.convertTemplateToReact(html, options).replace(/\r/g, '').trim();
compareAndWrite(t, actual, expected, filename);
}
@ -135,7 +135,7 @@ function testFiles(t, files, options) {
}
test('conversion test - native', function (t) {
var options = {
const options = {
propTemplates: {
MyComp: {
Row: {prop: 'renderRow', arguments: ['rowData']}
@ -143,12 +143,12 @@ test('conversion test - native', function (t) {
},
native: true
};
var files = ['nativeView.rt', 'listViewTemplate.rt', 'listViewAndCustomTemplate.rt'];
const files = ['nativeView.rt', 'listViewTemplate.rt', 'listViewAndCustomTemplate.rt'];
testFiles(t, files, options);
});
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.amd.js', options: {modules: 'amd', 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);
function check(testData) {
var filename = path.join(dataPath, testData.source);
var html = readFileNormalized(filename);
var expected = readFileNormalized(path.join(dataPath, testData.expected));
// var expected = fs.readFileSync(filename.replace(".html", ".js")).toString();
var actual = reactTemplates.convertTemplateToReact(html, testData.options).replace(/\r/g, '').trim();
const filename = path.join(dataPath, testData.source);
const html = readFileNormalized(filename);
const expected = readFileNormalized(path.join(dataPath, testData.expected));
const actual = reactTemplates.convertTemplateToReact(html, testData.options).replace(/\r/g, '').trim();
compareAndWrite(t, actual, expected, filename);
}
});
test('convert jsrt and test source results', function (t) {
var files = ['simple.jsrt'];
const files = ['simple.jsrt'];
t.plan(files.length);
files.forEach(check);
function check(file) {
var filename = path.join(dataPath, file);
var js = readFileNormalized(filename);
var expected = readFileNormalized(path.join(dataPath, file.replace('.jsrt', '.js')));
// var expected = fs.readFileSync(filename.replace(".html", ".js")).toString();
var actual = reactTemplates.convertJSRTToJS(js, context).replace(/\r/g, '').trim();
const filename = path.join(dataPath, file);
const js = readFileNormalized(filename);
const expected = readFileNormalized(path.join(dataPath, file.replace('.jsrt', '.js')));
const actual = reactTemplates.convertJSRTToJS(js, context).replace(/\r/g, '').trim();
compareAndWrite(t, actual, expected, filename);
}
});
test('html tests', function (t) {
var files = [
const files = [
'scope.rt',
'scope-trailing-semicolon.rt',
'scope-variable-references.rt',
@ -212,20 +210,17 @@ test('html tests', function (t) {
files.forEach(check);
function check(testFile) {
var filename = path.join(dataPath, testFile);
var options = {
const filename = path.join(dataPath, testFile);
const options = {
readFileSync: fsUtil.createRelativeReadFileSync(filename)
};
var code = '';
let code = '';
try {
var html = fs.readFileSync(filename).toString();
var expected = readFileNormalized(filename + '.html');
// var expected = fs.readFileSync(filename.replace(".html", ".js")).toString();
const html = fs.readFileSync(filename).toString();
const expected = util.normalizeHtml(readFileNormalized(filename + '.html'));
code = reactTemplates.convertTemplateToReact(html, options).replace(/\r/g, '');
var actual = util.codeToHtml(code);
actual = util.normalizeHtml(actual);
expected = util.normalizeHtml(expected);
var equal = compareAndWrite(t, actual, expected, filename);
const actual = util.normalizeHtml(util.codeToHtml(code));
const equal = compareAndWrite(t, actual, expected, filename);
if (!equal) {
fs.writeFileSync(filename + '.code.js', code);
}
@ -248,17 +243,17 @@ test('test context', function (t) {
});
test('test shell', function (t) {
var shell = require('../../src/shell');
var newContext = _.cloneDeep(context);
var outputJSON = '';
const shell = require('../../src/shell');
const newContext = _.cloneDeep(context);
let outputJSON = '';
newContext.options.format = 'json';
newContext.report = function (text) { outputJSON = text; };
var r = shell.printResults(newContext);
let r = shell.printResults(newContext);
t.equal(r, 0);
context.error('hi', '', 1, 1);
r = shell.printResults(newContext);
t.equal(r, 1);
var output = JSON.parse(outputJSON);
const output = JSON.parse(outputJSON);
t.deepEqual(output, [{
column: 1,
endOffset: -1,
@ -274,40 +269,40 @@ test('test shell', function (t) {
});
test('test shell', function (t) {
var filename = path.join(dataPath, 'div.rt');
var cli = require('../../src/cli');
var r = cli.execute(`${filename} -r --dry-run`);
const filename = path.join(dataPath, 'div.rt');
const cli = require('../../src/cli');
const r = cli.execute(`${filename} -r --dry-run`);
t.equal(r, 0);
t.end();
});
test('test convertText', function (t) {
var texts = [
const texts = [
{input: '{}', expected: '()'},
{input: "a {'b'}", expected: '"a "+(\'b\')'}
];
t.plan(texts.length);
texts.forEach(check);
function check(testData) {
var r = reactTemplates._test.convertText({}, {}, testData.input);
const r = reactTemplates._test.convertText({}, {}, testData.input);
t.equal(r, testData.expected);
}
});
test('util.isStale', function (t) {
var a = path.join(dataPath, 'a.tmp');
var b = path.join(dataPath, 'b.tmp');
const a = path.join(dataPath, 'a.tmp');
const b = path.join(dataPath, 'b.tmp');
fs.writeFileSync(a, '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);
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);
var actual = fsUtil.isStale(a, b);
let actual = fsUtil.isStale(a, b);
t.equal(actual, false);
actual = fsUtil.isStale(b, a);
t.equal(actual, true);

View File

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