Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for basic addVariant plugins with new @plugin directive #13982

Merged
merged 17 commits into from
Jul 11, 2024
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jobs:
- uses: actions/checkout@v3
- uses: pnpm/action-setup@v3
with:
version: ^8.15.0
version: ^9.5.0

- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ permissions:
env:
APP_NAME: tailwindcss-oxide
NODE_VERSION: 20
PNPM_VERSION: ^8.15.0
PNPM_VERSION: ^9.5.0
OXIDE_LOCATION: ./crates/node

jobs:
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Discard invalid `variants` and `utilities` with modifiers ([#13977](https://github.com/tailwindlabs/tailwindcss/pull/13977))
- Add missing utilities that exist in v3, such as `resize`, `fill-none`, `accent-none`, `drop-shadow-none`, and negative `hue-rotate` and `backdrop-hue-rotate` utilities ([#13971](https://github.com/tailwindlabs/tailwindcss/pull/13971))

### Added

- Add support for basic `addVariant` plugins with new `@plugin` directive ([#13982](https://github.com/tailwindlabs/tailwindcss/pull/13982))

## [4.0.0-alpha.17] - 2024-07-04

### Added
Expand Down
18 changes: 17 additions & 1 deletion packages/@tailwindcss-cli/src/commands/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import fs from 'node:fs/promises'
import path from 'node:path'
import postcss from 'postcss'
import atImport from 'postcss-import'
import { compile } from 'tailwindcss'
import * as tailwindcss from 'tailwindcss'
import type { Arg, Result } from '../../utils/args'
import {
eprintln,
Expand Down Expand Up @@ -124,6 +124,22 @@ export async function handle(args: Result<ReturnType<typeof options>>) {
}
}

let inputFile = args['--input'] && args['--input'] !== '-' ? args['--input'] : process.cwd()

let basePath = path.dirname(path.resolve(inputFile))

function compile(css: string) {
return tailwindcss.compile(css, {
loadPlugin: (pluginPath) => {
if (pluginPath[0] === '.') {
return require(path.resolve(basePath, pluginPath))
}

return require(pluginPath)
},
})
}

// Compile the input
let { build } = compile(input)

Expand Down
3 changes: 2 additions & 1 deletion packages/@tailwindcss-postcss/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"devDependencies": {
"@types/node": "^20.12.12",
"@types/postcss-import": "^14.0.3",
"postcss": "8.4.24"
"postcss": "8.4.24",
"tailwindcss-test-utils": "workspace:*"
}
}
Original file line number Diff line number Diff line change
@@ -1 +1 @@
<div class="underline 2xl:font-bold"></div>
<div class="underline 2xl:font-bold hocus:underline inverted:flex"></div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = function ({ addVariant }) {
addVariant('inverted', '@media (inverted-colors: inverted)')
addVariant('hocus', ['&:focus', '&:hover'])
}
62 changes: 62 additions & 0 deletions packages/@tailwindcss-postcss/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,65 @@ describe('processing without specifying a base path', () => {
})
})
})

describe('plugins', () => {
test('local CJS plugin', async () => {
let processor = postcss([
tailwindcss({ base: `${__dirname}/fixtures/example-project`, optimize: { minify: false } }),
])

let result = await processor.process(
css`
@import 'tailwindcss/utilities';
@plugin 'tailwindcss-test-utils';
`,
{ from: INPUT_CSS_PATH },
)

expect(result.css.trim()).toMatchInlineSnapshot(`
".underline {
text-decoration-line: underline;
}

@media (inverted-colors: inverted) {
.inverted\\:flex {
display: flex;
}
}

.hocus\\:underline:focus, .hocus\\:underline:hover {
text-decoration-line: underline;
}"
`)
})

test('published CJS plugin', async () => {
let processor = postcss([
tailwindcss({ base: `${__dirname}/fixtures/example-project`, optimize: { minify: false } }),
])

let result = await processor.process(
css`
@import 'tailwindcss/utilities';
@plugin 'tailwindcss-test-utils';
`,
{ from: INPUT_CSS_PATH },
)

expect(result.css.trim()).toMatchInlineSnapshot(`
".underline {
text-decoration-line: underline;
}

@media (inverted-colors: inverted) {
.inverted\\:flex {
display: flex;
}
}

.hocus\\:underline:focus, .hocus\\:underline:hover {
text-decoration-line: underline;
}"
`)
})
})
12 changes: 11 additions & 1 deletion packages/@tailwindcss-postcss/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { scanDir } from '@tailwindcss/oxide'
import fs from 'fs'
import { Features, transform } from 'lightningcss'
import path from 'path'
import postcss, { type AcceptedPlugin, type PluginCreator } from 'postcss'
import postcssImport from 'postcss-import'
import { compile } from 'tailwindcss'
Expand Down Expand Up @@ -130,7 +131,16 @@ function tailwindcss(opts: PluginOptions = {}): AcceptedPlugin {
}

if (rebuildStrategy === 'full') {
let { build } = compile(root.toString())
let basePath = path.dirname(path.resolve(inputFile))
let { build } = compile(root.toString(), {
loadPlugin: (pluginPath) => {
if (pluginPath[0] === '.') {
return require(path.resolve(basePath, pluginPath))
}

return require(pluginPath)
},
})
context.build = build
css = build(hasTailwind ? candidates : [])
} else if (rebuildStrategy === 'incremental') {
Expand Down
22 changes: 16 additions & 6 deletions packages/@tailwindcss-vite/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,22 @@ export default function tailwindcss(): Plugin[] {
return updated
}

function generateCss(css: string) {
return compile(css).build(Array.from(candidates))
function generateCss(css: string, inputPath: string) {
let basePath = path.dirname(path.resolve(inputPath))

return compile(css, {
loadPlugin: (pluginPath) => {
if (pluginPath[0] === '.') {
return require(path.resolve(basePath, pluginPath))
}

return require(pluginPath)
},
}).build(Array.from(candidates))
}

function generateOptimizedCss(css: string) {
return optimizeCss(generateCss(css), { minify })
function generateOptimizedCss(css: string, inputPath: string) {
return optimizeCss(generateCss(css, inputPath), { minify })
}

// Manually run the transform functions of non-Tailwind plugins on the given CSS
Expand Down Expand Up @@ -189,7 +199,7 @@ export default function tailwindcss(): Plugin[] {
await server?.waitForRequestsIdle?.(id)
}

let code = await transformWithPlugins(this, id, generateCss(src))
let code = await transformWithPlugins(this, id, generateCss(src, id))
return { code }
},
},
Expand All @@ -213,7 +223,7 @@ export default function tailwindcss(): Plugin[] {
continue
}

let css = generateOptimizedCss(file.content)
let css = generateOptimizedCss(file.content, id)

// These plugins have side effects which, during build, results in CSS
// being written to the output dir. We need to run them here to ensure
Expand Down
18 changes: 16 additions & 2 deletions packages/tailwindcss/src/design-system.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { toCss } from './ast'
import { rule, toCss } from './ast'
import { parseCandidate, parseVariant } from './candidate'
import { compileAstNodes, compileCandidates } from './compile'
import { getClassList, getVariants, type ClassEntry, type VariantEntry } from './intellisense'
Expand All @@ -8,6 +8,10 @@ import { Utilities, createUtilities } from './utilities'
import { DefaultMap } from './utils/default-map'
import { Variants, createVariants } from './variants'

export type Plugin = (api: {
addVariant: (name: string, selector: string | string[]) => void
}) => void

export type DesignSystem = {
theme: Theme
utilities: Utilities
Expand All @@ -25,7 +29,7 @@ export type DesignSystem = {
getUsedVariants(): ReturnType<typeof parseVariant>[]
}

export function buildDesignSystem(theme: Theme): DesignSystem {
export function buildDesignSystem(theme: Theme, plugins: Plugin[] = []): DesignSystem {
let utilities = createUtilities(theme)
let variants = createVariants(theme)

Expand Down Expand Up @@ -77,5 +81,15 @@ export function buildDesignSystem(theme: Theme): DesignSystem {
},
}

for (let plugin of plugins) {
plugin({
addVariant: (name: string, selectors: string | string[]) => {
variants.static(name, (r) => {
r.nodes = ([] as string[]).concat(selectors).map((selector) => rule(selector, r.nodes))
})
},
})
}

return designSystem
}
61 changes: 60 additions & 1 deletion packages/tailwindcss/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import fs from 'node:fs'
import path from 'node:path'
import { describe, expect, it, test } from 'vitest'
import { compileCss, run } from './test-utils/run'
import { compile } from '.'
import { compileCss, optimizeCss, run } from './test-utils/run'

const css = String.raw

Expand Down Expand Up @@ -1123,3 +1124,61 @@ describe('Parsing themes values from CSS', () => {
)
})
})

