ProjectAccessPanel.tsx 27.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
import { useCallback, useEffect, useMemo, useState } from 'react';
import { toast } from 'sonner';
import {
  FolderSearch,
  Save,
  Plus,
  Trash2,
  RefreshCw,
  Boxes,
  Wrench,
  Palette,
  FileText,
  Info,
  AlertTriangle,
  CheckCircle2,
  Layers,
  Play,
  Square,
  ExternalLink,
  Loader2,
} from 'lucide-react';
import { api, onSSE } from '@/lib/api';
import type {
  ProjectProfile,
  ProjectRunState,
  TokenCategory,
  TokenMapping,
  ComponentMapping,
  UtilMapping,
} from '@/lib/types';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';
import { DirectoryField } from './DirectoryField';
import { Combobox } from './Combobox';
import {
  FRAMEWORK_PRESETS,
  LANGUAGE_PRESETS,
  STYLING_PRESETS,
  COMPONENT_LIBRARY_PRESETS,
  STATE_MANAGEMENT_PRESETS,
  DATA_FETCHING_PRESETS,
  ROUTING_PRESETS,
} from './profile-presets';

type TabKey = 'meta' | 'components' | 'utils' | 'tokens' | 'conventions';

const TOKEN_CATEGORIES: TokenCategory[] = [
  'color',
  'radius',
  'spacing',
  'fontSize',
  'fontFamily',
  'shadow',
  'other',
];

const TABS: { key: TabKey; label: string; icon: typeof Boxes }[] = [
  { key: 'meta', label: '概览', icon: Info },
  { key: 'components', label: '组件', icon: Boxes },
  { key: 'utils', label: '工具 / Hook', icon: Wrench },
  { key: 'tokens', label: '设计令牌', icon: Palette },
  { key: 'conventions', label: '约束 (CODERIO.md)', icon: FileText },
];

function emptyProfile(): ProjectProfile {
  return {
    projectName: '',
    rootDir: '',
    framework: '',
    styling: '',
    componentLibrary: '',
    importAlias: '@/',
    landingPath: 'src/generated/',
    tokens: [],
    components: [],
    utils: [],
    conventions: '',
    lastScannedAt: undefined,
  };
}

