How to preserve dynamically created Tailwind classes (JIT mode) from being purged? - laravel-blade

I want to build a color palette Blade component, but I noticed that dynamically created Tailwind class strings are not preserved in Tailwinds JIT mode (see Tailwind Docs).
Example
A minimal example of what I want to achieve would look something like this:
/tailwind.config.js
...
module.exports = {
mode: 'jit',
purge: [
'./vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php',
'./vendor/laravel/jetstream/**/*.blade.php',
'./storage/framework/views/*.php',
'./resources/views/**/*.blade.php',
],
theme: {
colors: {
primary-400: '#3892e6',
},
},
};
/routes/web.php
...
Route::get('/', function () {
return view('welcome', ['color' => 'primary']);
});
...
/resources/views/welcome.blade.php
...
<body class="antialiased min-h-screen flex items-center justify-center">
<h1 class="text-4xl text-{{ $color }}-400">{{ $color }}</h1>
</body>
...
The documentations approach of dynamically selecting a complete class name would render the component useless:
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
The documentation mentions two features that might help: Safelisting and Transforming content.
So one way would be transforming the Blade templates to HTML but I believe this is not possible. The other way I can think of, would be generating the Safelist dynamically from the theme object, but I have no clue how to start.
Does anybody have had to tackle this problem before, or can think of another approach?

Related

Vue 3 with Tailwind using v-bind:class shows classes in html element but not render while style works correctly

I am new to Vue and I'm trying to bind multiple classes in a v-for loop from a const array of object imported from a file.js.
But the trick I'm trying is to import const and than return classes from method that evaluates one property of object looped.
I've tried all ways, methods, computed, setup, onMounted, beforeMount, but even if i can see my classes in html they aren't rendered in styles section of DevTools.
The only way that works is to v-bind:style instead of class. Or just put exact classes in my const array object as a property but I prefer to avoid this.
It seems to save something in cache, but i have tried to delete and to lunch application in hidden mode but it won't works
Is there someone who can help me to understand and maybe to resolve?
Thanks in advance
this is my actual code:
<template>
<div id="cv" class="tp3-flex md:tp3-grid md:tp3-grid-cols-[repeat(27,_minmax(0,_1fr))] md:tp3-grid-rows-[repeat(6,_minmax(0, 5rem))] tp3-justify-center tp3-content-center tp3-justify-items-center tp3-mx-auto tp3-p-2 tp3-bg-cyan-500 tp3-text-blue-50">
<div v-for="(softSkill, index) in softSkills" :key="`softSkill-${index}`"
class="tp3-flex tp3-w-20 tp3-h-20 -tp3-rotate-45 tp3-rounded-full tp3-rounded-tr-none tp3-justify-center tp3-items-center tp3-bg-slate-400 tp3-opacity-70 tp3-mb-4 tp3-mt-4 tp3-shadow-md tp3-overflow-hidden"
v-bind:class="posCols(softSkill)">
<div class="tp3-rotate-45">
<span v-html="softSkill.text"></span>
</div>
</div>
</div>
</template>
<script>
import {softSkills} from "#/assets/skills/softSkills";
export default {
name: "ComponentSoftSkills",
data(){
return{
softSkills: null
}
},
beforeMount() {
this.softSkills = softSkills;
},
methods: {
posCols(softSkill){
console.log(softSkill);
return ' tp3-col-start-['+softSkill.col+'] tp3-col-end-['+(softSkill.col+1)+']';
}
}
}
</script>
<style lang="css" scoped>
</style>
and my file.js is:
export const softSkills = [
{text:`skill 1`, col:1, row:1},
{text:`skill 2`, col:5, row:1},
{text:`skill 3`, col:2, row:2},
{text:`skill 4`, col:15, row:1},
]
I have a suspicion that this might be due to your tailwind setup.
Because the classes are assigned dynamically and tailwind (depending on the configuration) is only making classes available that it can find during compilation. So the classes, even though you see them populated correctly, are not made available through tailwind. simply put, when tailwind scans the code, it doesn't recognize md:tp3-grid-cols-[repeat(27,_minmax(0,_1fr))] or tp3-col-start-[${softSkill.col}] as a valid class name and does not generate the class for it.
Assuming this is the issue and not knowing the exact version on configuration can't give an exact solution, but here are some tips for it.
Instead of using dynamic class names, define all the class names and assign dynamically
so instead of using tp3-col-start-[${softSkill.col}] tp3-col-end-[${(softSkill.col+1)}]
you could make sure all possible classes are clear and accessible by the tailwind parser:
let colClass = `tp3-col-start-[0] tp3-col-end-[1]`;
if(softSkill.col === 1) colClass = "tp3-col-start-[1] tp3-col-end-[2]";
if(softSkill.col === 2) colClass = "tp3-col-start-[2] tp3-col-end-[3]";
if(softSkill.col === 3) colClass = "tp3-col-start-[3] tp3-col-end-[4]";
if(softSkill.col === 4) colClass = "tp3-col-start-[4] tp3-col-end-[5]";
if(softSkill.col === 5) colClass = "tp3-col-start-[5] tp3-col-end-[6]";
// ...etc
this is obviously very verbose, but the classes are clearly defined in the code, so tailwind can find them when scanning your code.
Safelisting classes
using safelisting of classes is another option. Instead of having the code in your js, you would have it in the configuration
// tailwind.config.js
module.exports = {
// ...other stuff
safelist: [
'tp3-col-start-[0]',
'tp3-col-start-[1]',
'tp3-col-start-[2]',
'tp3-col-start-[3]',
'tp3-col-start-[4]',
'tp3-col-start-[5]',
// ...etc
'tp3-col-end-[1]',
'tp3-col-end-[2]',
'tp3-col-end-[3]',
'tp3-col-end-[4]',
'tp3-col-end-[5]',
// ...etc
],
}
there's also a way to use regex, which might look something like this:
// tailwind.config.js
module.exports = {
// ...other stuff
safelist: [
{
pattern: /tp3-col-start-[(0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15)]/,
variants: ['sm', 'lg'], // you can add variants too
},
{
pattern: /tp3-col-end-[(1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16)]/,
},
],
}
you can read more about safelisting here safelisting-classes

