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

@@ -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 输出目录
},
});