export function ProjectAccessPanel() {
  const [profile, setProfile] = useState<ProjectProfile | null>(null);
  const [exists, setExists] = useState(false);
  const [loading, setLoading] = useState(true);
  const [scanning, setScanning] = useState(false);
  const [saving, setSaving] = useState(false);
  const [warnings, setWarnings] = useState<string[]>([]);
  const [pages, setPages] = useState<string[]>([]);
  const [tab, setTab] = useState<TabKey>('meta');
  const [dirty, setDirty] = useState(false);
  const [rootDirDraft, setRootDirDraft] = useState('');
  const [run, setRun] = useState<ProjectRunState | null>(null);
  const [runBusy, setRunBusy] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const r = await api.getProjectProfile();
      setExists(r.exists);
      setProfile(r.profile ?? emptyProfile());
      setRootDirDraft(r.profile?.rootDir ?? '');
    } catch {
      setProfile(emptyProfile());
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  // 初始拉一次目标项目运行态作为快照;随后完全由 SSE 的 'projectRun' 事件推送更新,
  // 不再使用任何 setInterval 轮询(ProjectRunner 在启动 / 停止 / 端口识别时都会 broadcast 该事件)。
  useEffect(() => {
    let alive = true;
    api.getProjectRun().then((s) => { if (alive) setRun(s); }).catch(() => {});
    return () => { alive = false; };
  }, []);

  useEffect(() => {
    return onSSE('projectRun', (data) => setRun(data as ProjectRunState));
  }, []);

  const runDir = (rootDirDraft || profile?.rootDir || '').trim();

  const handleRun = useCallback(async () => {
    if (!runDir) {
      toast.error('请先选择工作目录');
      return;
    }
    setRunBusy(true);
    try {
      const r = await api.startProject(runDir);
      if (r.ok) toast.success('正在启动目标项目…(识别到端口后会自动显示)');
      else toast.error('启动失败', { description: r.error });
    } catch (e) {
      toast.error('启动失败', { description: e instanceof Error ? e.message : String(e) });
    } finally {
      setRunBusy(false);
    }
  }, [runDir]);

  const handleStop = useCallback(async () => {
    setRunBusy(true);
    try {
      await api.stopProject();
      toast.success('已停止目标项目');
    } catch (e) {
      toast.error('停止失败', { description: e instanceof Error ? e.message : String(e) });
    } finally {
      setRunBusy(false);
    }
  }, []);

  const update = useCallback((patch: Partial<ProjectProfile>) => {
    setProfile((p) => (p ? { ...p, ...patch } : p));
    setDirty(true);
  }, []);

  const setComponents = useCallback(
    (fn: (prev: ComponentMapping[]) => ComponentMapping[]) => {
      setProfile((p) => (p ? { ...p, components: fn(p.components) } : p));
      setDirty(true);
    },
    [],
  );
  const setUtils = useCallback(
    (fn: (prev: UtilMapping[]) => UtilMapping[]) => {
      setProfile((p) => (p ? { ...p, utils: fn(p.utils) } : p));
      setDirty(true);
    },
    [],
  );
  const setTokens = useCallback(
    (fn: (prev: TokenMapping[]) => TokenMapping[]) => {
      setProfile((p) => (p ? { ...p, tokens: fn(p.tokens) } : p));
      setDirty(true);
    },
    [],
  );

  const handleScan = useCallback(async (auto = false, switchTab = !auto) => {
    const dir = (rootDirDraft || profile?.rootDir || '').trim();
    if (!dir) {
      if (!auto) toast.error('请先填写目标项目根目录');
      return;
    }
    setScanning(true);
    setWarnings([]);
    try {
      const r = await api.scanProjectProfile(dir);
      const isSwitch = !!profile?.rootDir && profile.rootDir !== dir;
      setProfile({ ...r.profile, rootDir: dir });
      setPages(r.pages ?? []);
      setWarnings(r.warnings ?? []);
      setExists(true);
      setDirty(true);
      if (switchTab) setTab('meta');
      toast.success(
        auto && isSwitch
          ? '已根据项目自动填写画像,请复核后保存'
          : '已生成项目画像草稿,请复核后保存',
      );
    } catch (e) {
      toast.error('扫描失败', { description: e instanceof Error ? e.message : String(e) });
    } finally {
      setScanning(false);
    }
  }, [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 () => {
    if (!profile) return;
    setSaving(true);
    try {
      await api.putProjectProfile(profile);
      setDirty(false);
      toast.success('项目画像已保存');
    } catch (e) {
      toast.error('保存失败', { description: e instanceof Error ? e.message : String(e) });
    } finally {
      setSaving(false);
    }
  }, [profile]);

  const summary = useMemo(() => {
    if (!profile) return null;
    return {
      components: profile.components.length,
      utils: profile.utils.length,
      tokens: profile.tokens.length,
    };
  }, [profile]);

  const drift = useMemo(() => {
    if (!profile?.lastScannedAt) return null;
    const diff = Date.now() - new Date(profile.lastScannedAt).getTime();
    const days = Math.floor(diff / 86400000);
    if (days <= 0) return { tone: 'ok' as const, text: '刚刚扫描' };
    if (days <= 7) return { tone: 'ok' as const, text: `${days} 天前扫描` };
    return { tone: 'warn' as const, text: `${days} 天前扫描,可能已过时` };
  }, [profile?.lastScannedAt]);

  if (loading || !profile) {
    return (
      <section className="rounded-2xl border border-border bg-card p-5">
        <div className="h-40 animate-pulse rounded-xl bg-muted/60" />
      </section>
    );
  }

  return (
    <section className="rounded-2xl border border-border bg-card p-5">
      <div className="mb-4 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Layers className="h-4 w-4 text-primary" />
          <h3 className="text-sm font-semibold">项目接入(画像)</h3>
        </div>
        <div className="flex items-center gap-2">
          {exists ? (
            <Badge variant="success" className="px-2 py-0.5">
              已配置
            </Badge>
          ) : (
            <Badge variant="neutral" className="px-2 py-0.5">
              未配置
            </Badge>
          )}
          {drift ? (
            <span
              className={cn(
                'flex items-center gap-1 text-xs',
                drift.tone === 'ok' ? 'text-emerald-500' : 'text-amber-500',
              )}
            >
              {drift.tone === 'ok' ? (
                <CheckCircle2 className="h-3 w-3" />
              ) : (
                <AlertTriangle className="h-3 w-3" />
              )}
              {drift.text}
            </span>
          ) : null}
        </div>
      </div>

      <p className="mb-4 text-xs text-muted-foreground">
        设置目标项目根目录后一键扫描其组件库、设计令牌与公共能力,生成「画像」约束后续代码生成,让产出像团队手写的而非通用脚手架。
      </p>

      {/* Working directory + scan */}
      <div className="flex flex-col gap-2 sm:flex-row sm:items-end">
        <div className="flex-1">
          <DirectoryField
            label="工作目录(目标项目根)"
            value={rootDirDraft}
            onChange={setRootDirDraft}
            placeholder="例如 D:/work/company/fe-project"
            mono
            hint="填好目录后自动扫描并填写画像,有出入可手动修改"
          />
        </div>
        <Button
          variant="outline"
          className="h-10"
          onClick={() => handleScan()}
          disabled={scanning}
        >
          {scanning ? (
            <RefreshCw className="h-4 w-4 animate-spin" />
          ) : (
            <FolderSearch className="h-4 w-4" />
          )}
          {scanning ? '扫描中…' : '生成画像'}
        </Button>
      </div>

      {/* 启动目标项目 */}
      <div className="mt-3 flex flex-col gap-2 rounded-xl border border-border bg-muted/30 p-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex min-w-0 items-center gap-2 text-xs">
          <Play className="h-3.5 w-3.5 text-primary" />
          <span className="font-medium">目标项目</span>
          {run?.running ? (
            <Badge variant="success" className="px-2 py-0.5">运行中</Badge>
          ) : (
            <Badge variant="neutral" className="px-2 py-0.5">已停止</Badge>
          )}
          {run?.script && (
            <span className="truncate font-mono text-muted-foreground">
              {run.manager} run {run.script}
            </span>
          )}
          {run?.localUrl && (
            <a href={run.localUrl} target="_blank" rel="noreferrer" className="truncate font-mono text-primary hover:underline">
              {run.localUrl}
            </a>
          )}
          {run?.error && !run.running && (
            <span className="truncate text-rose-500">{run.error}</span>
          )}
        </div>
        <div className="flex shrink-0 items-center gap-2">
          {!run?.running ? (
            <Button size="sm" onClick={handleRun} disabled={runBusy || !runDir}>
              {runBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
              启动项目
            </Button>
          ) : (
            <Button size="sm" variant="destructive" onClick={handleStop} disabled={runBusy}>
              {runBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Square className="h-4 w-4" />}
              停止
            </Button>
          )}
          {run?.localUrl && (
            <a
              href={run.localUrl}
              target="_blank"
              rel="noreferrer"
              className="flex h-8 w-8 items-center justify-center rounded-lg border border-border text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
              title="新窗口打开"
            >
              <ExternalLink className="h-4 w-4" />
            </a>
          )}
        </div>
      </div>

      {summary && (profile.components.length || profile.utils.length || profile.tokens.length) ? (
        <div className="mt-3 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
          <span>已识别</span>
          <Badge variant="neutral" className="px-2 py-0.5">{summary.components} 组件</Badge>
          <Badge variant="neutral" className="px-2 py-0.5">{summary.utils} 工具</Badge>
          <Badge variant="neutral" className="px-2 py-0.5">{summary.tokens} 令牌</Badge>
          {profile.framework && <span>· {profile.framework}</span>}
          {profile.styling && <span>· {profile.styling}</span>}
        </div>
      ) : null}

      {warnings.length > 0 ? (
        <div className="mt-3 space-y-1.5">
          {warnings.map((w, i) => (
            <div
              key={i}
              className="flex items-start gap-2 rounded-lg border border-amber-500/25 bg-amber-500/5 p-2.5 text-xs text-amber-600 dark:text-amber-400"
            >
              <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
              <span className="break-all">{w}</span>
            </div>
          ))}
        </div>
      ) : null}

      {pages.length > 0 ? (
        <div className="mt-3 rounded-lg border border-border bg-muted/40 p-2.5">
          <div className="mb-1.5 text-xs font-medium text-muted-foreground">
            已枚举页面 / 路由({pages.length})
          </div>
          <div className="flex flex-wrap gap-1.5">
            {pages.slice(0, 24).map((p) => (
              <span
                key={p}
                className="rounded-md bg-card px-2 py-0.5 font-mono text-[11px] text-muted-foreground"
              >
                {p}
              </span>
            ))}
          </div>
        </div>
      ) : null}

      {/* Tabs */}
      <div className="mt-4 flex flex-wrap gap-1.5 border-b border-border pb-2">
        {TABS.map((t) => {
          const Icon = t.icon;
          const active = tab === t.key;
          return (
            <button
              key={t.key}
              onClick={() => setTab(t.key)}
              className={cn(
                'flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium transition-colors',
                active
                  ? 'bg-primary/15 text-primary'
                  : 'text-muted-foreground hover:bg-accent hover:text-foreground',
              )}
            >
              <Icon className="h-3.5 w-3.5" />
              {t.label}
              {t.key === 'components' && profile.components.length ? (
                <span className="text-[10px] opacity-70">{profile.components.length}</span>
              ) : null}
              {t.key === 'utils' && profile.utils.length ? (
                <span className="text-[10px] opacity-70">{profile.utils.length}</span>
              ) : null}
              {t.key === 'tokens' && profile.tokens.length ? (
                <span className="text-[10px] opacity-70">{profile.tokens.length}</span>
              ) : null}
            </button>
          );
        })}
      </div>

      <div className="mt-4">
        {tab === 'meta' && (
          <MetaEditor profile={profile} update={update} />
        )}
        {tab === 'components' && (
          <ComponentTable
            items={profile.components}
            setItems={setComponents}
          />
        )}
        {tab === 'utils' && <UtilTable items={profile.utils} setItems={setUtils} />}
        {tab === 'tokens' && <TokenTable items={profile.tokens} setItems={setTokens} />}
        {tab === 'conventions' && (
          <ConventionsEditor value={profile.conventions ?? ''} onChange={(v) => update({ conventions: v })} />
        )}
      </div>

      {/* Save bar */}
      <div className="mt-5 flex items-center justify-between border-t border-border pt-4">
        <span className="text-xs text-muted-foreground">
          {dirty ? '有未保存的修改' : '已保存至服务端(生成时自动生效,无需重启)'}
        </span>
        <div className="flex gap-2">
          <Button variant="ghost" onClick={() => handleScan()} disabled={scanning}>
            <RefreshCw className={cn('h-4 w-4', scanning && 'animate-spin')} /> 重新扫描
          </Button>
          <Button onClick={handleSave} disabled={saving || !dirty}>
            {saving ? <RefreshCw className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
            保存画像
          </Button>
        </div>
      </div>
    </section>
  );
}

/* ----------------------------- editors ----------------------------- */

function MetaEditor({
  profile,
  update,
}: {
  profile: ProjectProfile;
  update: (patch: Partial<ProjectProfile>) => void;
}) {
  const combos: {
    key: keyof ProjectProfile;
    label: string;
    placeholder: string;
    options: string[];
  }[] = [
    { key: 'framework', label: '技术栈 / 框架', placeholder: 'React 18', options: FRAMEWORK_PRESETS },
    { key: 'language', label: '语言', placeholder: 'TypeScript', options: LANGUAGE_PRESETS },
    { key: 'styling', label: '样式策略', placeholder: 'Tailwind CSS', options: STYLING_PRESETS },
    {
      key: 'componentLibrary',
      label: '组件库',
      placeholder: 'Ant Design',
      options: COMPONENT_LIBRARY_PRESETS,
    },
    {
      key: 'stateManagement',
      label: '状态管理',
      placeholder: 'Zustand',
      options: STATE_MANAGEMENT_PRESETS,
    },
    {
      key: 'dataFetching',
      label: '数据请求',
      placeholder: 'React Query',
      options: DATA_FETCHING_PRESETS,
    },
    { key: 'routing', label: '路由', placeholder: 'React Router', options: ROUTING_PRESETS },
  ];
  const texts: { key: keyof ProjectProfile; label: string; placeholder: string; mono?: boolean }[] = [
    { key: 'projectName', label: '项目名', placeholder: 'A 项目' },
    { key: 'importAlias', label: '导入别名', placeholder: '@/', mono: true },
  ];
  const rootForLanding = profile.rootDir || '';
  return (
    <div className="space-y-3">
      <div className="grid gap-3 sm:grid-cols-2">
        {texts.map((f) => (
          <div key={f.key} className="space-y-1.5">
            <Label className="text-xs">{f.label}</Label>
            <Input
              className={cn('h-9', f.mono && 'font-mono text-[12px]')}
              value={(profile[f.key] as string) ?? ''}
              placeholder={f.placeholder}
              onChange={(e) => update({ [f.key]: e.target.value } as Partial<ProjectProfile>)}
            />
          </div>
        ))}
        {combos.map((f) => (
          <div key={f.key} className="space-y-1.5">
            <Label className="text-xs">{f.label}</Label>
            <Combobox
              value={(profile[f.key] as string) ?? ''}
              onChange={(v) => update({ [f.key]: v } as Partial<ProjectProfile>)}
              options={f.options}
              placeholder={f.placeholder}
            />
          </div>
        ))}
      </div>
      <DirectoryField
        label="落地路径(生成代码存放处)"
        value={profile.landingPath ?? ''}
        onChange={(v) => update({ landingPath: v })}
        relativeTo={rootForLanding}
        mono
        placeholder="src/features/<page>/"
        hint="位于项目根内时自动存为相对路径;也可选绝对目录"
      />
    </div>
  );
}

function RowHeader({ children }: { children: React.ReactNode }) {
  return (
    <div className="grid grid-cols-[1.4fr_2fr_2fr_auto] items-center gap-2 px-1 text-[11px] font-medium text-muted-foreground">
      {children}
    </div>
  );
}

function ComponentTable({
  items,
  setItems,
}: {
  items: ComponentMapping[];
  setItems: (fn: (prev: ComponentMapping[]) => ComponentMapping[]) => void;
}) {
  return (
    <div className="space-y-2">
      <RowHeader>
        <span>组件名</span>
        <span>导入路径</span>
        <span>说明</span>
        <span />
      </RowHeader>
      <div className="max-h-[340px] space-y-2 overflow-auto pr-1">
        {items.length === 0 ? (
          <div className="rounded-xl border border-dashed border-border p-6 text-center text-sm text-muted-foreground">
            暂无组件,点击「添加」手动补充,或先执行「生成画像」自动扫描。
          </div>
        ) : (
          items.map((c, i) => (
            <div key={i} className="grid grid-cols-[1.4fr_2fr_2fr_auto] items-center gap-2">
              <Input
                className="h-9"
                value={c.name}
                placeholder="Button"
                onChange={(e) =>
                  setItems((prev) => prev.map((x, j) => (j === i ? { ...x, name: e.target.value } : x)))
                }
              />
              <Input
                className="h-9 font-mono text-[12px]"
                value={c.importPath}
                placeholder="@/components/ui/button"
                onChange={(e) =>
                  setItems((prev) => prev.map((x, j) => (j === i ? { ...x, importPath: e.target.value } : x)))
                }
              />
              <Input
                className="h-9"
                value={c.description ?? ''}
                placeholder="主操作按钮"
                onChange={(e) =>
                  setItems((prev) => prev.map((x, j) => (j === i ? { ...x, description: e.target.value } : x)))
                }
              />
              <IconBtn
                onClick={() => setItems((prev) => prev.filter((_, j) => j !== i))}
                title="删除"
              />
            </div>
          ))
        )}
      </div>
      <Button
        variant="outline"
        size="sm"
        className="h-8"
        onClick={() => setItems((prev) => [...prev, { name: '', importPath: '', description: '', exportType: 'named' }])}
      >
        <Plus className="h-3.5 w-3.5" /> 添加组件
      </Button>
    </div>
  );
}

function UtilTable({
  items,
  setItems,
}: {
  items: UtilMapping[];
  setItems: (fn: (prev: UtilMapping[]) => UtilMapping[]) => void;
}) {
  return (
    <div className="space-y-2">
      <RowHeader>
        <span>名称</span>
        <span>导入路径</span>
        <span>说明</span>
        <span />
      </RowHeader>
      <div className="max-h-[340px] space-y-2 overflow-auto pr-1">
        {items.length === 0 ? (
          <div className="rounded-xl border border-dashed border-border p-6 text-center text-sm text-muted-foreground">
            暂无工具 / Hook。
          </div>
        ) : (
          items.map((u, i) => (
            <div key={i} className="grid grid-cols-[1.4fr_2fr_2fr_auto] items-center gap-2">
              <Input
                className="h-9"
                value={u.name}
                placeholder="useAuth"
                onChange={(e) => setItems((prev) => prev.map((x, j) => (j === i ? { ...x, name: e.target.value } : x)))}
              />
              <Input
                className="h-9 font-mono text-[12px]"
                value={u.importPath}
                placeholder="@/hooks/useAuth"
                onChange={(e) => setItems((prev) => prev.map((x, j) => (j === i ? { ...x, importPath: e.target.value } : x)))}
              />
              <Input
                className="h-9"
                value={u.description ?? ''}
                placeholder="鉴权 Hook"
                onChange={(e) => setItems((prev) => prev.map((x, j) => (j === i ? { ...x, description: e.target.value } : x)))}
              />
              <IconBtn onClick={() => setItems((prev) => prev.filter((_, j) => j !== i))} title="删除" />
            </div>
          ))
        )}
      </div>
      <Button
        variant="outline"
        size="sm"
        className="h-8"
        onClick={() => setItems((prev) => [...prev, { name: '', importPath: '', description: '' }])}
      >
        <Plus className="h-3.5 w-3.5" /> 添加工具
      </Button>
    </div>
  );
}

function TokenTable({
  items,
  setItems,
}: {
  items: TokenMapping[];
  setItems: (fn: (prev: TokenMapping[]) => TokenMapping[]) => void;
}) {
  return (
    <div className="space-y-2">
      <RowHeader>
        <span>名称</span>
        <span>引用 (code)</span>
        <span>分类 / 值</span>
        <span />
      </RowHeader>
      <div className="max-h-[340px] space-y-2 overflow-auto pr-1">
        {items.length === 0 ? (
          <div className="rounded-xl border border-dashed border-border p-6 text-center text-sm text-muted-foreground">
            暂无设计令牌(CSS 变量)。
          </div>
        ) : (
          items.map((t, i) => (
            <div key={i} className="grid grid-cols-[1.4fr_2fr_2fr_auto] items-center gap-2">
              <Input
                className="h-9"
                value={t.name}
                placeholder="brand.primary"
                onChange={(e) => setItems((prev) => prev.map((x, j) => (j === i ? { ...x, name: e.target.value } : x)))}
              />
              <Input
                className="h-9 font-mono text-[12px]"
                value={t.code}
                placeholder="var(--color-brand)"
                onChange={(e) => setItems((prev) => prev.map((x, j) => (j === i ? { ...x, code: e.target.value } : x)))}
              />
              <div className="flex items-center gap-1.5">
                <select
                  className="h-9 flex-1 rounded-lg border border-border bg-card px-2 text-xs text-foreground"
                  value={t.category}
                  onChange={(e) =>
                    setItems((prev) =>
                      prev.map((x, j) => (j === i ? { ...x, category: e.target.value as TokenCategory } : x)),
                    )
                  }
                >
                  {TOKEN_CATEGORIES.map((c) => (
                    <option key={c} value={c}>
                      {c}
                    </option>
                  ))}
                </select>
                <Input
                  className="h-9 w-20"
                  value={t.value ?? ''}
                  placeholder="#2563eb"
                  onChange={(e) => setItems((prev) => prev.map((x, j) => (j === i ? { ...x, value: e.target.value } : x)))}
                />
              </div>
              <IconBtn onClick={() => setItems((prev) => prev.filter((_, j) => j !== i))} title="删除" />
            </div>
          ))
        )}
      </div>
      <Button
        variant="outline"
        size="sm"
        className="h-8"
        onClick={() => setItems((prev) => [...prev, { name: '', code: '', value: '', category: 'other' }])}
      >
        <Plus className="h-3.5 w-3.5" /> 添加令牌
      </Button>
    </div>
  );
}

function ConventionsEditor({
  value,
  onChange,
}: {
  value: string;
  onChange: (v: string) => void;
}) {
  return (
    <div className="space-y-2">
      <p className="text-xs text-muted-foreground">
        以 Markdown 编写团队约束,将作为系统指令注入 CODE 节点(命名、目录、状态管理、i18n、禁止项等)。保存后自动生效。
      </p>
      <textarea
        className="h-[320px] w-full resize-none rounded-xl border border-border bg-[#0b0e14] p-3 font-mono text-[12px] leading-relaxed text-zinc-100 outline-none focus:border-primary/50"
        value={value}
        placeholder="# 生成约束(CODERIO.md)&#10;&#10;- 目标项目:&#10;- 组件优先:&#10;- 设计令牌:"
        onChange={(e) => onChange(e.target.value)}
      />
    </div>
  );
}

function IconBtn({
  onClick,
  title,
}: {
  onClick: () => void;
  title: string;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      title={title}
      className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border text-muted-foreground transition-colors hover:border-rose-500/40 hover:bg-rose-500/10 hover:text-rose-400"
    >
      <Trash2 className="h-4 w-4" />
    </button>
  );
}