This commit is contained in:
2026-05-16 00:51:11 +08:00
parent 92e4fd11f1
commit 0f23a8f7a0
67 changed files with 153 additions and 384 deletions

View File

@@ -1 +0,0 @@
import './index.css'

View File

@@ -1,39 +0,0 @@
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

@@ -1,29 +0,0 @@
import React, { ReactNode, isValidElement, Children } from "react";
import { ButtonIcon } from "./ButtonIcon";
import { ButtonLoading } from "./ButtonLoading";
export function useButtonSlot(children: ReactNode) {
const iconNodes: React.ReactElement[] = [];
const loadingNodes: React.ReactElement[] = [];
const collectNodes = (nodes: ReactNode) => {
Children.forEach(nodes, (child) => {
if (!isValidElement(child)) return;
if (child.type === ButtonIcon) {
iconNodes.push(child);
} else if (child.type === ButtonLoading) {
loadingNodes.push(child);
} else if ((child as any).props.children) {
collectNodes((child as any).props.children);
}
});
};
collectNodes(children);
return {
iconNode: iconNodes.at(-1),
loadingNode: loadingNodes.at(-1),
};
}

View File

@@ -1,44 +0,0 @@
{
"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

@@ -1,147 +0,0 @@
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

@@ -1,41 +0,0 @@
{
"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

@@ -1,26 +0,0 @@
{
"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

@@ -1,5 +0,0 @@
export function useProps<S, P>(props: Record<string, any>) {
const stateProps = {};
const primitiveProps = {};
return;
}

View File

@@ -1,39 +0,0 @@
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

@@ -1,5 +1,5 @@
{
"name": "@defgov/css",
"name": "@defgov/ui-web",
"version": "0.0.0",
"private": true,
"type": "module",
@@ -24,7 +24,7 @@
"scripts": {
"gen-index": "ts-node scripts/gen-index.ts",
"gen-dts": "tsc -p tsconfig.build.json",
"dev": "pnpm gen-index && vite build --watch",
"dev": "pnpm gen-index && vite",
"build": "pnpm gen-index && vite build && pnpm gen-dts"
},
"devDependencies": {

View File

@@ -0,0 +1,7 @@
import { useState } from "react";
function App() {
return <div></div>;
}
export default App;

View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>vite-project</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/main.tsx"></script>
</body>
</html>

View File

@@ -0,0 +1,9 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@@ -1,13 +1,14 @@
import { ComponentPropsWithoutRef, forwardRef } from "react";
import { type ComponentPropsWithoutRef, forwardRef } from "react";
import { useButtonSlot } from "./useButtonSlots";
import { useStateProps } from "../../utils/useStateProps";
export type ButtonRootOwnProps = {
iconOnly?: boolean;
hideIcon?: boolean;
loading?: boolean;
};
export type ButtonRootStateProps = {
loading?: boolean;
disabled?: boolean;
};
@@ -22,17 +23,22 @@ export type ButtonRootProps = ButtonRootOwnProps &
export const ButtonRoot = forwardRef<HTMLButtonElement, ButtonRootProps>(
(props, ref) => {
const { children, loading, iconOnly, hideIcon, ...rest } = props;
const { iconNode, loadingNode } = useButtonSlot(children);
const {
children,
loading,
iconOnly,
hideIcon,
disabled = false,
...rest
} = props;
const stateProps = useStateProps({ disabled: disabled });
const filteredChildren = useButtonSlot(children, props);
return (
<button ref={ref} {...rest}>
{loadingNode ?? loadingNode}
{!loadingNode && iconNode ? (hideIcon ? null : iconNode) : null}
{children}
<button ref={ref} {...stateProps} {...rest}>
{filteredChildren}
</button>
);
},
);
ButtonRoot.displayName = "ButtonRoot";
// 我需要一个通用hook方法 useProps<ownProps,stateProps,primitiveProps>(props),返一个对象 { ownPropsstateProps,primitiveProps}

View File

@@ -0,0 +1,52 @@
import {
type ReactNode,
Children,
isValidElement,
cloneElement,
type ReactElement,
} from "react";
import { ButtonIcon } from "./ButtonIcon";
import { ButtonLoading } from "./ButtonLoading";
export function useButtonSlot(
children: ReactNode,
props: { hideIcon?: boolean; loading?: boolean },
) {
const filterNodes = (nodes: ReactNode): ReactNode => {
const filtered: ReactNode[] = [];
Children.forEach(nodes, (child) => {
if (!isValidElement(child)) {
filtered.push(child);
return;
}
// loading只保留 Loading
if (props.loading) {
if (child.type === ButtonLoading) {
filtered.push(child);
}
return;
}
// 隐藏图标:移除 ButtonIcon
if (props.hideIcon && child.type === ButtonIcon) {
return;
}
// 普通节点
const element = child as ReactElement<{ children?: ReactNode }>;
filtered.push(
cloneElement(element, {
children: filterNodes(element.props.children),
}),
);
});
return filtered;
};
return filterNodes(children);
}

View File

@@ -1,4 +1,4 @@
function innerClassMergeFn(...classes: string[]): string {
function defaultClassMergeFn(...classes: string[]): string {
return classes
.map((str) => str.trim())
.filter(Boolean)
@@ -23,7 +23,7 @@ export function mergeProps(
...rest: Record<string, any>[]
) {
let options: { classMergeFn: Function } = {
classMergeFn: innerClassMergeFn,
classMergeFn: defaultClassMergeFn,
};
let propsN: Record<string, any>[];

View File

@@ -0,0 +1,12 @@
export function useStateProps(props: Record<string, any>) {
const state: Record<string, any> = {};
Object.entries(props).forEach(([key, value]) => {
const stateKey = `data-${key}:`;
const stateValue = `"${value}"`;
state[stateKey] = stateValue;
});
return state;
}

View File

@@ -0,0 +1,41 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
export default defineConfig(({ command }) => {
if (command === "serve") {
return {
plugins: [react()],
root: "playground",
};
}
return {
plugins: [react()],
build: {
cssMinify: false,
lib: {
entry: path.resolve(import.meta.dirname, "src/index.ts"),
formats: ["es", "cjs"],
fileName: (format) => `index.${format}.js`,
},
rolldownOptions: {
external: ["react", "react-dom", "react/jsx-runtime"],
output: {
globals: {
react: "React",
"react-dom": "ReactDOM",
},
},
},
emptyOutDir: true,
sourcemap: true,
cssCodeSplit: false,
outDir: "dist",
},
};
});