Commit graph

5465 commits

Author SHA1 Message Date
Jordan Pittman
85d6da4884 Make the ESM cache hook ESM-only 2024-09-02 15:26:30 +02:00
Jordan Pittman
1b848f38b0 Make getModuleDependencies async 2024-09-02 15:26:30 +02:00
Philipp Spiess
61429d0d3b Add the same workaround for postcss esm 2024-09-02 15:26:30 +02:00
Philipp Spiess
3666a98a6a Only reset the require cache for build dependencies 2024-09-02 15:26:30 +02:00
Philipp Spiess
266d0184b7 Fix esm cache hook for esm usage with vitest 2024-09-02 15:26:30 +02:00
Philipp Spiess
b8fd2e704f Revert change to integrations/postcss/index.test.ts 2024-09-02 15:26:30 +02:00
Philipp Spiess
f37565de7a Fix js config file and plugin dependnecy rebuilds for vite 2024-09-02 15:26:30 +02:00
Philipp Spiess
a72ca61f26 WIP 2024-09-02 15:26:30 +02:00
Philipp Spiess
a5c379386b Add the @tailwindcss/node module to handle shared node specific dependencies between our clients 2024-09-02 15:26:28 +02:00
Philipp Spiess
d607f0a40e Detect changes to the config file and plugins for the CLI 2024-09-02 15:26:04 +02:00
Jordan Pittman
3a7feb7930 wip 2024-09-02 15:26:04 +02:00
Jordan Pittman
7e9db364c9 update test 2024-09-02 15:26:04 +02:00
Jordan Pittman
882c39dd0c Add integration tests 2024-09-02 15:26:04 +02:00
Jordan Pittman
faf98b364a Upgrade merged theme keys from colors.* to color-* 2024-09-02 15:26:04 +02:00
Jordan Pittman
c13d221d58 Update tests 2024-09-02 15:26:04 +02:00
Jordan Pittman
ea54594515 Handle inline theme keys in resolveWith 2024-09-02 15:26:04 +02:00
Jordan Pittman
5078ccdc9f wip 2024-09-02 15:26:04 +02:00
Jordan Pittman
b44c4f90dc prettier 2024-09-02 15:26:04 +02:00
Jordan Pittman
8ffe833f40 Format code 2024-09-02 15:26:04 +02:00
Jordan Pittman
73b5dfa9e7 Ensure CSS variants and utilities always take precedence 2024-09-02 15:26:04 +02:00
Jordan Pittman
bb89c7c6df Work on theme value merging 2024-09-02 15:26:04 +02:00
Jordan Pittman
f2b7fbae6b Add config test 2024-09-02 15:26:04 +02:00
Jordan Pittman
67efbfe628 Allow configuring dark mode from configs 2024-09-02 15:26:04 +02:00
Jordan Pittman
cc353d310b Merge sources from config files 2024-09-02 15:26:04 +02:00
Jordan Pittman
73ab0a61d7 Load config files via @config directive 2024-09-02 15:26:04 +02:00
Jordan Pittman
f878a90893 Add config helper 2024-09-02 15:26:04 +02:00
Jordan Pittman
20f001cb3c Allow resolve config to take in optional paths alongside configs 2024-09-02 15:26:04 +02:00
Jordan Pittman
f876304557 Add support for presets 2024-09-02 15:26:04 +02:00
Jordan Pittman
3553b5912e Use resolveConfig to normalize plugins 2024-09-02 15:26:04 +02:00
Philipp Spiess
d9e3fd613b
Add standalone CLI (#14270)
This PR adds a new standalone client: A single-binary file that you can
use to run Tailwind v4 without having a node setup. To make this work we
use Bun's single-binary build which can properly package up native
modules and the bun runtime for us so we do not have to rely on any
expand-into-tmp-folder-at-runtime workarounds.

When running locally, `pnpm build` will now standalone artifacts inside
`packages/@tailwindcss-standalone/dist`. Note that since we do not build
Oxide for other environments in the local setup, you won't be able to
use the standalone artifacts for other platforms in local dev mode.

Unfortunately Bun does not have support for Windows ARM builds yet but
we found that using the `bun-baseline` runtime for Windows x64 would
make the builds work fine in ARM emulation mode:

![Screenshot
windows](https://github.com/user-attachments/assets/5b39387f-ec50-4757-9469-19b98e43162d)


Some Bun related issues we faced and worked around:

- We found that the regular Windows x64 build of `bun` does not run on
Windows ARM via emulation. Instead, we have to use the `bun-baseline`
builds which emulate correctly.

- When we tried to bundle artifacts with [embed
directories](https://bun.sh/docs/bundler/executables#embed-directories),
node binary dependencies were no longer resolved correctly even though
they would still be bundled and accessible within the [`embeddedFiles`
list](https://bun.sh/docs/bundler/executables#listing-embedded-files).
We worked around this by using the `import * as from ... with { type:
"file" };` and patching the resolver we use in our CLI.
  
  
- If you have an import to a module that is used as a regular import
_and_ a `with { type: "file" }`, it will either return the module in
both cases _or_ the file path when we would expect only the `with {
type: "file" }` import to return the path. We do read the Tailwind CSS
version via the file system and `require.resolve()` in the CLI and via
`import * from './package.json'` in core and had to work around this by
patching the version resolution in our CLI.
 
  ```ts
  import packageJson from "./package.json"
  import packageJsonPath from "./package.json" with {type: "file"}
  
  // We do not expect these to be equal
  packageJson === packageJsonPath 
  ```
- We can not customize the app icon used for Windows `.exe` builds
without decompiling the binary. For now we will leave the default but
one workaround is to [use tools like
ResourceHacker](698d9c4bd1)
to decompile the binary first.

---------

Co-authored-by: Jordan Pittman <jordan@cryptica.me>
Co-authored-by: Robin Malfait <malfait.robin@gmail.com>
2024-09-02 15:23:46 +02:00
Philipp Spiess
ac6d4a6e8e
Spreading tailwindcss/defaultTheme exports keeps bare values (#14257)
In #14221 we added a new export to the `tailwindcss` package:
`tailwindcss/defaultTheme`. This is build on top of the full config from
V3 and will allow plugins to keep being compatible.

However, spreading in from this package has overwritten the bare value
callback handler. This PR fixes it by sharing the bare value callbacks
with the compat config.
2024-08-29 14:05:41 +02:00
Jordan Pittman
fa8253e42a
Fix support for declaration fallbacks in plugins (#14265)
This PR fixes support for "fallback" values for declarations in plugins.

A plugin using `addUtilities`, `matchUtilities`, `addComponents`, etc…
should be able to specify "fallback" values for declarations by passing
an array as the value of a declaration however this does not currently
work in v4 (but it does in v3):

```js
export default {
  plugins: [
    function ({ addUtilities }) {
      addUtilities({
        '.outlined': {
          outline: ['1px solid ButtonText', '1px auto -webkit-focus-ring-color'],
        },
      })
    },
  ],
};
```

After this PR the candidate `outlined` will now produce the following
CSS — like it does in v3:

```css
.outlined {
  outline: 1px solid ButtonText;
  outline: 1px auto -webkit-focus-ring-color;
}
```
2024-08-27 12:18:53 +02:00
Philipp Spiess
f5499aac95
Fix issues with the CSS theme() function (#14262)
While working on #14257, we noticed two issues with the CSS `theme()`
function:

1. In V3 it's possible to set arrays inside the theme object. An example
for this is the default font families as defined here:
https://github.com/tailwindlabs/tailwindcss/blob/main/stubs/config.full.js#L303-L311.
We now properly join these arrays that are not tuples.
2. We noticed that in the case where there are no modifiers, the
fallback values for the CSS `theme()` function had the first word
removed. A regression test for this was added.
2024-08-26 18:55:27 +02:00
Philipp Spiess
35398e0ffb Add .gitattributes and define a merge strategy for changelog files 2024-08-26 16:27:41 +02:00
Philipp Spiess
0796653527
Correctly merge tuple values when using the plugin API (#14260)
We noticed that when the `defaultTheme` (change for this is coming in
#14257) defines a tuple that is also defined in the CSS theme, the
values are incorrectly merged as objects instead of overwritten.
However, CSS theme values should take precedence, even when they use
tuple syntax.

Proper coverage of this will come once `#14257` is merged when calling
`theme(fontSize.xs[1].lineHeight)` will also have a default value passed
in from the `defaultTheme`.
2024-08-26 16:23:52 +02:00
Philipp Spiess
ab8972749c
Postcss: Bring back proper type exports (#14256)
Closes #14253

Since we changed the export strategy for the postcss client in #14132,
we accidentally no longer generated type exports for this package.

This PR adds a type export back. We now use a similar pattern to the
`./colors` and `./defaultTheme` exports in the tailwindcss package where
we have a separate cjs entrypoint.

The changes were validated manually in a playground project that were
installing the updated dependencies from tarballs.

Here is one example of it working as expected:
 
<img width="750" alt="Screenshot 2024-08-26 at 14 10 07"
src="https://github.com/user-attachments/assets/83de15f2-1543-4805-9231-9b8df1636c5e">
2024-08-26 15:54:07 +02:00
Philipp Spiess
d5f563b746
Prepare v4.0.0-alpha.20 (#14244)
Prepare next `4.0.0-alpha.20` release
2024-08-23 15:51:53 +02:00
Philipp Spiess
a84e52a46c
Move value parser into tailwindcss root (#14236)
This PR is moving content from
`packages/tailwindcss/src/value-parser/*.ts` into
`packages/tailwindcss/src/value-parser.ts` to simplify the file
structure.
2024-08-22 12:32:49 -04:00
Philipp Spiess
fcc07826f7
Remove unused resolveNamespace method (#14235)
Removing a leftover API from the recent changes in
https://github.com/tailwindlabs/tailwindcss/pull/14177
2024-08-22 11:21:14 -04:00
Jordan Pittman
cc228fbfc3
Add support for matching multiple utility definitions for one candidate (#14231)
Currently if a plugin adds a utility called `duration` it will take
precedence over the built-in utilities — or any utilities with the same
name in previously included plugins. However, in v3, we emitted matches
from _all_ plugins where possible.

Take this plugin for example which adds utilities for
`animation-duration` via the `duration-*` class:

```ts
import plugin from 'tailwindcss/plugin'

export default plugin(
  function ({ matchUtilities, theme }) {
    matchUtilities(
      { duration: (value) => ({ animationDuration: value }) },
      { values: theme("animationDuration") },
    )
  },
  {
    theme: {
      extend: {
        animationDuration: ({ theme }) => ({
          ...theme("transitionDuration"),
        }),
      }
    },
  }
)
```

Before this PR this plugin's `duration` utility would override the
built-in `duration` utility so you'd get this for a class like
`duration-3500`:
```css
.duration-3000 {
  animation-duration: 3500ms;
}
```

Now, after this PR, we'll emit rules for `transition-duration`
(Tailwind's built-in `duration-*` utility) and `animation-duration`
(from the above plugin) and you'll get this instead:
```css
.duration-3000 {
  transition-duration: 3500ms;
}

.duration-3000 {
  animation-duration: 3500ms;
}
```

These are output as separate rules to ensure that they can all be sorted
appropriately against other utilities.

---------

Co-authored-by: Philipp Spiess <hello@philippspiess.com>
2024-08-22 16:22:12 +02:00
Philipp Spiess
bc88958855
Add support for the CSS theme() function (#14177)
This PR adds the CSS `theme()` function to Tailwind V4. It's intended
use is to get the raw value of a theme variable. This can be handy when
trying to reference theme values in places where `var()` is not
supported, for example:

```css
@media (min-width: theme(--breakpoint-md)) {
  /*...*/
}
```

The CSS `theme()` function is backward compatible with Tailwind V3 which
means that it can also be used with the old key path syntax, like:
`theme(colors.red.500)`. The lookup for this is shared with the plugin
`theme()` function and this PR adds a bunch of edge cases to validate
the backward compatibility. Here are a few interesting cases that we
found to be valid in Tailwind V3 and are now also valid in Tailwind V4:

```js
// First argument can be inside quotes
theme('colors.red.500') 
// Square brackets are valid separators in V3, even when chained with dots
theme(color[red].500)
// Slashes can be used for adding opacity to colors. This can also be inside quotes
theme('colors.red.500 / 75%')
// Oh yeah and there's also the tuple syntax for accessing v3 scoped variables
theme(fontSize.xs[1].lineHeight)
// themes can also define fallback values which could be theme calls again...
theme(colors.red.unknown / 75%, theme(colors.red.500 / 25%))
// ... or list of values:
theme(fontFamily.sans, 'Helvetica Neue', Helvetica, sans-serif)
// Theme function can also be used in candidate class names...
sm:[--color:theme(colors.red[500])
// ... and of course @media queries
@media (min-width: theme(breakpoint.md)) and (max-width: theme(--breakpoint-lg))
```

The way this is implemented right now is by adding a separate walk that
scans all declaration values. If these values look like they could have
a `theme()` function call, we will parse these values using a new
`ValueParser` into a small AST that can be used to substitute function
calls.
2024-08-22 15:46:44 +02:00
Jordan Pittman
30bbe51a38
Improve compatibility with @tailwindcss/typography and @tailwindcss/forms (#14221)
This PR enables compatibility for the `@tailwindcss/typography` and
`@tailwindcss/forms` plugins. This required the addition of new Plugin
APIs and new package exports.

## New Plugin APIs and compatibility improvements

We added support for `addComponents`, `matchComponents`, and `prefix`.
The component APIs are an alias for the utilities APIs because the
sorting in V4 is different and emitting components in a custom `@layer`
is not necessary. Since `prefix` is not supported in V4, the `prefix()`
API is currently an identity function.

```js
 addComponents({
  '.btn': {
    padding: '.5rem 1rem',
    borderRadius: '.25rem',
    fontWeight: '600',
  },
  '.btn-blue': {
    backgroundColor: '#3490dc',
    color: '#fff',
    '&:hover': {
      backgroundColor: '#2779bd',
    },
  },
  '.btn-red': {
    backgroundColor: '#e3342f',
    color: '#fff',
    '&:hover': {
      backgroundColor: '#cc1f1a',
    },
  },
})
```

The behavioral changes effect the `addUtilities` and `matchUtilities`
functions, we now:

- Allow arrays of CSS property objects to be emitted:
  ```js
  addUtilities({
    '.text-trim': [
      {'text-box-trim': 'both'},
      {'text-box-edge': 'cap alphabetic'},
    ],
  })
  ```
- Allow arrays of utilities
  ```js
  addUtilities([
    {
      '.text-trim':{
        'text-box-trim': 'both',
        'text-box-edge': 'cap alphabetic',
      },
    }
  ])
  ```
- Allow more complicated selector names
  ```js
  addUtilities({
    '.form-input, .form-select, .form-radio': {
      /* styles here */
    },
    '.form-input::placeholder': {
      /* styles here */
    },
    '.form-checkbox:indeterminate:checked': {
      /* styles here */
    }
  })
  ```

## New `tailwindcss/color` and `tailwindcss/defaultTheme` export

To be compatible to v3, we're adding two new exports to the tailwindcss
package. These match the default theme values as defined in v3:

```ts
import colors from 'tailwindcss/colors'

console.log(colors.red[600])
```

```ts
import theme from 'tailwindcss/defaultTheme'

console.log(theme.spacing[4])
```

---------

Co-authored-by: Philipp Spiess <hello@philippspiess.com>
2024-08-22 08:06:21 -04:00
Philipp Spiess
84ebe19da2
Vite: Retain candidates between input CSS updates (#14228)
This PR fixes an issue introduced with the changed candidate cache
behavior in #14187.

Prior to #14187, candidates were cached globally within an instance of
Oxide. This meant that once a candidate was discovered, it would not
reset until you either manually cleared the cache or restarted the Oxide
process. With the changes in #14187 however, the cache was scoped to the
instance of the `Scanner` class with the intention of making the caching
behavior more easy to understand and to avoid a global cache.

This, however, had an unforeseen side-effect in our Vite extension.
Vite, in dev mode, discovers files _lazily_. So when a developer goes to
`/index.html` the first time, we will scan the `/index.html` file for
Tailwind candidates and then build a CSS file with those candidate. When
they go to `/about.html` later, we will _append_ the candidates from the
new file and so forth.

The problem now arises when the dev server detects changes to the input
CSS file. This requires us to do a re-scan of that CSS file which, after
#14187, caused the candidate cache to be gone. This is usually fine
since we would just scan files again for the changed candidate list but
in the Vite case we would only get the input CSS file change _but no
subsequent change events for all other files, including those currently
rendered in the browser_). This caused updates to the CSS file to remove
all candidates from the CSS file again.

Ideally, we can separate between two concepts: The candidate cache and
the CSS input file scan. An instance of the `Scanner` could re-parse the
input CSS file without having to throw away previous candidates. This,
however, would have another issue with the current Vite extension where
we do not properly retain instances of the `Scanner` class anyways. To
properly improve the cache behavior, we will have to fix the Vite
`Scanner` retaining behavior first. Unfortunately this means that for
the short term, we have to add some manual bookkeeping to the Vite
client and retain the candidate cache between builds ourselves.

---------

Co-authored-by: Jordan Pittman <jordan@cryptica.me>
2024-08-21 12:54:42 +02:00
Adam Wathan
45fb21e753
Add support for the theme() function in the plugin API (#14207)
This PR adds support for the [`theme()`
function](https://tailwindcss.com/docs/plugins#dynamic-utilities) from
the v3 plugin API, used for configuring which values functional
utilities support:

```js
plugin(function({ matchUtilities, theme }) {
  matchUtilities(
    {
      tab: (value) => ({
        tabSize: value
      }),
    },
    { values: theme('tabSize') }
  )
})
```

Things this handles:

- "Upgrading" theme keys to their v4 names, so if you do
`theme('colors')` that will correctly retrieve all the colors from the
`--color-*` namespace with the new CSS variable based configuration
- Polyfilling dependent keys, so `theme('backgroundColor')` will still
pull everything in `--color-*` even though there is no values in the
`backgroundColor` namespace in v4 by default
- Polyfilling theme values that are now handled by "bare values"
internally, so even though there is no `flexShrink` theme values in v4,
`theme('flexShrink')` will still configure your plugin to properly
support any value that the built-in `shrink-*` utilities support

Things that aren't handled:

- Theme values that have been replaced by static utilities can't be
retrieved yet, so for example `theme('cursor')` returns nothing right
now because there are no values for the `cursor-*` utilities in the
theme anymore, they are all just baked in to the framework.

This will be handled in a future PR.

---------

Co-authored-by: Adam Wathan <4323180+adamwathan@users.noreply.github.com>
Co-authored-by: Jordan Pittman <jordan@cryptica.me>
Co-authored-by: Robin Malfait <malfait.robin@gmail.com>
2024-08-20 11:05:08 -04:00
Adam Wathan
3df38a7458
Don't wrap relative selectors in arbitrary variants with :is(…) (#14203)
Prior to this PR, we weren't accounting for the fact that `:has(…)`
supports [relative
selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors/Selector_structure#relative_selector),
which are sort of like partial selectors that can start with a
combinator like `>`, `+`, or `~`.

Before, a class like `has-[>img]:flex` would generate this:

```css
.has-\[\>img\]\:flex:has(*:is(> img)) {
  display: flex;
}
```

This was incorrect because `*:is(> img)` isn't even valid CSS at all, so
the rule would do nothing.

After this change, we generate this instead:

```css
.has-\[\>img\]\:flex:has(> img) {
  display: flex;
}
```

This PR also ensures that relative selectors are recognized as invalid
in places where they are not supported, so classes like
`group-[>img]:flex` for example will produce nothing now instead of
invalid CSS.

This is mostly a simple change but it did involve storing some
additional information in the variant AST.

Fixes #14202.

---------

Co-authored-by: Adam Wathan <4323180+adamwathan@users.noreply.github.com>
Co-authored-by: Robin Malfait <malfait.robin@gmail.com>
2024-08-16 13:42:04 -04:00
Philipp Spiess
e10b786437
Add Next.js integration test (#14163)
Using the [new integration test
setup](https://github.com/tailwindlabs/tailwindcss/pull/14089), this PR
adds a test for a V4 Next.js setup using the Postcss plugin. It's
testing both a full build and the dev mode (non-turbo for now).

Because of webpack, tests are quite slow which is worrisome since we
probably need to add many more integrations in the future. One idea I
have is that we separate tests in two buckets: _essential_ tests that
run often and are fast and advanced suites that we only run on CI via
custom, non-blocking, jobs.

---------

Co-authored-by: Jordan Pittman <jordan@cryptica.me>
2024-08-16 15:45:52 +02:00
Robin Malfait
a902128640
Improve Oxide scanner API (#14187)
This PR updates the API for interacting with the Oxide API. Until now,
we used the name `scanDir(…)` which is fine, but we do way more work
right now.

We now have features such as:

1. Auto source detection (can be turned off, e.g.: `@tailwindcss/vite`
doesn't need it)
2. Scan based on `@source`s found in CSS files
3. Do "incremental" rebuilds (which means that the `scanDir(…)` result
was stateful).

To solve these issues, this PR introduces a new `Scanner` class where
you can pass in the `detectSources` and `sources` options. E.g.:

```ts
let scanner = new Scanner({
  // Optional, omitting `detectSources` field disables automatic source detection
  detectSources: { base: __dirname }, 

  // List of glob entries to scan. These come from `@source` directives in CSS.
  sources: [
    { base: __dirname, pattern: "src/**/*.css" },
    // …
  ],
});
```

The scanner object has the following API:

```ts
export interface ChangedContent {
  /** File path to the changed file */
  file?: string
  /** Contents of the changed file */
  content?: string
  /** File extension */
  extension: string
}
export interface DetectSources {
  /** Base path to start scanning from */
  base: string
}
export interface GlobEntry {
  /** Base path of the glob */
  base: string
  /** Glob pattern */
  pattern: string
}
export interface ScannerOptions {
  /** Automatically detect sources in the base path */
  detectSources?: DetectSources
  /** Glob sources */
  sources?: Array<GlobEntry>
}
export declare class Scanner {
  constructor(opts: ScannerOptions)
  scan(): Array<string>
  scanFiles(input: Array<ChangedContent>): Array<string>
  get files(): Array<string>
  get globs(): Array<GlobEntry>
}
```

The `scanFiles(…)` method is used for incremental rebuilds. It takes the
`ChangedContent` array for all the new/changes files. It returns whether
we scanned any new candidates or not.

Note that the `scanner` object is stateful, this means that we don't
have to track candidates in a `Set` anymore. We can just call
`getCandidates()` when we need it.

This PR also removed some unused code that we had in the `scanDir(…)`
function to allow for sequential or parallel `IO`, and sequential or
parallel `Parsing`. We only used the same `IO` and `Parsing` strategies
for all files, so I just got rid of it.

---------

Co-authored-by: Jordan Pittman <jordan@cryptica.me>
2024-08-16 15:05:42 +02:00
Martin Feckie
cc4689deef
Add Glimmer template extensions to Oxide content detection (#14199)
Co-authored-by: Jordan Pittman <jordan@cryptica.me>
2024-08-15 09:34:19 -04:00
Robin Malfait
5035c106fb
Bump GitHub actions to latest version (#14182)
This PR bumps the versions of common GitHub workflows to the latest
version.
2024-08-13 18:12:19 +02:00
Jordan Pittman
e299ea381f
Add support for the tailwindcss/plugin export (#14173)
This PR adds support for the `tailwindcss/plugin` import which has
historically been used to define custom plugins:

```js
import plugin from "tailwindcss/plugin";

export default plugin(function ({ addBase }) {
  addBase({
    // ...
  });
});
```

This also adds support for `plugin.withOptions` which was used to define
plugins that took optional initilization options when they were
registered in your `tailwind.config.js` file:

```js
import plugin from "tailwindcss/plugin";

export default plugin.withOptions((options = {}) => {
  return function ({ addBase }) {
    addBase({
      // ...
    });
  };
});
```

We've stubbed out support for the `config` argument but we're not
actually doing anything with it at the time of this PR. The scope of
this PR is just to allow people to create plugins that currently work
using the raw function syntax but using the `plugin` and
`plugin.withOptions` APIs. Support for `config` will land separately.

---------

Co-authored-by: Adam Wathan <4323180+adamwathan@users.noreply.github.com>
2024-08-13 10:25:29 -04:00