Skip to content

Commit

Permalink
Always use double quotes for JSX and properly escape
Browse files Browse the repository at this point in the history
JSX quotes are unfortunately using html escaping. Also, we should disregard the single-quote option for JSX quotes as we always want double quotes.
  • Loading branch information
vjeux committed Jan 11, 2017
1 parent 0eda444 commit 158f98a
Show file tree
Hide file tree
Showing 5 changed files with 38 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 @@ -1038,8 +1038,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;
9 changes: 9 additions & 0 deletions tests/jsx/__snapshots__/jsfmt.spec.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
exports[`test quotes.js 1`] = `
"<div id=\"&quot;\'<>&amp;quot;\" />;
<div id=\'\"&#39;<>&amp;quot;\' />;
<div id={\'\\\'\"&quot;<>&amp;quot;\'} />;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<div id=\"\\\"\'<>&quot;\" />;
<div id=\"\\\"\'<>&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 158f98a

Please sign in to comment.