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
3 changes: 3 additions & 0 deletions .changelog/postcss-keyframe-sources.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- Fix Vite's missing `from` warning when `@tailwindcss/postcss` emits keyframes defined in a JavaScript config
116 changes: 116 additions & 0 deletions packages/@tailwindcss-postcss/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,122 @@ describe('plugins', () => {
})
})

test('keyframes from JavaScript configs retain their PostCSS source', async ({
onTestFinished,
}) => {
let dir = await realpath(await mkdtemp(path.join(tmpdir(), 'tw-postcss')))
onTestFinished(() => rm(dir, { recursive: true, force: true }))

await writeFile(
path.join(dir, 'base.cjs'),
`module.exports = {
theme: {
animation: { 'fade-in': 'fade-in 1s' },
keyframes: { 'fade-in': { from: { opacity: '0' } } },
},
}`,
)
await writeFile(
path.join(dir, 'extension.cjs'),
`module.exports = {
theme: {
extend: {
animation: { 'fade-out': 'fade-out 1s' },
keyframes: () => ({ 'fade-out': { to: { opacity: '0' } } }),
},
},
}`,
)

let from = path.join(dir, 'input.css')
let result = await postcss([tailwindcss({ base: dir, optimize: false })]).process(
css`
@config './base.cjs';
@config './extension.cjs';
@theme {
--color-example: red;
}
@tailwind utilities source(none);
@source inline('animate-fade-in animate-fade-out');
`,
{ from },
)

let sources: [string, string | undefined, number | undefined][] = []
result.root.walkAtRules('keyframes', (rule) => {
rule.walkDecls((decl) => {
sources.push([rule.params, decl.source?.input.file, decl.source?.start?.line])
})
})

expect(sources).toEqual([
['fade-in', from, 1],
['fade-out', from, 2],
])
})

test('merged keyframe declarations retain their individual source files', async ({
onTestFinished,
}) => {
let dir = await realpath(await mkdtemp(path.join(tmpdir(), 'tw-postcss')))
onTestFinished(() => rm(dir, { recursive: true, force: true }))
await mkdir(path.join(dir, 'nested'))

await writeFile(
path.join(dir, 'base.cjs'),
`module.exports = {
theme: {
animation: { fade: 'fade 1s' },
keyframes: {
fade: { from: { backgroundImage: 'url(./image.svg)', opacity: '0', display: ['block', 'flex'] } },
},
},
}`,
)
await writeFile(
path.join(dir, 'nested/extension.cjs'),
`module.exports = {
theme: {
extend: {
keyframes: () => ({
fade: { from: { opacity: '1' }, to: { backgroundImage: 'url(./other.svg)' } },
}),
},
},
}`,
)
await writeFile(path.join(dir, 'nested/extra.css'), '@config "./extension.cjs";')

let from = path.join(dir, 'input.css')
let extension = path.join(dir, 'nested/extra.css')
let result = await postcss([tailwindcss({ base: dir, optimize: false })]).process(
css`
@import './nested/extra.css';
@config './base.cjs';
@theme {
--color-example: red;
}
@tailwind utilities source(none);
@source inline('animate-fade');
`,
{ from },
)

let declarations: [string, string, string | undefined][] = []
result.root.walkAtRules('keyframes', (rule) => {
rule.walkDecls((decl) => {
declarations.push([decl.prop, decl.value, decl.source?.input.file])
})
})
expect(declarations).toEqual([
['background-image', 'url(./image.svg)', from],
['opacity', '1', extension],
['display', 'block', from],
['display', 'flex', from],
['background-image', 'url(./other.svg)', extension],
])
})

