Skip to content

Commit

Permalink
fix (quoted-expression): false positive in quoted-expressions (#209) (#…
Browse files Browse the repository at this point in the history
…210)

Allows quoted expressions in all cases which have mixed values (e.g. an expr in the middle of a string)
  • Loading branch information
jpradelle authored Jul 30, 2024
1 parent 406b902 commit 427627c
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 7 deletions.
13 changes: 6 additions & 7 deletions src/rules/quoted-expressions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const rule: Rule.RuleModule = {
create(context): Rule.RuleListener {
// variables should be defined here
const alwaysQuote = context.options[0] === 'always';
const quotePattern = /=(["'])?$/;

//----------------------------------------------------------------------
// Helpers
Expand All @@ -57,20 +58,18 @@ const rule: Rule.RuleModule = {
const expression = node.quasi.expressions[i];
const previousQuasi = node.quasi.quasis[i];
const nextQuasi = node.quasi.quasis[i + 1];
const isAttribute = /=["']?$/.test(previousQuasi.value.raw);
const quoteMatch = previousQuasi.value.raw.match(quotePattern);

// don't care about non-attribute bindings
if (!isAttribute) {
if (!quoteMatch) {
continue;
}

const hasStartQuote = quoteMatch[1] !== undefined;
const isQuoted =
(previousQuasi.value.raw.endsWith('="') &&
nextQuasi.value.raw.startsWith('"')) ||
(previousQuasi.value.raw.endsWith("='") &&
nextQuasi.value.raw.startsWith("'"));
hasStartQuote && nextQuasi.value.raw.startsWith(quoteMatch[1]);

if (alwaysQuote && !isQuoted) {
if (alwaysQuote && !hasStartQuote) {
context.report({
node: expression,
messageId: 'alwaysQuote',
Expand Down
32 changes: 32 additions & 0 deletions src/test/rules/quoted-expressions_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,38 @@ ruleTester.run('quoted-expressions', rule, {
{
code: "html`<x-foo attr='${v}'></x-foo>`",
options: ['always']
},
{
code: 'html`<x-foo attr="${v} foo">${expr}</x-foo>`',
options: ['always']
},
{
code: 'html`<x-foo attr="foo ${v} bar">${expr}</x-foo>`',
options: ['always']
},
{
code: 'html`<x-foo attr="foo ${v}${w} bar">${expr}</x-foo>`',
options: ['always']
},
{
code: 'html`<x-foo attr="foo ${v} bar ${w} baz">${expr}</x-foo>`',
options: ['always']
},
{
code: 'html`<x-foo attr="${v ? "foo" : "bar"} baz">${expr}</x-foo>`',
options: ['always']
},
{
code: 'html`<x-foo attr="foo ${v}">${expr}</x-foo>`',
options: ['always']
},
{
code: 'html`<p attr="${v} foo">${expr}</p>`',
options: ['never']
},
{
code: 'html`<p attr="foo ${v} bar">${expr}</p>`',
options: ['never']
}
],

Expand Down

0 comments on commit 427627c

Please sign in to comment.