
# 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 활성화하기

`blockstudio.json`에 `tailwind` 구성을 추가합니다:

```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가 자동으로 컴파일되어 삽입됩니다. 블록 템플릿, 테마 템플릿, `the_content` 필터, 페이지 출력에 나타나는 모든 HTML에서 Tailwind 유틸리티 클래스를 사용할 수 있습니다.

### 프런트엔드 출력

컴파일된 CSS은 기본적으로 인라인으로 삽입되어 이전 버전에서 사용된 출력을 유지합니다. 공유 규칙이 많은 사이트는 대신 콘텐츠 해시 스타일시트를 사용할 수 있습니다:

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

`"output": "link"`은 기존 `tailwind/{content-hash}.css` 캐시 파일을 `<link rel="stylesheet">`로 제공합니다. 런타임 ID, 후보, 엔진 또는 CSS 입력이 바뀌면 URL도 바뀌므로 브라우저와 엣지 캐시는 이전 URL을 안전하게 유지할 수 있습니다. 이 캐시 범위에 장기간 유효한 `Cache-Control: public, immutable` 헤더를 보내도록 웹 서버나 CDN를 구성하세요.

기본 캐시 루트는 `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은 같은 번들 TailwindPHP 엔진을 PHP 템플릿에서도 사용할 수 있게 합니다. 테마 측 사본이나 대체 구현은 필요하지 않습니다:

```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()`는 기본값, 변형, 기본 변형, 복합 변형, `class` 및 `className`를 지원하는 CVA 스타일 호출 가능 함수를 반환합니다.

## 구성

Tailwind v4는 CSS 우선 구성 방식을 사용합니다. JavaScript 설정 파일을 사용하는 대신 `@theme` 지시문을 사용해 구성을 CSS로 직접 작성합니다.

```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;
});
```

### 사용자 지정 유틸리티 클래스

재사용 가능한 클래스 별칭을 정의하려면 구성 문자열에서 Tailwind의 `@apply` 지시문과 함께 `@layer utilities`를 직접 사용합니다:

```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` | 불리언 | `false` | 프런트엔드에서 Tailwind CSS 컴파일 사용 |
| `config` | 문자열 | `""` | 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를 해시하는 대신(논스, 타임스탬프 및 기타 동적 콘텐츠 때문에 요청할 때마다 캐시가 무효화됨) Blockstudio는 HTML에서 CSS 클래스 후보만 추출합니다. 이 후보를 정렬한 뒤 CSS 구성과 함께 해시해 안정적인 캐시 키를 만듭니다.

따라서 다음과 같은 결과가 생깁니다:

- 동일한 Tailwind 클래스 집합을 사용하는 두 페이지는 HTML가 완전히 달라도 동일한 캐시 CSS 파일을 공유합니다
- 논스, 로그인 사용자 표시줄, 댓글 수, 타임스탬프와 같은 동적 콘텐츠는 캐시를 무효화하지 않습니다
- 페이지의 CSS 클래스 집합이 바뀌거나 Tailwind 구성이 변경될 때만 캐시가 무효화됩니다

런타임에서 [논리적 검색 소스](https://blockstudio.dev/ko/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` 필터, 위젯 영역 등 모든 소스의 클래스를 검색할 수 있습니다.

컴파일 필터는 `blockstudio/buffer/output` 훅에서 우선순위 `999999`로 실행되어 다른 모든 수정이 끝난 뒤 최종 HTML를 처리합니다. 버퍼는 `template_redirect` 작업에서 시작하므로 프런트엔드 요청에서만 실행되며 관리자 화면, REST API 또는 AJAX 컨텍스트에서는 실행되지 않습니다.

전체 문서를 버퍼링해야 이 기능을 사용할 수 있으므로 기본적으로 활성화되어 있습니다. Tailwind와 블록 에셋을 모두 사용하지 않는 사이트에서는 이 기능을 끌 수 있습니다:

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

`false`를 반환하면 버퍼를 완전히 건너뛰며, Tailwind 컴파일과 블록 스타일 및 스크립트를 헤드와 푸터로 이동하는 기능도 비활성화됩니다.

## 아키텍처

```
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/ko/guides/block-library/)**
>
> 프로덕션 테마에 사용할 디자인 토큰, 사용자 지정 유틸리티, 완전한 Tailwind v4 설정.