test('bail early when Tailwind is not used', async () => {
let processor = postcss([
tailwindcss({ base: `${__dirname}/fixtures/example-project`, optimize: { minify: false } }),
Expand Down
11 changes: 6 additions & 5 deletions packages/tailwindcss/src/compat/apply-compat-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,10 +284,11 @@ function upgradeToFullPluginSupport({
...userConfig,
{ config: { plugins: [darkModePlugin] }, base, reference: true, src: undefined },
])
let { resolvedConfig: resolvedUserConfig, replacedThemeKeys } = resolveConfig(
designSystem,
userConfig,
)
let {
resolvedConfig: resolvedUserConfig,
replacedThemeKeys,
keyframeSources,
} = resolveConfig(designSystem, userConfig)

let pluginApiConfig = {
designSystem,
Expand Down Expand Up @@ -368,7 +369,7 @@ function upgradeToFullPluginSupport({
// config would otherwise expand into namespaces like `background-color` which
// core utilities already read from.
applyConfigToTheme(designSystem, resolvedUserConfig, replacedThemeKeys)
applyKeyframesToTheme(designSystem, resolvedUserConfig)
applyKeyframesToTheme(designSystem, resolvedUserConfig, keyframeSources)

registerThemeVariantOverrides(resolvedUserConfig, designSystem)
registerScreensConfig(resolvedUserConfig, designSystem)
Expand Down
14 changes: 10 additions & 4 deletions packages/tailwindcss/src/compat/apply-keyframes-to-theme.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
import { atRule, type AtRule } from '../ast'
import type { DesignSystem } from '../design-system'
import type { ResolvedConfig } from './config/types'
import { objectToAst } from './plugin-api'
import { objectToAst, type CssInJsSources } from './plugin-api'

export function applyKeyframesToTheme(
designSystem: DesignSystem,
resolvedConfig: Pick<ResolvedConfig, 'theme'>,
sources?: CssInJsSources,
) {
for (let rule of keyframesToRules(resolvedConfig)) {
for (let rule of keyframesToRules(resolvedConfig, sources)) {
designSystem.theme.addKeyframes(rule)
}
}

export function keyframesToRules(resolvedConfig: Pick<ResolvedConfig, 'theme'>): AtRule[] {
export function keyframesToRules(
resolvedConfig: Pick<ResolvedConfig, 'theme'>,
sources?: CssInJsSources,
): AtRule[] {
let rules: AtRule[] = []
if ('keyframes' in resolvedConfig.theme) {
for (let [name, keyframe] of Object.entries(resolvedConfig.theme.keyframes)) {
rules.push(atRule('@keyframes', name, objectToAst(keyframe as any)))
let rule = atRule('@keyframes', name, objectToAst(keyframe as any, sources))
rule.src = sources?.get(resolvedConfig.theme.keyframes)?.get(name)
rules.push(rule)
}
}
return rules
Expand Down
78 changes: 64 additions & 14 deletions packages/tailwindcss/src/compat/config/resolve-config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { DesignSystem } from '../../design-system'
import type { SourceLocation } from '../../source-maps/source'
import colors from '../colors'
import type { PluginWithConfig } from '../plugin-api'
import type { CssInJsSources, PluginWithConfig } from '../plugin-api'
import { createThemeFn } from '../plugin-functions'
import { deepMerge, isPlainObject } from './deep-merge'
import {
Expand All @@ -22,11 +22,11 @@ export interface ConfigFile {

interface ResolutionContext {
design: DesignSystem
configs: UserConfig[]
configs: Pick<ConfigFile, 'config' | 'src'>[]
plugins: PluginWithConfig[]
content: ResolvedContentConfig
theme: Record<string, ThemeValue>
extend: Record<string, ThemeValue[]>
extend: Record<string, { value: ThemeValue; src: SourceLocation | undefined }[]>
result: ResolvedConfig
}

Expand All @@ -47,7 +47,11 @@ let minimal: ResolvedConfig = {
export function resolveConfig(
design: DesignSystem,
files: ConfigFile[],
): { resolvedConfig: ResolvedConfig; replacedThemeKeys: Set<string> } {
): {
resolvedConfig: ResolvedConfig
replacedThemeKeys: Set<string>
keyframeSources: CssInJsSources
} {
let ctx: ResolutionContext = {
design,
configs: [],
Expand All @@ -67,7 +71,7 @@ export function resolveConfig(
}

// Merge top level keys
for (let config of ctx.configs) {
for (let { config } of ctx.configs) {
if ('darkMode' in config && config.darkMode !== undefined) {
ctx.result.darkMode = config.darkMode ?? null
}
Expand All @@ -86,7 +90,7 @@ export function resolveConfig(
}

// Merge themes
let replacedThemeKeys = mergeTheme(ctx)
let { replacedThemeKeys, keyframeSources } = mergeTheme(ctx)

return {
resolvedConfig: {
Expand All @@ -96,6 +100,7 @@ export function resolveConfig(
plugins: ctx.plugins,
},
replacedThemeKeys,
keyframeSources,
}
}

Expand Down Expand Up @@ -192,11 +197,13 @@ function extractConfigs(
}

// Then apply the "user" config
ctx.configs.push(config)
ctx.configs.push({ config, src })
}

function mergeTheme(ctx: ResolutionContext): Set<string> {
function mergeTheme(ctx: ResolutionContext) {
let replacedThemeKeys: Set<string> = new Set()
let keyframeSources: CssInJsSources = new WeakMap()
let baseKeyframesSource: SourceLocation | undefined

let themeFn = createThemeFn(ctx.design, () => ctx.theme, resolveValue)
let theme = Object.assign(themeFn, {
Expand All @@ -212,7 +219,34 @@ function mergeTheme(ctx: ResolutionContext): Set<string> {
return value ?? null
}

for (let config of ctx.configs) {
// Configs can share objects, so clone before associating them with a source.
function recordKeyframeSources(value: any, src: SourceLocation | undefined): any {
if (Array.isArray(value)) {
return value.map((item) => recordKeyframeSources(item, src))
}
if (!isPlainObject(value)) return value

let copy = Object.fromEntries(
Object.entries(value).map(([key, value]) => [key, recordKeyframeSources(value, src)]),
)
keyframeSources.set(copy, new Map(Object.keys(copy).map((key) => [key, src])))
return copy
}

function mergeKeyframes(a: any, b: any): any {
let merged = mergeThemeExtension(a, b)
if (merged !== undefined) return merged
if (!isPlainObject(a) || !isPlainObject(b)) return b

let result = deepMerge({}, [a, b], mergeKeyframes)
keyframeSources.set(
result,
new Map([...(keyframeSources.get(a) ?? []), ...(keyframeSources.get(b) ?? [])]),
)
return result
}

for (let { config, src } of ctx.configs) {
let theme = config.theme ?? {}
let extend = theme.extend ?? {}

Expand All @@ -226,11 +260,14 @@ function mergeTheme(ctx: ResolutionContext): Set<string> {

// Shallow merge themes so latest "group" wins
Object.assign(ctx.theme, theme)
if (Object.hasOwn(theme, 'keyframes')) {
baseKeyframesSource = src
}

// Collect extensions by key so each group can be lazily deep merged
for (let key in extend) {
ctx.extend[key] ??= []
ctx.extend[key].push(extend[key])
ctx.extend[key].push({ value: extend[key], src })
}
}

Expand All @@ -240,18 +277,31 @@ function mergeTheme(ctx: ResolutionContext): Set<string> {

// Deep merge every `extend` key into the theme
for (let key in ctx.extend) {
let values = [ctx.theme[key], ...ctx.extend[key]]
let values = [
{ value: ctx.theme[key], src: key === 'keyframes' ? baseKeyframesSource : undefined },
...ctx.extend[key],
]

ctx.theme[key] = () => {
let v = values.map(resolveValue)
let v = values.map(({ value, src }) => {
let resolved = resolveValue(value)
return key === 'keyframes' ? recordKeyframeSources(resolved, src) : resolved
})
if (key === 'keyframes') {
return v.reduce((a, b) => mergeKeyframes(a, b ?? {}), {})
}

let result = deepMerge({}, v, mergeThemeExtension)
return result
}
}

for (let key in ctx.theme) {
ctx.theme[key] = resolveValue(ctx.theme[key])
let value = resolveValue(ctx.theme[key])
ctx.theme[key] = value
if (key === 'keyframes' && !ctx.extend.keyframes) {
ctx.theme[key] = recordKeyframeSources(value, baseKeyframesSource)
}
}

// Turn {min: '123px'} into '123px' in screens
Expand All @@ -269,5 +319,5 @@ function mergeTheme(ctx: ResolutionContext): Set<string> {
}
}

return replacedThemeKeys
return { replacedThemeKeys, keyframeSources }
}
Loading
Loading