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
5 changes: 5 additions & 0 deletions .changeset/quiet-shadows-blend.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-email": patch
---

`<Tailwind>` now uses a value that another class on the same element defines instead of the fallback, so `text-shadow-*` colors apply, gradients with an arbitrary position (`bg-radial-[at_25%_25%]`, `bg-linear-[25deg]`, `bg-conic-[from_45deg]`) keep their color stops, and `leading-*` holds when it comes before `text-*`. A variable set to `initial` or `inherit` now uses its fallback instead of inlining the keyword.
44 changes: 44 additions & 0 deletions packages/react-email/src/components/tailwind/tailwind.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,50 @@ describe('Tailwind component', () => {
expect(transformed?.getAttribute('style')).toContain('translate:0.5rem 0');
});

it('uses values that another class on the element defines', async () => {
const html = await render(
<Tailwind>
<p className="text-shadow-lg text-shadow-red-500">colored</p>
<p className="text-shadow-lg">default</p>
<p className="leading-[24px] text-sm">leading</p>
<div className="bg-radial-[at_25%_25%] from-red-500 to-blue-500">
gradient
</div>
</Tailwind>,
);
const document = new DOMParser().parseFromString(html, 'text/html');
const [colored, defaultShadow, leading] = document.querySelectorAll('p');
const gradient = document.querySelector('div');

expect(html).not.toContain('var(');
expect(colored?.getAttribute('style')).toContain('rgb(251,44,54');
expect(defaultShadow?.getAttribute('style')).toContain('rgb(0,0,0,0.1)');
expect(defaultShadow?.getAttribute('style')).not.toContain('rgb(251,44,54');
expect(leading?.getAttribute('style')).toContain('line-height:24px');
expect(gradient?.getAttribute('style')).toContain(
'radial-gradient(at 25% 25%,rgb(251,44,54) 0%,rgb(43,127,255) 100%)',
);
});

it('does not depend on classes added by earlier renders', async () => {
const config: TailwindConfig = { theme: { extend: {} } };
const defaults = (
<Tailwind config={config}>
<p className="text-shadow-lg">text</p>
<p className="text-sm">leading</p>
</Tailwind>
);
const before = await render(defaults);
await render(
<Tailwind config={config}>
<p className="text-shadow-lg text-shadow-red-500">text</p>
<p className="leading-[24px] text-sm">leading</p>
</Tailwind>,
);

expect(await render(defaults)).toBe(before);
});

