Skip to content

Commit

Permalink
Merge pull request #126 from vjeux/jsx_quotes
Browse files Browse the repository at this point in the history
Always use double quotes for JSX and properly escape
  • Loading branch information
jlongster committed Jan 12, 2017
2 parents d2318cf + a6cdede commit d258815
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/printer.js
Original file line number Diff line number Diff line change
Expand Up @@ -1044,8 +1044,18 @@ function genericPrintNoParens(path, options, print) {
case "JSXAttribute":
parts.push(path.call(print, "name"));

if (n.value)
parts.push("=", path.call(print, "value"));
if (n.value) {
let res;
if (
(n.value.type === 'StringLiteral' || n.value.type === 'Literal') &&
typeof n.value.value === 'string'
) {
res = '"' + util.htmlEscapeInsideDoubleQuote(n.value.value) + '"';
} else {
res = path.call(print, "value");
}
parts.push("=", res);
}

return concat(parts);
case "JSXIdentifier":
Expand Down
13 changes: 13 additions & 0 deletions src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -311,3 +311,16 @@ function setLocEnd(node, index) {
}
}
util.setLocEnd = setLocEnd;

// http://stackoverflow.com/a/7124052
function htmlEscapeInsideDoubleQuote(str) {
return str
.replace(/&/g, '&')
.replace(/"/g, '"');
// Intentionally disable the following since it is safe inside of a
// double quote context
// .replace(/'/g, ''')
// .replace(/</g, '&lt;')
// .replace(/>/g, '&gt;');
}
util.htmlEscapeInsideDoubleQuote = htmlEscapeInsideDoubleQuote;
10 changes: 10 additions & 0 deletions tests/jsx/__snapshots__/jsfmt.spec.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
exports[`test quotes.js 1`] = `
"<div id=\"&quot;\'<>&amp;quot;\" />;
<div id=\'\"&#39;<>&amp;quot;\' />;
<div id={\'\\\'\"&quot;<>&amp;quot;\'} />;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<div id=\"&quot;\'<>&amp;quot;\" />;
<div id=\"&quot;\'<>&amp;quot;\" />;
<div id={\"\'\\\"&quot;<>&amp;quot;\"} />;
"
`;
1 change: 1 addition & 0 deletions tests/jsx/jsfmt.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
run_spec(__dirname);
3 changes: 3 additions & 0 deletions tests/jsx/quotes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<div id="&quot;'<>&amp;quot;" />;
<div id='"&#39;<>&amp;quot;' />;
<div id={'\'"&quot;<>&amp;quot;'} />;

0 comments on commit d258815

Please sign in to comment.