This commit is contained in:
2026-05-11 05:30:03 +08:00
parent eeda1e68e8
commit 33951a649b
48 changed files with 640 additions and 1018 deletions

View File

@@ -30,10 +30,12 @@
"devDependencies": {
"@types/node": "^25.6.0",
"@vitejs/plugin-react": "^6.0.1",
"glob": "^13.0.6",
"tinyglobby": "^0.2.16",
"ts-node": "^10.9.2",
"typescript": "^6.0.3",
"vite": "^8.0.10"
"vite": "^8.0.10",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3"
},
"peerDependencies": {
"react": "^19",

View File

@@ -1,6 +1,7 @@
import fs from "fs";
import path from "path";
import { globSync } from "glob";
// 1. 引入 tinyglobby
import { globSync } from "tinyglobby";
interface Config {
outputDir: string;
@@ -77,13 +78,12 @@ function generateIndexFile(config: Config) {
// ------ scanDirs forEach start ------------------------
config.scanDirs.forEach((dir) => {
// 2. 路径模式保持不变tinyglobby 能够正确处理
const scanPattern = path.resolve(currentPath, dir, "**", "*.*");
const allFilePath = globSync(scanPattern, {
absolute: true,
windowsPathsNoEscape: true,
dot: false,
follow: true,
// 3. 移除了 windowsPathsNoEscapetinyglobby 默认处理路径更智能
});
const validFiles = allFilePath.filter((filePath) => {

View File

@@ -1,37 +0,0 @@
@import './base/root.css';
@import './utility/size-insensitive/align-content.css';
@import './utility/size-insensitive/align-items.css';
@import './utility/size-insensitive/align-self.css';
@import './utility/size-insensitive/animation.css';
@import './utility/size-insensitive/box-decoration.css';
@import './utility/size-insensitive/box-inside.css';
@import './utility/size-insensitive/box-sizing.css';
@import './utility/size-insensitive/brand.css';
@import './utility/size-insensitive/break-after.css';
@import './utility/size-insensitive/break-before.css';
@import './utility/size-insensitive/cursor.css';
@import './utility/size-insensitive/display.css';
@import './utility/size-insensitive/drop-shadow.css';
@import './utility/size-insensitive/flex-direction.css';
@import './utility/size-insensitive/flex-wrap.css';
@import './utility/size-insensitive/font-family.css';
@import './utility/size-insensitive/justify-content.css';
@import './utility/size-insensitive/justify-items.css';
@import './utility/size-insensitive/justify-self.css';
@import './utility/size-insensitive/overflow.css';
@import './utility/size-insensitive/overscroll-behavior.css';
@import './utility/size-insensitive/position.css';
@import './utility/size-insensitive/screen-reader.css';
@import './utility/size-insensitive/theme.css';
@import './utility/size-insensitive/user-select.css';
@import './utility/size-insensitive/z-index.css';
@import './utility/size-sensitive/border-radius.css';
@import './utility/size-sensitive/font-size.css';
@import './utility/size-sensitive/font-weight.css';
@import './utility/size-sensitive/gap.css';
@import './utility/size-sensitive/height.css';
@import './utility/size-sensitive/margin-block.css';
@import './utility/size-sensitive/margin-inline.css';
@import './utility/size-sensitive/padding-long.css';
@import './utility/size-sensitive/padding-short.css';
@import './utility/size-sensitive/width.css';

View File

@@ -1,4 +1 @@
import "./index.css";
export * from "./utils/cpm.ts";
export * from "./utils/cvr.ts";
export * from "./utils/prefix-list.ts";
import './index.css'

View File

@@ -0,0 +1,89 @@
import { cvr } from "../utils/cvr";
export const itemSizeRecipe = cvr({
base: "relative select-none flex flex-nowrap justify-center items-center",
variants: {
size: {
xs: "text-xs h-item-xs gap-xs px-xs",
sm: "text-sm h-item-sm gap-sm px-sm",
md: "text-md h-item-md gap-md px-md",
lg: "text-lg h-item-lg gap-lg px-lg",
xl: "text-xl h-item-xl gap-xl px-xl",
"2xl": "text-2xl h-item-2xl gap-2xl px-2xl",
},
shape: {
square: "rounded-none",
rounded: "",
circle: "rounded-full",
},
iconOnly: {
true: "px-none",
false: "",
},
},
compoundVariants: [
{ iconOnly: false, size: "xs", class: "px-xs" },
{ iconOnly: false, size: "sm", class: "px-sm" },
{ iconOnly: false, size: "md", class: "px-md" },
{ iconOnly: false, size: "lg", class: "px-lg" },
{ iconOnly: false, size: "xl", class: "px-xl" },
{ iconOnly: false, size: "2xl", class: "px-2xl" },
{ shape: "rounded", size: "xs", class: "rounded-sm" },
{
shape: "rounded",
size: "sm",
class: "rounded-md",
},
{
shape: "rounded",
size: "md",
class: "rounded-lg",
},
{
shape: "rounded",
size: "lg",
class: "rounded-xl",
},
{
shape: "rounded",
size: "xl",
class: "rounded-2xl",
},
{
shape: "rounded",
size: "2xl",
class: "rounded-3xl",
},
// --------------------------------------------------
{
iconOnly: true,
size: "xs",
class: "w-item-xs",
},
{
iconOnly: true,
size: "sm",
class: "w-item-sm",
},
{
iconOnly: true,
size: "md",
class: "w-item-md",
},
{
iconOnly: true,
size: "lg",
class: "w-item-lg",
},
{
iconOnly: true,
size: "xl",
class: "w-item-xl",
},
{
iconOnly: true,
size: "2xl",
class: "w-item-2xl",
},
],
});

View File

@@ -1,13 +1,13 @@
@layer utility {
.flex-wrap-nowrap {
.flex-nowrap {
flex-wrap: nowrap;
}
.flex-wrap-wrap {
.flex-wrap {
flex-wrap: wrap;
}
.flex-wrap-wrap-reverse {
.flex-wrap-reverse {
flex-wrap: wrap-reverse;
}
}

View File

@@ -25,9 +25,11 @@
}
/* -------------- */
.h-inline-xs {
/* 16px */
height: calc(var(--font-size-xs) * var(--line-height-xs));
}
.h-inline-sm {
/* 20px */
height: calc(var(--font-size-sm) * var(--line-height-sm));
}
.h-inline-md {

View File

@@ -3,11 +3,11 @@
padding-inline: 0px;
}
.px-xs {
/* 6px */
/* 4px, 24px - 16px = 8px */
padding-inline: var(--padding-xs);
}
.px-sm {
/* 8px */
/* 4px, 28px - 20px = 8px */
padding-inline: var(--padding-sm);
}
.px-md {

View File

@@ -14,23 +14,22 @@ function matchLongestPrefix(cls: string, prefixList: string[]): string {
}
// 重载 1
export function cpm(...classes: Array<string | readonly string[]>): string;
export function cpm(...classes: Array<string | string[]>): string;
// 重载 2
export function cpm(
options: { extendedPrefixList?: string[] },
...classes: Array<string | readonly string[]>
...classes: Array<string | string[]>
): string;
export function cpm(
arg1: { extendedPrefixList?: string[] } | string | readonly string[],
...rest: Array<string | readonly string[]>
arg1: { extendedPrefixList?: string[] } | string | string[],
...rest: Array<string | string[]>
): string {
const map = new Map<string, string>();
// ✅ 明确拆分 options / classes
let options: { extendedPrefixList?: string[] } = {};
let classes: Array<string | readonly string[]>;
let classes: Array<string | string[]>;
if (typeof arg1 === "object" && !Array.isArray(arg1)) {
options = arg1 as { extendedPrefixList?: string[] };

View File

@@ -1,15 +1,21 @@
import { cpm } from "./cpm";
// 1. 允许变体值的键可以是字符串,也可以是布尔值(为了开发体验,允许传 true/false
// 但底层存储我们统一视为字符串处理
type VariantValue = string | boolean;
type VariantsConfig<V extends Record<string, Record<string, string>>> = {
base?: string;
variants?: V;
compoundVariants?: Array<
Partial<{ [K in keyof V]: keyof V[K] }> & { class: string }
// 修改这里:允许 compoundVariants 的值是 VariantValue而不仅仅是 keyof V[K]
Partial<{ [K in keyof V]: VariantValue }> & { class: string }
>;
};
// 2. 修改 Props 定义,允许传入 boolean因为 JS 对象 key 访问时boolean 会被转为 string
type VariantProps<V extends Record<string, Record<string, string>>> = Partial<{
[K in keyof V]: keyof V[K];
[K in keyof V]: keyof V[K] | boolean;
}>;
export function cvr<V extends Record<string, Record<string, string>>>(
@@ -21,10 +27,12 @@ export function cvr<V extends Record<string, Record<string, string>>>(
if (config.base) classes.push(config.base);
if (config.variants) {
for (const [key, map] of Object.entries(config.variants) as any) {
for (const [key, map] of Object.entries(config.variants)) {
const value = props[key];
if (value && map[value]) {
classes.push(map[value]);
// 运行时修复:如果传入的是 boolean true需要转为字符串 "true" 才能匹配 map
const stringifiedValue = String(value);
if (value && map[stringifiedValue]) {
classes.push(map[stringifiedValue]);
}
}
}
@@ -33,7 +41,11 @@ export function cvr<V extends Record<string, Record<string, string>>>(
for (const cv of config.compoundVariants) {
const match = Object.entries(cv)
.filter(([k]) => k !== "class")
.every(([k, v]) => props[k] === v);
.every(([k, v]) => {
const propValue = props[k as keyof V];
// 运行时修复:统一转为字符串比较,确保 "true" === true 能匹配(虽然不建议混用,但要兼容)
return String(propValue) === String(v);
});
if (match && cv.class) {
classes.push(cv.class);

View File

@@ -13,7 +13,7 @@ export const defaultPrefixList = [
"cursor",
"display",
"flex-direction",
"flex-wrap",
"flex",
"font-family",
"font-weight",
"text",

View File

@@ -4,9 +4,9 @@
"noEmit": false,
"emitDeclarationOnly": true,
"declaration": true,
"declarationDir": "./dist",
"rootDir": "./src",
"outDir": "./dist",
"declarationDir": "./dist"
"outDir": "./dist"
},
"include": ["src"],
"exclude": [

View File

@@ -0,0 +1,33 @@
import { mergeProps } from "@base-ui/react";
import * as React from "react";
import { cn } from "tailwind-variants";
export interface SlotProps extends React.HTMLAttributes<HTMLElement> {
children: React.ReactNode;
}
export const Slot = React.forwardRef<HTMLElement, SlotProps>(
({ children, className: externalClassName, ...restProps }, ref) => {
if (!React.isValidElement(children)) {
return null;
}
const child = children as React.ReactElement<Record<string, unknown>>;
const childProps = child.props || {};
const mergedClassName = cn(
childProps.className as string | undefined,
externalClassName,
);
const otherMergedProps = mergeProps(childProps, restProps);
return React.cloneElement(child, {
...otherMergedProps,
className: mergedClassName,
ref,
});
},
);
Slot.displayName = "Slot";

View File

@@ -0,0 +1,18 @@
import { ComponentPropsWithRef, forwardRef, ReactNode } from "react";
export type ButtonState = {
loading?: boolean;
disabled?: boolean;
};
export type ButtonProps = {
size?: "xs" | "sm" | "md" | "lg";
shape?: "circle" | "rounded" | "square";
iconSvg?: ReactNode;
iconOnly?: boolean;
hideIcon?: boolean;
loadingIconSvg?: ReactNode;
} & ButtonState &
ComponentPropsWithRef<"button">;
export const Button = forwardRef();

View File

@@ -0,0 +1,44 @@
{
"name": "@defgov/ui-web-headless",
"version": "0.0.0",
"private": true,
"type": "module",
"sideEffects": [
"*.css"
],
"module": "./dist/index.es.js",
"main": "./dist/index.cjs.js",
"types": "./dist/index.d.ts",
"style": "./dist/index.css",
"exports": {
".": {
"import": "./dist/index.es.js",
"require": "./dist/index.cjs.js",
"types": "./dist/index.d.ts"
},
"./index.css": "./dist/index.css"
},
"files": [
"dist"
],
"scripts": {
"gen-index": "ts-node scripts/gen-index.ts",
"gen-dts": "tsc -p tsconfig.build.json",
"dev": "pnpm gen-index && vite build --watch",
"build": "pnpm gen-index && vite build && pnpm gen-dts"
},
"devDependencies": {
"@types/node": "^25.6.0",
"@vitejs/plugin-react": "^6.0.1",
"tinyglobby": "^0.2.16",
"ts-node": "^10.9.2",
"typescript": "^6.0.3",
"vite": "^8.0.10",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3"
},
"peerDependencies": {
"react": "^19",
"react-dom": "^19"
}
}

View File

@@ -0,0 +1,147 @@
import fs from "fs";
import path from "path";
// 1. 引入 tinyglobby
import { globSync } from "tinyglobby";
interface Config {
outputDir: string;
outputFilenameWithExt: string;
scanDirs: string[];
importPrefix: string;
predefineStatements: string[];
includeExtensions: string[];
excludeDirs: string[];
excludeFileExtensions: string[];
excludePatterns: RegExp[];
}
const cssConfig: Config = {
outputDir: "src",
outputFilenameWithExt: "index.css",
scanDirs: ["src"],
importPrefix: "@import",
predefineStatements: [],
includeExtensions: [".css"],
excludeDirs: ["__tests__", "tests", "story", "stories", "types"],
excludeFileExtensions: [],
excludePatterns: [/^index\.(css)$/, /\.(test|spec)\./, /\.(story|stories)\./],
};
const tsConfig: Config = {
outputDir: "src",
outputFilenameWithExt: "index.ts",
scanDirs: ["src"],
importPrefix: "export * from",
predefineStatements: ["import './index.css'"],
includeExtensions: [".ts", "tsx", "js", "jsx"],
excludeDirs: ["__tests__", "tests", "story", "stories", "types"],
excludeFileExtensions: [".d.ts"],
excludePatterns: [
/^index\.(ts|tsx|js|jsx)$/,
/\.(test|spec)\./,
/\.(story|stories)\./,
],
};
const normalizePath = (p: string) => p.replace(/\\/g, "/");
const isExcludeDir = (filePath: string, excludeDirs: string[]) => {
const normalized = normalizePath(filePath);
return excludeDirs.some((dir) => normalized.includes(`/${dir}/`));
};
const isExcludeFileExtensions = (
filePath: string,
excludeFileExtensions: string[],
) => excludeFileExtensions.some((ext) => filePath.endsWith(ext));
const isExcludePattern = (fileName: string, excludePatterns: RegExp[]) =>
excludePatterns.some((pattern) => pattern.test(fileName));
// ----------------------------------------
function isValidFile(filePath: string, config: Config): boolean {
const fileName = filePath.split(/[\\/]/).pop()!;
if (isExcludeDir(filePath, config.excludeDirs)) return false;
if (isExcludeFileExtensions(filePath, config.excludeFileExtensions))
return false;
if (isExcludePattern(fileName, config.excludePatterns)) return false;
const ext = path.extname(filePath);
return config.includeExtensions.includes(ext);
}
// -----------------------------------------
function generateIndexFile(config: Config) {
const currentPath = process.cwd();
const outputPath = path.resolve(currentPath, config.outputDir);
let exportStatements: string[] = [];
// ------ scanDirs forEach start ------------------------
config.scanDirs.forEach((dir) => {
// 2. 路径模式保持不变tinyglobby 能够正确处理
const scanPattern = path.resolve(currentPath, dir, "**", "*.*");
const allFilePath = globSync(scanPattern, {
absolute: true,
// 3. 移除了 windowsPathsNoEscapetinyglobby 默认处理路径更智能
});
const validFiles = allFilePath.filter((filePath) => {
return isValidFile(filePath, config);
});
if (validFiles.length === 0) {
console.log(
`⚠️ 未找到符合条件的文件,跳过生成 ${config.outputFilenameWithExt}`,
);
return;
}
validFiles.sort();
validFiles.forEach((file) => {
const relativePath = path.relative(outputPath, file);
const importPath = `./${relativePath.replace(/\\/g, "/")}`;
exportStatements.push(`${config.importPrefix} '${importPath}';`);
});
});
// --------- scanDirs forEach end ----------------
const indexFileContent = `
${config.predefineStatements.join("\n")}
${exportStatements.join("\n")}
`.trim();
const indexFilePath = path.resolve(
currentPath,
config.outputDir,
config.outputFilenameWithExt,
);
// ✅ 内容比对,避免重复写入
if (fs.existsSync(indexFilePath)) {
const old = fs.readFileSync(indexFilePath, "utf8");
if (old === indexFileContent) {
console.log(
`${config.outputFilenameWithExt} 内容无变化,无需重新生成`,
);
return;
}
}
fs.writeFileSync(indexFilePath, indexFileContent, "utf8");
console.log(`✅ 成功生成 ${config.outputFilenameWithExt}: ${indexFilePath}`);
}
// --------------------------------------------------
try {
console.log(`🚀 [gen-index] 开始扫描`);
generateIndexFile(cssConfig);
generateIndexFile(tsConfig);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
console.error(`❌ [gen-index] 执行失败: ${msg}`);
process.exit(1);
}

View File

@@ -0,0 +1,41 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": false,
"emitDeclarationOnly": true,
"declaration": true,
"declarationDir": "./dist",
"rootDir": "./src",
"outDir": "./dist"
},
"include": ["src"],
"exclude": [
"node_modules",
"dist",
".turbo/**/*",
".cache/**/*",
".vite/**/*",
"vite.config.ts",
"*.config.ts",
"*.config.js",
"tsconfig.*.json",
"__tests__/**/*",
"test/**/*",
"tests/**/*",
"**/*.test.ts",
"**/*.test.tsx",
"**/*.spec.ts",
"**/*.spec.tsx",
".storybook/**/*",
"stories/**/*",
"example/**/*",
"examples/**/*",
"scripts/**/*",
".env",
".env.*",
"public/**/*",
"docs/**/*",
"README.md",
"LICENSE"
]
}

View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es2025",
"lib": ["ES2025", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["node", "vite/client"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src", "scripts", "vite.config.ts"]
}

View File

@@ -0,0 +1,103 @@
function innerClassMergeFn(...classes: string[]): string {
return classes
.map((str) => str.trim())
.filter(Boolean)
.join(" ")
.trim();
}
// 重载1
export function mergeProps(
...propsN: Record<string, any>[]
): Record<string, any>;
// 重载2
export function mergeProps(
options: { classMergeFn: Function },
...propsN: Record<string, any>[]
): Record<string, any>;
// 实现
export function mergeProps(
arg1: { classMergeFn: Function } | Record<string, any>,
...rest: Record<string, any>[]
) {
let options: { classMergeFn: Function } = {
classMergeFn: innerClassMergeFn,
};
let propsN: Record<string, any>[];
if (
arg1 &&
typeof arg1 === "object" &&
!Array.isArray(arg1) &&
"classMergeFn" in arg1 &&
typeof (arg1 as any).classMergeFn === "function"
) {
options = arg1 as { classMergeFn: Function };
propsN = rest;
} else {
propsN = [arg1 as Record<string, any>, ...rest];
}
// --------------------------------
const result: any = {};
const eventHandlerMap = new Map<string, Function[]>();
const refs: any[] = [];
propsN.forEach((props) => {
if (!props) return;
if (props.className) {
result.className = options.classMergeFn(
result.className || "",
props.className,
);
}
if (props.style) {
result.style = { ...(result.style || {}), ...props.style };
}
if (props.ref) {
refs.push(props.ref);
}
Object.keys(props).forEach((key) => {
if (key.startsWith("on") && typeof props[key] === "function") {
if (!eventHandlerMap.has(key)) {
eventHandlerMap.set(key, []);
}
eventHandlerMap.get(key)!.push(props[key]);
} else if (key !== "ref" && key !== "className" && key !== "style") {
// 其他普通属性,后面的覆盖前面的
result[key] = props[key];
}
});
});
// 合并 Refs
if (refs.length > 0) {
if (refs.length === 1) {
result.ref = refs[0];
} else {
result.ref = (node: any) => {
refs.forEach((ref) => {
if (typeof ref === "function") {
ref(node);
} else if (ref) {
ref.current = node;
}
});
};
}
}
// 合并事件处理器
eventHandlerMap.forEach((handlers, key) => {
result[key] = (...args: any[]) => {
handlers.forEach((handler) => handler(...args));
};
});
return result;
}

View File

@@ -0,0 +1,39 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
export default defineConfig({
// d.ts 由 tsc 完成,使用专门配置 tsconfig.build.json
// 转换由 oxc 完成
// 打包由 rolldown 完成
plugins: [react()],
build: {
cssMinify: false,
lib: {
entry: path.resolve(import.meta.dirname, "src/index.ts"),
// 不写 vite 默认是 index.mjs 和 index.js不方便识别
formats: ["es", "cjs"],
// package.json 管别人怎么使用,
// build.lib 管怎么打包,生成什么
// 如果不一致,就会报错,指向文件不存在
fileName: (format) => `index.${format}.js`,
},
rolldownOptions: {
// 避免这些被打包peerDependencies 对 rolldown 是无效的,不会自动 external
external: ["react", "react-dom", "react/jsx-runtime"],
// 专门给 UMD / IIFE 的映射表
output: {
globals: {
react: "React",
"react-dom": "ReactDOM",
},
},
},
emptyOutDir: true, // 防止旧产物残留
sourcemap: true, // 方便调试
cssCodeSplit: false, // 合并成一个css文件
outDir: "dist", // 专管打包输出目录tsconfig.build.json 中的 outDir 管的是 d.ts 输出目录
},
});

View File

@@ -35,7 +35,7 @@
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "~5.2.0",
"glob": "^13.0.6",
"tinyglobby": "^0.2.16",
"ts-node": "^10.9.2",
"typescript": "~6.0.3",
"vite": "~7.3.2",