DirectoryField.tsx 2.15 KB
import { useState } from 'react';
import { FolderOpen } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';
import { DirectoryPickerDialog } from './DirectoryPickerDialog';
import { relativePath, resolveStartDir } from './profile-presets';

interface Props {
  label: string;
  value: string;
  onChange: (v: string) => void;
  /** 相对基准目录:若选中目录位于其内,则存储相对路径(更通用)。 */
  relativeTo?: string;
  placeholder?: string;
  mono?: boolean;
  hint?: string;
  /** 输入框失焦回调(如用于触发自动扫描)。 */
  onBlur?: () => void;
}

/**
 * 目录输入:文本可手填,也可点「浏览…」打开服务端目录选择器选真实绝对路径。
 * 若提供 relativeTo(如项目根),选中目录在其内部时存为相对路径。
 */
export function DirectoryField({
  label,
  value,
  onChange,
  relativeTo,
  placeholder,
  mono,
  hint,
  onBlur,
}: Props) {
  const [open, setOpen] = useState(false);

  const startDir = resolveStartDir(value, relativeTo);

  const handlePick = (abs: string) => {
    onChange(relativePath(relativeTo ?? '', abs));
    setOpen(false);
  };

  return (
    <div className="space-y-1.5">
      <Label className="flex items-center gap-1.5 text-xs">
        <FolderOpen className="h-3.5 w-3.5 text-primary" /> {label}
      </Label>
      <div className="flex gap-2">
        <Input
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onBlur={onBlur}
          placeholder={placeholder}
          className={cn('flex-1', mono && 'font-mono text-[12px]')}
        />
        <Button variant="outline" className="h-9 shrink-0" onClick={() => setOpen(true)}>
          <FolderOpen className="h-4 w-4" /> 浏览…
        </Button>
      </div>
      {hint ? <p className="text-[11px] text-muted-foreground">{hint}</p> : null}
      <DirectoryPickerDialog
        open={open}
        initialDir={startDir}
        onClose={() => setOpen(false)}
        onPick={handlePick}
      />
    </div>
  );
}