From 4cb8c4524c2a932fd0e6a94091819215f32e397a Mon Sep 17 00:00:00 2001 From: Omer Ganim Date: Wed, 27 Apr 2016 14:04:02 +0300 Subject: [PATCH] enable rules no-var and prefer-const and fix errors --- .babelrc | 3 +- .eslintrc | 2 - Gruntfile.js | 7 +- bin/rt.js | 4 +- playground/.eslintrc | 3 +- sample/.eslintrc | 3 +- src/RTCodeError.js | 18 ++-- src/api.js | 29 +++--- src/cli.js | 34 +++---- src/context.js | 10 +- src/formatters/stylish.js | 44 ++++----- src/fsUtil.js | 10 +- src/options.js | 8 +- src/reactDOMSupport.js | 14 +-- src/reactNativeSupport.js | 6 +- src/reactPropTemplates.js | 4 +- src/reactSupport.js | 24 ++--- src/reactTemplates.js | 184 +++++++++++++++++------------------ src/rt-style-support-data.js | 2 +- src/rtStyle.js | 24 ++--- src/shell.js | 8 +- src/stringUtils.js | 2 +- src/utils.js | 12 +-- test/src/styleTest.js | 10 +- test/src/test.js | 129 ++++++++++++------------ test/src/util.js | 28 +++--- 26 files changed, 301 insertions(+), 321 deletions(-) diff --git a/.babelrc b/.babelrc index c13c5f6..37db7f6 100644 --- a/.babelrc +++ b/.babelrc @@ -1,3 +1,4 @@ { - "presets": ["es2015"] + "presets": ["es2015"], + "ignore": "test/data" } diff --git a/.eslintrc b/.eslintrc index c6363b0..f6c76c4 100644 --- a/.eslintrc +++ b/.eslintrc @@ -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, diff --git a/Gruntfile.js b/Gruntfile.js index 15e7435..9f094e3 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -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; }); diff --git a/bin/rt.js b/bin/rt.js index 788e66e..d7a0cd8 100755 --- a/bin/rt.js +++ b/bin/rt.js @@ -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); diff --git a/playground/.eslintrc b/playground/.eslintrc index 2efca40..233c9e1 100644 --- a/playground/.eslintrc +++ b/playground/.eslintrc @@ -1,6 +1,7 @@ { "rules": { - "strict": [2, "function"] + "strict": [2, "function"], + "no-var": 0 }, "env": { "browser": true, diff --git a/sample/.eslintrc b/sample/.eslintrc index 2efca40..233c9e1 100644 --- a/sample/.eslintrc +++ b/sample/.eslintrc @@ -1,6 +1,7 @@ { "rules": { - "strict": [2, "function"] + "strict": [2, "function"], + "no-var": 0 }, "env": { "browser": true, diff --git a/src/RTCodeError.js b/src/RTCodeError.js index bd9382d..789ec8d 100644 --- a/src/RTCodeError.js +++ b/src/RTCodeError.js @@ -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 diff --git a/src/api.js b/src/api.js index 5346d2c..89ccae0 100644 --- a/src/api.js +++ b/src/api.js @@ -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: {} diff --git a/src/cli.js b/src/cli.js index 1c058ef..3ead963 100755 --- a/src/cli.js +++ b/src/cli.js @@ -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) { diff --git a/src/context.js b/src/context.js index 12aee63..3c3413f 100644 --- a/src/context.js +++ b/src/context.js @@ -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.} */ messages: [], /** @type {boolean} */ diff --git a/src/formatters/stylish.js b/src/formatters/stylish.js index 6891a05..ab7d1a7 100644 --- a/src/formatters/stylish.js +++ b/src/formatters/stylish.js @@ -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'); diff --git a/src/fsUtil.js b/src/fsUtil.js index 481ae04..34f47a5 100644 --- a/src/fsUtil.js +++ b/src/fsUtil.js @@ -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)); } diff --git a/src/options.js b/src/options.js index 97cba99..f66abfb 100644 --- a/src/options.js +++ b/src/options.js @@ -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 diff --git a/src/reactDOMSupport.js b/src/reactDOMSupport.js index 8b498ae..eb93554 100644 --- a/src/reactDOMSupport.js +++ b/src/reactDOMSupport.js @@ -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, diff --git a/src/reactNativeSupport.js b/src/reactNativeSupport.js index c2a6a42..b151e6a 100644 --- a/src/reactNativeSupport.js +++ b/src/reactNativeSupport.js @@ -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; \ No newline at end of file +module.exports = versions; diff --git a/src/reactPropTemplates.js b/src/reactPropTemplates.js index e3029e4..78ff76c 100644 --- a/src/reactPropTemplates.js +++ b/src/reactPropTemplates.js @@ -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: {} -}; \ No newline at end of file +}; diff --git a/src/reactSupport.js b/src/reactSupport.js index b607be7..cdc6432 100644 --- a/src/reactSupport.js +++ b/src/reactSupport.js @@ -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, diff --git a/src/reactTemplates.js b/src/reactTemplates.js index 10a2cab..d4c337c 100644 --- a/src/reactTemplates.js +++ b/src/reactTemplates.js @@ -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 = /