Skip to content

Commit

Permalink
feat(combinestrings): support template literals
Browse files Browse the repository at this point in the history
  • Loading branch information
merceyz committed Jun 8, 2019
1 parent ee44dd4 commit 3d63596
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 2 deletions.
75 changes: 73 additions & 2 deletions src/visitors/combineStringLiterals.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,74 @@ function combineStringsInArray(array) {
return array;
}

const [match, noMatch] = _.partition(array, t.isStringLiteral);
const [match, noMatch] = _.partition(
array,
item => t.isStringLiteral(item) || t.isTemplateLiteral(item),
);

if (match.length < 2) {
return array;
}

return [match.reduce((prev, curr) => t.stringLiteral(prev.value + ' ' + curr.value)), ...noMatch];
const [strings, templates] = _.partition(match, t.isStringLiteral);

const expressions = [];
const quasis = [];

// Combine string literals
if (strings.length > 0) {
quasis.push(
templateElement(
strings.reduce((prev, curr) => t.stringLiteral(prev.value + ' ' + curr.value)).value,
true,
),
);
}

// Combine template literals
templates.forEach(item => {
if (item.expressions.length === 0) {
const newValue = item.quasis.reduce((prev, curr) =>
templateElement(prev.value.raw + ' ' + curr.value.raw, true),
);

if (quasis.length === 0) {
quasis.push(newValue);
return;
}

const prevItem = quasis[quasis.length - 1];
quasis[quasis.length - 1] = templateElement(
prevItem.value.raw + ' ' + newValue.value.raw,
true,
);
return;
}

item.quasis.forEach(item => {
if (quasis.length !== 0) {
const prevItem = quasis[quasis.length - 1];

if (item.tail === false && prevItem.tail) {
quasis[quasis.length - 1] = templateElement(
prevItem.value.raw + ' ' + item.value.raw,
true,
);
return;
}
}

quasis.push(item);
});

expressions.push(...item.expressions);
});

if (expressions.length === 0 && quasis.length === 1) {
return [t.stringLiteral(quasis[0].value.raw), ...noMatch];
}

return [t.templateLiteral(quasis, expressions), ...noMatch];
}

const arrayVisitor = {
Expand Down Expand Up @@ -41,3 +102,13 @@ const visitor = {
export default (path, options) => {
path.traverse(visitor, { options });
};

function templateElement(value, tail = false) {
return {
type: 'TemplateElement',
value: {
raw: value,
},
tail,
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
const x = clsx('foo', `foo${foo}`, `bar`);
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
const x = clsx(`foo foo${foo} bar`);

0 comments on commit 3d63596

Please sign in to comment.