describe('plugins', () => {
test('addVariant with string selector', () => {
let compiled = compile(
css`
@plugin "my-plugin";
@layer utilities {
@tailwind utilities;
}
`,
{
loadPlugin: () => {
return ({ addVariant }) => {
addVariant('hocus', '&:hover, &:focus')
}
},
},
).build(['hocus:underline'])

expect(optimizeCss(compiled).trim()).toMatchInlineSnapshot(`
"@layer utilities {
.hocus\\:underline:hover, .hocus\\:underline:focus {
text-decoration-line: underline;
}
}"
`)
})

test('addVariant with array of selectors', () => {
let compiled = compile(
css`
@plugin "my-plugin";
@layer utilities {
@tailwind utilities;
}
`,
{
loadPlugin: () => {
return ({ addVariant }) => {
addVariant('hocus', ['&:hover', '&:focus'])
}
},
},
).build(['hocus:underline', 'group-hocus:flex'])

expect(optimizeCss(compiled).trim()).toMatchInlineSnapshot(`
"@layer utilities {
.group-hocus\\:flex:is(:where(.group):hover *), .group-hocus\\:flex:is(:where(.group):focus *) {
display: flex;
}

.hocus\\:underline:hover, .hocus\\:underline:focus {
text-decoration-line: underline;
}
}"
`)
})
})
25 changes: 22 additions & 3 deletions packages/tailwindcss/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,21 @@ import { version } from '../package.json'
import { WalkAction, comment, decl, rule, toCss, walk, type AstNode, type Rule } from './ast'
import { compileCandidates } from './compile'
import * as CSS from './css-parser'
import { buildDesignSystem } from './design-system'
import { buildDesignSystem, type Plugin } from './design-system'
import { Theme } from './theme'

