All files / src/components PipelineResultPreview.tsx

0% Statements 0/218
0% Branches 0/1
0% Functions 0/1
0% Lines 0/218

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
/**
 * PipelineResultPreview - Pipeline 执行结果预览组件
 *
 * 展示 Pipeline 执行完成后的结果,支持多种预览模式:
 * - JSON 数据预览
 * - Markdown 渲染
 * - 文件下载列表
 * - 课堂预览器(特定 Pipeline)
 */
 
import { useState } from 'react';
import {
  FileText,
  Download,
  ExternalLink,
  Copy,
  Check,
  Code,
  File,
  Presentation,
  FileSpreadsheet,
  X,
} from 'lucide-react';
import { PipelineRunResponse } from '../lib/pipeline-client';
import { useToast } from './ui/Toast';
 
// === Types ===
 
interface PipelineResultPreviewProps {
  result: PipelineRunResponse;
  pipelineId: string;
  onClose?: () => void;
}
 
type PreviewMode = 'auto' | 'json' | 'markdown' | 'classroom' | 'files';
 
// === Utility Functions ===
 
function getFileIcon(filename: string): React.ReactNode {
  const ext = filename.split('.').pop()?.toLowerCase();
  switch (ext) {
    case 'pptx':
    case 'ppt':
      return <Presentation className="w-5 h-5 text-orange-500" />;
    case 'xlsx':
    case 'xls':
      return <FileSpreadsheet className="w-5 h-5 text-green-500" />;
    case 'pdf':
      return <FileText className="w-5 h-5 text-red-500" />;
    case 'html':
      return <Code className="w-5 h-5 text-blue-500" />;
    case 'md':
    case 'markdown':
      return <FileText className="w-5 h-5 text-gray-500" />;
    default:
      return <File className="w-5 h-5 text-gray-400" />;
  }
}
 
function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
 
// === Sub-Components ===
 
interface FileDownloadCardProps {
  file: {
    name: string;
    url: string;
    size?: number;
  };
}
 
function FileDownloadCard({ file }: FileDownloadCardProps) {
  const handleDownload = () => {
    // Create download link
    const link = document.createElement('a');
    link.href = file.url;
    link.download = file.name;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };
 
  return (
    <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-800 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
      {getFileIcon(file.name)}
      <div className="flex-1 min-w-0">
        <p className="text-sm font-medium text-gray-900 dark:text-white truncate">
          {file.name}
        </p>
        {file.size && (
          <p className="text-xs text-gray-500 dark:text-gray-400">
            {formatFileSize(file.size)}
          </p>
        )}
      </div>
      <div className="flex items-center gap-2">
        <button
          onClick={() => window.open(file.url, '_blank')}
          className="p-1.5 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
          title="在新窗口打开"
        >
          <ExternalLink className="w-4 h-4" />
        </button>
        <button
          onClick={handleDownload}
          className="flex items-center gap-1 px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-md transition-colors"
        >
          <Download className="w-4 h-4" />
          下载
        </button>
      </div>
    </div>
  );
}
 
interface JsonPreviewProps {
  data: unknown;
}
 
function JsonPreview({ data }: JsonPreviewProps) {
  const [copied, setCopied] = useState(false);
  const { toast } = useToast();
 
  const jsonString = JSON.stringify(data, null, 2);
 
  const handleCopy = async () => {
    await navigator.clipboard.writeText(jsonString);
    setCopied(true);
    toast('已复制到剪贴板', 'success');
    setTimeout(() => setCopied(false), 2000);
  };
 
  return (
    <div className="relative">
      <button
        onClick={handleCopy}
        className="absolute top-2 right-2 p-1.5 bg-gray-200 dark:bg-gray-700 rounded hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors"
        title="复制"
      >
        {copied ? <Check className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}
      </button>
      <pre className="p-4 bg-gray-900 text-gray-100 rounded-lg overflow-auto text-sm max-h-96">
        {jsonString}
      </pre>
    </div>
  );
}
 
interface MarkdownPreviewProps {
  content: string;
}
 
