prettier-plugin-tailwindcss icon indicating copy to clipboard operation
prettier-plugin-tailwindcss copied to clipboard

feat: Add support for callable template literals when using custom JSX parser

Open dimitribarbot opened this issue 6 months ago • 2 comments

Support for callable template literals

Description

This PR adds support for callable template literals as it was done for member template literals. It aims at solving use cases when using the tailwind-styled-components library.

Problem

When extending components using tailwind-styled-components and following the documentation described here, we must write something such as:

const DefaultContainer = tw.div`
    flex
    items-center
`

const RedContainer = tw(DefaultContainer)`
    bg-red-300
`

However, the classes under the RedContainer component will not be handled by the prettier plugin as only the following options are currently supported:

tw.foo`sm:p-1 p-2`;
tw.foo.bar`sm:p-1 p-2`;
tw.foo('sm:p-1 p-2');
tw.foo.bar('sm:p-1 p-2');

Solution

I added the following as supported options:

tw(Foo)`sm:p-1 p-2`;
tw(Foo)(Bar)`sm:p-1 p-2`;
tw(Foo)('sm:p-1 p-2');
tw(Foo)(Bar)('sm:p-1 p-2');

Testing

I added new test cases and ran npm run test to confirm plugin compatibility and ensure no regressions.

dimitribarbot avatar May 23 '25 17:05 dimitribarbot

@dimitribarbot I made some tweaks so traverse both calls and property accesses at the same time.

This will let things like these work:

tw(SomeComponent).div`this is now sorted`
tw.div(SomeComponent)`this is now sorted`

Not sure if this syntax is commonplace or not but seems reasonable to support it regardless (and it simplifies the code a bit too).

I don't suspect there will be any issues with that. Can you think of any?

thecrypticace avatar May 23 '25 22:05 thecrypticace

Thanks for these changes, the code is indeed simpler this way!

I hesitated to apply them, but ultimately felt it would be simpler (in terms of PR review) to leave them as is. For example, the factorization between isSortableTemplateExpression and isSortableCallExpression hadn't been done before, so I didn't do it myself.

I also don't think there will be any issues with these modifications, they allow generalization to all use cases.

Thanks again!

dimitribarbot avatar May 24 '25 08:05 dimitribarbot

Planning on taking another look at this soon (this week or next week) as i'm gonna get some changes into a v0.7.0 release.

thecrypticace avatar Jul 09 '25 16:07 thecrypticace

~~todo for me (soon): See if this resolves #248 as well~~ confirmed

thecrypticace avatar Jul 23 '25 17:07 thecrypticace