export function compile(css: string): {
type CompileOptions = {
loadPlugin?: (path: string) => Plugin
}

function throwOnPlugin(): never {
throw new Error('No `loadPlugin` function provided to `compile`')
}

export function compile(
css: string,
{ loadPlugin = throwOnPlugin }: CompileOptions = {},
): {
build(candidates: string[]): string
} {
let ast = CSS.parse(css)
Expand All @@ -22,12 +33,20 @@ export function compile(css: string): {

// Find all `@theme` declarations
let theme = new Theme()
let plugins: Plugin[] = []
let firstThemeRule: Rule | null = null
let keyframesRules: Rule[] = []

walk(ast, (node, { replaceWith }) => {
if (node.kind !== 'rule') return

// Collect paths from `@plugin` at-rules
if (node.selector.startsWith('@plugin ')) {
plugins.push(loadPlugin(node.selector.slice(9, -1)))
replaceWith([])
return
}

// Drop instances of `@media reference`
//
// We support `@import "tailwindcss/theme" reference` as a way to import an external theme file
Expand Down Expand Up @@ -125,7 +144,7 @@ export function compile(css: string): {
firstThemeRule.nodes = nodes
}

let designSystem = buildDesignSystem(theme)
let designSystem = buildDesignSystem(theme, plugins)

let tailwindUtilitiesNode: Rule | null = null

Expand Down
4 changes: 4 additions & 0 deletions packages/test-utils/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = function ({ addVariant }) {
addVariant('inverted', '@media (inverted-colors: inverted)')
addVariant('hocus', ['&:focus', '&:hover'])
}
5 changes: 5 additions & 0 deletions packages/test-utils/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "tailwindcss-test-utils",
"private": true,
"main": "index.js"
}
1 change: 1 addition & 0 deletions playgrounds/vite/src/app.css
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
@import 'tailwindcss';
@plugin "./plugin.js";
Loading
Loading