hit-cxf
2026-04-23 2f48fc1d4c80a4c25a04d5f4e1e6c19fbb3528db
aigc-director/aigc-claw/frontend/components/HomePage.tsx
@@ -1,7 +1,7 @@
'use client';
'use client';
import React, { useState } from 'react';
import { Sparkles, Play, Settings2, Clock, ArrowRight, Zap, CheckCircle, Trash2, X, Lock, Globe } from 'lucide-react';
import React, { useState, useRef } from 'react';
import { Sparkles, Play, Settings2, Clock, ArrowRight, Zap, CheckCircle, Trash2, X, Lock, Globe, ListOrdered, Upload, Loader2 } from 'lucide-react';
import clsx from 'clsx';
import { PROMPT_EXAMPLES } from '@/config/examples';
import { LLM_MODELS, T2I_MODELS, I2I_MODELS, VIDEO_MODELS, VLM_MODELS, STYLES, VIDEO_RATIOS, LLM_PROVIDERS, T2I_PROVIDERS, I2I_PROVIDERS, VIDEO_PROVIDERS, VLM_PROVIDERS, ProviderGroup } from '@/config/models';
@@ -9,6 +9,7 @@
export interface ProjectParams {
  idea: string;
  file_path?: string; // 上传的文件路径 (由后端返回的文件名)
  style: string;
  video_ratio: string;
  llm_model: string;
@@ -19,6 +20,7 @@
  expand_idea?: boolean;
  enable_concurrency?: boolean;
  web_search?: boolean;
  episodes?: number;
}
interface HistoryItem {
@@ -27,7 +29,7 @@
  style?: string;
  date: string;
  status: string;
  stages?: string[];
  stages?: Record<string, string>;
}
interface HomePageProps {
@@ -37,15 +39,18 @@
  history: HistoryItem[];
}
/* 根据 stages_completed 生成进度文本 */
function stageProgressLabel(stages?: string[]): { text: string; color: string } {
  if (!stages || stages.length === 0) return { text: '未开始', color: 'text-gray-400' };
  if (stages.length >= STAGES.length) return { text: '已完成', color: 'text-green-600' };
  // 显示最后完成的阶段名称
  const lastStageId = stages[stages.length - 1];
/* 根据 status 映射生成进度文本 */
function stageProgressLabel(statusMap?: Record<string, string>): { text: string; color: string } {
  const map = statusMap || {};
  const completed = Object.keys(map).filter(k => ["completed", "session_completed"].includes(map[k]));
  if (completed.length === 0) return { text: '未开始', color: 'text-gray-400' };
  if (completed.length >= STAGES.length) return { text: '已完成', color: 'text-green-600' };
  // 对比 STAGES 获取最后一个已完成的
  const lastStageId = STAGES.filter(s => completed.includes(s.id)).pop()?.id || completed[completed.length - 1];
  const stageDef = STAGES.find(s => s.id === lastStageId);
  const name = stageDef?.shortName || lastStageId;
  return { text: `已完成: ${name} (${stages.length}/${STAGES.length})`, color: 'text-blue-600' };
  return { text: `已完成: ${name} (${completed.length}/${STAGES.length})`, color: 'text-blue-600' };
}
export default function HomePage({ onStartProject, onResumeProject, onDeleteSession, history }: HomePageProps) {
@@ -60,6 +65,13 @@
  const [selectedRatio, setSelectedRatio] = useState('16:9');
  const [enableConcurrency, setEnableConcurrency] = useState(true);
  const [webSearch, setWebSearch] = useState(false);
  const [episodes, setEpisodes] = useState(4);
  const [showEpisodesPanel, setShowEpisodesPanel] = useState(false);
  // 上传相关状态
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [uploadedFile, setUploadedFile] = useState<{name: string, path: string} | null>(null);
  // 管理模式状态
  const [manageMode, setManageMode] = useState(false);
@@ -82,9 +94,10 @@
  };
  const handleStart = (auto?: boolean) => {
    if (!idea.trim()) return;
    if (!idea.trim() && !uploadedFile) return;
    onStartProject({
      idea,
      file_path: uploadedFile?.path, // 如果上传了文件,传给后端
      style: selectedStyle,
      video_ratio: selectedRatio,
      llm_model: selectedLLM,
@@ -94,11 +107,56 @@
      video_model: selectedVideo,
      enable_concurrency: enableConcurrency,
      web_search: webSearch,
      episodes,
    }, auto);
  };
  const handleExampleClick = (text: string) => {
    setIdea(text);
  };
  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const allowedExtensions = ['.doc', '.docx', '.txt', '.md', '.pdf'];
    const extension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
    if (!allowedExtensions.includes(extension)) {
      alert(`仅支持 ${allowedExtensions.join(', ')} 格式的文件`);
      return;
    }
    setUploading(true);
    const formData = new FormData();
    formData.append('file', file);
    try {
      const response = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8000'}/api/upload_file`, {
        method: 'POST',
        body: formData,
      });
      if (!response.ok) {
        throw new Error('文件上传失败');
      }
      const data = await response.json();
      if (data.file_path) {
        // 记录已上传的文件信息,不修改输入框
        setUploadedFile({
          name: file.name,
          path: data.file_path
        });
      }
    } catch (error) {
      console.error('上传错误:', error);
      alert('上传提取内容失败,请重试');
    } finally {
      setUploading(false);
      // 清空 input 方便下次选择同一文件
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };
  return (
@@ -124,7 +182,7 @@
            placeholder="描述你的视频创意... 例如:一只叫Luna的猫意外进入太空站,遇到一个孤独的宇航员"
            className="w-full bg-transparent text-sm text-gray-800 placeholder-gray-400 resize-none outline-none min-h-[100px]"
            onKeyDown={e => {
              if (e.key === 'Enter' && !e.shiftKey && idea.trim()) {
              if (e.key === 'Enter' && !e.shiftKey && (idea.trim() || uploadedFile)) {
                e.preventDefault();
                handleStart(false);
              }
@@ -133,6 +191,72 @@
          <div className="flex items-center justify-between mt-3 pt-3 border-t border-gray-100">
            <div className="flex items-center gap-3">
              <div className="relative">
                <button
                  onClick={() => setShowEpisodesPanel(!showEpisodesPanel)}
                  className={clsx(
                    'flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors',
                    showEpisodesPanel
                      ? 'bg-blue-50 text-blue-600'
                      : 'text-gray-400 hover:text-gray-600 hover:bg-gray-50'
                  )}
                >
                  <ListOrdered className="w-3.5 h-3.5" />
                  剧集: {episodes}集
                </button>
                {showEpisodesPanel && (
                  <>
                    <div
                      className="fixed inset-0 z-10"
                      onClick={() => setShowEpisodesPanel(false)}
                    />
                    <div className="absolute bottom-full left-0 mb-2 w-48 bg-white rounded-xl shadow-xl border border-gray-100 p-4 z-20 animate-in fade-in slide-in-from-bottom-2">
                      <div className="flex flex-col gap-3">
                        <div className="flex items-center justify-between">
                          <span className="text-xs font-semibold text-gray-700">设置总集数</span>
                          <span className="text-[10px] text-blue-500 font-bold bg-blue-50 px-1.5 py-0.5 rounded-full">
                            {episodes} 集
                          </span>
                        </div>
                        <div className="flex items-center gap-2">
                          <button
                            onClick={(e) => { e.stopPropagation(); setEpisodes(Math.max(1, episodes - 1)); }}
                            className="w-7 h-7 flex items-center justify-center rounded-lg bg-gray-50 text-gray-600 hover:bg-gray-100 active:scale-95 transition-all text-sm font-bold"
                          >
                            -
                          </button>
                          <input
                            type="range"
                            min={1}
                            max={10}
                            value={episodes}
                            onChange={(e) => setEpisodes(parseInt(e.target.value))}
                            className="flex-1 h-1.5 bg-gray-100 rounded-lg appearance-none cursor-pointer accent-blue-500"
                          />
                          <button
                            onClick={(e) => { e.stopPropagation(); setEpisodes(Math.min(10, episodes + 1)); }}
                            className="w-7 h-7 flex items-center justify-center rounded-lg bg-gray-50 text-gray-600 hover:bg-gray-100 active:scale-95 transition-all text-sm font-bold"
                          >
                            +
                          </button>
                        </div>
                        <div className="space-y-1 border-t border-gray-50 pt-2">
                          <p className="text-[10px] text-gray-400 leading-tight">
                            • 每集预估时长约 1-2 分钟
                          </p>
                          <p className="text-[10px] text-blue-400/80 leading-tight">
                            • 推荐设置 4-6 集
                          </p>
                        </div>
                      </div>
                    </div>
                  </>
                )}
              </div>
              <button
                onClick={() => setShowSettings(!showSettings)}
                className={clsx(
@@ -159,12 +283,53 @@
              </button>
            </div>
            <div className="flex items-center gap-2">
              {/* 隐藏的文件输入框 */}
              <input
                type="file"
                ref={fileInputRef}
                onChange={handleFileUpload}
                accept=".doc,.docx,.txt,.md,.pdf"
                className="hidden"
              />
              <button
                onClick={() => {
                  if (uploadedFile) {
                    setUploadedFile(null); // 已有文件则点击取消
                  } else {
                    fileInputRef.current?.click();
                  }
                }}
                disabled={uploading}
                className={clsx(
                  'flex items-center gap-2 px-5 py-2 rounded-xl text-sm font-medium transition-colors border shadow-sm relative',
                  uploading
                    ? 'bg-gray-50 text-gray-400 cursor-not-allowed border-gray-100'
                    : uploadedFile
                    ? 'bg-blue-50 text-blue-600 border-blue-100 hover:bg-blue-100'
                    : 'bg-white text-gray-600 hover:bg-gray-50 border-gray-200'
                )}
                title={uploadedFile ? `已选择: ${uploadedFile.name} (点击取消)` : "上传文档 (Word/TXT/MD)"}
              >
                {uploading ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : uploadedFile ? (
                  <CheckCircle className="w-4 h-4" />
                ) : (
                  <Upload className="w-4 h-4" />
                )}
                {uploading ? '上传中...' : uploadedFile ? `已选: ${uploadedFile.name.length > 8 ? uploadedFile.name.substring(0, 8) + '...' : uploadedFile.name}` : '上传文件'}
                {uploadedFile && (
                  <div className="absolute -top-1 -right-1 bg-red-500 text-white rounded-full p-0.5">
                    <X className="w-2.5 h-2.5" />
                  </div>
                )}
              </button>
              <button
                onClick={() => handleStart(false)}
                disabled={!idea.trim()}
                disabled={!idea.trim() && !uploadedFile}
                className={clsx(
                  'flex items-center gap-2 px-5 py-2 rounded-xl text-sm font-medium transition-colors',
                  idea.trim()
                  (idea.trim() || uploadedFile)
                    ? 'bg-blue-500 text-white hover:bg-blue-600 shadow-sm'
                    : 'bg-gray-100 text-gray-400 cursor-not-allowed'
                )}
@@ -174,10 +339,10 @@
              </button>
              <button
                onClick={() => handleStart(true)}
                disabled={!idea.trim()}
                disabled={!idea.trim() && !uploadedFile}
                className={clsx(
                  'flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium transition-colors',
                  idea.trim()
                  (idea.trim() || uploadedFile)
                    ? 'bg-amber-500 text-white hover:bg-amber-600 shadow-sm'
                    : 'bg-gray-100 text-gray-400 cursor-not-allowed'
                )}
@@ -398,7 +563,7 @@
                        <span className="text-[10px] text-gray-400">{item.date}</span>
                      </div>
                      <div className={`flex items-center gap-1 mt-1.5 text-[10px] font-medium ${progress.color}`}>
                        {item.stages && item.stages.length >= STAGES.length ? (
                        {item.stages && Object.keys(item.stages).filter(k => ["completed", "session_completed"].includes(item.stages![k])).length >= STAGES.length ? (
                          <CheckCircle className="w-3 h-3" />
                        ) : (
                          <span className="w-1.5 h-1.5 rounded-full bg-current flex-shrink-0" />