Skip to content

Commit

Permalink
Code style and bump to 1.0.0-beta9
Browse files Browse the repository at this point in the history
  • Loading branch information
karellm committed Apr 7, 2018
1 parent 9ef46f5 commit ce08b6c
Show file tree
Hide file tree
Showing 7 changed files with 113 additions and 32 deletions.
13 changes: 10 additions & 3 deletions dist/helpers.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.populateHash = exports.mergeHashes = exports.dotPathToHash = undefined;var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {return typeof obj;} : function (obj) {return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;};var _lodash = require('lodash');var _lodash2 = _interopRequireDefault(_lodash);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.ParsingError = exports.populateHash = exports.mergeHashes = exports.dotPathToHash = undefined;var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {return typeof obj;} : function (obj) {return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;};var _lodash = require('lodash');var _lodash2 = _interopRequireDefault(_lodash);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self, call) {if (!self) {throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call && (typeof call === "object" || typeof call === "function") ? call : self;}function _inherits(subClass, superClass) {if (typeof superClass !== "function" && superClass !== null) {throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;}

// Turn an entry for the Parser and turn in into a hash,
// turning the key path 'foo.bar' into an hash {foo: {bar: ""}}
Expand Down Expand Up @@ -103,10 +103,17 @@ function populateHash(source) {var target = arguments.length > 1 && arguments[1]
});

return target;
}exports.
}var

ParsingError = function (_Error) {_inherits(ParsingError, _Error);
function ParsingError(message) {_classCallCheck(this, ParsingError);var _this = _possibleConstructorReturn(this, (ParsingError.__proto__ || Object.getPrototypeOf(ParsingError)).call(this,
message));
_this.name = 'ParsingError';return _this;
}return ParsingError;}(Error);exports.



