Extract class name composition logic

This commit is contained in:
Alex 2025-03-04 04:01:55 -05:00
parent 52b19b3b36
commit bd683df539
14 changed files with 933 additions and 1182 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "@aet/tailwind", "name": "@aet/tailwind",
"version": "1.0.31", "version": "1.0.32",
"license": "MIT", "license": "MIT",
"type": "module", "type": "module",
"scripts": { "scripts": {
@ -14,7 +14,7 @@
"exports": { "exports": {
".": "./dist/index.js", ".": "./dist/index.js",
"./package.json": "./package.json", "./package.json": "./package.json",
"./classed": "./dist/classed.js", "./utils": "./dist/utils.js",
"./css-to-js": "./dist/css-to-js.js", "./css-to-js": "./dist/css-to-js.js",
"./base": { "./base": {
"types": "./dist/base.d.ts" "types": "./dist/base.d.ts"
@ -36,14 +36,14 @@
} }
}, },
"devDependencies": { "devDependencies": {
"@aet/eslint-rules": "^2.0.36", "@aet/eslint-rules": "^2.0.42",
"@types/babel__core": "^7.20.5", "@types/babel__core": "^7.20.5",
"@types/bun": "^1.2.2", "@types/bun": "^1.2.4",
"@types/dedent": "^0.7.2", "@types/dedent": "^0.7.2",
"@types/lodash-es": "^4.17.12", "@types/lodash-es": "^4.17.12",
"@types/node": "^22.13.1", "@types/node": "^22.13.9",
"@types/postcss-safe-parser": "^5.0.4", "@types/postcss-safe-parser": "^5.0.4",
"@types/react": "^19.0.8", "@types/react": "^19.0.10",
"@types/stylis": "^4.2.7", "@types/stylis": "^4.2.7",
"@vitejs/plugin-react": "^4.3.4", "@vitejs/plugin-react": "^4.3.4",
"cli-highlight": "^2.1.11", "cli-highlight": "^2.1.11",
@ -52,31 +52,32 @@
"css-what": "^6.1.0", "css-what": "^6.1.0",
"dedent": "^1.5.3", "dedent": "^1.5.3",
"esbuild-register": "^3.6.0", "esbuild-register": "^3.6.0",
"eslint": "^9.20.0", "eslint": "^9.21.0",
"nolyfill": "^1.0.43", "nolyfill": "^1.0.43",
"postcss-nested": "^7.0.2", "postcss-nested": "^7.0.2",
"prettier": "^3.4.2", "prettier": "^3.5.3",
"tailwindcss": "^3.4.17", "tailwindcss": "^3.4.17",
"tslib": "^2.8.1", "tslib": "^2.8.1",
"tsup": "^8.3.6", "tsup": "^8.4.0",
"typescript": "^5.7.3", "typescript": "^5.8.2",
"vite": "^6.1.0", "vite": "^6.2.0",
"vitest": "^3.0.5" "vitest": "^3.0.7"
}, },
"peerDependencies": { "peerDependencies": {
"tailwindcss": "^3.4.17" "tailwindcss": "^3.4.17"
}, },
"dependencies": { "dependencies": {
"@babel/core": "^7.26.8", "@babel/core": "^7.26.9",
"@emotion/hash": "^0.9.2", "@emotion/hash": "^0.9.2",
"clsx": "^2.1.1",
"esbuild": "^0.25.0", "esbuild": "^0.25.0",
"json5": "^2.2.3", "json5": "^2.2.3",
"lodash-es": "^4.17.21", "lodash-es": "^4.17.21",
"postcss": "^8.5.1", "postcss": "^8.5.3",
"postcss-selector-parser": "^7.1.0", "postcss-selector-parser": "^7.1.0",
"stylis": "^4.3.6", "stylis": "^4.3.6",
"tiny-invariant": "^1.3.3", "tiny-invariant": "^1.3.3",
"type-fest": "^4.33.0" "type-fest": "^4.37.0"
}, },
"prettier": { "prettier": {
"arrowParens": "avoid", "arrowParens": "avoid",

1922
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
#!/usr/bin/env bun #!/usr/bin/env tsx
import { promises as fs } from "node:fs"; import { promises as fs } from "node:fs";
import { build, defineConfig } from "tsup"; import { build, defineConfig } from "tsup";
@ -23,7 +23,7 @@ const tsupConfig = defineConfig({
await build({ await build({
...tsupConfig, ...tsupConfig,
entry: ["src/classed.tsx", "src/css-to-js.ts"], entry: ["src/utils.tsx", "src/css-to-js.ts"],
outDir: "dist", outDir: "dist",
external: ["react", "react/jsx-runtime", "clsx"], external: ["react", "react/jsx-runtime", "clsx"],
clean: true, clean: true,
@ -32,7 +32,7 @@ await build({
await Promise.all([ await Promise.all([
build({ build({
...tsupConfig, ...tsupConfig,
entry: ["src/classed.tsx", "src/css-to-js.ts"], entry: ["src/utils.tsx", "src/css-to-js.ts"],
outDir: "dist", outDir: "dist",
external: ["react", "react/jsx-runtime", "clsx"], external: ["react", "react/jsx-runtime", "clsx"],
}), }),
@ -63,7 +63,10 @@ await Promise.all([
fs.copyFile("LICENSE.md", "dist/LICENSE.md"), fs.copyFile("LICENSE.md", "dist/LICENSE.md"),
fs.copyFile("src/macro.d.ts", "dist/macro.d.ts"), fs.copyFile("src/macro.d.ts", "dist/macro.d.ts"),
fs.copyFile("src/react-env.d.ts", "dist/react-env.d.ts"), fs.copyFile("src/react-env.d.ts", "dist/react-env.d.ts"),
Bun.write(`dist/base.d.ts`, `/**\n * \`@tailwind base\` component.\n */\nexport {};`), fs.writeFile(
`dist/base.d.ts`,
`/**\n * \`@tailwind base\` component.\n */\nexport {};`
),
]); ]);
process.exit(0); process.exit(0);

View File

@ -41,7 +41,7 @@ exports[`babel-tailwind > supports grouped tw 2`] = `
`; `;
exports[`babel-tailwind > supports styled components usage 1`] = ` exports[`babel-tailwind > supports styled components usage 1`] = `
"import { classed as _classed } from "@aet/tailwind/classed"; "import { classed as _classed } from "@aet/tailwind/utils";
var Div = _classed("div", "tw-gqn2k6");" var Div = _classed("div", "tw-gqn2k6");"
`; `;

View File

@ -5,7 +5,7 @@ import { getBuild, matchSnapshot } from "./utils";
describe("emit", () => { describe("emit", () => {
const compileESBuild = getBuild("emit"); const compileESBuild = getBuild("emit");
it("supports emitting as CSS module", async () => { it.only("supports emitting as CSS module", async () => {
const { files } = await compileESBuild({ const { files } = await compileESBuild({
clsx: "emotion", clsx: "emotion",
expectFiles: 2, expectFiles: 2,

View File

@ -68,7 +68,7 @@ describe("merges with existing className attribute", () => {
const clsName = getClassName("text-center"); const clsName = getClassName("text-center");
expect(files.js.text).toContain( expect(files.js.text).toContain(
`{ ...props, className: typeof _className === "function" ? (...args) => _cx("${clsName}", _className(...args)) : _cx("${clsName}", _className),` `{ ...props, className: _composeClassName("${clsName}", _className),`
); );
}); });
@ -90,7 +90,7 @@ describe("merges with existing className attribute", () => {
const clsName = getClassName("text-center"); const clsName = getClassName("text-center");
expect(files.js.text).toContain( expect(files.js.text).toContain(
`{ className: typeof className === "function" ? (...args) => _cx("${clsName}", className(...args)) : _cx("${clsName}", className),` `{ className: _composeClassName("${clsName}", className),`
); );
}); });

View File

@ -56,7 +56,7 @@ export function getBuild(name: string) {
"@emotion/css", "@emotion/css",
"clsx", "clsx",
"tslib", "tslib",
"@aet/tailwind/classed", "@aet/tailwind/utils",
], ],
outdir: "dist", outdir: "dist",
format: "esm", format: "esm",

View File

@ -1,12 +1,13 @@
import { basename, dirname, extname, join } from "node:path"; import { basename, dirname, extname, join } from "node:path";
import type b from "@babel/core"; import type b from "@babel/core";
import { type NodePath, type types as t } from "@babel/core"; import { type Node, type NodePath, type types as t } from "@babel/core";
import hash from "@emotion/hash"; import hash from "@emotion/hash";
import { memoize } from "lodash-es";
import invariant from "tiny-invariant"; import invariant from "tiny-invariant";
import { type ResolveTailwindOptions, getClassName } from "../index"; import { type ResolveTailwindOptions, getClassName } from "../index";
import { type SourceLocation, type StyleMapEntry, classedName } from "../shared"; import { type SourceLocation, type StyleMapEntry, utilsName } from "../shared";
import { handleMacro } from "./macro"; import { handleMacro } from "./macro";
import { evaluateArgs, trim } from "./utils"; import { evaluateArgs, trim } from "./utils";
@ -49,10 +50,6 @@ function getUtils({
} = options; } = options;
let cx: t.Identifier; let cx: t.Identifier;
let tslibImport: t.Identifier;
let styleImport: t.Identifier;
let classedImport: t.Identifier;
let cssModuleImport: t.Identifier;
const cssMap = new Map<string, StyleMapEntry>(); const cssMap = new Map<string, StyleMapEntry>();
const jsMap = new Map<string, StyleMapEntry>(); const jsMap = new Map<string, StyleMapEntry>();
@ -87,18 +84,6 @@ function getUtils({
break; break;
} }
function getStyleImport() {
styleImport ??= path.scope.generateUidIdentifier("styles");
return t.cloneNode(styleImport);
}
const getCssModuleImport = () => {
if (cssModuleImport == null) {
cssModuleImport = path.scope.generateUidIdentifier("cssModule");
}
return t.cloneNode(cssModuleImport);
};
function reuseImport(scope: Scope) { function reuseImport(scope: Scope) {
if ( if (
existingCx && existingCx &&
@ -108,6 +93,32 @@ function getUtils({
} }
} }
function cacheNode<N extends Node>(fn: () => N) {
let cache: N | undefined;
return Object.assign(
(): N => {
cache ??= fn();
return t.cloneNode(cache);
},
{
getCache() {
return cache;
},
}
);
}
const getStyleImport = cacheNode(() => path.scope.generateUidIdentifier("styles"));
const getCssModuleImport = cacheNode(() =>
path.scope.generateUidIdentifier("cssModule")
);
const getUtilsImport = memoize(() => {
const importDecl = t.importDeclaration([], t.stringLiteral(utilsName));
path.node.body.unshift(importDecl);
return importDecl;
});
return { return {
program: path, program: path,
existingCx, existingCx,
@ -163,31 +174,32 @@ function getUtils({
return t.cloneNode(cx); return t.cloneNode(cx);
}, },
getTSlibImport: () => { getTSlibImport: cacheNode(() => {
if (tslibImport == null) { const tslibImport = path.scope.generateUidIdentifier("tslib");
tslibImport = path.scope.generateUidIdentifier("tslib"); path.node.body.unshift(
path.node.body.unshift( t.importDeclaration(
t.importDeclaration( [t.importNamespaceSpecifier(tslibImport)],
[t.importNamespaceSpecifier(tslibImport)], t.stringLiteral("tslib")
t.stringLiteral("tslib") )
) );
); return tslibImport;
} }),
return t.cloneNode(tslibImport);
},
getClassedImport: () => { getClsCompose: cacheNode(() => {
if (classedImport == null) { const clsComposeImport = path.scope.generateUidIdentifier("composeClassName");
classedImport = path.scope.generateUidIdentifier("classed"); getUtilsImport().specifiers.push(
path.node.body.unshift( t.importSpecifier(clsComposeImport, t.identifier("composeClassName"))
t.importDeclaration( );
[t.importSpecifier(classedImport, t.identifier("classed"))], return clsComposeImport;
t.stringLiteral(classedName) }),
)
); getClassedImport: cacheNode(() => {
} const classedImport = path.scope.generateUidIdentifier("classed");
return t.cloneNode(classedImport); getUtilsImport().specifiers.push(
}, t.importSpecifier(classedImport, t.identifier("classed"))
);
return classedImport;
}),
getCssModuleImport, getCssModuleImport,
@ -207,6 +219,7 @@ function getUtils({
if (!cssMap.size && !jsMap.size) return; if (!cssMap.size && !jsMap.size) return;
invariant(filename, "babel: missing state.filename"); invariant(filename, "babel: missing state.filename");
const cssModuleImport = getCssModuleImport.getCache();
if (cssMap.size) { if (cssMap.size) {
const cssName = const cssName =
basename(filename, extname(filename)) + basename(filename, extname(filename)) +
@ -338,9 +351,6 @@ export function babelTailwind(
}, },
})); }));
const $eq = (left: t.Expression, right: t.Expression) =>
t.binaryExpression("===", left, right);
const $typeof = (expr: t.Expression) => t.unaryExpression("typeof", expr);
const { const {
identifier: id, identifier: id,
jsxExpressionContainer: jsxBox, jsxExpressionContainer: jsxBox,
@ -359,26 +369,10 @@ export function babelTailwind(
); );
} }
const wrap = (existing: b.types.Expression) => { const wrap = (existing: b.types.Expression) =>
const callExp = call(_.getCx(path.scope), [valuePathNode, existing]); composeRenderProps
? call(_.getClsCompose(), [valuePathNode, existing])
return composeRenderProps : call(_.getCx(path.scope), [valuePathNode, existing]);
? // typeof className === "function"
// ? (...args) => clsx("${clsName}", className(...args))
// : clsx("${clsName}", className)
t.conditionalExpression(
$eq($typeof(existing), t.stringLiteral("function")),
t.arrowFunctionExpression(
[t.restElement(id("args"))],
call(_.getCx(path.scope), [
valuePathNode,
call(existing, [t.spreadElement(id("args"))]),
])
),
/* else */ callExp
)
: callExp;
};
// There is an existing className attribute // There is an existing className attribute
if (classNameAttribute) { if (classNameAttribute) {

View File

@ -1,6 +1,6 @@
import type { NodePath } from "@babel/core";
import { isPlainObject } from "lodash-es"; import { isPlainObject } from "lodash-es";
import invariant from "tiny-invariant"; import invariant from "tiny-invariant";
import { type NodePath } from "@babel/core";
export function evaluateArgs(path: NodePath) { export function evaluateArgs(path: NodePath) {
const { confident, value } = path.evaluate(); const { confident, value } = path.evaluate();

View File

@ -151,7 +151,7 @@ export function getTailwindPlugins(options: TailwindPluginOptions) {
const compiled = await compile( const compiled = await compile(
styles styles
.map(({ classNames, key }) => { .map(({ classNames, key }) => {
const tw = without(classNames, "group").join(" "); const tw = without(classNames, "group", "peer").join(" ");
return [ return [
`.${key} {`, `.${key} {`,
addSourceAsComment && ` /* @preserve ${tw} */`, addSourceAsComment && ` /* @preserve ${tw} */`,

View File

@ -6,7 +6,7 @@ declare const __PKG_NAME__: string;
export const pkgName = __PKG_NAME__; export const pkgName = __PKG_NAME__;
export const macroNames = [`${pkgName}/macro`, `${pkgName}`]; export const macroNames = [`${pkgName}/macro`, `${pkgName}`];
export const classedName = `${pkgName}/classed`; export const utilsName = `${pkgName}/utils`;
interface LineColumn { interface LineColumn {
line: number; line: number;

View File

@ -7,7 +7,7 @@ declare const __PKG_NAME__: string;
export const pkgName = __PKG_NAME__; export const pkgName = __PKG_NAME__;
export const macroNames = [`${pkgName}/macro`, `${pkgName}`]; export const macroNames = [`${pkgName}/macro`, `${pkgName}`];
export const classedName = `${pkgName}/classed`; export const utilsName = `${pkgName}/utils`;
interface LineColumn { interface LineColumn {
line: number; line: number;

View File

@ -67,3 +67,10 @@ export const classed: {
component.className = className; component.className = className;
return component; return component;
}; };
export function composeClassName<T>(
value: string,
prop: string | ((values: T) => string) | undefined
) {
return typeof prop === "function" ? (arg: T) => cx(value, prop(arg)) : cx(value, prop);
}

View File

@ -62,4 +62,4 @@ export const vitePlugin = ({
* `babel-plugin-macros` compatible `isMacrosName` function that works with this plugin. * `babel-plugin-macros` compatible `isMacrosName` function that works with this plugin.
*/ */
export const isMacrosName = (v: string) => export const isMacrosName = (v: string) =>
!macroNames.includes(v) && /[./]macro(\.c?js)?$/.test(v); !macroNames.includes(v) && /[./]macro(?:\.c?js)?$/.test(v);