Skip to content

Commit

Permalink
feat(react-jsx-source): add column property
Browse files Browse the repository at this point in the history
This will be useful to tools that consume the injected `__source` prop, allowing precise source locations to be displayed.
  • Loading branch information
motiz88 committed Feb 13, 2020
1 parent 3c6a8ae commit d1437d0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
26 changes: 20 additions & 6 deletions packages/babel-plugin-transform-react-jsx-source/src/index.js
@@ -1,7 +1,7 @@
/**
* This adds {fileName, lineNumber} annotations to React component definitions
* and to jsx tag literals.
* This adds {fileName, lineNumber, column} annotations to JSX tags.
*
* NOTE: lineNumber is 1-based and column is 0-based.
*
* == JSX Literals ==
*
Expand All @@ -10,7 +10,7 @@
* becomes:
*
* var __jsxFileName = 'this/file.js';
* <sometag __source={{fileName: __jsxFileName, lineNumber: 10}}/>
* <sometag __source={{fileName: __jsxFileName, lineNumber: 10, column: 0}}/>
*/
import { declare } from "@babel/helper-plugin-utils";
import { types as t } from "@babel/core";
Expand All @@ -21,9 +21,11 @@ const FILE_NAME_VAR = "_jsxFileName";
export default declare(api => {
api.assertVersion(7);

function makeTrace(fileNameIdentifier, lineNumber) {
function makeTrace(fileNameIdentifier, lineNumber, column) {
const fileLineLiteral =
lineNumber != null ? t.numericLiteral(lineNumber) : t.nullLiteral();
const fileColumnLiteral =
column != null ? t.numericLiteral(column) : t.nullLiteral();
const fileNameProperty = t.objectProperty(
t.identifier("fileName"),
fileNameIdentifier,
Expand All @@ -32,7 +34,15 @@ export default declare(api => {
t.identifier("lineNumber"),
fileLineLiteral,
);
return t.objectExpression([fileNameProperty, lineNumberProperty]);
const columnProperty = t.objectProperty(
t.identifier("column"),
fileColumnLiteral,
);
return t.objectExpression([
fileNameProperty,
lineNumberProperty,
columnProperty,
]);
}

const visitor = {
Expand Down Expand Up @@ -69,7 +79,11 @@ export default declare(api => {
state.fileNameIdentifier = fileNameIdentifier;
}

const trace = makeTrace(state.fileNameIdentifier, location.start.line);
const trace = makeTrace(
state.fileNameIdentifier,
location.start.line,
location.start.column,
);
attributes.push(t.jsxAttribute(id, t.jsxExpressionContainer(trace)));
},
};
Expand Down
Expand Up @@ -7,7 +7,8 @@ var expected = multiline([
'var _jsxFileName = "/fake/path/mock.js";',
'var x = <sometag __source={{',
' fileName: _jsxFileName,',
' lineNumber: 1',
' lineNumber: 1,',
' column: 8',
'}} />;',
]);

Expand Down

0 comments on commit d1437d0

Please sign in to comment.