This commit is contained in:
Alex
2025-01-24 01:29:15 -05:00
parent 5a3b03b69b
commit 4db894d061
27 changed files with 1985 additions and 2063 deletions

View File

@ -6,4 +6,6 @@ Compile-run Tailwind compiler.
export function App() {
return <div css="flex m-0"></div>;
}
const Container = tw.div`flex m-0`;
```

View File

@ -1,7 +1,7 @@
// @ts-check
const { extendConfig } = require("@aet/eslint-rules");
import { extendConfig } from "@aet/eslint-rules";
module.exports = extendConfig({
export default await extendConfig({
rules: {
"class-methods-use-this": "error",
"import-x/no-unresolved": ["error", { ignore: ["react"] }],

View File

@ -1,7 +1,8 @@
{
"name": "@aet/tailwind",
"version": "1.0.10",
"version": "1.0.19",
"license": "MIT",
"type": "module",
"scripts": {
"build": "./scripts/index.ts",
"test": "vitest",
@ -13,7 +14,11 @@
"exports": {
".": "./dist/index.js",
"./package.json": "./package.json",
"./classed": "./dist/classed.mjs",
"./classed": "./dist/classed.js",
"./css-to-js": "./dist/css-to-js.js",
"./base": {
"types": "./dist/base.d.ts"
},
"./µ": {
"types": "./dist/macro.d.ts"
},
@ -28,46 +33,46 @@
}
},
"devDependencies": {
"@aet/eslint-rules": "1.0.1-beta.24",
"@aet/eslint-rules": "2.0.29",
"@types/babel__core": "^7.20.5",
"@types/bun": "^1.1.6",
"@types/bun": "^1.2.0",
"@types/dedent": "^0.7.2",
"@types/lodash": "^4.17.7",
"@types/node": "^22.4.0",
"@types/lodash-es": "^4.17.12",
"@types/node": "^22.10.10",
"@types/postcss-safe-parser": "^5.0.4",
"@types/react": "^18.3.3",
"@types/stylis": "^4.2.6",
"@types/react": "^19.0.8",
"@types/stylis": "^4.2.7",
"cli-highlight": "^2.1.11",
"clsx": "^2.1.1",
"colord": "^2.9.3",
"css-what": "^6.1.0",
"dedent": "^1.5.3",
"esbuild-register": "^3.6.0",
"eslint": "^8.57.0",
"nolyfill": "^1.0.39",
"postcss-nested": "^6.2.0",
"prettier": "^3.3.3",
"tailwindcss": "^3.4.10",
"tslib": "^2.6.3",
"tsup": "^8.2.4",
"typescript": "^5.5.4",
"vite": "^5.4.1",
"vitest": "^2.0.5"
"eslint": "^9.18.0",
"nolyfill": "^1.0.43",
"postcss-nested": "^7.0.2",
"prettier": "^3.4.2",
"tailwindcss": "^3.4.17",
"tslib": "^2.8.1",
"tsup": "^8.3.5",
"typescript": "^5.7.3",
"vite": "^6.0.11",
"vitest": "^3.0.4"
},
"peerDependencies": {
"tailwindcss": "^3.4.3"
"tailwindcss": "^3.4.17"
},
"dependencies": {
"@babel/core": "^7.25.2",
"@babel/core": "^7.26.0",
"@emotion/hash": "^0.9.2",
"esbuild": "^0.23.1",
"esbuild": "^0.24.2",
"json5": "^2.2.3",
"lodash": "^4.17.21",
"postcss": "^8.4.41",
"postcss-selector-parser": "^6.1.2",
"stylis": "^4.3.2",
"lodash-es": "^4.17.21",
"postcss": "^8.5.1",
"postcss-selector-parser": "^7.0.0",
"stylis": "^4.3.5",
"tiny-invariant": "^1.3.3",
"type-fest": "^4.25.0"
"type-fest": "^4.33.0"
},
"prettier": {
"arrowParens": "avoid",

3581
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,9 @@
#!/usr/bin/env bun
import { promises as fs } from "node:fs";
import { pick } from "lodash-es";
import { build, defineConfig } from "tsup";
import { pick } from "lodash";
import pkg from "../package.json" with { type: "json" };
const tsupConfig = defineConfig({
@ -11,19 +13,29 @@ const tsupConfig = defineConfig({
dts: true,
treeshake: true,
platform: "node",
format: "esm",
banner: {
js: "/* eslint-disable */",
},
define: {
__PKG_NAME__: JSON.stringify(pkg.name),
},
});
await build({
...tsupConfig,
entry: ["src/classed.tsx", "src/css-to-js.ts"],
outDir: "dist",
external: ["react", "react/jsx-runtime", "clsx"],
clean: true,
});
await Promise.all([
build({
...tsupConfig,
entry: ["src/classed.tsx"],
entry: ["src/classed.tsx", "src/css-to-js.ts"],
outDir: "dist",
external: ["react", "react/jsx-runtime", "clsx"],
format: "esm",
clean: true,
}),
build({
...tsupConfig,
@ -48,10 +60,18 @@ await Promise.all([
Bun.write(
"dist/package.json",
JSON.stringify(
pick(pkg, ["name", "version", "license", "dependencies", "author"]),
pick(pkg, [
"name",
"version",
"type",
"license",
"dependencies",
"author",
"exports",
]),
null,
2
)
).replaceAll("./dist/", "./")
),
]);

67
scripts/update-tags.ts Executable file
View File

@ -0,0 +1,67 @@
#!/usr/bin/env bun
import fs from "node:fs";
const supportedTags = [
"a",
"abbr",
"article",
"blockquote",
"button",
"cite",
"code",
"details",
"div",
"figure",
"footer",
"h1",
"h2",
"h3",
"h4",
"hr",
"iframe",
"img",
"input",
"ins",
"label",
"li",
"main",
"nav",
"ol",
"output",
"p",
"pre",
"rt",
"ruby",
"section",
"select",
"span",
"strong",
"sub",
"summary",
"sup",
"table",
"tbody",
"td",
"thead",
"tr",
"ul",
"var",
"video",
].sort();
function replaceFile(file: string, search: string | RegExp, replace: string) {
const content = fs.readFileSync(file, "utf-8");
fs.writeFileSync(file, content.replace(search, replace));
}
replaceFile(
"src/macro.d.ts",
/export type SupportedTag =(\n\s+\| "\w+")+;/,
`export type SupportedTag =\n | "${supportedTags.join('"\n | "')}";`
);
replaceFile(
"src/babel/macro.ts",
/const supportedTags = new Set<SupportedTag>\(\[(\n\s+"\w+",)+\n]\);/,
`const supportedTags = new Set<SupportedTag>([\n "${supportedTags.join('",\n "')}",\n]);`
);

View File

@ -39,3 +39,14 @@ exports[`babel-tailwind > supports grouped tw 2`] = `
font-weight: 600;
}"
`;
exports[`babel-tailwind > supports styled components usage 1`] = `
"import { classed as _classed } from "@aet/tailwind/classed";
var Div = _classed("div", "tw-gqn2k6");"
`;
exports[`babel-tailwind > supports styled components usage 2`] = `
".tw-gqn2k6 {
text-align: center;
}"
`;

View File

@ -40,4 +40,20 @@ describe("babel-tailwind", () => {
matchSnapshot(files);
});
it("supports styled components usage", async () => {
const { files } = await compileESBuild({
clsx: "emotion",
expectFiles: 2,
javascript: `
import {tw} from "@aet/tailwind/macro";
const Div = tw.div\`
text-center
\`;
`,
});
matchSnapshot(files);
});
});

