
# Tailwind CSS

Blockstudio 内置 Tailwind CSS v4 支持。启用后，每个前端页面都会通过 [TailwindPHP](https://github.com/dnnsjsk/tailwindphp) 在服务器端编译，并自动进行基于文件的缓存。在区块编辑器中，打包的 Tailwind CDN 脚本会在编辑时提供实时预览。

无需构建步骤，无需CLI，也无需Node.js。

## 工作原理

Blockstudio会根据上下文采用两种不同的编译策略：

### 前端（服务器端）

每次前端请求中，Blockstudio都会通过输出缓冲区捕获完整页面HTML，提取所有CSS类候选项，只编译实际用到的CSS，并在`</head>`之前将结果作为内联`<style>`标签注入。

编译流程：

1. WordPress将完整页面HTML渲染到输出缓冲区中
2. `TailwindPHP::extractCandidates()`扫描HTML，提取所有可能的CSS类名（使用快速正则表达式，不进行编译）
3. 将排序后的候选项与CSS配置一起哈希，生成缓存键
4. **缓存命中**时：从磁盘读取已编译的CSS并注入
5. **缓存未命中**时：`TailwindPHP::generate()`编译CSS，将其写入缓存目录并注入

已编译的CSS会以如下方式注入：

```html
<style id="blockstudio-tailwind">
  /* compiled CSS */
</style>
```

其中包括Tailwind的预检（CSS重置）以及所有匹配的实用工具类。

### 编辑器（客户端）

在区块编辑器中，打包的 Tailwind CDN 脚本（Tailwind CSS v4 的浏览器构建版本）会在客户端运行。输入类名时，它会即时提供实时预览，无需任何服务器往返请求。CDN 仅在编辑器中加载，绝不会在前端提供。

启用`assets.reset.enabled`时，Blockstudio还会在编辑器画布中恢复Tailwind常用的显示和定位实用工具。这样，WordPress编辑器区块包装器规则就不会覆盖`flex`、`grid`、`absolute`、`fixed`和`sticky`等包装器级类名，使由实用工具类驱动的布局更接近前端效果。

## 启用Tailwind

将`tailwind`配置添加到你的`blockstudio.json`中：

```json title="blockstudio.json"
{
  "$schema": "https://blockstudio.dev/schema/blockstudio",
  "tailwind": {
    "enabled": true
  }
}
```

或者通过筛选器启用：

```php title="functions.php"
add_filter('blockstudio/settings/tailwind/enabled', '__return_true');
```

当`enabled`设为`true`时，每个前端页面都会自动编译并注入Tailwind CSS。你可以在任何位置使用Tailwind实用工具类：区块模板、主题模板、`the_content`筛选器，或页面输出中的任意HTML。

### 前端输出

默认情况下，已编译的CSS采用内联方式，以保留早期版本使用的输出形式。具有大量共享规则的站点可以选择使用带内容哈希的样式表：

```json title="blockstudio.json"
{
  "tailwind": {
    "enabled": true,
    "output": "link"
  }
}
```

`"output": "link"`会将现有的`tailwind/{content-hash}.css`缓存文件作为`<link rel="stylesheet">`输出。运行时身份、候选项、引擎或CSS输入发生变化时，URL也会随之变化，因此浏览器和边缘缓存可以安全地保留旧 URL。请配置 Web 服务器或CDN，为此缓存作用域发送长期有效的`Cache-Control: public, immutable`标头。

默认缓存根目录位于`wp-content`下的公开目录中。如果`cache.path`指向私有绝对路径卷，除非现有的`blockstudio/files/url`筛选器为`tailwind`作用域提供公开的URL，否则Blockstudio会回退为内联CSS：

```php title="functions.php"
add_filter(
    'blockstudio/files/url',
    function (string $url, string $path, string $scope): string {
        if ('tailwind' !== $scope) {
            return $url;
        }

        return 'https://static.example.com/blockstudio/' . basename($path);
    },
    10,
    3
);
```

## 模板组合辅助工具

Blockstudio向PHP模板提供同一个捆绑的TailwindPHP引擎，无需在主题侧复制代码或实现回退方案：

```php title="functions.php"
$classes = bs_tw_merge('px-2 text-sm', 'px-4');
// text-sm px-4

$button = bs_tw_variants([
    'base' => 'inline-flex items-center',
    'variants' => [
        'size' => [
            'sm' => 'h-8 px-3',
            'lg' => 'h-12 px-6',
        ],
    ],
    'defaultVariants' => [
        'size' => 'sm',
    ],
]);

echo $button(['size' => 'lg', 'class' => 'rounded']);
```

`bs_tw_merge()` 接受嵌套的类值，并解析冲突的 Tailwind 工具类。`bs_tw_variants()` 返回一个 CVA 风格的可调用对象，支持基础类、变体、默认变体、复合变体、`class` 和 `className`。

## 配置

Tailwind v4 采用以 CSS 为先的配置方式。你无需使用 JavaScript 配置文件，而是直接将配置写成 CSS，并使用 `@theme` 指令。

```json title="blockstudio.json"
{
  "tailwind": {
    "enabled": true,
    "config": "@theme { --color-primary: #3b82f6; --color-secondary: #10b981; --font-family-heading: 'Inter', sans-serif; }"
  }
}
```

`config` 值是一个 CSS 字符串，会追加在 `@import "tailwindcss"` 指令之后。此处可以使用任何有效的 Tailwind v4 CSS 语法：

```json title="blockstudio.json"
{
  "tailwind": {
    "enabled": true,
    "config": "@theme { --color-brand: oklch(0.7 0.15 200); } @layer base { h1 { font-size: var(--text-4xl); } }"
  }
}
```

对于多行配置，使用过滤器的方式更便捷：

```php title="functions.php"
add_filter('blockstudio/settings/tailwind/config', function () {
    return <<<CSS
@theme {
    --color-primary: #3b82f6;
    --color-secondary: #10b981;
    --font-family-heading: 'Inter', sans-serif;
    --breakpoint-xs: 30rem;
}

@layer base {
    body {
        font-family: var(--font-family-sans);
    }
}

@layer utilities {
    .btn { @apply px-4 py-2 rounded-lg font-medium; }
    .btn-primary { @apply bg-blue-500 text-white hover:bg-blue-600; }
    .card { @apply bg-white rounded-xl shadow-lg p-6; }
}
CSS;
});
```

### 自定义工具类

要定义可复用的类别名，请在配置字符串中直接使用 `@layer utilities` 和 Tailwind 的 `@apply` 指令：

```json title="blockstudio.json"
{
  "tailwind": {
    "enabled": true,
    "config": "@theme { --color-brand: #6366f1; } @layer utilities { .btn { @apply px-4 py-2 rounded-lg font-medium; } .section { @apply py-16 px-4 max-w-7xl mx-auto; } }"
  }
}
```

这些类会与所有标准 Tailwind 工具类一同编译。它们在前端（服务器端编译）和编辑器中（CDN 预览）均可使用。

Blockstudio 保留 Tailwind 规范的层叠层顺序：
`theme`、`base`、`components`，然后是 `utilities`。这与 Tailwind CSS 一致，因此
较晚层中的规则可以按预期覆盖较早层中的规则。

## 类字段类型

要在区块的 `classes` 字段中使用 Tailwind 类并启用自动补全，请在该字段上设置 `tailwind: true`：

```json title="block.json"
{
  "name": "my-theme/hero",
  "title": "Hero",
  "blockstudio": {
    "attributes": [
      {
        "id": "classes",
        "type": "classes",
        "label": "Classes",
        "tailwind": true,
        "default": "bg-white text-gray-900"
      }
    ]
  }
}
```

当 `tailwind` 为 `true` 时：

- 该字段会根据完整的 Tailwind 类列表提供自动补全建议
- 编辑器中会加载 Tailwind CDN 脚本以提供实时预览
- 类会以空格分隔的字符串形式存储在区块属性中

在模板中使用类值：

```php title="index.php"
<div class="<?php echo $a['classes']; ?>">
  <!-- block content -->
</div>
```

## 设置参考

| 选项 | 类型 | 默认值 | 说明 |
| --------- | ------- | ------- | ----------------------------------------------- |
| `enabled` | boolean | `false` | 在前端启用 Tailwind CSS 编译 |
| `config` | string | `""` | Tailwind v4 优先的 CSS 配置字符串 |

### 通过 JSON 设置

```json title="blockstudio.json"
{
  "tailwind": {
    "enabled": true,
    "config": "@theme { --color-brand: pink; }"
  }
}
```

### 通过过滤器设置

```php title="functions.php"
add_filter('blockstudio/settings/tailwind/enabled', '__return_true');

add_filter('blockstudio/settings/tailwind/config', function () {
    return '@theme { --color-brand: pink; }';
});
```

## 缓存

Blockstudio 使用专为 Tailwind 工具类架构设计的自定义缓存策略。

### 缓存的工作方式

与对整个页面 HTML 进行哈希相比（由于 nonce、时间戳和其他动态内容，每次请求都会导致缓存失效），Blockstudio 只从 HTML 中提取 CSS 类候选项。随后将这些候选项排序，并与 CSS 配置一起进行哈希，生成稳定的缓存键。

这意味着：

- 使用相同 Tailwind 类集合的两个页面会共享同一个缓存 CSS 文件，即使它们的 HTML 完全不同
- 随机数、已登录用户栏、评论数和时间戳等动态内容不会使缓存失效
- 仅当页面上的 CSS 类集合或 Tailwind 配置发生变化时，缓存才会失效

运行时使用 [ 逻辑发现源 ](https://blockstudio.dev/zh/docs/dev/discovery-sources/) 时，所选源和运行时上下文也会参与缓存命名空间。上次成功的 CSS 会在不同预览之间隔离，不会从一个源选择泄漏到另一个源选择。

### 缓存位置

缓存文件存储于：

```
wp-content/blockstudio/cache/sites/{network-blog}/{runtime-identity}/tailwind/
```

配置的 `cache.path`、当前多站点身份和完整运行时身份共同决定确切的前缀。每个文件都以 MD5 哈希命名：
`{hash}.css`。

### 清除缓存

删除缓存目录中的内容以强制重新编译：

```php
// Clear all cached Tailwind CSS
Blockstudio\Runtime_Cache::purge('tailwind');
```

或者通过 WP-CLI：

```bash
wp eval "Blockstudio\\Runtime_Cache::purge('tailwind');"
```

下一次前端请求会自动重新编译并缓存 CSS。

## 过滤器

### `blockstudio/tailwind/css`

在编译前修改 CSS 输入。CSS 输入字符串以 `@import "tailwindcss";` 开头，后面跟着任意配置。使用此过滤器可添加其他 CSS 指令、自定义 `@layer` 规则或插件导入。

```php
add_filter('blockstudio/tailwind/css', function (string $css): string {
    // Add a custom utility
    $css .= "\n@utility container-narrow { max-width: 48rem; margin-inline: auto; }";

    return $css;
});
```

编译后的完整 CSS 输入如下所示：

```css
/* Base import */
@import 'tailwindcss';

/* Config from settings (if set) */
@theme {
  --color-brand: pink;
}

/* Anything added via the blockstudio/tailwind/css filter */
```

## 输出缓冲区

Tailwind 编译接入 Blockstudio 的输出缓冲系统。缓冲区会在 WordPress 完成渲染后捕获完整的页面 HTML，使 Tailwind 能够扫描所有来源中的类：区块模板、主题模板、插件输出、`the_content` 过滤器和小工具区域。

编译过滤器以优先级 `999999` 在 `blockstudio/buffer/output` 钩子上运行，确保它在所有其他修改完成后处理最终的 HTML。缓冲区在 `template_redirect` 操作上启动，因此只会在前端请求中运行，不会在管理后台、REST API 或 AJAX 上下文中运行。

缓冲整个文档是实现此功能的关键，因此默认启用。如果网站既不使用 Tailwind，也不使用区块资源，则可以将其关闭：

```php
add_filter( 'blockstudio/buffer/enabled', '__return_false' );
```

返回 `false` 会完全跳过缓冲，同时也会禁用 Tailwind 编译，以及将区块样式和脚本提升到 head 和页脚中的功能。

## 架构

```
Frontend Request
  │
  ├─ WordPress renders HTML into output buffer
  │
  ├─ blockstudio/buffer/output filter (priority 999999)
  │   │
  │   ├─ Settings::get('tailwind/enabled') → false? Return HTML unchanged
  │   │
  │   ├─ build_css_input()
  │   │   ├─ @import "tailwindcss"
  │   │   ├─ + tailwind/config setting
  │   │   └─ + blockstudio/tailwind/css filter
  │   │
  │   ├─ TailwindPHP::extractCandidates($html)
  │   │   └─ Returns array of CSS class names found in HTML
  │   │
  │   ├─ Cache key = md5(sorted candidates + css input)
  │   │
  │   ├─ Cache hit?
  │   │   ├─ Yes → Read CSS from the shared runtime `tailwind/{hash}.css` scope
  │   │   └─ No  → TailwindPHP::generate() → Write to cache file
  │   │
  │   └─ Inject inline CSS, or link the content-hashed cache file when tailwind.output is "link"
  │
  └─ Browser receives HTML with compiled CSS


Editor Request
  │
  ├─ Admin loads block editor
  │
  ├─ Block with classes field (tailwind: true) detected
  │   └─ Block_Registry::set_tailwind_active(true)
  │
  ├─ Admin passes isTailwindActive + tailwindUrl to JS
  │
  └─ useTailwind() hook
      ├─ Injects Tailwind CDN script into document
      ├─ Creates hidden template div with HTML content
      ├─ Creates style tag for config
      └─ CDN compiles CSS in-browser for live preview
```

## 完整示例

一个完整可运行的设置，其中包含自定义主题颜色和使用这些颜色的区块：

```json title="blockstudio.json"
{
  "$schema": "https://blockstudio.dev/schema/blockstudio",
  "tailwind": {
    "enabled": true,
    "config": "@theme { --color-brand: #6366f1; --color-brand-light: #a5b4fc; --color-surface: #f8fafc; } @layer utilities { .section-padding { @apply py-20 px-6; } .content-width { @apply max-w-5xl mx-auto; } .heading-xl { @apply text-4xl font-bold tracking-tight; } }"
  }
}
```

```json title="hero/block.json"
{
  "name": "my-theme/hero",
  "title": "Hero Section",
  "blockstudio": {
    "attributes": [
      {
        "id": "title",
        "type": "text",
        "label": "Title",
        "default": "Welcome"
      },
      {
        "id": "wrapperClasses",
        "type": "classes",
        "label": "Wrapper Classes",
        "tailwind": true,
        "default": "section-padding bg-surface"
      },
      {
        "id": "titleClasses",
        "type": "classes",
        "label": "Title Classes",
        "tailwind": true,
        "default": "heading-xl text-brand"
      }
    ]
  }
}
```

```php title="hero/index.php"
<section class="<?php echo $a['wrapperClasses']; ?>">
  <div class="content-width">
    <h1 class="<?php echo $a['titleClasses']; ?>">
      <?php echo esc_html($a['title']); ?>
    </h1>
  </div>
</section>
```

这会在前端渲染，所有 Tailwind 工具类和自定义主题颜色都会编译到一个内联的 `<style>` 标签中。

> **[构建区块库](https://blockstudio.dev/zh/guides/block-library/)**
>
> 面向生产主题的设计令牌、自定义工具类和完整 Tailwind v4 设置。
