숏폼생성 기능 추가

This commit is contained in:
skkim committed 2026-06-12 09:44:02 +09:00
1 parent cb68b2da97
commit 530416026d
45 files changed
+5398 -960

No files matched your search

+17 -35
View File
@@ -2,6 +2,7 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import Sidebar from '../../components/Sidebar';
import ShortformContent from './ShortformContent';
import AssetManagementContent from './AssetManagementContent';
import SoundStudioContent from './SoundStudioContent';
import CompletionContent from './CompletionContent';
@@ -54,6 +55,7 @@ interface GenerationFlowProps {
initialImageList?: string[];
businessInfo?: BusinessInfo;
initialAnalysisData?: CrawlingResponse | null;
initialShortform?: boolean;
}
// 위저드 단계:
@@ -69,7 +71,8 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
initialActiveItem = '대시보드',
initialImageList = [],
businessInfo,
initialAnalysisData
initialAnalysisData,
initialShortform = false,
}) => {
const { t, i18n } = useTranslation();
// localStorage에서 저장된 상태 복원
@@ -94,6 +97,9 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
// 초기 위저드 단계 결정
const getInitialWizardStep = (): number => {
// 숏폼 진입 플래그가 있으면 숏폼 화면(-3)으로 바로
if (initialShortform) return -3;
if (savedWizardStep !== null) {
const step = parseInt(savedWizardStep, 10);
// 분석 데이터가 있는데 URL 입력(-2) 또는 로딩(-1) 단계로 저장된 경우:
@@ -289,37 +295,6 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
};
// 테스트용 랜덤 m_id 생성 (99 ~ 300)
const generateRandomMId = (): number => {
return Math.floor(Math.random() * (300 - 99 + 1)) + 99;
};
// 테스트 데이터로 브랜드 분석 페이지 이동
const handleTestData = (data: CrawlingResponse) => {
const tagged = { ...data, m_id: generateRandomMId(), _isTestData: true };
setAnalysisData(tagged);
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(tagged));
goToWizardStep(0); // 브랜드 분석 결과로
};
// 언어 변경 시 테스트 데이터 다시 로드
useEffect(() => {
const saved = localStorage.getItem(ANALYSIS_DATA_KEY);
if (!saved) return;
try {
const parsed = JSON.parse(saved);
if (!parsed._isTestData) return;
const jsonFile = i18n.language === 'en' ? '/example_analysis_en.json' : '/example_analysis.json';
fetch(jsonFile)
.then(res => res.json())
.then((data: CrawlingResponse) => {
// 언어 변경 시에는 기존 m_id 유지
const tagged = { ...data, m_id: parsed.m_id || generateRandomMId(), _isTestData: true };
setAnalysisData(tagged);
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(tagged));
})
.catch(err => console.error('Failed to reload test data:', err));
} catch { /* ignore */ }
}, [i18n.language]);
// URL 분석 시작
const handleStartAnalysis = async (url: string) => {
@@ -432,6 +407,13 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
// 새 프로젝트 만들기 - 단계별 컨텐츠 렌더링
const renderWizardContent = () => {
switch (wizardStep) {
case -3:
// 숏폼 생성 단계
return (
<ShortformContent
onComplete={refreshCredits}
/>
);
case -2:
// URL 입력 단계
return (
@@ -439,7 +421,7 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
onAnalyze={handleStartAnalysis}
onAutocomplete={handleAutocomplete}
onManualInput={handleManualInput}
onTestData={handleTestData}
onShortform={() => goToWizardStep(-3)}
error={analysisError}
/>
);
@@ -551,8 +533,8 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
case '내 정보':
return <MyInfoContent initialTab={myInfoInitialTab} />;
case '새 프로젝트 만들기':
// 브랜드 분석(0)과 로딩(-1)은 전체 화면으로 표시
if (wizardStep === 0 || wizardStep === -1) {
// 브랜드 분석(0), 로딩(-1), 숏폼(-3)은 전체 화면으로 표시
if (wizardStep === 0 || wizardStep === -1 || wizardStep === -3) {
return renderWizardContent();
}
return (
+478
View File
@@ -0,0 +1,478 @@
import React, { useRef, useState } from 'react';
import { uploadImages, generateShortform, waitForShortformComplete, previewShortform } from '../../utils/api';
import { ShortformStatusResponse, VideoSpec } from '../../types/api';
type Kind = 'place' | 'product' | 'message';
type Step = 1 | 2 | 3 | 4;
interface ShortformContentProps {
onComplete?: () => void;
}
const KIND_OPTIONS: { value: Kind; label: string; desc: string }[] = [
{ value: 'place', label: '장소', desc: '펜션·카페·식당·매장 등 공간' },
{ value: 'product', label: '물건', desc: '제품, 음식 등 시각적인 아이템' },
{ value: 'message', label: '메시지', desc: '축하·안부·홍보 등' },
];
const STEP_META = [
{ label: '사진 업로드', sub: '4~5장' },
{ label: '정보 입력', sub: '몇 가지만 답하기' },
{ label: '영상 생성', sub: 'AI 카메라 + 자막' },
{ label: '완성', sub: '다운로드' },
];
const MIN_PHOTOS = 4;
const MIN_PHOTOS_LABEL = `${MIN_PHOTOS}장`;
const ShortformContent: React.FC<ShortformContentProps> = ({ onComplete }) => {
const fileInputRef = useRef<HTMLInputElement>(null);
const dropRef = useRef<HTMLDivElement>(null);
// 단계
const [step, setStep] = useState<Step>(1);
// Step 1 — 사진
const [files, setFiles] = useState<File[]>([]);
const [previews, setPreviews] = useState<string[]>([]);
// Step 2 — 폼
const [kind, setKind] = useState<Kind>('place');
const [bizName, setBizName] = useState('');
const [selling, setSelling] = useState('');
const [addr, setAddr] = useState('');
const [price, setPrice] = useState('');
// Step 3/4 — 생성 상태
const [statusMsg, setStatusMsg] = useState('');
const [result, setResult] = useState<ShortformStatusResponse | null>(null);
const [errorMsg, setErrorMsg] = useState('');
// 자막 미리보기
const [preview, setPreview] = useState<VideoSpec | null>(null);
const [previewLoading, setPreviewLoading] = useState(false);
const [previewError, setPreviewError] = useState('');
// --- 사진 관리 ---
const addFiles = (newFiles: File[]) => {
const images = newFiles.filter(f => f.type.startsWith('image/'));
if (!images.length) return;
const newUrls = images.map(f => URL.createObjectURL(f));
setFiles(prev => [...prev, ...images]);
setPreviews(prev => [...prev, ...newUrls]);
};
const removeFile = (index: number) => {
URL.revokeObjectURL(previews[index]);
setFiles(prev => prev.filter((_, i) => i !== index));
setPreviews(prev => prev.filter((_, i) => i !== index));
};
const handleDragOver = (e: React.DragEvent) => { e.preventDefault(); };
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
addFiles(Array.from(e.dataTransfer.files));
};
// --- 미리보기 필드 수정 ---
const patchPreview = (updater: (prev: NonNullable<typeof preview>) => NonNullable<typeof preview>) => {
setPreview(prev => prev ? updater(prev) : prev);
};
// --- 자막 미리보기 ---
const handlePreview = async () => {
if (!selling.trim()) return;
setPreviewLoading(true);
setPreviewError('');
try {
const spec = await previewShortform({
kind,
biz_name: bizName.trim(),
selling: selling.trim(),
addr: addr.trim() || undefined,
price: price.trim() || undefined,
});
setPreview(spec);
} catch (err) {
setPreviewError(err instanceof Error ? err.message : '미리보기 생성에 실패했습니다.');
} finally {
setPreviewLoading(false);
}
};
// --- 다운로드 ---
const [isDownloading, setIsDownloading] = useState(false);
const handleDownload = async (url: string) => {
if (isDownloading) return;
setIsDownloading(true);
try {
const resp = await fetch(url);
const blob = await resp.blob();
const blobUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = blobUrl;
link.download = `${bizName || 'shortform'}.mp4`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(blobUrl);
} catch {
const link = document.createElement('a');
link.href = url;
link.download = `${bizName || 'shortform'}.mp4`;
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} finally {
setIsDownloading(false);
}
};
// --- 생성 실행 ---
const handleGenerate = async () => {
setStep(3);
setErrorMsg('');
setResult(null);
try {
setStatusMsg('사진 업로드 중...');
const uploadResp = await uploadImages([], files);
setStatusMsg('영상 생성 요청 중...');
await generateShortform({
task_id: uploadResp.task_id,
kind,
biz_name: bizName.trim(),
addr: addr.trim() || undefined,
price: price.trim() || undefined,
selling: selling.trim(),
spec: preview ?? undefined,
dry_run: true,
});
setStatusMsg('AI 카메라 무브·자막 렌더링 중...');
const statusResp = await waitForShortformComplete(uploadResp.task_id, s => {
setStatusMsg(s === 'processing' ? 'AI 카메라 무브·자막 렌더링 중...' : s);
});
setResult(statusResp);
setStep(4);
onComplete?.();
} catch (err) {
setErrorMsg(err instanceof Error ? err.message : '생성 중 오류가 발생했습니다.');
setStep(2);
}
};
const step1Valid = files.length >= MIN_PHOTOS;
const step2Valid = bizName.trim() && selling.trim();
// ===================== 렌더 =====================
// 스텝 인디케이터
const StepBar = () => (
<div className="sf-step-bar">
{STEP_META.map((s, i) => {
const n = (i + 1) as Step;
const done = step > n;
const active = step === n;
return (
<div key={n} className={`sf-step-item ${active ? 'active' : ''} ${done ? 'done' : ''}`}>
<div className="sf-step-circle">
{done
? <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><polyline points="20 6 9 17 4 12"/></svg>
: n}
</div>
<div className="sf-step-label">
<span className="sf-step-name">{s.label}</span>
<span className="sf-step-sub">{s.sub}</span>
</div>
</div>
);
})}
</div>
);
// ---- Step 1: 사진 업로드 ----
if (step === 1) return (
<main className="sf-page">
<div className="sf-scroll-area">
<div className="sf-hero">
<h1 className="sf-hero-title">사진 몇 장과 한마디면, <span className="sf-hero-accent">8초 홍보 영상</span>이 됩니다</h1>
<p className="sf-hero-desc">복잡한 분석 없이 — 사진을 올리고 몇 가지만 답하면, AI 카메라 무브와 자막을 입힌 세로형 숏폼이 완성됩니다.</p>
</div>
<StepBar />
<div className="sf-card">
<h2 className="sf-card-title">사진 업로드</h2>
<p className="sf-card-desc">홍보할 장소나 물건 사진 4~5장. 전경 1장·디테일 2~3장을 섞으면 영상의 서사가 살아납니다.</p>
<div
ref={dropRef}
className="sf-drop-zone"
onClick={() => fileInputRef.current?.click()}
onDragOver={handleDragOver}
onDrop={handleDrop}
>
<div className="sf-drop-icon">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
</div>
<p className="sf-drop-text">여기로 사진을 끌어다 놓거나 클릭</p>
<p className="sf-drop-hint">JPG·PNG·{MIN_PHOTOS_LABEL} 이상</p>
</div>
<input ref={fileInputRef} type="file" accept="image/*" multiple style={{ display: 'none' }} onChange={e => { addFiles(Array.from(e.target.files || [])); e.target.value = ''; }} />
{previews.length > 0 && (
<div className="sf-photo-grid">
{previews.map((url, i) => (
<div key={i} className="sf-photo-item">
<span className="sf-photo-num">{i + 1}</span>
<img src={url} alt={`사진 ${i + 1}`} />
<button className="sf-photo-remove" onClick={() => removeFile(i)}>×</button>
</div>
))}
</div>
)}
</div>
</div>
<div className="sf-footer">
<div className="sf-footer-info">
<span className="sf-footer-count">{files.length}장</span>
{step1Valid
? <span className="sf-footer-status ok">업로드됨·준비 완료</span>
: <span className="sf-footer-status">{MIN_PHOTOS - files.length}장 더 추가해주세요</span>}
</div>
<button
className="sf-btn-next"
disabled={!step1Valid}
onClick={() => setStep(2)}
>
다음: 정보 입력 →
</button>
</div>
</main>
);
// ---- Step 2: 정보 입력 ----
if (step === 2) return (
<main className="sf-page">
<div className="sf-scroll-area">
<StepBar />
<div className="sf-card">
<h2 className="sf-card-title">몇 가지만 알려주세요</h2>
<p className="sf-card-desc">사장님·마케터가 가장 잘 아는 정보로 카피를 만듭니다.</p>
{/* Kind */}
<div className="sf-field">
<label className="sf-label">영상의 목적이 무엇인가요? <span className="sf-required">*</span></label>
<div className="sf-kind-grid">
{KIND_OPTIONS.map(opt => (
<button
key={opt.value}
type="button"
className={`sf-kind-card ${kind === opt.value ? 'active' : ''}`}
onClick={() => setKind(opt.value)}
>
<span className="sf-kind-label">{opt.label}</span>
<span className="sf-kind-desc">{opt.desc}</span>
</button>
))}
</div>
</div>
{/* 업체명 */}
<div className="sf-field">
<label className="sf-label">업체·상품·메시지 제목 <span className="sf-required">*</span></label>
<input
className="sf-input"
type="text"
placeholder="예: 스테이 머뭄"
value={bizName}
onChange={e => setBizName(e.target.value)}
maxLength={50}
/>
</div>
{/* 셀링포인트 */}
<div className="sf-field">
<label className="sf-label">가장 자랑하고 싶은 한 가지 <span className="sf-required">*</span></label>
<textarea
className="sf-textarea"
placeholder="예: 열방 손님 없는 완전한 독채, 개별 정원까지"
value={selling}
onChange={e => setSelling(e.target.value)}
maxLength={100}
rows={3}
/>
<p className="sf-field-hint">이 한마디가 영상의 후킹 타이틀·핵심 메시지가 됩니다. 구체적일수록 좋아요.</p>
</div>
{/* 자막 미리보기 */}
<div className="sf-field">
<div className="sf-subtitle-header">
<label className="sf-label">영상 자막·스크립트</label>
<button
className="sf-subtitle-btn"
disabled={!selling.trim() || previewLoading}
onClick={handlePreview}
>
{previewLoading ? '생성 중...' : preview ? '재생성하기' : '자막 생성하기'}
</button>
</div>
<p className="sf-field-hint">위 한 가지를 적은 뒤 누르면, AI가 인트로·셀링포인트·감성 스토리·CTA 4가지를 만들어줍니다.</p>
{previewError && <p className="sf-field-error">{previewError}</p>}
{preview && (
<div className="sf-preview-spec">
<div className="sf-preview-block">
<span className="sf-preview-tag">인트로</span>
<input className="sf-preview-input" value={preview.hook.eyebrow}
onChange={e => patchPreview(p => ({ ...p, hook: { ...p.hook, eyebrow: e.target.value } }))} />
<input className="sf-preview-input sf-preview-input-bold" value={preview.hook.title}
onChange={e => patchPreview(p => ({ ...p, hook: { ...p.hook, title: e.target.value } }))} />
</div>
<div className="sf-preview-block">
<span className="sf-preview-tag">셀링포인트</span>
<div className="sf-preview-badge-inputs">
{preview.selling_point.items.slice(0, 3).map((item, i) => (
<input key={i} className="sf-preview-badge-input" value={item}
onChange={e => patchPreview(p => {
const items = [...p.selling_point.items];
items[i] = e.target.value;
return { ...p, selling_point: { items } };
})} />
))}
</div>
</div>
<div className="sf-preview-block">
<span className="sf-preview-tag">감성 스토리</span>
{preview.brand_lines.slice(0, 2).map((line, i) => (
<input key={i} className="sf-preview-input" value={line}
onChange={e => patchPreview(p => {
const brand_lines = [...p.brand_lines];
brand_lines[i] = e.target.value;
return { ...p, brand_lines };
})} />
))}
</div>
<div className="sf-preview-block">
<span className="sf-preview-tag">CTA</span>
<input className="sf-preview-input" value={preview.end_card.brand}
onChange={e => patchPreview(p => ({ ...p, end_card: { ...p.end_card, brand: e.target.value } }))} />
<input className="sf-preview-input" value={preview.end_card.location}
onChange={e => patchPreview(p => ({ ...p, end_card: { ...p.end_card, location: e.target.value } }))} />
</div>
</div>
)}
</div>
{/* 주소 */}
<div className="sf-field">
<label className="sf-label">주소 또는 판매 사이트 URL <span className="sf-optional">(선택)</span></label>
<input
className="sf-input"
type="text"
placeholder="예: 전북 군산시 절골길 18"
value={addr}
onChange={e => setAddr(e.target.value)}
maxLength={100}
/>
<p className="sf-field-hint">영상 엔드카드·해시태그에 활용됩니다.</p>
</div>
{/* 가격 */}
<div className="sf-field">
<label className="sf-label">가격 정보 <span className="sf-optional">(선택)</span></label>
<input
className="sf-input"
type="text"
placeholder="예: 1박 19만원~"
value={price}
onChange={e => setPrice(e.target.value)}
maxLength={50}
/>
</div>
</div>
</div>
<div className="sf-footer sf-footer-two">
<button className="sf-btn-prev" onClick={() => setStep(1)}>← 사진 다시</button>
<button className="sf-btn-generate" disabled={!step2Valid} onClick={handleGenerate}>
영상 생성 →
</button>
</div>
{errorMsg && (
<div className="sf-error-toast">{errorMsg}</div>
)}
</main>
);
// ---- Step 3: 생성 중 ----
if (step === 3) return (
<main className="sf-page">
<div className="sf-scroll-area">
<StepBar />
<div className="sf-generating">
<div className="sf-gen-orb-ring">
<div className="sf-gen-spinner-lg" />
<div className="sf-gen-icon">
<svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<path d="M15 10l4.553-2.069A1 1 0 0121 8.87V15.13a1 1 0 01-1.447.899L15 14M3 8a2 2 0 012-2h10a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V8z"/>
</svg>
</div>
</div>
<h2 className="sf-gen-title">AI가 영상을 만들고 있어요</h2>
<p className="sf-gen-msg">{statusMsg || 'AI 카메라 무브·자막 렌더링 중...'}</p>
<p className="sf-gen-sub">보통 1~3분 정도 소요됩니다. 잠시만 기다려주세요.</p>
<div className="sf-gen-steps">
<div className={`sf-gen-step ${statusMsg.includes('업로드') ? 'active' : statusMsg ? 'done' : ''}`}>
<span className="sf-gen-step-dot" />사진 업로드
</div>
<div className={`sf-gen-step ${statusMsg.includes('요청') ? 'active' : statusMsg.includes('렌더링') || statusMsg.includes('완성') ? 'done' : ''}`}>
<span className="sf-gen-step-dot" />영상 생성 요청
</div>
<div className={`sf-gen-step ${statusMsg.includes('렌더링') ? 'active' : ''}`}>
<span className="sf-gen-step-dot" />AI 렌더링
</div>
</div>
</div>
</div>
</main>
);
// ---- Step 4: 완성 ----
return (
<main className="sf-page">
<div className="sf-scroll-area">
<StepBar />
<div className="sf-result">
<p className="sf-result-label">✓ 영상이 완성됐습니다!</p>
{result?.result_url && (
<div className="sf-result-video-wrap">
<video className="sf-result-video" src={result.result_url} controls playsInline />
</div>
)}
<div className="sf-result-actions">
{result?.result_url && (
<button
className="sf-download-btn"
disabled={isDownloading}
onClick={() => handleDownload(result.result_url!)}
>
{isDownloading ? '다운로드 중...' : '다운로드'}
</button>
)}
<button className="sf-btn-prev" onClick={() => { setStep(1); setFiles([]); setPreviews([]); setBizName(''); setSelling(''); setAddr(''); setPrice(''); }}>
새 영상 만들기
</button>
</div>
</div>
</div>
</main>
);
};
export default ShortformContent;
+4 -37
View File
@@ -1,39 +1,16 @@
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import React from 'react';
import { AutocompleteRequest } from '../../utils/api';
import { CrawlingResponse } from '../../types/api';
import SearchInputForm, { SearchType } from '../../components/SearchInputForm';
// 환경변수에서 테스트 모드 확인
const isTestPage = import.meta.env.VITE_IS_TESTPAGE === 'true';
interface UrlInputContentProps {
onAnalyze: (value: string, type?: SearchType) => void;
onAutocomplete?: (data: AutocompleteRequest) => void;
onManualInput?: (businessName: string, address: string) => void;
onTestData?: (data: CrawlingResponse) => void;
onShortform?: () => void;
error: string | null;
}
const UrlInputContent: React.FC<UrlInputContentProps> = ({ onAnalyze, onAutocomplete, onManualInput, onTestData, error }) => {
const { t, i18n } = useTranslation();
const [isLoadingTest, setIsLoadingTest] = useState(false);
const handleTestData = async () => {
if (!onTestData) return;
setIsLoadingTest(true);
try {
const jsonFile = i18n.language === 'en' ? '/example_analysis_en.json' : '/example_analysis.json';
const response = await fetch(jsonFile);
const data: CrawlingResponse = await response.json();
onTestData(data);
} catch (err) {
console.error('테스트 데이터 로드 실패:', err);
} finally {
setIsLoadingTest(false);
}
};
const UrlInputContent: React.FC<UrlInputContentProps> = ({ onAnalyze, onAutocomplete, onManualInput, onShortform, error }) => {
return (
<div className="url-input-container">
<div className="url-input-content">
@@ -46,20 +23,10 @@ const UrlInputContent: React.FC<UrlInputContentProps> = ({ onAnalyze, onAutocomp
onAnalyze={onAnalyze}
onAutocomplete={onAutocomplete}
onManualInput={onManualInput}
onShortform={onShortform}
error={error}
/>
</div>
{/* 테스트 버튼 (VITE_IS_TESTPAGE=true일 때만 표시) */}
{isTestPage && onTestData && (
<button
onClick={handleTestData}
disabled={isLoadingTest}
className="test-data-button"
>
{isLoadingTest ? t('urlInput.testDataLoading') : t('urlInput.testData')}
</button>
)}
</div>
);
};
+7 -100
View File
@@ -1,18 +1,4 @@
import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { AutocompleteRequest, isLoggedIn } from '../../utils/api';
import { CrawlingResponse } from '../../types/api';
import { useTutorial } from '../../components/Tutorial/useTutorial';
import { TUTORIAL_KEYS } from '../../components/Tutorial/tutorialSteps';
import TutorialOverlay from '../../components/Tutorial/TutorialOverlay';
import BusinessNameInputModal from '../../components/BusinessNameInputModal';
import LoginPromptModal from '../../components/LoginPromptModal';
import SearchInputForm from '../../components/SearchInputForm';
import { SearchType } from '../../components/SearchInputForm';
// 환경변수에서 테스트 모드 확인
const isTestPage = import.meta.env.VITE_IS_TESTPAGE === 'true';
import React, { useEffect, useRef } from 'react';
// Orb configuration with movement zones to prevent overlap
interface OrbConfig {
@@ -37,50 +23,14 @@ const orbConfigs: OrbConfig[] = [
];
interface HeroSectionProps {
onAnalyze?: (value: string, type?: SearchType) => void;
onAutocomplete?: (data: AutocompleteRequest) => void;
onManualInput?: (businessName: string, address: string) => void;
onTestData?: (data: CrawlingResponse) => void;
onLogin?: () => void;
onNext?: () => void;
error?: string | null;
scrollProgress?: number;
}
const HeroSection: React.FC<HeroSectionProps> = ({ onAnalyze, onAutocomplete, onManualInput, onTestData, onNext, error: externalError, scrollProgress = 0 }) => {
const { t, i18n } = useTranslation();
const [isManualModalOpen, setIsManualModalOpen] = useState(false);
const [isLoginPromptOpen, setIsLoginPromptOpen] = useState(false);
const [testError, setTestError] = useState('');
const [isLoadingTest, setIsLoadingTest] = useState(false);
const HeroSection: React.FC<HeroSectionProps> = ({ onLogin, onNext, scrollProgress = 0 }) => {
const orbRefs = useRef<(HTMLDivElement | null)[]>([]);
const animationRefs = useRef<number[]>([]);
const tutorial = useTutorial();
// 첫 방문 시 랜딩 튜토리얼 시작
useEffect(() => {
if (!tutorial.hasSeen(TUTORIAL_KEYS.LANDING)) {
const timer = setTimeout(() => {
tutorial.startTutorial(TUTORIAL_KEYS.LANDING);
}, 800);
return () => clearTimeout(timer);
}
}, []);
// 테스트 데이터 로드 핸들러
const handleTestData = async () => {
if (!onTestData) return;
setIsLoadingTest(true);
try {
const jsonFile = i18n.language === 'en' ? '/example_analysis_en.json' : '/example_analysis.json';
const response = await fetch(jsonFile);
const data: CrawlingResponse = await response.json();
onTestData(data);
} catch {
setTestError(t('landing.hero.testDataLoadFailed'));
} finally {
setIsLoadingTest(false);
}
};
// Orb 랜덤 이동 애니메이션
useEffect(() => {
@@ -168,63 +118,20 @@ const HeroSection: React.FC<HeroSectionProps> = ({ onAnalyze, onAutocomplete, on
className="hero-logo"
/>
<SearchInputForm
onAnalyze={onAnalyze}
onAutocomplete={onAutocomplete}
onManualInput={onManualInput}
onManualButtonClick={() => {
if (isLoggedIn()) {
setIsManualModalOpen(true);
} else {
setIsLoginPromptOpen(true);
}
}}
error={externalError || testError || null}
/>
<button className="hero-login-btn" onClick={onLogin}>
로그인
</button>
</div>
{/* Footer Indicator */}
<button onClick={onNext} className="scroll-indicator">
<span className="scroll-indicator-text">{t('landing.hero.scrollMore')}</span>
<span className="scroll-indicator-text">더 알아보기</span>
<div className="scroll-indicator-icon">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round">
<path d="M7 10l5 5 5-5" />
</svg>
</div>
</button>
{/* 테스트 버튼 */}
{isTestPage && onTestData && (
<button onClick={handleTestData} disabled={isLoadingTest} className="test-data-button">
{isLoadingTest ? t('landing.hero.testDataLoading') : t('landing.hero.testData')}
</button>
)}
{tutorial.isActive && !isManualModalOpen && (
<TutorialOverlay
hints={tutorial.hints}
currentIndex={tutorial.currentHintIndex}
onNext={tutorial.nextHint}
onPrev={tutorial.prevHint}
onSkip={tutorial.skipTutorial}
groupProgress={tutorial.groupProgress}
/>
)}
{isManualModalOpen && (
<BusinessNameInputModal
onClose={() => setIsManualModalOpen(false)}
onSubmit={(businessName, address) => {
if (tutorial.isActive) tutorial.nextHint();
setIsManualModalOpen(false);
onManualInput?.(businessName, address);
}}
/>
)}
{isLoginPromptOpen && (
<LoginPromptModal onClose={() => setIsLoginPromptOpen(false)} />
)}
</div>
);
};