dotPathToHash = dotPathToHash;exports.
mergeHashes = mergeHashes;exports.
populateHash = populateHash;
populateHash = populateHash;exports.
ParsingError = ParsingError;
62 changes: 60 additions & 2 deletions dist/lexers/jsx-lexer.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
'use strict';Object.defineProperty(exports, "__esModule", { value: true });var _extends = Object.assign || function (target) {for (var i = 1; i < arguments.length; i++) {var source = arguments[i];for (var key in source) {if (Object.prototype.hasOwnProperty.call(source, key)) {target[key] = source[key];}}}return target;};var _createClass = function () {function defineProperties(target, props) {for (var i = 0; i < props.length; i++) {var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);}}return function (Constructor, protoProps, staticProps) {if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;};}();var _htmlLexer = require('./html-lexer');var _htmlLexer2 = _interopRequireDefault(_htmlLexer);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self, call) {if (!self) {throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call && (typeof call === "object" || typeof call === "function") ? call : self;}function _inherits(subClass, superClass) {if (typeof superClass !== "function" && superClass !== null) {throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;}var
'use strict';Object.defineProperty(exports, "__esModule", { value: true });var _extends = Object.assign || function (target) {for (var i = 1; i < arguments.length; i++) {var source = arguments[i];for (var key in source) {if (Object.prototype.hasOwnProperty.call(source, key)) {target[key] = source[key];}}}return target;};var _createClass = function () {function defineProperties(target, props) {for (var i = 0; i < props.length; i++) {var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);}}return function (Constructor, protoProps, staticProps) {if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;};}();var _acornJsx = require('acorn-jsx');var acorn = _interopRequireWildcard(_acornJsx);
var _assert = require('assert');var _assert2 = _interopRequireDefault(_assert);
var _htmlLexer = require('./html-lexer');var _htmlLexer2 = _interopRequireDefault(_htmlLexer);
var _baseLexer = require('./base-lexer');var _baseLexer2 = _interopRequireDefault(_baseLexer);
var _helpers = require('../helpers');function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _interopRequireWildcard(obj) {if (obj && obj.__esModule) {return obj;} else {var newObj = {};if (obj != null) {for (var key in obj) {if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];}}newObj.default = obj;return newObj;}}function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self, call) {if (!self) {throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call && (typeof call === "object" || typeof call === "function") ? call : self;}function _inherits(subClass, superClass) {if (typeof superClass !== "function" && superClass !== null) {throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;}var

JsxLexer = function (_HTMLLexer) {_inherits(JsxLexer, _HTMLLexer);
function JsxLexer() {var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};_classCallCheck(this, JsxLexer);
Expand Down Expand Up @@ -44,7 +48,7 @@ JsxLexer = function (_HTMLLexer) {_inherits(JsxLexer, _HTMLLexer);
var key = attrs.keys;

if (matches[3] && !attrs.options.defaultValue) {
attrs.options.defaultValue = matches[3].trim();
attrs.options.defaultValue = this.eraseTags(matches[0]).replace(/\s+/g, ' ');
}

if (key) {
Expand All @@ -53,4 +57,58 @@ JsxLexer = function (_HTMLLexer) {_inherits(JsxLexer, _HTMLLexer);
}

return this.keys;
}

/**
* Recursively convert html tags and js injections to tags with the child index in it
* @param {string} string
*
* @returns string
*/ }, { key: 'eraseTags', value: function eraseTags(
string) {
var acornAst = acorn.parse(string, { plugins: { jsx: true } });
var acornTransAst = acornAst.body[0].expression;
var children = this.parseAcornPayload(acornTransAst.children, string);

var elemsToString = function elemsToString(children) {return children.map(function (child, index) {
switch (child.type) {
case 'text':return child.content;
case 'js':return '<' + index + '>' + child.content + '</' + index + '>';
case 'tag':return '<' + index + '>' + elemsToString(child.children) + '</' + index + '>';
default:throw new _helpers.ParsingError('Unknown parsed content: ' + child.type);}

}).join('');};

return elemsToString(children);
}

/**
* Simplify the bulky AST given by Acorn
* @param {*} children An array of elements contained inside an html tag
* @param {string} originalString The original string being parsed
*/ }, { key: 'parseAcornPayload', value: function parseAcornPayload(
children, originalString) {var _this2 = this;
return children.map(function (child) {
if (child.type === 'JSXText') {
return {
type: 'text',
content: child.value.replace(/^(?:\s*(\n|\r)\s*)?(.*)(?:\s*(\n|\r)\s*)?$/, '$2') };

} else
if (child.type === 'JSXElement') {
return {
type: 'tag',
children: _this2.parseAcornPayload(child.children, originalString) };

} else
if (child.type === 'JSXExpressionContainer') {
return {
type: 'js',
content: originalString.slice(child.start, child.end) };

} else
{
throw new _helpers.ParsingError('Unknown ast element when parsing jsx: ' + child.type);
}
}).filter(function (child) {return child.type !== 'text' || child.content;});
} }]);return JsxLexer;}(_htmlLexer2.default);exports.default = JsxLexer;
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"author": "Karel Ledru",
"description": "Command Line tool for i18next",
"name": "i18next-parser",
"version": "1.0.0-beta8",
"version": "1.0.0-beta9",
"license": "MIT",
"main": "src/index.js",
"bin": {
Expand Down
2 changes: 1 addition & 1 deletion src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ function populateHash(source, target = {}) {
class ParsingError extends Error {
constructor(message) {
super(message);
this.name = "ParsingError";
this.name = 'ParsingError';
}
}

Expand Down
50 changes: 27 additions & 23 deletions src/lexers/jsx-lexer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as acorn from 'acorn-jsx';
import * as acorn from 'acorn-jsx'
import assert from 'assert'
import HTMLLexer from './html-lexer'
import BaseLexer from './base-lexer';
import { ParsingError } from '../helpers';
import BaseLexer from './base-lexer'
import { ParsingError } from '../helpers'

export default class JsxLexer extends HTMLLexer {
constructor(options = {}) {
Expand Down Expand Up @@ -61,26 +61,25 @@ export default class JsxLexer extends HTMLLexer {

/**
* Recursively convert html tags and js injections to tags with the child index in it
*
* @param {string} string
*
* @returns string
*/
eraseTags(string) {
const acornAst = acorn.parse(string, {plugins: {jsx: true}});
const acornTransAst = acornAst.body[0].expression;
const children = this.parseAcornPayload(acornTransAst.children, string);
const acornAst = acorn.parse(string, {plugins: {jsx: true}})
const acornTransAst = acornAst.body[0].expression
const children = this.parseAcornPayload(acornTransAst.children, string)

const elemsToString = children => children.map((child, index) => {
switch(child.type) {
case 'text': return child.content;
case 'js': return `<${index}>${child.content}</${index}>`;
case 'tag': return `<${index}>${elemsToString(child.children)}</${index}>`;
default: throw new ParsingError('Unknown parsed content: ' + child.type);
case 'text': return child.content
case 'js': return `<${index}>${child.content}</${index}>`
case 'tag': return `<${index}>${elemsToString(child.children)}</${index}>`
default: throw new ParsingError('Unknown parsed content: ' + child.type)
}
}).join('');
}).join('')

return elemsToString(children);
return elemsToString(children)
}

/**
Expand All @@ -90,22 +89,27 @@ export default class JsxLexer extends HTMLLexer {
*/
parseAcornPayload(children, originalString) {
return children.map(child => {
switch (child.type) {
case 'JSXText': return {
if (child.type === 'JSXText') {
return {
type: 'text',
content: child.value.replace(/^(?:\s*(\n|\r)\s*)?(.*)(?:\s*(\n|\r)\s*)?$/, '$2')
};
case 'JSXElement': return {
}
}
else if (child.type === 'JSXElement') {
return {
type: 'tag',
children: this.parseAcornPayload(child.children, originalString)
};
case 'JSXExpressionContainer': return {
}
}
else if (child.type === 'JSXExpressionContainer') {
return {
type: 'js',
content: originalString.slice(child.start, child.end)
};
default: throw new ParsingError("Unknown ast element when parsing jsx: " + child.type)
}
}
else {
throw new ParsingError('Unknown ast element when parsing jsx: ' + child.type)
}
// Remove empty text elements
}).filter(child => child.type !== 'text' || child.content);
}).filter(child => child.type !== 'text' || child.content)
}
}
6 changes: 4 additions & 2 deletions test/lexers/jsx-lexer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@ describe('JsxLexer', () => {
])
done()
})
})

