Commit 8def5834 by liimin

feat: 项目接入画像按 package.json 自动填充,并修复选目录不触发

扫描器 (project-scanner.ts):补齐 stateManagement/dataFetching/routing 推断;framework/styling/componentLibrary 输出对齐前端预设下拉,识别不到则留空不硬猜

前端:工作目录选择或手填后自动扫描并填充画像表单,用户再复核修改

修复:原仅在输入框 onBlur 触发自动扫描,经浏览弹窗选目录不走 blur 故不触发;改为 useEffect 监听 rootDirDraft 变化(防抖 600ms,与已配置根相同则不重复扫),统一覆盖两种路径
1 parent db725899
...@@ -177,62 +177,101 @@ function toImportPath(file: string, root: string, alias: AliasInfo | null): stri ...@@ -177,62 +177,101 @@ function toImportPath(file: string, root: string, alias: AliasInfo | null): stri
function detectFramework(deps: Record<string, string>): string { function detectFramework(deps: Record<string, string>): string {
const has = (k: string) => k in deps; const has = (k: string) => k in deps;
const isVue = has('vue'); // 元框架优先(它们已隐含框架,单独成项便于与预设下拉匹配)
const isReact = has('react') || has('react-dom'); if (has('next')) return 'Next.js (App Router)';
const lib = isVue ? 'Vue' : isReact ? 'React' : 'Unknown'; if (has('nuxt') || has('@nuxt/kit') || has('@nuxt/schema')) return 'Nuxt 3';
let ver = ''; if (has('@remix-run/react') || has('@remix-run/node')) return 'Remix';
if (isVue) { if (has('@sveltejs/kit')) return 'SvelteKit';
const v = deps['vue'] || ''; if (has('svelte')) return 'Svelte';
ver = v.startsWith('^3') || v.startsWith('3') ? ' 3' : ''; if (has('@angular/core')) return 'Angular';
} else if (isReact) { if (has('astro')) return 'Astro';
if (has('solid-js') || has('@solidjs/router')) return 'SolidJS';
if (has('@builder.io/qwik') || has('@qwikcity/router')) return 'Qwik';
if (has('vue')) {
// 预设只有 "Vue 3",版本号丢失但可接受
return 'Vue 3';
}
if (has('react') || has('react-dom')) {
const v = deps['react'] || ''; const v = deps['react'] || '';
ver = v.startsWith('^18') || v.startsWith('18') ? ' 18' : v.startsWith('^19') || v.startsWith('19') ? ' 19' : ''; if (v.startsWith('^19') || v.startsWith('19')) return 'React 19';
return 'React 18';
} }
let bundler = 'Vite'; return '';
if (has('next')) bundler = 'Next.js';
else if (has('@vue/cli-service') || has('react-scripts')) bundler = 'Webpack';
else if (has('nuxt')) bundler = 'Nuxt';
else if (has('@angular/core')) return 'Angular';
const lang = has('typescript') ? 'TypeScript' : 'JavaScript';
return `${lib}${ver} + ${bundler} + ${lang}`;
} }
function detectStyling(deps: Record<string, string>): string { function detectStyling(deps: Record<string, string>): string {
const has = (k: string) => k in deps; const has = (k: string) => k in deps;
const parts: string[] = []; const parts: string[] = [];
if (has('tailwindcss')) { if (has('tailwindcss')) parts.push('Tailwind CSS');
const v = deps['tailwindcss'] || ''; if (has('sass')) parts.push('Sass / SCSS');
parts.push(v.startsWith('^4') || v.startsWith('4') ? 'Tailwind CSS v4' : 'Tailwind CSS');
}
if (has('sass')) parts.push('Sass');
if (has('less')) parts.push('Less'); if (has('less')) parts.push('Less');
if (has('styled-components') || has('@emotion/react') || has('@emotion/styled')) parts.push('CSS-in-JS'); if (has('styled-components')) parts.push('styled-components');
if (has('@emotion/react') || has('@emotion/styled')) parts.push('Emotion');
if (has('@stitches/react')) parts.push('Stitches'); if (has('@stitches/react')) parts.push('Stitches');
if (parts.length === 0) parts.push('CSS Modules / 原生 CSS'); if (has('unocss')) parts.push('UnoCSS');
if (has('styled-jsx')) parts.push('Styled JSX');
// 未检测到样式依赖时不硬猜(CSS Modules 取决于构建配置,无法从依赖判断)
return parts.join(' + '); return parts.join(' + ');
} }
function detectComponentLibrary(deps: Record<string, string>): string { function detectComponentLibrary(deps: Record<string, string>): string {
const known: [string, string][] = [ const known: [string, string][] = [
['antd', 'Ant Design'], ['antd', 'Ant Design'],
['@mui/material', 'MUI'], ['@ant-design/pro-components', 'Ant Design'],
['@mui/material', 'Material UI (MUI)'],
['@chakra-ui/react', 'Chakra UI'], ['@chakra-ui/react', 'Chakra UI'],
['@nextui-org/react', 'NextUI'], ['@nextui-org/react', 'NextUI'],
['@arco-design/web-react', 'Arco Design'], ['@arco-design/web-react', 'Arco Design'],
['@ant-design/pro-components', 'Ant Design Pro'], ['@semi-design/react', 'Semi Design'],
['react-bootstrap', 'React Bootstrap'], ['react-bootstrap', 'React Bootstrap'],
['@mantine/core', 'Mantine'], ['@mantine/core', 'Mantine'],
['element-plus', 'Element Plus'], ['element-plus', 'Element Plus'],
['naive-ui', 'Naive UI'], ['naive-ui', 'Naive UI'],
['vant', 'Vant'], ['vant', 'Vant'],
['@headlessui/react', 'Headless UI'], ['@headlessui/react', 'Headless UI'],
['radix-ui', 'Radix'], ['@radix-ui/react', 'Radix UI'],
]; ];
const found = known.filter(([k]) => k in deps).map(([, label]) => label); const found = known.filter(([k]) => k in deps).map(([, label]) => label);
if (found.length === 0) return '无第三方组件库(原生元素 + 业务组件)'; if (found.length === 0) return '无(原生元素)';
return found.join(' / '); return found.join(' / ');
} }
/** 状态管理:能从依赖明确识别才填,否则留空让用户选。 */
function detectStateManagement(deps: Record<string, string>): string {
const has = (k: string) => k in deps;
if (has('@reduxjs/toolkit') || has('redux')) return 'Redux Toolkit';
if (has('zustand')) return 'Zustand';
if (has('jotai')) return 'Jotai';
if (has('recoil')) return 'Recoil';
if (has('mobx') || has('mobx-react') || has('mobx-react-lite')) return 'MobX';
if (has('pinia')) return 'Pinia';
if (has('vuex')) return 'Vuex';
return '';
}
/** 数据请求层:能从依赖明确识别才填,否则留空。 */
function detectDataFetching(deps: Record<string, string>): string {
const has = (k: string) => k in deps;
if (has('@tanstack/react-query') || has('react-query')) return 'React Query (TanStack Query)';
if (has('swr')) return 'SWR';
if (has('@apollo/client') || has('apollo-client') || has('@apollo/client/core')) return 'Apollo Client';
if (has('axios')) return 'Axios';
if (has('@vue/apollo-composable') || has('vue-query')) return 'Vue Query';
return '';
}
/** 路由:能从依赖明确识别才填,否则留空。 */
function detectRouting(deps: Record<string, string>): string {
const has = (k: string) => k in deps;
if (has('next')) return 'Next.js 路由';
if (has('nuxt') || has('@nuxt/kit')) return 'Nuxt 路由';
if (has('react-router') || has('react-router-dom')) return 'React Router';
if (has('vue-router')) return 'Vue Router';
if (has('@tanstack/router')) return 'TanStack Router';
if (has('@angular/router') || has('@angular/core')) return 'Angular Router';
return '';
}
/** Extract all local import specifiers from a source file. */ /** Extract all local import specifiers from a source file. */
function extractImportSpecifiers(code: string): string[] { function extractImportSpecifiers(code: string): string[] {
const specs: string[] = []; const specs: string[] = [];
...@@ -448,6 +487,9 @@ export function scanProject(rootDir: string): ScanResult { ...@@ -448,6 +487,9 @@ export function scanProject(rootDir: string): ScanResult {
const framework = detectFramework(deps); const framework = detectFramework(deps);
const styling = detectStyling(deps); const styling = detectStyling(deps);
const componentLibrary = detectComponentLibrary(deps); const componentLibrary = detectComponentLibrary(deps);
const stateManagement = detectStateManagement(deps);
const dataFetching = detectDataFetching(deps);
const routing = detectRouting(deps);
const projectName = path.basename(rootDir); const projectName = path.basename(rootDir);
const conventions = draftConventions({ const conventions = draftConventions({
...@@ -469,6 +511,9 @@ export function scanProject(rootDir: string): ScanResult { ...@@ -469,6 +511,9 @@ export function scanProject(rootDir: string): ScanResult {
language: 'typescript' in deps ? 'TypeScript' : 'JavaScript', language: 'typescript' in deps ? 'TypeScript' : 'JavaScript',
styling, styling,
componentLibrary, componentLibrary,
stateManagement,
dataFetching,
routing,
importAlias: alias ? `${alias.prefix}/` : undefined, importAlias: alias ? `${alias.prefix}/` : undefined,
landingPath: alias ? `${alias.prefix}/` + 'features/<page>/' : 'src/generated/', landingPath: alias ? `${alias.prefix}/` + 'features/<page>/' : 'src/generated/',
tokens, tokens,
......
...@@ -16,6 +16,8 @@ interface Props { ...@@ -16,6 +16,8 @@ interface Props {
placeholder?: string; placeholder?: string;
mono?: boolean; mono?: boolean;
hint?: string; hint?: string;
/** 输入框失焦回调(如用于触发自动扫描)。 */
onBlur?: () => void;
} }
/** /**
...@@ -30,6 +32,7 @@ export function DirectoryField({ ...@@ -30,6 +32,7 @@ export function DirectoryField({
placeholder, placeholder,
mono, mono,
hint, hint,
onBlur,
}: Props) { }: Props) {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
...@@ -49,6 +52,7 @@ export function DirectoryField({ ...@@ -49,6 +52,7 @@ export function DirectoryField({
<Input <Input
value={value} value={value}
onChange={(e) => onChange(e.target.value)} onChange={(e) => onChange(e.target.value)}
onBlur={onBlur}
placeholder={placeholder} placeholder={placeholder}
className={cn('flex-1', mono && 'font-mono text-[12px]')} className={cn('flex-1', mono && 'font-mono text-[12px]')}
/> />
......
...@@ -134,23 +134,28 @@ export function ProjectAccessPanel() { ...@@ -134,23 +134,28 @@ export function ProjectAccessPanel() {
[], [],
); );
const handleScan = useCallback(async () => { const handleScan = useCallback(async (auto = false, switchTab = !auto) => {
const dir = (rootDirDraft || profile?.rootDir || '').trim(); const dir = (rootDirDraft || profile?.rootDir || '').trim();
if (!dir) { if (!dir) {
toast.error('请先填写目标项目根目录'); if (!auto) toast.error('请先填写目标项目根目录');
return; return;
} }
setScanning(true); setScanning(true);
setWarnings([]); setWarnings([]);
try { try {
const r = await api.scanProjectProfile(dir); const r = await api.scanProjectProfile(dir);
const isSwitch = !!profile?.rootDir && profile.rootDir !== dir;
setProfile({ ...r.profile, rootDir: dir }); setProfile({ ...r.profile, rootDir: dir });
setPages(r.pages ?? []); setPages(r.pages ?? []);
setWarnings(r.warnings ?? []); setWarnings(r.warnings ?? []);
setExists(true); setExists(true);
setDirty(true); setDirty(true);
setTab('meta'); if (switchTab) setTab('meta');
toast.success('已生成项目画像草稿,请复核后保存'); toast.success(
auto && isSwitch
? '已根据项目自动填写画像,请复核后保存'
: '已生成项目画像草稿,请复核后保存',
);
} catch (e) { } catch (e) {
toast.error('扫描失败', { description: e instanceof Error ? e.message : String(e) }); toast.error('扫描失败', { description: e instanceof Error ? e.message : String(e) });
} finally { } finally {
...@@ -158,6 +163,17 @@ export function ProjectAccessPanel() { ...@@ -158,6 +163,17 @@ export function ProjectAccessPanel() {
} }
}, [rootDirDraft, profile]); }, [rootDirDraft, profile]);
// 工作目录变化(手填或选目录均触发)后自动扫描填一轮;与已配置根相同则不重复扫
useEffect(() => {
const dir = (rootDirDraft || '').trim();
if (!dir) return;
if (profile?.rootDir && profile.rootDir === dir) return;
const t = setTimeout(() => {
void handleScan(true, false);
}, 600);
return () => clearTimeout(t);
}, [rootDirDraft, profile, handleScan]);
const handleSave = useCallback(async () => { const handleSave = useCallback(async () => {
if (!profile) return; if (!profile) return;
setSaving(true); setSaving(true);
...@@ -246,13 +262,13 @@ export function ProjectAccessPanel() { ...@@ -246,13 +262,13 @@ export function ProjectAccessPanel() {
onChange={setRootDirDraft} onChange={setRootDirDraft}
placeholder="例如 D:/work/company/fe-project" placeholder="例如 D:/work/company/fe-project"
mono mono
hint="可手动输入,或点「浏览…」从本机选择真实目录" hint="填好目录后自动扫描并填写画像,有出入可手动修改"
/> />
</div> </div>
<Button <Button
variant="outline" variant="outline"
className="h-10" className="h-10"
onClick={handleScan} onClick={() => handleScan()}
disabled={scanning} disabled={scanning}
> >
{scanning ? ( {scanning ? (
...@@ -362,7 +378,7 @@ export function ProjectAccessPanel() { ...@@ -362,7 +378,7 @@ export function ProjectAccessPanel() {
{dirty ? '有未保存的修改' : '已保存至服务端(生成时自动生效,无需重启)'} {dirty ? '有未保存的修改' : '已保存至服务端(生成时自动生效,无需重启)'}
</span> </span>
<div className="flex gap-2"> <div className="flex gap-2">
<Button variant="ghost" onClick={handleScan} disabled={scanning}> <Button variant="ghost" onClick={() => handleScan()} disabled={scanning}>
<RefreshCw className={cn('h-4 w-4', scanning && 'animate-spin')} /> 重新扫描 <RefreshCw className={cn('h-4 w-4', scanning && 'animate-spin')} /> 重新扫描
</Button> </Button>
<Button onClick={handleSave} disabled={saving || !dirty}> <Button onClick={handleSave} disabled={saving || !dirty}>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!