How to change specific elements style in storybook?

In my case I just want to change the default default color, take as example the default home section:
We recommend building UIs with a [**component-driven**](https://componentdriven.org)
That leads to:
I'd like to change that blue to, say, red.
I saw that the a class has the following themes:
class="sbdocs sbdocs-a css-19nbuh3"
So, I created a .storybook/manager-head.html and inside I wrote:
<style>
.sbdocs-a {
color: red;
}
But I see no changes! What am I doing wrong?
You can do this two ways but all in .storybook/preview.js.
Altering the docs theme:
export const parameters = {
...
docs: {
theme: {
colorSecondary: 'red',
},
},
...
};
This have the side effect to cause other unwanted components to change their color, as this color is not used only for links.
Provide your own <a> component to docs [best solution]:
export const parameters = {
...
docs: {
components: {
a: ({children, ...args}) => <a style={{color: 'red'}} {...args}>{children}</a>
},
},
...
};
This is the best way i found to style docs components.
also token name used for a can be found in storybook sources
See theming docs page for a full theme example.

JIT tailwindcss using variable in bg-[] not rendering color

when passing my color as props like this <List text="something" color="#84AB86" /> and using in the code className={'bg-[${color}] '} it does not render properly.
when looking at chrome dev tools color are added correctly like this bg-[#84AB86]
while putting the color manually without taking it from props, it does work correctly
after more testing it seems not possible either to do it like this
const color = "#84CC79"
className={`bg-[${color}]`}
any idea why
To use dynamic classes with JIT tailwind you either need to use safelist config key or create stub file where you list all your dynamic classes that you will use.
Config example:
module.exports = {
content: [
'./pages/**/*.{html,js}',
'./components/**/*.{html,js}',
],
safelist: [
'bg-red-500',
'text-3xl',
'lg:text-4xl',
]
// ...
}
Or make safelist.txt in your src folder, then add classes there just like so:
bg-[#84AB86]
bg-[#fffeee]
// etc..
And don't forget to include this safelist.txt file to your config content so tailwind could watch it.
Explanation from tailwind docs
If you are not using JIT, then you can use safelist option for PurgeCSS:
// tailwind.config.js
module.exports = {
purge: {
// Configure as you need
content: ['./src/**/*.html'],
// These options are passed through directly to PurgeCSS
options: {
// List your classes here, or you can even use RegExp
safelist: ['bg-red-500', 'px-4', /^text-/],
blocklist: [/^debug-/],
keyframes: true,
fontFace: true,
},
},
// ...
}
From the Tailwindcss documentation
Dynamic values Note that you still need to write purgeable HTML when
using arbitrary values, and your classes need to exist as complete
strings for Tailwind to detect them correctly.
Don't use string concatenation to create class names --> <div className={mt-[${size === 'lg' ? '22px' : '17px' }]}></div>
Do dynamically select a complete class name --> <div className={ size === 'lg' ? 'mt-[22px]' : 'mt-[17px]' }></div>
Tailwind doesn’t include any sort of client-side runtime, so class
names need to be statically extractable at build-time, and can’t
depend on any sort of arbitrary dynamic values that change on the
client. Use inline styles for these situations, or combine Tailwind
with a CSS-in-JS library like Emotion if it makes sense for your
project.
As mentioned above tailwind engine In order to render a custom class dynamicaly:
Does not like:
className={`bg-[${custom-color}]-100`}
It expects:
const customBgColorLight = 'bg-custom-color-100';
className={`${customBgColorLight} .....`}
For this to work properly you have to include the name of the class in the safelist:[] in your tailwind.config.js.
For tailwind v.3
/** #type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
safelist: [
'bg-custom-color-500', // your-custom-css-class
'text-custom-color-500',
'border-custom-color-500',
..... // other classes
'hover:bg-custom-color-500', // *** also include it with the selector if needed ***
.... // other classes
],
theme: {
extend: {
colors: {
'custom-color': { // you have to use quotes if key is not in camelCase format
100: '#d6d6d6',
500: '#5E8EA2',
..... //other variants
},
...... // other colors
So you can use it:
// if you want store the values to an object
const yourClassObj = {
customBgColor: 'bg-custom-color-500',
customBrdColor: 'border-custom-color-500',
customTxtColor: 'text-custom-color-500',
};
const { customBgColor, customBrdColor, customTxtColor } = yourClassObj;
<YourComponent
className={`mb-2 font-semibold py-2 px-4 rounded-lg
${ conditionGoesHere ? `${customBgColor} text-white cursor-default`
: `${customTxtColor} border ${customBrdColor}
bg-transparent hover:border-transparent
hover:${customBgColor} hover:text-white`
}`}
/>
An easy solution is to use the built in style property.
For example in React:
Dont Use:
className={`bg-[${color}]`}
Use Instead:
style={{
backgroundColor: color,
}}

adding dynamic class name in svelte

I am currently writing an app with svelte, sapper and tailwind. So to get tailwind working I have added this to my rollup config
svelte({
compilerOptions: {
dev,
hydratable: true,
},
preprocess: sveltePreprocess({
sourceMap: dev,
postcss: {
plugins: [
require("tailwindcss"),
require("autoprefixer"),
require("postcss-nesting"),
],
},
}),
emitCss: true,
})
All in all this works, but I am getting some issues with dynamic class names.
Writing something like this always seems to work
<div class={true ? 'class-a' : 'class-b'}>
both class-a and class-b will be included in the final emitted CSS and everything works as expected.
But when I try to add a variable class name it won't work. So imagine this:
<div class={`col-span-6`}>
It will work exactly as expected and it will get the proper styling from the css class col-span-6 in tailwind.
But if I change it to this:
<div class={`col-span-${6}`}>
Then the style won't be included.
If I on the other hand already have a DOM element with the class col-span-6 then the styling will be added to both elements.
So my guess here is that the compiler sees that the css is not used and it gets removed.
And I suppose that my question is then if there is any way to force in all the styling from tailwind? so that I can use more dynamic class names
and not sure if it is relevant but the component I have been testing this on, have this style block
<style>
#tailwind base;
#tailwind components;
#tailwind utilities;
</style>
edit: can add that I am getting a bunch of prints in the log saying that there are unused css selectors that seems to match all tailwind classes
I think it was purgeCSS (built-in in tailwind 2.0) that did not recognize the dynamic classes.
It is difficult to solve this problem for every tailwind classes, but if you don't have a lot of these you can manually safe list those classnames:
// tailwind.config.js
module.exports = {
purge: {
content: ['./src/**/*.html'],
// These options are passed through directly to PurgeCSS
options: {
// Generate col-span-1 -> 12
safelist: [...Array.from({ length: 12. }).fill('').map((_, i) => `col-span-${i + 1}`],
},
},
// ...
}
I think that when the class attribute is a variable or depends on a variable it will not used to extract style during compilation (class-${6} is not evaluated during compilation but during runtime), because svelte marks it as unused css selector because the value of that class attribute is not known when the code is compiled.
To force svelte to include your style you must mark it as global, and to do that we have two options:
<script>
// component logic goes here
</script>
div class={`class-${6}`}/>
option 1:
<style>
:global(.class-6){
// style goes here
}
</style>
option 2: this will mark all your style as global
<style global>
.class-6{
// style goes here
}
</style>
I encounter the same problem, <div class="pl-{indent*4}"> do not work in svelte.
My solution is to use inline style,
<div style="padding-left:{indent}rem">,
which is inferred from pl-1=padding-left: 0.25rem; /* 4px */.
I think it's convenient for simple class.

Tailwind css dark mode does not enable

I am trying to enable dark mode based on the system default using tailwind.
To accomplish this I am using the plugin: Tailwind dark mode.
My config fail for tailwind is as follows:
defaultTheme = require('tailwindcss/defaultTheme');
module.exports = {
experimental: {
darkModeVariant: true
},
purge: [],
theme: {
extend: {
fontFamily: {
sans: ['Nunito', ...defaultTheme.fontFamily.sans],
},
screens: {
'dark': {'raw': '(prefers-color-scheme: dark)'},
// => #media (prefers-color-scheme: dark) { ... }
},
},
},
variants: {
backgroundColor: ['dark', 'dark-hover', 'dark-group-hover', 'dark-even', 'dark-odd'],
borderColor: ['dark', 'dark-disabled', 'dark-focus', 'dark-focus-within'],
textColor: ['dark', 'dark-hover', 'dark-active', 'dark-placeholder'],
opacity: ['responsive', 'hover', 'focus', 'disabled']
},
plugins: [require('tailwindcss-dark-mode')()],
}
defaultTheme = require('tailwindcss/defaultTheme');
And in my html file I am adding the following:
<span class="dark:text-yellow-400">
1
</span>
The plugin checks for my dark mode but the text wont turn yellow it stays black.
Does anyone know why it wont work?
First things first, now TailWIndCSS supports dark-mode out-of-the-box by adding the dark: prefix before any class after it is enabled. Not sure if it is related to the question, but thought you need to know.
The plugin you are using states the following use for enabling dark mode:
< tailwind.config.js >
...
plugins: [
require('tailwindcss-dark-mode')()
]
// To enable dark mode for all classes:
variants: ['dark', 'dark-hover', 'dark-group-hover', 'dark-even', 'dark-odd', ...]
// To enable dark mode for only single utility class:
variants: {
backgroundColor: ['dark', 'dark-hover', 'dark-group-hover', 'dark-even', 'dark-odd']
}
...
It also states that
Styles generated by this plugin are only used if the selector is applied to the <html> element. How you do that is up to you. prefers-dark.js is provided as an option, which is a simple script that enables dark mode based on the user's system theme.
So, to enable dark mode through the plugin, use:
< mypage.html >
...
<body class="mode-dark">
<div class="bg-white dark:bg-black">
<p class="text-black dark:text-white">
My eyes are grateful.
<a class="text-blue-300 hover:text-blue-400">
Learn more
</a>
</p>
</div>
...
</body>
Add that extra mode-dark class to the wrapper element (body in this case).
To change the theme based on user preferences through the plugin:
< mypage.html >
<head>
<script src="to/prefers-dark.js"></script>
</head>
...
<body class="mode-dark">
<div class="bg-white dark:bg-black">
<p class="text-black dark:text-white">
My eyes are grateful.
<a class="text-blue-300 hover:text-blue-400">
Learn more
</a>
</p>
</div>
...
</body>
With the above, the theme will change as the user changes his/her preferences in the system settings.
P.S. If you wanna use dark mode, use the one in-built in TailWindCSS v2. Enable it like this:
< tailwind.config.js >
module.exports = {
darkMode: 'media',
...
}
media can be changed to class.
Media: Now whenever dark mode is enabled on the user's operating system, dark:{class} classes will take precedence over unprefixed classes. The media strategy uses the prefers-color-scheme media feature under the hood.
Class: If you want to support toggling dark mode manually instead of relying on the operating system preference, use the class strategy instead of the media strategy.
Hope this helped you :)
I had this problem due to forgetting to update tailwind.config.js:
I changed:
darkMode: false,
to
darkMode: 'class',
I have a simple watcher in Vue that toggles it via:
document.querySelector('html').classList.add('dark')
document.querySelector('html').classList.remove('dark')
You can read more here:
https://tailwindcss.com/docs/dark-mode

Resources