Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion lib/rules/no-raw-text.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,28 @@ const hasAllowedParent = (parent, allowedElements) => {
function create(context) {
const options = context.options[0] || {};

const templateLiteralValue = (node) => {
const firstExpression = node.expressions[0];

// A template literal with no interpolations has an empty `expressions`, so
// there is no expression to name. Describe the literal text instead, which
// matches how a plain string expression is reported.
if (!firstExpression) {
return node.quasis.map((quasi) => quasi.value.cooked).join('').trim();
}

if (firstExpression.type === 'Identifier') {
return `TemplateLiteral: ${firstExpression.name}`;
}

// Member expressions, calls and the like have no `.name`, which previously
// rendered as `TemplateLiteral: undefined`.
return `TemplateLiteral: ${context.getSourceCode().getText(firstExpression)}`;
};

const report = (node) => {
const errorValue = node.type === 'TemplateLiteral'
? `TemplateLiteral: ${node.expressions[0].name}`
? templateLiteralValue(node)
: node.value.trim();

const formattedErrorValue = errorValue.length > 0
Expand Down
28 changes: 28 additions & 0 deletions tests/lib/rules/no-raw-text.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,34 @@ const tests = {
message: 'Raw text (TemplateLiteral: text) cannot be used outside of a <Text> tag',
}],
},
{
// A template literal with no interpolations used to throw:
// `Cannot read properties of undefined (reading 'name')`
code: `
export default class MyComponent extends Component {
render() {
return (<View>{\`some text\`}</View>);
}
}
`,
errors: [{
message: 'Raw text (some text) cannot be used outside of a <Text> tag',
}],
},
{
// A non-Identifier interpolation has no `.name`, so this used to report
// `Raw text (TemplateLiteral: undefined)`.
code: `
export default class MyComponent extends Component {
render() {
return (<View>{\`\${this.props.text}\`}</View>);
}
}
`,
errors: [{
message: 'Raw text (TemplateLiteral: this.props.text) cannot be used outside of a <Text> tag',
}],
},
{
code: `
export default class MyComponent extends Component {
Expand Down