function MarkdownPreview({ content }: MarkdownPreviewProps) {
  // Simple markdown rendering (for production, use a proper markdown library)
  const renderMarkdown = (md: string): string => {
    return md
      // Headers
      .replace(/^### (.*$)/gim, '<h3 class="text-lg font-semibold mt-4 mb-2">$1</h3>')
      .replace(/^## (.*$)/gim, '<h2 class="text-xl font-semibold mt-4 mb-2">$1</h2>')
      .replace(/^# (.*$)/gim, '<h1 class="text-2xl font-bold mt-4 mb-2">$1</h1>')
      // Bold
      .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      // Italic
      .replace(/\*(.*?)\*/g, '<em>$1</em>')
      // Lists
      .replace(/^- (.*$)/gim, '<li class="ml-4">$1</li>')
      // Paragraphs
      .replace(/\n\n/g, '</p><p class="my-2">')
      // Line breaks
      .replace(/\n/g, '<br>');
  };
 
  return (
    <div
      className="prose dark:prose-invert max-w-none p-4 bg-white dark:bg-gray-800 rounded-lg"
      dangerouslySetInnerHTML={{ __html: renderMarkdown(content) }}
    />
  );
}
 
// === Main Component ===
 
export function PipelineResultPreview({
  result,
  pipelineId,
  onClose,
}: PipelineResultPreviewProps) {
  const [mode, setMode] = useState<PreviewMode>('auto');
 
  // Determine the best preview mode
  const outputs = result.outputs as Record<string, unknown> | undefined;
  const exportFiles = (outputs?.export_files as Array<{ name: string; url: string; size?: number }>) || [];
 
  // Check if this is a classroom pipeline
  const isClassroom = pipelineId === 'classroom-generator' || pipelineId.includes('classroom');
 
  // Auto-detect preview mode
  const autoMode: PreviewMode = isClassroom ? 'classroom' :
    exportFiles.length > 0 ? 'files' :
    typeof outputs === 'object' ? 'json' : 'json';
 
  const activeMode = mode === 'auto' ? autoMode : mode;
 
  // Render based on mode
  const renderContent = () => {
    switch (activeMode) {
      case 'json':
        return <JsonPreview data={outputs} />;
 
      case 'markdown':
        const mdContent = (outputs?.summary || outputs?.report || JSON.stringify(outputs, null, 2)) as string;
        return <MarkdownPreview content={mdContent} />;
 
      case 'classroom':
        // Will be handled by ClassroomPreviewer component
        return (
          <div className="text-center py-8 text-gray-500">
            <Presentation className="w-12 h-12 mx-auto mb-3 text-gray-400" />
            <p>课堂预览功能正在开发中...</p>
            <p className="text-sm mt-2">您可以在下方下载生成的文件</p>
          </div>
        );
 
      default:
        return <JsonPreview data={outputs} />;
    }
  };
 
  return (
    <div className="bg-white dark:bg-gray-900 rounded-lg shadow-xl max-w-3xl w-full max-h-[90vh] overflow-hidden">
      {/* Header */}
      <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
        <div>
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
            Pipeline 执行完成
          </h2>
          <p className="text-sm text-gray-500 dark:text-gray-400">
            {result.pipelineId} · {result.status === 'completed' ? '成功' : result.status}
          </p>
        </div>
        {onClose && (
          <button
            onClick={onClose}
            className="p-1 hover:bg-gray-100 dark:hover:bg-gray-800 rounded"
          >
            <X className="w-5 h-5 text-gray-500" />
          </button>
        )}
      </div>
 
      {/* Mode Tabs */}
      <div className="flex items-center gap-2 p-2 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
        <button
          onClick={() => setMode('auto')}
          className={`px-3 py-1.5 text-sm rounded-md transition-colors ${
            mode === 'auto'
              ? 'bg-white dark:bg-gray-700 text-blue-600 dark:text-blue-400 shadow-sm'
              : 'text-gray-600 dark:text-gray-300 hover:bg-white dark:hover:bg-gray-700'
          }`}
        >
          自动
        </button>
        <button
          onClick={() => setMode('json')}
          className={`px-3 py-1.5 text-sm rounded-md transition-colors ${
            mode === 'json'
              ? 'bg-white dark:bg-gray-700 text-blue-600 dark:text-blue-400 shadow-sm'
              : 'text-gray-600 dark:text-gray-300 hover:bg-white dark:hover:bg-gray-700'
          }`}
        >
          JSON
        </button>
        <button
          onClick={() => setMode('markdown')}
          className={`px-3 py-1.5 text-sm rounded-md transition-colors ${
            mode === 'markdown'
              ? 'bg-white dark:bg-gray-700 text-blue-600 dark:text-blue-400 shadow-sm'
              : 'text-gray-600 dark:text-gray-300 hover:bg-white dark:hover:bg-gray-700'
          }`}
        >
          Markdown
        </button>
        {isClassroom && (
          <button
            onClick={() => setMode('classroom')}
            className={`px-3 py-1.5 text-sm rounded-md transition-colors ${
              mode === 'classroom'
                ? 'bg-white dark:bg-gray-700 text-blue-600 dark:text-blue-400 shadow-sm'
                : 'text-gray-600 dark:text-gray-300 hover:bg-white dark:hover:bg-gray-700'
            }`}
          >
            课堂预览
          </button>
        )}
      </div>
 
      {/* Content */}
      <div className="p-4 overflow-auto max-h-96">
        {renderContent()}
      </div>
 
      {/* Export Files */}
      {exportFiles.length > 0 && (
        <div className="p-4 border-t border-gray-200 dark:border-gray-700">
          <h3 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
            导出文件 ({exportFiles.length})
          </h3>
          <div className="space-y-2">
            {exportFiles.map((file, index) => (
              <FileDownloadCard key={index} file={file} />
            ))}
          </div>
        </div>
      )}
 
      {/* Footer */}
      <div className="flex items-center justify-end gap-3 p-4 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
        <span className="text-xs text-gray-500 dark:text-gray-400">
          执行时间: {new Date(result.startedAt).toLocaleString()}
        </span>
        {onClose && (
          <button
            onClick={onClose}
            className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-md"
          >
            关闭
          </button>
        )}
      </div>
    </div>
  );
}
 
export default PipelineResultPreview;