View File

@ -47,7 +47,14 @@ export function getBuild(name: string) {
const result = await esbuild.build({
bundle: true,
write: false,
external: ["react/jsx-runtime", "@emotion/css", "clsx", "tslib"],
external: [
"react",
"react/jsx-runtime",
"@emotion/css",
"clsx",
"tslib",
"@aet/tailwind/classed",
],
outdir: "dist",
format: "esm",
entryPoints: [await write("index.tsx", dedent(javascript))],

View File

@ -1,10 +1,13 @@
import { basename, dirname, extname, join } from "node:path";
import type b from "@babel/core";
import { type NodePath, type types as t } from "@babel/core";
import hash from "@emotion/hash";
import invariant from "tiny-invariant";
import { type NodePath, type types as t } from "@babel/core";
import { type SourceLocation, type StyleMapEntry } from "../shared";
import { type ResolveTailwindOptions, getClassName } from "../index";
import { type SourceLocation, type StyleMapEntry, classedName } from "../shared";
import { handleMacro } from "./macro";
import { evaluateArgs, trim } from "./utils";
@ -37,6 +40,7 @@ function getUtils({
let cx: t.Identifier;
let tslibImport: t.Identifier;
let styleImport: t.Identifier;
let classedImport: t.Identifier;
const cssMap = new Map<string, StyleMapEntry>();
const jsMap = new Map<string, StyleMapEntry>();
@ -108,6 +112,19 @@ function getUtils({
return t.cloneNode(tslibImport);
},
getClassedImport: () => {
if (classedImport == null) {
classedImport = path.scope.generateUidIdentifier("classed");
path.node.body.unshift(
t.importDeclaration(
[t.importSpecifier(classedImport, t.identifier("classed"))],
t.stringLiteral(classedName)
)
);
}
return t.cloneNode(classedImport);
},
finish(node: t.Program) {
const { filename } = state;
if (!cssMap.size && !jsMap.size) return;
@ -159,7 +176,6 @@ export function babelTailwind(
enter(path, state) {
const _ = getUtils({ path, state, t, options, onCollect });
Object.assign(state, _);
handleMacro({ t, path, _ });
},

View File

@ -1,10 +1,14 @@
import type b from "@babel/core";
import invariant from "tiny-invariant";
import { type NodePath, type types as t } from "@babel/core";
import invariant from "tiny-invariant";
import type { SupportedTag } from "../macro";
import { macroNames } from "../shared";
import type { BabelPluginUtils } from "./index";
import { evaluateArgs, trimPrefix } from "./utils";
import type { BabelPluginUtils } from "./index";
type BabelTypes = typeof b.types;
export function handleMacro({
@ -16,9 +20,9 @@ export function handleMacro({
path: NodePath<t.Program>;
_: BabelPluginUtils;
}) {
for (const { callee, imported, prefix } of getMacros(t, path, macroNames).map(macro =>
mapMacro(t, macro)
)) {
const macros = getMacros(t, path, macroNames).map(macro => mapMacro(t, macro));
for (const { callee, imported, prefix } of macros) {
const type = imported === "tw" ? "css" : imported === "tws" ? "js" : undefined;
if (!type) continue;
@ -30,18 +34,34 @@ export function handleMacro({
const value = quasi.quasis[0].value.cooked;
if (value) {
const list = trimPrefix(value, prefix ? prefix + ":" : undefined);
const className = _.getClass(type, list.join(" "));
_.recordIfAbsent(type, {
key: className,
classNames: list,
location: _.sliceText(node),
});
_.replaceWithImport({
type,
path: callee,
className: addIf(className, list.includes("group") && " group"),
});
if (prefix && supportedTags.has(prefix as SupportedTag) && type === "css") {
const list = trimPrefix(value);
const className = _.getClass(type, list.join(" "));
_.recordIfAbsent(type, {
key: className,
classNames: list,
location: _.sliceText(node),
});
callee.replaceWith(
t.callExpression(_.getClassedImport(), [
t.stringLiteral(prefix),
t.stringLiteral(className),
])
);
} else {
const list = trimPrefix(value, prefix ? prefix + ":" : undefined);
const className = _.getClass(type, list.join(" "));
_.recordIfAbsent(type, {
key: className,
classNames: list,
location: _.sliceText(node),
});
_.replaceWithImport({
type,
path: callee,
className: addIf(className, list.includes("group") && " group"),
});
}
}
} else if (isNodePath(callee, t.isCallExpression)) {
const { node } = callee;
@ -140,3 +160,51 @@ const isNodePath = <T extends t.Node>(
nodePath: NodePath<t.Node | null | undefined> | null,
predicate: (node: t.Node) => node is T
): nodePath is NodePath<T> => Boolean(nodePath?.node && predicate(nodePath.node));
const supportedTags = new Set<SupportedTag>([
"a",
"abbr",
"article",
"blockquote",
"button",
"cite",
"code",
"details",
"div",
"figure",
"footer",
"h1",
"h2",
"h3",
"h4",
"hr",
"iframe",
"img",
"input",
"ins",
"label",
"li",
"main",
"nav",
"ol",
"output",
"p",
"pre",
"rt",
"ruby",
"section",
"select",
"span",
"strong",
"sub",
"summary",
"sup",
"table",
"tbody",
"td",
"thead",
"tr",
"ul",
"var",
"video",
]);

View File

@ -1,12 +1,6 @@
import { basename, dirname, extname, join } from "node:path";
import type b from "@babel/core";
import hash from "@emotion/hash";
import { isPlainObject } from "lodash";
import { isPlainObject } from "lodash-es";
import invariant from "tiny-invariant";
import { type NodePath, type types as t } from "@babel/core";
import { type SourceLocation, type StyleMapEntry } from "../shared";
import { type ResolveTailwindOptions, getClassName } from "../index";
import { handleMacro } from "./macro";
import { type NodePath } from "@babel/core";
export function evaluateArgs(path: NodePath) {
const { confident, value } = path.evaluate();

View File

@ -23,11 +23,11 @@ export const classed: {
className: PresetClassName<InputProps>,
defaultProps?: Partial<InputProps>
): React.FunctionComponent<InputProps>;
<K extends keyof JSX.IntrinsicElements>(
<K extends keyof React.JSX.IntrinsicElements>(
type: K,
className: PresetClassName<JSX.IntrinsicElements[K]>,
defaultProps?: Partial<JSX.IntrinsicElements[K]>
): React.FunctionComponent<JSX.IntrinsicElements[K]>;
className: PresetClassName<React.JSX.IntrinsicElements[K]>,
defaultProps?: Partial<React.JSX.IntrinsicElements[K]>
): React.FunctionComponent<React.JSX.IntrinsicElements[K]>;
(
type: string,
className: PresetClassName,

View File

@ -1,5 +1,7 @@
// MIT License. Copyright (c) 2017 Brice BERNARD
// https://github.com/brikou/CSS-in-JS-generator/commit/2a887d0d96f1d5044039d0e0457001f0fde0def0
import JSON5 from "json5";
import { camelCase } from "lodash-es";
import {
type AtRule,
type Builder,
@ -8,11 +10,9 @@ import {
type Rule,
parse,
} from "postcss";
import JSON5 from "json5";
import parseSelector from "postcss-selector-parser";
import Stringifier from "postcss/lib/stringifier";
import parseSelector from "postcss-selector-parser";
import { type Element, compile } from "stylis";
import { camelCase } from "lodash";
function getSelectorScope(selector: string): string {
let selectorScope = "root";
@ -129,7 +129,8 @@ const convertScopeToModuleName = (scope: string) =>
"_$1"
);
export function convertCssToJS(
/** @internal */
export function toJSCode(
css: string,
mapClassNames: (className: string) => string = convertScopeToModuleName
): string {
@ -211,7 +212,7 @@ export function convertCssToJS(
? `injectGlobal\`${style}\n\`;\n`
: `\nexport const ${mapClassNames(
scope
)} = ${JSON5.stringify(asJSObject(style), null, 2)};\n`;
)} = ${JSON5.stringify(cssToJS(style), null, 2)};\n`;
}
return res.trim();
@ -299,7 +300,7 @@ function simplifyValue(propName: string, value: string) {
return value;
}
function asJSObject(inputCssText: string) {
export function cssToJS(inputCssText: string): Record<string, any> {
const css = compile(inputCssText);
const result: Record<string, string> = {};
@ -338,5 +339,5 @@ function asJSObject(inputCssText: string) {
for (const node of css) {
walk(result, node);
}
return result as React.CSSProperties;
return result;
}

View File

@ -1,6 +1,6 @@
import { readFileSync } from "node:fs";
import { extname } from "node:path";
import { once } from "lodash";
import { once } from "lodash-es";
import type babel from "@babel/core";
import type * as esbuild from "esbuild";
import { transformSync } from "@babel/core";

View File

@ -1,7 +1,10 @@
import { dirname, join } from "node:path";
import type * as esbuild from "esbuild";
import { CssSyntaxError } from "postcss";
import { type Compile, type StyleMap, type StyleMapEntry, pkgName } from "./shared";
import type { BuildStyleFile } from "./index";
const PLUGIN_NAME = "tailwind";

View File

@ -1,7 +1,9 @@
import { describe, expect, it } from "vitest";
import { getClassName } from "./index";
import { getBuild } from "./__tests__/utils";
import { getClassName } from "./index";
describe("babel-tailwind", () => {
const compileESBuild = getBuild("main");

View File

@ -1,14 +1,15 @@
import hash from "@emotion/hash";
import { transformSync } from "esbuild";
import { memoize, without } from "lodash-es";
import type postcss from "postcss";
import type { Config } from "tailwindcss";
import type { SetRequired } from "type-fest";
import { transformSync } from "esbuild";
import type postcss from "postcss";
import { memoize, without } from "lodash";
import { type ClassNameCollector, babelTailwind } from "./babel/index";
import { toJSCode } from "./css-to-js";
import { esbuildPlugin } from "./esbuild-postcss";
import { vitePlugin } from "./vite-plugin";
import { type StyleMap, createPostCSS } from "./shared";
import { convertCssToJS } from "./css-to-js";
import { vitePlugin } from "./vite-plugin";
export { isMacrosName } from "./vite-plugin";
@ -156,7 +157,7 @@ export function getTailwindPlugins(options: TailwindPluginOptions) {
if (path.endsWith(".css")) {
return ["css", transformSync(compiled, { loader: "css" }).code] as const;
} else if (path.endsWith(".js")) {
const js = convertCssToJS(compiled, x => x.slice(1));
const js = toJSCode(compiled, x => x.slice(1));
return ["js", js] as const;
} else {
throw new Error("Unknown file extension");

51
src/macro.d.ts vendored
View File

@ -10,6 +10,53 @@ interface RecursiveStringObject {
type CSSAttributeValue = string | (string | RecursiveStringObject)[];
export type SupportedTag =
| "a"
| "abbr"
| "article"
| "blockquote"
| "button"
| "cite"
| "code"
| "details"
| "div"
| "figure"
| "footer"
| "h1"
| "h2"
| "h3"
| "h4"
| "hr"
| "iframe"
| "img"
| "input"
| "ins"
| "label"
| "li"
| "main"
| "nav"
| "ol"
| "output"
| "p"
| "pre"
| "rt"
| "ruby"
| "section"
| "select"
| "span"
| "strong"
| "sub"
| "summary"
| "sup"
| "table"
| "tbody"
| "td"
| "thead"
| "tr"
| "ul"
| "var"
| "video";
type Modifier =
| "2xl"
| "active"
@ -69,6 +116,10 @@ export type TailwindFunction = {
(...args: (string | RecursiveStringObject)[]): string;
} & {
[key in Modifier]: TailwindFunction;
} & {
[tag in SupportedTag]: (
strings: TemplateStringsArray
) => React.FunctionComponent<JSX.IntrinsicElements[tag]>;
};
/**

View File

@ -1,9 +1,13 @@
import tailwind from "tailwindcss";
import postcss from "postcss";
import tailwind from "tailwindcss";
import type { ResolveTailwindOptions } from "./index";
export const { name: pkgName } = [require][0]("../package.json");
declare const __PKG_NAME__: string;
export const pkgName = __PKG_NAME__;
export const macroNames = [`${pkgName}/macro`, `${pkgName}`];
export const classedName = `${pkgName}/classed`;
interface LineColumn {
line: number;

View File

@ -1,5 +1,5 @@
// https://github.com/jamiebuilds/tailwindcss-animate/commit/ac0dd3a3c81681b78f1d8ea5e7478044213995e1
import plugin from "tailwindcss/plugin";
import plugin from "tailwindcss/plugin.js";
import type { PluginAPI } from "tailwindcss/types/config";
function filterDefault<T extends object>(values: T) {

View File

@ -1,5 +1,5 @@
// https://github.com/tailwindlabs/tailwindcss-aspect-ratio/commit/b2a9d02229946f3430c0013198be2affa7a175da
import plugin from "tailwindcss/plugin";
import plugin from "tailwindcss/plugin.js";
const baseStyles = {
position: "relative",

View File

@ -1,5 +1,5 @@
// https://github.com/tailwindlabs/tailwindcss-container-queries/commit/f8d4307afdd3d913c3ddd406334c1a07f427c5b3
import plugin from "tailwindcss/plugin";
import plugin from "tailwindcss/plugin.js";
function parseValue(value: string) {
const numericValue = value.match(/^(\d+\.\d+|\d+|\.\d+)\D+/)?.[1] ?? null;

6
src/vendor/forms.ts vendored
View File

@ -1,7 +1,7 @@
// https://github.com/tailwindlabs/tailwindcss-forms/commit/c9d9da3e010b194a1f0e9c36fbd98c83e4762840
import plugin from "tailwindcss/plugin";
import defaultTheme from "tailwindcss/defaultTheme";
import colors from "tailwindcss/colors";
import colors from "tailwindcss/colors.js";
import defaultTheme from "tailwindcss/defaultTheme.js";
import plugin from "tailwindcss/plugin.js";
import type { CSSRuleObject } from "tailwindcss/types/config";
const shorterNames = {

View File

@ -1,5 +1,5 @@
// https://github.com/adobe/react-spectrum/blob/14f324fe890fcedc6e34889d9b04d5d6bfeb8380/packages/tailwindcss-react-aria-components/src/index.js
import plugin from "tailwindcss/plugin";
import plugin from "tailwindcss/plugin.js";
import type { PluginAPI } from "tailwindcss/types/config";
// Order of these is important because it determines which states win in a conflict.
@ -43,7 +43,7 @@ const attributes = {
"drop-target",
"resizing",
"disabled",
],
] as const,
enum: {
placement: ["left", "right", "top", "bottom"],
type: ["literal", "year", "month", "day"],
@ -167,7 +167,9 @@ export default plugin.withOptions<{ prefix: string }>(
!!future?.hoverOnlyWhenSupported);
// Enum attributes go first because currently they are all non-interactive states.
for (const [attributeName, value] of Object.entries(attributes.enum)) {
for (const [attributeName, value] of Object.entries(
attributes.enum
) as (keyof typeof attributes.enum)[][]) {
for (const attributeValue of value) {
const name = shortNames[attributeName] || attributeName;
const variantName = `${prefix}${name}-${attributeValue}`;

View File

@ -1,8 +1,8 @@
// https://github.com/tailwindlabs/tailwindcss-typography/commit/7b43b3b33bb74c57a68852330105bb34d11a806a
import plugin from "tailwindcss/plugin";
import colors from "tailwindcss/colors";
import { castArray, merge } from "lodash";
import { castArray, merge } from "lodash-es";
import parser, { type Pseudo } from "postcss-selector-parser";
import colors from "tailwindcss/colors.js";
import plugin from "tailwindcss/plugin.js";
const parseSelector = parser();

View File

@ -1,5 +1,10 @@
import { defineConfig } from "vitest/config";
import pkg from "./package.json" with { type: "json" };
export default defineConfig({
test: {},
define: {
__PKG_NAME__: JSON.stringify(pkg.name),
},
});