it('does not use hover shadow colors for the inline default', async () => {
const html = await render(
<Tailwind>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,4 +121,31 @@ describe('makeInlineStylesFor()', async () => {
}
`);
});

it('falls back when a variable is set to a CSS-wide keyword', () => {
const tailwindStyles = parse(`
.text-shadow-lg {
text-shadow: 0px 1px 2px var(--tw-text-shadow-color, black);
}
.text-shadow-initial {
--tw-text-shadow-color: initial;
}
.bg-custom {
background-color: var(--bg);
--bg: initial;
}
`) as StyleSheet;

expect(
makeInlineStylesFor(
tailwindStyles.children.toArray(),
getCustomProperties(tailwindStyles),
),
).toMatchInlineSnapshot(`
{
"backgroundColor": "initial",
"textShadow": "0px 1px 2px black",
}
`);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ import { sanitizeDeclarations } from './sanitize-declarations.js';
import { stripEmptyTailwindVars } from './strip-empty-tailwind-vars.js';
import { unwrapValue } from './unwrap-value.js';

const CSS_WIDE_KEYWORDS = new Set([
'initial',
'inherit',
'unset',
'revert',
'revert-layer',
]);

function hasVarFunction(node: CssNode) {
let found = false;
walk(node, {
Expand Down Expand Up @@ -58,11 +66,17 @@ export function makeInlineStylesFor(
const name = children[0] ? generate(children[0]).trim() : '';
if (resolving.has(name)) return;

const definition = localVariableDeclarations.get(name);
const initialValue = customProperties.get(name)?.initialValue;
const comma = children.findIndex(
(child) => child.type === 'Operator' && child.value === ',',
);
const declared = localVariableDeclarations.get(name);
const definition =
declared &&
(comma !== -1 || initialValue) &&
CSS_WIDE_KEYWORDS.has(generate(declared.value).trim().toLowerCase())
? undefined
: declared;
const fallback =
comma === -1
? undefined
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,35 @@ describe('resolveAllCSSVariables', () => {
);
});

it('leaves a fallback for inlining when another class defines the variable', () => {
const root = parse(`.text-shadow-lg {
text-shadow: 0px 1px 2px var(--tw-text-shadow-color, rgb(0 0 0 / 0.1));
}
.text-shadow-red-500 {
--tw-text-shadow-color: red;
}`);
resolveAllCssVariables(root);
expect(generate(root)).toMatchInlineSnapshot(
`".text-shadow-lg{text-shadow:0px 1px 2px var(--tw-text-shadow-color, rgb(0 0 0 / 0.1))}.text-shadow-red-500{--tw-text-shadow-color: red}"`,
);
});

it('does not wait for definitions in descendant or attribute rules', () => {
const root = parse(`.card {
background-color: var(--card-bg, white);
}
.dark .card {
--card-bg: black;
}
.card[data-theme='dark'] {
--card-bg: black;
}`);
resolveAllCssVariables(root);
expect(generate(root)).toMatchInlineSnapshot(
`".card{background-color:white}.dark .card{--card-bg: black}.card[data-theme="dark"]{--card-bg: black}"`,
);
});

it('handles nested var() functions in fallbacks', () => {
const root = parse(`:root {
--fallback-width: 300px;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {
type Value,
walk,
} from 'css-tree';
import { NON_INLINABLE_ATRULES } from './constants.js';
import { isRuleInlinable } from './is-rule-inlinable.js';

interface VariableUse {
declaration: Declaration;
Expand Down Expand Up @@ -66,6 +68,25 @@ function doSelectorsIntersect(
);
}

function isInClassRule(path: CssNode[]) {
const [block, rule] = path;
if (block?.type !== 'Block' || rule?.type !== 'Rule') return false;
const [selector, ...others] =
rule.prelude.type === 'SelectorList' ? rule.prelude.children.toArray() : [];
return (
others.length === 0 &&
selector?.type === 'Selector' &&
selector.children.size === 1 &&
selector.children.first?.type === 'ClassSelector' &&
isRuleInlinable(rule) &&
!path.some(
(ancestor) =>
ancestor.type === 'Atrule' &&
NON_INLINABLE_ATRULES.has(ancestor.name.toLowerCase()),
)
);
}

export function resolveAllCssVariables(node: CssNode) {
const variableDefinitions = new Set<VariableDefinition>();
const variableUses = new Set<VariableUse>();
Expand Down Expand Up @@ -162,12 +183,22 @@ export function resolveAllCssVariables(node: CssNode) {
}
}

const variablesDefinedByClasses = new Set<string>();
for (const definition of variableDefinitions) {
if (isInClassRule(definition.path)) {
variablesDefinedByClasses.add(definition.variableName);
}
}

for (const use of variableUses) {
let hasReplaced = false;
const localDefinition = use.path[0]
? localDefinitions.get(use.path[0])?.get(use.variableName)
: undefined;
const useRule = use.path.find((ancestor) => ancestor.type === 'Rule');
const mayBeDefinedByOtherClass =
isInClassRule(use.path) &&
variablesDefinedByClasses.has(use.variableName);

for (const definition of variableDefinitions) {
if (use.variableName !== definition.variableName) {
Expand Down Expand Up @@ -280,7 +311,8 @@ export function resolveAllCssVariables(node: CssNode) {
if (
!hasReplaced &&
use.fallback &&
!use.declaration.property.startsWith('--')
!use.declaration.property.startsWith('--') &&
!mayBeDefinedByOtherClass
) {
use.declaration.value = parse(
generate(use.declaration.value).replaceAll(use.raw, use.fallback),
Expand Down