Skip to content
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
20 changes: 20 additions & 0 deletions packages/core/__tests__/e2e/next-ssr.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,26 @@ import { test, expect } from "@playwright/test";

test.describe.configure({ mode: "serial" });

test("local fonts load without leaking Tailwind directives into their CSS", async ({ page }) => {
await page.goto("/test", { waitUntil: "networkidle" });
const stylesheetUrls = await page.locator('link[rel="stylesheet"]').evaluateAll((links) => links.map((link) => link.href));
let fontCss = "";
for (const url of stylesheetUrls) {
const response = await page.request.get(url);
expect(response.ok()).toBe(true);
const css = await response.text();
expect(/@(?:custom-variant|slot)\b/.test(css), `Uncompiled Tailwind directives in ${url}`).toBe(false);
if (css.includes("--font-test")) fontCss += css;
}
expect(fontCss).toContain("@font-face");
const loadedFontCount = await page.evaluate(async () => {
// Load the bundled font only; Next's Arial fallback may be absent on CI hosts.
const family = window.getComputedStyle(document.body).getPropertyValue("--font-test").split(",")[0].trim();
return (await document.fonts.load(`16px ${family}`)).length;
});
expect(loadedFontCount).toBeGreaterThan(0);
});

test.describe("Zero-UI Comprehensive Test Suite", () => {
test.beforeEach(async ({ page }) => {
await page.goto("/test", { waitUntil: "networkidle" });
Expand Down
93 changes: 93 additions & 0 deletions packages/core/__tests__/fixtures/next/app/fonts/OFL.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
Copyright 2024 The Geist Project Authors (https://github.com/vercel/geist-font)

This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org


-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).

"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).

"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.

"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.

PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:

1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.

2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.

3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.

4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.

5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.

TERMINATION
This license becomes null and void if any of the above conditions are
not met.

DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
4 changes: 4 additions & 0 deletions packages/core/__tests__/fixtures/next/app/fonts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
`geist-latin.woff2` is the Geist Latin font bundled with Next.js 15.5.18
(`next/dist/next-devtools/server/font/geist-latin.woff2`). It is used to exercise
`next/font/local` without network requests. Its SIL Open Font License is in
[OFL.txt](./OFL.txt); upstream: https://github.com/vercel/geist-font.
Binary file not shown.
10 changes: 9 additions & 1 deletion packages/core/__tests__/fixtures/next/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
import { bodyAttributes } from "@zero-ui/attributes";
import localFont from "next/font/local";
import "./globals.css";

import ZeroUiRuntime from "./zero-runtime";

const testFont = localFont({
src: "./fonts/geist-latin.woff2",
variable: "--font-test",
display: "swap",
style: "normal",
});

export default function RootLayout({ children }) {
return (
<html lang="en">
<body
{...bodyAttributes}
className="bg-red test-ww this is to test the body tag"
className={`${testFont.variable} bg-red test-ww this is to test the body tag`}
id="88">
<ZeroUiRuntime />
{children}
Expand Down
71 changes: 68 additions & 3 deletions packages/core/__tests__/unit/index.test.cjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const postcss = require("postcss");
const tailwindcss = require("@tailwindcss/postcss");
const { test } = require("node:test");
const assert = require("node:assert");
const fs = require("fs");
Expand Down Expand Up @@ -46,7 +47,7 @@ async function runTest(files, callback, cache = true) {
}

// Run PostCSS
const result = await postcss([plugin()]).process("", { from: undefined });
const result = await postcss([plugin()]).process("@tailwind utilities;", { from: undefined });

// Run assertions
await callback(result);
Expand Down Expand Up @@ -96,6 +97,70 @@ test("generates body attributes file correctly", async () => {
);
});

test("leaves non-Tailwind CSS unchanged, including generated local-font modules", async () => {
await runTest(
{
"app/test.jsx": `import { useUI } from '@react-zero-ui/core';
function Component() {
const [theme, setTheme] = useUI('theme', 'light');
return <div className="theme-light:block" />;
}`,
},
async () => {
const stylesheets = [
["empty.css", ""],
["plain.css", '/* @import "tailwindcss"; */ @media (width > 600px) { .label { color: red; } }'],
["plain.module.css", ".label { color: red; }"],
[
"testfont_123.module.css",
'@font-face { font-family: "testFont"; src: url("./test.woff2") format("woff2"); font-display: swap; }\n.variable { --font-test: "testFont"; }',
],
];
// A plain stylesheet still triggers attribute generation, even when it runs first.
fs.unlinkSync(getAttrFile());
for (const [filename, css] of stylesheets) {
const result = await postcss([plugin(), tailwindcss({ optimize: false })]).process(css, { from: path.resolve(filename) });
assert.strictEqual(result.css, css, `${filename} must not receive Tailwind-only directives`);
assert(result.messages.some((message) => message.type === "dependency" && message.file.endsWith("app/test.jsx")));
assert(fs.readFileSync(getAttrFile(), "utf8").includes('"data-theme": "light"'));
}
}
);
});

test("compiles Zero UI variants in Tailwind entrypoints and CSS modules", async () => {
await runTest(
{
"app/test.jsx": `import { useUI, useScopedUI } from '@react-zero-ui/core';
function Component() {
const [theme, setTheme] = useUI('theme', 'light');
setTheme('dark');
const [panel, setPanel] = useScopedUI('panel', 'closed');
setPanel('open');
return <div className="theme-light:block theme-dark:hidden panel-open:block panel-closed:hidden" />;
}`,
"base.css": "@tailwind utilities source(none);",
},
async () => {
const stylesheets = [
["globals.css", '@import "./base.css"; @source inline("theme-dark:hidden panel-open:block");'],
["utilities.css", '@tailwind utilities source(none); @source inline("theme-dark:hidden panel-open:block");'],
["reference.module.css", '@reference "./base.css"; .label { @apply theme-dark:hidden panel-open:block; }'],
["apply.module.css", ".label { @apply theme-dark:hidden panel-open:block; }"],
["variant.module.css", ".label { @variant theme-dark { display: none; } @variant panel-open { display: block; } }"],
];
for (const [filename, css] of stylesheets) {
const result = await postcss([plugin(), tailwindcss({ optimize: false })]).process(css, { from: path.resolve(filename) });
assert.match(result.css, /body\[data-theme=['"]dark['"]\]/, `${filename} must compile the global variant`);
assert.match(result.css, /\[data-panel=['"]open['"]\]/, `${filename} must compile the scoped variant`);
assert.match(result.css, /display: none/);
assert.match(result.css, /display: block/);
assert.doesNotMatch(result.css, /@(?:custom-variant|slot|apply|variant)\b/, `${filename} must not leak Tailwind directives`);
}
}
);
});

test("warns instead of auto-initializing when project setup is missing", async () => {
await runTest(
{
Expand Down Expand Up @@ -240,7 +305,7 @@ test("watches for file changes", async () => {
await new Promise((resolve) => setTimeout(resolve, 500));

// Re-process to check if watcher picked up changes
const result2 = await postcss([plugin()]).process("", { from: undefined });
const result2 = await postcss([plugin()]).process("@tailwind utilities;", { from: undefined });

assert(result2.css.includes("@custom-variant watch-test-updated"), "Should detect new state");
}
Expand Down Expand Up @@ -344,7 +409,7 @@ test("handles concurrent file modifications", async () => {
}

// Final processing should work correctly
const finalResult = await postcss([plugin()]).process("", { from: undefined });
const finalResult = await postcss([plugin()]).process("@tailwind utilities;", { from: undefined });

assert(finalResult.css.includes("AUTO-GENERATED"), "Should handle rapid changes");
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@react-zero-ui/core",
"version": "0.4.4",
"version": "0.4.5",
"private": false,
"scripts": {
"build": "rm -rf dist && tsc -p tsconfig.build.json",
Expand Down
54 changes: 53 additions & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,74 @@
import { useRef } from "react";
import { cssVar, makeSetter } from "./internal.js";

/** A value or an updater receiving the current DOM value, falling back to the hook's initial value. */
type UIAction<T extends string> = T | ((prev: T) => T);

type ScopedRef = ((node: HTMLElement | null) => void) & { current: HTMLElement | null };

/** Updates the element attached through `ref` without triggering React re-renders. */
interface ScopedSetterFn<T extends string = string> {
(action: UIAction<T>): void; // ← SINGLE source of truth
/** Writes a value or applies an updater to the current DOM value. The ref must be attached first. */
(action: UIAction<T>): void;
/**
* Attach to exactly one scope root. The setter updates this element's `data-*` attribute
* (or CSS variable); render the initial value on the same element.
*/
ref?: ScopedRef;
cssVar?: typeof cssVar;
}

/** Updates `<body>` without triggering React re-renders; updater functions read the current DOM value. */
type GlobalSetterFn<T extends string> = (action: UIAction<T>) => void;

/**
* Returns the supplied initial value and a setter that writes `data-{key}` on `<body>`.
* Updates do not trigger React re-renders; the first value does not track DOM changes.
* Zero UI's PostCSS plugin generates the `key-value:` Tailwind variants used in your source,
* so elements anywhere under `<body>` can respond through CSS. Render alternate states up front.
*
* @param key - Stable kebab-case key, resolvable at build time.
* @param initial - Static default for generated `bodyAttributes`; use the same default everywhere this key is declared.
* @param flag - Pass {@link cssVar} to write `--{key}` instead of a data attribute.
* @returns `[initial, setter]`. The setter accepts a value or an updater reading the current DOM value.
* @example
* ```tsx
* const [, setScrolled] = useUI<"true" | "false">("scrolled", "false");
* return (
* <button onClick={() => setScrolled("true")} className="scrolled-true:opacity-50">
* Mark scrolled
* </button>
* );
* ```
* @see https://zero-ui.dev/docs/api-reference#useuitkey-initial-flag
*/
function useUI<T extends string>(key: string, initial: T, flag?: typeof cssVar): [T, GlobalSetterFn<T>] {
return [initial, useRef(makeSetter(key, initial, () => document.body, flag)).current as GlobalSetterFn<T>];
}

/**
* Returns the supplied initial value and a setter that writes `data-{key}` on one element.
* Updates do not trigger React re-renders; the first value does not track DOM changes.
* Attach `setter.ref` to the scope root: the setter updates this element's attribute.
* Render the initial `data-{key}` on the same element. Zero UI's PostCSS plugin generates
* `key-value:` Tailwind variants used in your source for this element and its descendants.
*
* @param key - Stable kebab-case key, resolvable at build time. Each hook instance has its own target.
* @param initialValue - Static default; use the same default everywhere this key is declared.
* @param flag - Pass {@link cssVar} to write `--{key}` instead of a data attribute.
* @returns `[initialValue, setter]`. The setter accepts a value or an updater reading the current DOM value.
* @example
* ```tsx
* const [initial, setPanel] = useScopedUI<"open" | "closed">("panel", "closed");
* return (
* <section ref={setPanel.ref} data-panel={initial}>
* <button onClick={() => setPanel(prev => prev === "closed" ? "open" : "closed")}>Toggle</button>
* <div className="panel-closed:hidden panel-open:block">Details</div>
* </section>
* );
* ```
* @see https://zero-ui.dev/docs/api-reference#usescopeduitkey-initial-flag
*/
function useScopedUI<T extends string = string>(key: string, initialValue: T, flag?: typeof cssVar): [T, ScopedSetterFn<T>] {
// Create a ref to hold the DOM element that will receive the data-* attributes
// This allows scoping UI state to specific elements instead of always using document.body
Expand Down
7 changes: 7 additions & 0 deletions packages/core/src/internal.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
// src/internal.ts
import type { UIAction } from "./index.js";

/**
* Pass as the third argument to `useUI` or `useScopedUI` to update an inline CSS variable
* `--{key}` on the target element instead of a `data-*` attribute, without React re-renders.
* Supply the initial CSS value in styles or a `var()` fallback; the hook does not initialize it.
*
* @see https://zero-ui.dev/docs/api-reference#cssvar
*/
export const cssVar: unique symbol = Symbol("cssVar");

export function makeSetter<T extends string>(key: string, initialValue: T, getTarget: () => HTMLElement, flag?: typeof cssVar) {
Expand Down
23 changes: 20 additions & 3 deletions packages/core/src/postcss/index.cts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
/**
* @type {import('postcss').PluginCreator}
*/
type Root = { prepend: (css: string) => void };
type Root = {
prepend: (css: string) => void;
walkAtRules: (name: RegExp, callback: () => false | void) => void;
};
type Result = {
messages: { type: string; plugin: string; file: string; parent: string }[];
opts: { from: string };
Expand Down Expand Up @@ -50,6 +53,18 @@ function warnIfNotInitialized(result: Result, isZeroUiInitialized: RuntimeModule
result.warn("[Zero-UI] Zero UI is not initialized. Run `react-zero-ui` to patch your project config.", { plugin: zeroUIPlugin });
}

function usesTailwind(root: Root): boolean {
// Match @tailwindcss/postcss's early-bail directives. @custom-variant alone
// does not trigger compilation, so injecting it into plain CSS (including
// next/font's generated modules) leaks @custom-variant and @slot to the bundler.
let found = false;
root.walkAtRules(/^(import|reference|theme|variant|config|plugin|apply|tailwind)$/, () => {
found = true;
return false;
});
return found;
}

const plugin = () => {
return {
postcssPlugin: zeroUIPlugin,
Expand All @@ -58,8 +73,10 @@ const plugin = () => {
const { buildCss, generateAttributesFile, isZeroUiInitialized, processVariants, formatError, registerDeps } = await loadRuntimeModules();
const { finalVariants, initialGlobalValues, sourceFiles } = await processVariants();

const cssBlock = buildCss(finalVariants);
if (cssBlock?.trim()) root.prepend(cssBlock + "\n");
if (usesTailwind(root)) {
const cssBlock = buildCss(finalVariants);
if (cssBlock?.trim()) root.prepend(cssBlock + "\n");
}

/* ── register file-dependencies for HMR ─────────────────── */
registerDeps(result, zeroUIPlugin, sourceFiles, result.opts.from ?? "");
Expand Down
Loading
Loading