DirectoryPickerDialog.tsx 7.25 KB
import { useCallback, useEffect, useState } from 'react';
import {
  X,
  ChevronRight,
  CornerUpLeft,
  FolderOpen,
  Check,
  Loader2,
} from 'lucide-react';
import { api } from '@/lib/api';
import type { FsListResult } from '@/lib/types';
import { joinPath } from './profile-presets';

interface Props {
  open: boolean;
  initialDir?: string;
  onClose: () => void;
  onPick: (absPath: string) => void;
}

/**
 * 服务端文件系统导航弹窗。通过 GET /api/fs/list 逐层浏览,最终选中一个
 * 真实绝对路径。无法用浏览器原生 <input webkitdirectory>(拿不到真实路径),
 * 因此由服务端枚举目录。
 */
export function DirectoryPickerDialog({ open, initialDir, onClose, onPick }: Props) {
  const [current, setCurrent] = useState<string | undefined>(initialDir);
  const [data, setData] = useState<FsListResult | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [manual, setManual] = useState('');

  const load = useCallback(async (dir?: string) => {
    setLoading(true);
    setError(null);
    try {
      const r = await api.fsList(dir);
      setData(r);
      setCurrent(r.path ?? undefined);
      setManual(r.path ?? '');
    } catch (e) {
      setError(e instanceof Error ? e.message : '读取目录失败');
    } finally {
      setLoading(false);
    }
  }, []);

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

  if (!open) return null;

  const enter = (name: string) => {
    const next = current ? joinPath(current, name) : name;
    void load(next);
  };

  const goUp = () => {
    if (data?.parent) void load(data.parent);
  };

  const goManual = () => {
    const v = manual.trim();
    if (v) void load(v);
  };

  // 面包屑分段(Windows 盘符 + 各级目录)
  const segments: { label: string; path: string }[] = [];
  if (current) {
    const norm = current.replace(/\//g, '\\').replace(/\\+$/, '');
    const driveMatch = norm.match(/^[a-zA-Z]:/);
    let acc = '';
    if (driveMatch) {
      acc = driveMatch[0] + '\\';
      segments.push({ label: acc, path: acc });
    }
    const rest = norm.slice(acc.length).split('\\').filter(Boolean);
    for (const part of rest) {
      acc = acc ? `${acc}\\${part}` : part;
      segments.push({ label: part, path: acc });
    }
  }

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
      onClick={onClose}
    >
      <div
        className="flex max-h-[80vh] w-full max-w-2xl flex-col overflow-hidden rounded-2xl border border-border bg-card shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between border-b border-border px-4 py-3">
          <div className="flex items-center gap-2 text-sm font-semibold">
            <FolderOpen className="h-4 w-4 text-primary" /> 选择目录
          </div>
          <button
            onClick={onClose}
            className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        {/* 面包屑 + 上级 */}
        <div className="flex items-center gap-1 border-b border-border px-4 py-2 text-[11px]">
          <button
            onClick={goUp}
            disabled={!data?.parent}
            className="flex items-center gap-1 rounded-md px-1.5 py-1 text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-40"
          >
            <CornerUpLeft className="h-3.5 w-3.5" /> 上级
          </button>
          <div className="flex flex-1 flex-wrap items-center gap-0.5 overflow-auto">
            {segments.length === 0 ? (
              <span className="text-muted-foreground">此电脑</span>
            ) : (
              segments.map((s, i) => (
                <span key={s.path} className="flex items-center">
                  {i > 0 && <ChevronRight className="h-3 w-3 text-muted-foreground/50" />}
                  <button
                    onClick={() => void load(s.path)}
                    className="rounded px-1 py-0.5 font-mono text-muted-foreground hover:bg-accent hover:text-foreground"
                  >
                    {s.label}
                  </button>
                </span>
              ))
            )}
          </div>
        </div>

        {/* 手动输入 */}
        <div className="flex items-center gap-2 border-b border-border px-4 py-2">
          <input
            value={manual}
            onChange={(e) => setManual(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter') goManual();
            }}
            placeholder="或直接输入路径,如 D:\\work\\company\\fe"
            className="h-9 flex-1 rounded-lg border border-border bg-background px-3 font-mono text-[12px] outline-none focus:border-primary/50"
          />
          <button
            onClick={goManual}
            className="h-9 rounded-lg border border-border px-3 text-xs hover:bg-accent"
          >
            前往
          </button>
        </div>

        {/* 目录列表 */}
        <div className="flex-1 overflow-auto p-2">
          {loading ? (
            <div className="flex items-center justify-center gap-2 py-10 text-sm text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" /> 读取中…
            </div>
          ) : error ? (
            <div className="py-10 text-center text-sm text-rose-500">{error}</div>
          ) : data && data.dirs.length === 0 ? (
            <div className="py-10 text-center text-sm text-muted-foreground">该目录下没有子文件夹</div>
          ) : (
            <div className="grid grid-cols-2 gap-1 sm:grid-cols-3">
              {data?.dirs.map((d) => (
                <button
                  key={d}
                  onClick={() => enter(d)}
                  className="flex items-center gap-2 rounded-lg border border-border bg-background/40 px-3 py-2 text-left text-[12px] hover:border-primary/40 hover:bg-primary/5"
                >
                  <FolderOpen className="h-4 w-4 shrink-0 text-primary/70" />
                  <span className="truncate font-mono">{d}</span>
                </button>
              ))}
            </div>
          )}
        </div>

        {/* 底部:当前路径 + 选择 */}
        <div className="flex items-center justify-between gap-3 border-t border-border px-4 py-3">
          <span className="min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground">
            {current || '此电脑'}
          </span>
          <div className="flex gap-2">
            <button
              onClick={onClose}
              className="h-9 rounded-lg border border-border px-3 text-xs hover:bg-accent"
            >
              取消
            </button>
            <button
              onClick={() => current && onPick(current)}
              disabled={!current}
              className="flex h-9 items-center gap-1.5 rounded-lg bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-40"
            >
              <Check className="h-3.5 w-3.5" /> 选择此目录
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}