it('erases tags from content', done => {
describe('eraseTags()', () => {
it('erases tags from content', (done) => {
const Lexer = new JsxLexer()
const content = '<Trans>a<b test={"</b>"}>c<c>z</c></b>{d}<br stuff={y}/></Trans>';
const content = '<Trans>a<b test={"</b>"}>c<c>z</c></b>{d}<br stuff={y}/></Trans>'
assert.equal(Lexer.eraseTags(content), 'a<1>c<1>z</1></1><2>{d}</2><3></3>')
done()
})
Expand Down
10 changes: 10 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,16 @@ abbrev@1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8"

acorn-jsx@^4.1.1:
version "4.1.1"
resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-4.1.1.tgz#e8e41e48ea2fe0c896740610ab6a4ffd8add225e"
dependencies:
acorn "^5.0.3"

acorn@^5.0.3:
version "5.5.3"
resolved "https://registry.yarnpkg.com/acorn/-/acorn-5.5.3.tgz#f473dd47e0277a08e28e9bec5aeeb04751f0b8c9"

ajv@^4.9.1:
version "4.11.8"
resolved "https://registry.yarnpkg.com/ajv/-/ajv-4.11.8.tgz#82ffb02b29e662ae53bdc20af15947706739c536"
Expand Down

0 comments on commit ce08b6c

Please sign in to comment.